MythTV Tips: Auto Restart Script

February 25th, 2012

MythTV has got a lot more stable in recent releases, but I have found that there is still occasional crashes, with MythMusic being the main offender. I have found that if you pause a song as it is just about to end, it invariably hangs and needs to be restarted. To do this I use the “power” button on my remote to kill mythtv, and use another script to automatially restart it.

To kill mythtv you will need irexec installed, then you can add the below to your ~/.lircrc file:

begin
    remote = mceusb
    prog = irexec
    button = KEY_POWER
    config = /usr/bin/pkill mythfrontend
    repeat = 0
    delay = 0
end

So far so good, but we need to make mytvtv restart itself too. I am sure there are many ways of doing this, but I settled on a utility called daemontools. You can install daemontools and daemontools-run from the Ubuntu repositories.
Create an /etc/service/mythfrontend directory, and within that directory create a script called “run”:

#!/bin/sh

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
MYPROCESS=/usr/bin/mythfrontend

if [ -x $MYPROCESS ]
then
        su -c /home/adam/Scripts/startMyth.sh adam
fi

I keep the actual startup script in the scripts directory in my home folder for ease of maintenance – this is the script:

#!/bin/bash
export DISPLAY=:0.0 && /usr/bin/mythfrontend \
   -l /var/log/mythtv/mythfrontend.log

As soon as you make the /etc/service/mythfrontend/run script executable (chmod +x run), mythfrontend should start. There are some more tips on using daemontools here.
I use a similar script to automatically restart “irexec” if it crashes. Create an /etc/service/irexec directory, with a “run” script:

#!/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

if pidof -x /usr/bin/irexec > /dev/null; then
        # Do nothing - already running
        echo ""
else
        su -c /home/adam/Scripts/startIRExec.sh adam
fi

And the startIRExec.sh script:

#!/bin/bash
DISPLAY=:0 ~/.local-display-coordinates.sh
DISPLAY=:0 irexec

In recent versions of Ubuntu there has been some changes to the way that scripts can connect to the active X session, so the line at the start of this script:

/home/adam/.local-display-coordinates.sh

calls a script that is generated automatically when the X session starts. This is created by adding the following to your ~/.profile script:

case $DISPLAY in
  :*) export | grep -E ' \
  (DISPLAY|XAUTHORITY)=' \
  >~/.local-display-coordinates.sh;;
esac

This is based on the advice on this page.

MythTV Tips: Universal Volume Control

February 25th, 2012

I have done a fair bit of tinkering with my MythTV box over the last year or two, and I thought I would share a couple of handy tips with the world.

One of the things I always found annoying about MythTV was the fact that I could not alter the volume unless I was in the music or video playback screens. Myth allows you to keep music playing in the background, for example while you browse some news feeds in MythNews – but if you do this you can no longer alter or mute the volume, which is annoying…

To get around this I decided to ditch Myth’s own internal volume controls and create a script that can alter the master volume control directly. This can be launched directly as a result of keypresses on the remote control thanks to a handy app called irexec. This allows me to control the volume even if MythTV is not running.

So, to begin with we need a script to alter the volume. The other problem is that we want to have some visual indication of the volume level as we alter it, so we need to use an OSD (On Screen Display) library of some sort. Initially I used the gnome notification library that ships with recent gnome versions, but I had a strange issue with it not updating quickly enough if I send a few updates in quick succession, so I tried a few others. In the end I settled on osd_cat. The script is loosely based on this one:

#!/bin/bash

/home/adam/.local-display-coordinates.sh

#####################
# Config
CHANNEL='Master'
FONT='10x20'
DELTA_VAL_UP=3+
DELTA_VAL_DOWN=3-

####################
# Code
action=$1; shift

# Unmute the volume and increase/decrease it
# Arg 1: volume change to set (1+ or 1-)
set_volume() {
    amixer sset $CHANNEL unmute &> /dev/null &
    volume=$(amixer sset $CHANNEL $1 unmute | \
             grep "Mono: Playback" | \
             grep -o "\[[0-9]*%\]" | \
             tr '[%]' ' ')
}

# Get the current volume %
# No args
get_volume() {
    volume=$(amixer sget $CHANNEL | \
             grep "Mono: Playback" | \
             grep -o "\[[0-9]*%\]" | \
             tr '[%]' ' ')
}

# Toggle Master volume mute on/off
# No args
mute_volume() {
    status=$(amixer sset $CHANNEL toggle | \
             grep "Mono: Playback" | \
             grep -o "\[on\]\|\[off\]" | \
             tr '[]' ' ')
}

show_volume() {
    killall -9 -q osd_cat
    (osd_cat --font="$FONT" --shadow=1 --color=green \
    --pos=bottom --align=center --delay=2 \
    --text "$( [ "z$2" = "z" ] && \
    echo Volume: $1% || echo $2 )" \
    --barmode=percentage --percentage=$1 )&
}

case "$action" in
    show)
        get_volume
                show_volume $volume
        ;;

    up)
        delta=$DELTA_VAL_UP
        set_volume $delta
        show_volume $volume
        ;;

    down)
        delta=$DELTA_VAL_DOWN
        set_volume $delta
        show_volume $volume
        ;;

    mute)
        mute_volume
        case "$status" in
            off)
                show_volume 0 "Muted"
                ;;
            on)
                get_volume
                show_volume $volume
                ;;
        esac
        ;;
    *)
        echo "Usage: $0 {up|down|mute|show}"
        ;;
esac

In recent versions of Ubuntu there has been some changes to the way that scripts can connect to the active X session, so the line at the start of this script:

/home/adam/.local-display-coordinates.sh

calls a script that is generated automatically when the X session starts. This is created by adding the following to your ~/.profile script:

case $DISPLAY in
  :*) export | grep -E ' \
  (DISPLAY|XAUTHORITY)=' \
  >~/.local-display-coordinates.sh;;
esac

This is based on the advice on this page.

You can test your script by running it from an xterminal using ./setVolume.sh up or ./setVolume.sh down to alter the system volume. You should see the volume displayed at the bottom of the screen in green.

The final step it to configure lirc to run your script when the volume buttons are pressed.
Make sure you have irexec installed, and add it to your startup applications so that it is always running (I will do a subsequent post about auto-restarting mythtv which will also cover auto-restarting lircmd in case it crashes).
You can now edit your .lircrc file to launch you script using irexec when the volume keys are pressed – add the following to your .lircrc file:

begin
    prog = irexec
    button = KEY_VOLUMEUP
    config = /home/adam/Scripts/setVolume.sh up
    repeat = 2
end
begin
    prog = irexec
    button = KEY_VOLUMEDOWN
    config = /home/adam/Scripts/setVolume.sh down
    repeat = 2
end

Make sure you remove the existing mythtv volume entries so you don’t end up controlling both volume controls whenever you press the button on the remote.
Restart lircd, and hopefully everything should work! You may have to restart your gnome session to make sure the script is able to pick up the active X session correctly.

Multi-room audio (the easy way)

July 3rd, 2010

I have a mythtv box in the lounge that I use for playing music and videos, but for a while now I have been looking into ways of extending the audio into additional rooms in the house (primarily the kitchen). I looked into running speaker cables (or a fibre optic cable) across the room but didn’t want to start pulling up the carpet or having unsightly wires everywhere, so I started looking into other options. I looked into software options using my existing powerline or wireless network, but with all of them there were synchronisation issues – the overhead of network streaming means getting the audio in the lounge and kitchen sychronised was impractical.

Then I stumbled on a much simpler option. I already have a good quality DAB and FM radio in the kitchen. It occurred to me that I could use an FM transmitter like the ones used in cars for mp3 players to transmit audio to the car radio. I found a basic FM transmitter on amazon for £6.99 – link.

I didn’t want to run it on batteries, and obviously I don’t have a cigarette lighter socket behind my PC, so I cut the cigarette lighter plug off the end of the cable and replaced it with a USB plug from Maplin for £1.39 – link. You can use this page to find out which pins provide the 5v output – the transmitter works fine on 5v.

FM Transmitter

Then, all I had to do was plug a splitter into the audio output from the myth box so it feeds into the speakers in the lounge as well as the FM transmitter. It works like a charm now and the music is perfectly in sync between the lounge and kitchen. Range is pretty good too – I can even tune in the radios upstairs and listen in there too!

Open source desktop search – and indexing Freemind maps

December 11th, 2009

I am always keen to investigate open source solutions to everyday problems I face, and my preference is for apps that run in a JRE. This is for two primary reasons:

  • They don’t generally require “installing” by which I mean I can use them on a windows machine without requiring admin rights or permission to update the registry
  • They are portable, so once I have figured out how to best use them to support my day-to-day tasks, I can easily transfer that solution to my Linux PC or Windows laptop

I have been using Freemind for organising all my notes as mindmaps for some time, and I am very pleased with it.

Another area I have been looking into recently is desktop search. The basic offerings in Linux are generally very good, but the Microsoft search solutions are very poor in comparison. I have used Google desktop before – which is very good, but it doesn’t meet the criteria above. To that end I did a bit of searching, and came across a nice pure java desktop search application called DynaQ. It uses various other best-of-breed java libraries to do the extraction and indexing, so is a very powerful search tool. It makes use of Catweasel and Aperture to trawl files and extract content, then uses Apache Lucene for indexing.

One problem I did come across however was that DynaQ did not seem to index my Freemind mind maps. After a bit of digging I discovered that this was because when Freemind saves it’s maps it does not include the standard XML header at the start of the file to identify it as an XML file. As a consequence, when Aperture looks at the file it cannot identify what type of file it is, and does not index it.

There are a few simple steps to remedy the problem:

  • Go to the DynaQ config directory and extract the contents of the apertureMimeConfiguration.xml.jar file
  • Edit the apertureMimeConfiguration.xml file, and amend the content of the XML section so it looks like this:
  • <description>
      <mimeType>text/xml</mimeType>
      <extensions>xml,xsl,xslt,wml,mm</extensions>
      <magicString>&lt;?xml</magicString>
      <magicString>&lt;map</magicString>
    </description>
    
  • Re-add the file to the jar and put it back in the config directory
  • Re-index the directory containing your Freemind files. NOTE: If the directory had been indexed previously you will probably need to update the timestamps on the files to force the indexer to re-index them

You should now be able to search on the contents of your mind maps.

Random Freezing in Amarok, Banshee, Rhythmbox

June 19th, 2009

I am a big fan of Amarok – as a music application I think it is the best there is (much better than iTunes).

I have for some time however had problems with it freezing up on a regular basis. It seemed to happen with no particular pattern, even if I opened the application and left it on screen without playing any music or touching the mouse or keyboard, after a few minutes it would freeze up. It generally didn’t freeze for very long – maybe 10 seconds or so, but seemed to be doing it quite regularly every few minutes.

I eventually got so fed up with it that I tried switching to Banshee, but had exactly the same issue. I then tried Rhythmbox and had the same issue yet again, so decided it had to be a common library in Ubuntu rather than the apps themselves.

I have tried various things to get to the bottom of the problem. I stumbled across quite a few posts relating to issues with ESD (Enlightenment Sound Daemon) causing problems in all sorts of applications, but switching to OSS or ALSA didn’t seem to improve matters.

So, for now I have still not found a solution – please let me know if you have any suggestions!

iPlayer in MythTV (the Easy Way)

December 1st, 2008

I use MythTV as a media centre in my lounge, not to record TV, but purely for browsing and playing my collection of mp3s, and occasionally playing downloaded video clips. It also allows me to read rss feeds and their linked web pages using a remote from the comfort of my sofa.

One of the things I have wanted to be able to do for a while is use mythtv to watch BBC iPlayer content. There has been some attempts at making mythtv plugins for this purpose, but they have always been rather complicated to set up which has always put me off.

I discovered however, that the BBC has added rss feeds of the iplayer programmes to each of the pages in the iPlayer, so I decided to see if it would be possible to use these to get at the content frmo mythtv. These feeds on the BBC site are actually Atom feeds rather than rss feeds, and unfortunately mythnews (the rss plugin for mythtv) doesn’t support atom feeds. Luckily I found a handy online utility that will do an on-the-fly conversion from atom to rss: http://atom2rss.semiologic.com/ Using that I managed to create some new entries in mythnews that let me see the listings of iPlayer programmes for various channels.

So far so good, but when I select one of the items using the remote, it opens a mythbrowser window, but it gives a message saying that our version of flash is out of date and there is no easy way of upgrading it using the link provided. Luckily some helpful person has solved this one: http://www.nabble.com/Re%3A-Mythbrowser-0.21-flash-p16200963s15552.html

So now I was able to choose a programme and open a browser window, and the player appears. The next problem is that the programme does not play automaticaly, but you get a “Click to Play” prompt, and you need to click play to start the playback. As I am using a simple media centre remote for this, and don’t want to use a mouse that is a problem.

To solve this one, I had a look at what the other iplayer plugin had done: http://www.mythtv.org/wiki/index.php/BBC_iPlayer. I realised there is a package called xautomation that can be used to script mouse movements and clicks, so I decided to make use of this to click play for me. First, I used synaptic (or apt-get) to get the xautomation package. You can test it by opening a terminal and typing:

echo mousemove 10 10 | xte

Your mouse pointer should move to the top left of the screen.
So, now I opened the iplayer page in mythbrowser and worked out the x and y co-ordinates of the play button. I then created a small shell script to move to the correct position, click, then move the mouse out of the way:

#!/bin/bash
echo mousemove 200 560 | xte
sleep 1
echo mouseclick 1 | xte
sleep 1
echo mousemove 9999 9999 | xte

So, now I had a script to click the play button, I needed to associate it with a keypress on my remote control. Rather than so something to mythtv to get it to trap the event, I decided to use irexec which is a simple utility that comes with lirc (the remote control utility). So, I edited my ~/.lircrc file, and added:

begin
    remote = mceusb
    prog = irexec
    button = LiveTV
    config = /home/adam/Scripts/iplayerStartPause.sh
    repeat = 0
    delay = 0
end

I needed to make sure irexec was running as a daemon when my server starts up (irexec –daemon). Now, whenever I press the “LiveTV” button on my remote (I was not using that button previously) my script gets executed and the mouse moves and clicks in the correct place.

So, now I have the ability to browse iplayer programme listings, select one and play it. I need to do some more work to add the ability to make the video full-screen, alter volume, etc, but for now it is great to be able to watch iplayer programmes from my sofa without having to fire up the laptop or PC :)

Ubuntu Gnome Application Menu Missing

September 8th, 2008

I have had a rather annoying problem on my Ubuntu box for the last few days. Not sure how it happened, but my application menu suddenly stopped working. Whenever I clicked on the menu I just got a tiny grey box with nothing in it where the menu should have been.

After a lot of googling with no success, I finally stumbled on a post that mentioned some files in ~/.config/. When I had a look in there, there was a subdirectory called menus which contained a file called applications.menu. I had a look at that file, and sure enough it was empty. After having a quick look at my other Ubuntu box I noticed that box had no applications.menu, so I deleted the empty file and hey presto!

Handy Shell Commands

March 20th, 2008

I thought I would share some commands and small single line bash scripts I have found useful in the past:

AWK

Output every 50th line from a file into a new file :

cat infile.csv | awk ' (NR % 50) == 0 { print $0 } ' > outfile.csv

Print the 13th column (space delimited):

awk ' { print $13} '

Print the 13th column (colon delimited):

awk -F":" '{ print $13 }'

Find

Recursive Grep (starting from current directory):

find . -name "*" -exec grep -i "searchValue" {} /dev/null \;

Compare files in two directories (-N for new files, -a for forcing ASCII, and -r for recursing subdirectories):

diff -Nuar dir1 dir2

Find all files under /dir older than 7 days, and delete them:

find /dir -type f -mtime +7 | xargs rm -f

Do a global search and replace from “html” to “shtml” across all html files in the current directory and all subdirectories:

find . -name "*.html" -exec perl -pi -e 's/\.html/\.shtml/g' {} \;

Rename all html files to shtml files in the current directory and all subdirectories:

find . -name "*.html" | while read f
do
mv ./"$f" "${f%html}shtml";
done

Find the largest files and directories on your hard disc (starting from the current directory):

du -k * | sort -nr | more

List Hardware in your machine:

sudo lshw

Using Printers in Linux Without a Linux Driver

February 17th, 2008

I recently bought a Lexmark X4550 all-in-one printer, scanner and copier. What I didn’t realise before I bought it is that Lexmark are horribly bad at providing Linux support for their printers. After speaking to their support people and finding out that the printer really doesn’t have any linux drivers and is unlikely to have any in the near future I began looking into ways of getting it to print.

The solution I came up with is a bit nasty, and not something you will probably want to do unless you really really want to get things printing from Linux.

Here’s how it works:

1) Install Innotek VirtualBox? (or some other virtualisation tool)

2) Create a new Windows virtual machine (I used Windows 2000 – I had a spare license I got free with an old PC and am not using)

3) Install the printer driver software on your windows virtual machine

4) Install GPL Ghostscript in your Windows VM – available here: http://sourceforge.net/projects/ghostscript/

5) Install “PrintFile” in your Windows VM – available here: http://hem1.passagen.se/ptlerup/prfile.html

6) Create a network share on your Linux machine and map to it from your Windows VM so it has a drive letter (e.g. K:)

7) Create a directory in this shared directory that you will monitor for new print jobs (e.g. K:\printspool)

8 ) Run PrintFile and configure it as follows:

Set “enable spooler function” to ticked
Click the “Conversion” button
Tick Enable Conversion for PostScript? Files
In the program box enter the path of your ghostscript installation
In the Parameters box enter the following:
-Ic:\gstools\gs8.61;c:\gstools\gs8.61\fonts -dSAFER -dBATCH -dNOPAUSE
-sDEVICE=mswinpr2 -dGraphicsAlphaBits=4 -sOutputFile=”\spool\&p” &i -c quit
(All on one line)
Click OK, then Save and the close the PrintFile

9) Create a new batch file in your Windows VM containing the following:

“C:\Program Files\PrintFile\prfile32.exe” /s:K:\printspool\*.ps
(Where K:\printspool is the spool directory you want to monitor)

10) Run your batch file and it will start monitoring your directory for new jobs to print

11) In your Linux PC you can now print from any application – in the print dialog tick the “print to file” box and save your print job in the shared print spool directory that is being monitored by your windows machine.

Not a neat solution I admit, but it works :)

Using RSync to backup from Windows to Linux

January 21st, 2008

I have a laptop running Windows Vista and a PC running Ubuntu Linux. When I take photos I generally transfer them to my laptop initially, but I wanted a simple way of keeping a copy of all the photos on the linux box too as a backup. Linux boxes have a great tool for data synchronisation called rsync. rsync is a very powerful tool that can copy across only files that have been modified, and is even clever enough only to copy the differences between the files rather than the whole file. It can also compress the file before transferring it and decompress it at the other end seamlessly to improve network performance.

To use rsync to backup from the windows laptop however, I first needed to find a windows rsync server application. Luckily there is a very nice free application called DeltaCopy , which is bascically the linux rsync with a windows wrapper around it (using cygwin). I found it was easy to install and runs as a service in Windows. You can get DeltaCopy from here: http://www.aboutmyip.com/AboutMyXApp/DeltaCopy.jsp

Most versions of linux come with rsync included by default, so the linux end was easy to set up. I created a small script to run the actual synchronisation, and added it to cron so that it runs every hour and checks for new Photos on the laptop. You can see the script below:

 #!/bin/bash
 if [ ! -f "/tmp/synchronising" ]
 then
   echo "Running" > /tmp/synchronising
   rsync --verbose --progress --stats --compress --recursive --times 192.168.10.101::Photos /home/adam/Photos > /home/adam/Scripts/synchronisation.log
   rm -f /tmp/synchronising
 fi

Another good article on how to use rsync can be found here: http://everythinglinux.org/rsync/