Index: mytharchive/mytharchive/archivesettings.cpp
===================================================================
--- mytharchive/mytharchive/archivesettings.cpp	(revision 11702)
+++ mytharchive/mytharchive/archivesettings.cpp	(working copy)
@@ -257,6 +257,25 @@
     return gc;
 };
 
+static HostLineEdit *MythArchiveJpeg2yuvCmd()
+{
+    HostLineEdit *gc = new HostLineEdit("MythArchiveJpeg2yuvCmd");
+    gc->setLabel(QObject::tr("jpeg2yuv command"));
+    gc->setValue("jpeg2yuv");
+    gc->setHelpText(QObject::tr("Command to run jpeg2yuv. Part of mjpegtools package"));
+    return gc;
+};
+
+static HostLineEdit *MythArchiveTranscodeCmd()
+{
+    HostLineEdit *gc = new HostLineEdit("MythArchiveTranscodeCmd");
+    gc->setLabel(QObject::tr("transcode command"));
+    gc->setValue("transcode");
+    gc->setHelpText(QObject::tr("Command to run transcode. Part of mjpegtools package. This is used to convert MPEG2 video to png files"));
+    return gc;
+};
+
+
 ArchiveSettings::ArchiveSettings()
 {
     VerticalConfigurationGroup* vcg1 = new VerticalConfigurationGroup(false);
@@ -295,5 +314,11 @@
     vcg4->addChild(MythArchiveGrowisofsCmd());
     vcg4->addChild(MythArchiveTcrequantCmd());
     vcg4->addChild(MythArchivePng2yuvCmd());
+    vcg4->addChild(MythArchiveJpeg2yuvCmd());
     addChild(vcg4);
+
+    VerticalConfigurationGroup* vcg5 = new VerticalConfigurationGroup(false);
+    vcg5->setLabel(QObject::tr("MythArchive External Commands (3)"));
+    vcg5->addChild(MythArchiveTranscodeCmd());
+    addChild(vcg5);
 }
Index: mytharchive/mythburn/scripts/mythburn.py
===================================================================
--- mytharchive/mythburn/scripts/mythburn.py	(revision 11702)
+++ mytharchive/mythburn/scripts/mythburn.py	(working copy)
@@ -303,21 +303,35 @@
     checkCancelFlag()
     return result
 
-def encodeMenu(background, tempvideo, music, musiclength, tempmovie, xmlfile, finaloutput, aspectratio):
+def secondsToFrames(seconds):
+    """Convert a time in seconds to a frame position"""
     if videomode=="pal":
         framespersecond=frameratePAL
     else:
         framespersecond=framerateNTSC
 
+    frames=int(seconds * framespersecond)
+    return frames
+
+def encodeMenu(background, tempvideo, music, musiclength, tempmovie, xmlfile, finaloutput, aspectratio, usejpeg):
+    if videomode=="pal":
+        framespersecond=frameratePAL
+    else:
+        framespersecond=framerateNTSC
+
     totalframes=int(musiclength * framespersecond)
 
-    command = path_png2yuv[0] + " -n %s -v0 -I p -f %s -j '%s' | %s -b 5000 -a %s -v 1 -f 8 -o '%s'" \
-               % (totalframes, framespersecond, background, path_mpeg2enc[0], aspectratio, tempvideo)
+    if usejpeg == True:
+        command = path_jpeg2yuv[0] + " -n %s -v0 -I p -f %s -j '%s' | %s -b 5000 -a %s -v 1 -f 8 -o '%s'" \
+                  % (totalframes, framespersecond, background, path_mpeg2enc[0], aspectratio, tempvideo)
+    else:
+        command = path_png2yuv[0] + " -n %s -v0 -I p -f %s -j '%s' | %s -b 5000 -a %s -v 1 -f 8 -o '%s'" \
+                  % (totalframes, framespersecond, background, path_mpeg2enc[0], aspectratio, tempvideo)
     result = runCommand(command)
     if result<>0:
-        fatalError("Failed while running png2yuv - %s" % command)
+        fatalError("Failed while running png2yuv or jpeg2yuv - %s" % command)
 
-    command = path_mplex[0] + " -f 8 -v 0 -o '%s' '%s' '%s'" % (tempmovie, tempvideo, music)
+    command = path_mplex[0] + " -l %d -f 8 -v 0 -o '%s' '%s' '%s'" % (musiclength, tempmovie, tempvideo, music)
     result = runCommand(command)
     if result<>0:
         fatalError("Failed while running mplex - %s" % command)
@@ -533,7 +547,9 @@
                         'MythArchiveDateFormat',
                         'MythArchiveTimeFormat',
                         'ISO639Language0',
-                        'ISO639Language1'
+                        'ISO639Language1',
+                        'MythArchiveJpeg2yuvCmd',
+                        'MythArchiveTranscodeCmd'
                         )) order by value"""
 
     #write( sqlstatement)
@@ -2167,6 +2183,55 @@
     #Destroy the DOM and free memory
     dvddom.unlink()
 
+def createEmptyPreviewFolder(videoitem):
+    previewfolder = os.path.join(getItemTempPath(videoitem), "preview")
+    if os.path.exists(previewfolder):
+        deleteAllFilesInFolder(previewfolder)
+        os.rmdir (previewfolder)
+    os.makedirs(previewfolder)
+    return previewfolder
+
+
+def generateVideoPreview(videoitem, itemonthispage, menuitem, starttime, menulength, previewfolder):
+    """generate thumnails for an preview in a menu"""
+
+    positionx = 9999
+    positiony = 9999
+    maskpicture = None
+
+    #run through the theme items and find any graphics that is using a movie identifier
+
+    for node in menuitem.childNodes:
+        if node.nodeName=="graphic":
+            if node.attributes["filename"].value == "%movie":
+
+                #This is an movie preview item so we need to generate the thumbnails
+
+                inputfile = os.path.join(getItemTempPath(videoitem),"stream.mv2")
+                outputfile = os.path.join(previewfolder, "preview-i%d-f" % itemonthispage)
+                previewsize = "%dx%d" %(getScaledAttribute(node, "w"), getScaledAttribute(node, "h"))
+                startframe=secondsToFrames(starttime)
+                endframe=int(secondsToFrames(int(starttime + menulength))-1)
+
+                splitcmd = path_transcode[0] + " -i %s -x auto,null -I 5 -Z %s -y im,null -F png -c %d-%d -o %s" %(inputfile, previewsize, startframe, endframe, outputfile)
+
+                result = runCommand(splitcmd)
+                if (result != 0):
+                    write( "split failed with code %d. Command = %s" % (result, splitcmd) )
+                positionx = getScaledAttribute(node, "x")
+                positiony = getScaledAttribute(node, "y")
+
+                #see if this graphics item has a mask
+
+                if node.hasAttribute("mask"):
+                    imagemaskfilename = getThemeFile(themeName, node.attributes["mask"].value)
+                    if node.attributes["mask"].value <> "" and doesFileExist(imagemaskfilename):
+                        maskpicture = Image.open(imagemaskfilename,"r").resize((getScaledAttribute(node, "w"), getScaledAttribute(node, "h")))
+                        maskpicture = maskpicture.convert("RGBA")
+
+    return (positionx, positiony, maskpicture)
+
+
 def drawThemeItem(page, itemsonthispage, itemnum, menuitem, bgimage, draw,
                   bgimagemask, drawmask, highlightcolor, spumuxdom, spunode,
                   numberofitems, chapternumber, chapterlist):
@@ -2187,19 +2252,43 @@
         #Process each type of item to add it onto the background image
         if node.nodeName=="graphic":
             #Overlay graphic image onto background
-            imagefilename = expandItemText(infoDOM,node.attributes["filename"].value, itemnum, page, itemsonthispage, chapternumber, chapterlist)
 
-            if doesFileExist(imagefilename):
-                picture = Image.open(imagefilename,"r").resize((getScaledAttribute(node, "w"), getScaledAttribute(node, "h")))
-                picture = picture.convert("RGBA")
-                bgimage.paste(picture, (getScaledAttribute(node, "x"), getScaledAttribute(node, "y")), picture)
-                del picture
-                write( "Added image %s" % imagefilename)
+            #if this graphic item is a movie thumbnail then we dont process it here
+            if node.attributes["filename"].value == "%movie":
 
+                #this is a movie item but we must still update the boundary box
+
                 boundarybox=checkBoundaryBox(boundarybox, node)
             else:
-                write( "Image file does not exist '%s'" % imagefilename)
+                imagefilename = expandItemText(infoDOM,node.attributes["filename"].value, itemnum, page, itemsonthispage, chapternumber, chapterlist)
 
+                if doesFileExist(imagefilename) == False:
+                    if imagefilename == node.attributes["filename"].value:
+                        imagefilename = getThemeFile(themeName, node.attributes["filename"].value)
+                if doesFileExist(imagefilename):
+                    picture = Image.open(imagefilename,"r").resize((getScaledAttribute(node, "w"), getScaledAttribute(node, "h")))
+                    picture = picture.convert("RGBA")
+
+                    #see if an image mask exists
+                    
+                    imagemaskfilename = None
+                    if node.hasAttribute("mask"):
+                        if node.attribute["mask"].value <> "":
+                            imagemaskfilename = getThemeFile(themeName, node.attributes["mask"].value)
+                    if imagemaskfilename <> None and doesFileExist(imagemaskfilename):
+                        maskpicture = Image.open(imagemaskfilename,"r").resize((getScaledAttribute(node, "w"), getScaledAttribute(node, "h")))
+                        maskpicture = maskpicture.convert("RGBA")
+                        bgimage.paste(picture, (getScaledAttribute(node, "x"), getScaledAttribute(node, "y")), maskpicture)
+                        del maskpicture
+                    else:
+                        bgimage.paste(picture, (getScaledAttribute(node, "x"), getScaledAttribute(node, "y")), picture)
+                    del picture
+                    write( "Added image %s" % imagefilename)
+
+                    boundarybox=checkBoundaryBox(boundarybox, node)
+                else:
+                    write( "Image file does not exist '%s'" % imagefilename)
+
         elif node.nodeName=="text":
             #Apply some text to the background, including wordwrap if required.
             text=expandItemText(infoDOM,node.attributes["value"].value, itemnum, page, itemsonthispage,chapternumber,chapterlist)
@@ -2469,17 +2558,58 @@
     while itemnum <= numberofitems:
         write( "Menu page %s" % page)
 
+        #need to check if any of the videos are flags as movies
+        #and if so generate the required preview
+
+        write( "Creating Preview Video")
+        previewitem = itemnum
+        itemsonthispage = 0
+        haspreview = False
+
+        previewx = []
+        previewy = []
+        previewmask = []
+        while previewitem <= numberofitems and itemsonthispage < itemsperpage:
+            menuitem=menuitems[ itemsonthispage ]
+            itemsonthispage+=1
+
+            #make sure the preview folder is empty and present
+
+            previewfolder = createEmptyPreviewFolder(previewitem)
+
+            #and then generate the preview if required (px=9999 means not required)
+
+            px, py, maskimage = generateVideoPreview(previewitem, itemsonthispage, menuitem, 0, menulength, previewfolder)
+            previewx.append(px)
+            previewy.append(py)
+            previewmask.append(maskimage)
+            if px != 9999:
+                haspreview = True
+
+            previewitem+=1
+
+        #previews generated but need to save where we started from
+        savedpreviewitem = itemnum
+
         #Default settings for this page
 
         #Number of video items on this menu page
         itemsonthispage=0
 
         #Load background image
-        bgimage=Image.open(backgroundfilename,"r").resize(screensize)
-        draw=ImageDraw.Draw(bgimage)
+        #bgimage=Image.open(backgroundfilename,"r").resize(screensize)
 
+        #instead of loading the background image and drawing on it we now
+        #make a transparent image and draw all items on it. This overlay
+        #image is then added to the required background image when the
+        #preview items are added (the reason for this is it will assist
+        #if the background image is actually a video)
+
+        overlayimage=Image.new("RGBA",screensize)
+        draw=ImageDraw.Draw(overlayimage)
+
         #Create image to hold button masks (same size as background)
-        bgimagemask=Image.new("RGBA",bgimage.size)
+        bgimagemask=Image.new("RGBA",overlayimage.size)
         drawmask=ImageDraw.Draw(bgimagemask)
 
         spumuxdom = xml.dom.minidom.parseString('<subpictures><stream><spu force="yes" start="00:00:00.0" highlight="" select="" ></spu></stream></subpictures>')
@@ -2492,7 +2622,7 @@
             itemsonthispage+=1
 
             drawThemeItem(page, itemsonthispage,
-                        itemnum, menuitem, bgimage,
+                        itemnum, menuitem, overlayimage,
                         draw, bgimagemask, drawmask, highlightcolor,
                         spumuxdom, spunode, numberofitems, 0,"")
 
@@ -2500,9 +2630,51 @@
             itemnum+=1
 
         #Save this menu image and its mask
+        bgimage=Image.open(backgroundfilename,"r").resize(screensize)
+        bgimage.paste(overlayimage, (0,0), overlayimage)
+
         bgimage.save(os.path.join(getTempPath(),"background-%s.png" % page),"PNG",quality=99,optimize=0,dpi=screendpi)
         bgimagemask.save(os.path.join(getTempPath(),"backgroundmask-%s.png" % page),"PNG",quality=99,optimize=0,dpi=screendpi)
 
+        #now that the base background has been made and all the previews generated
+        #we need to add the previews to the background
+        #Assumption: We assume that there is nothing in the location of where the items go (ie, no text on the images)
+
+        itemsonthispage = 0
+
+        numframes=secondsToFrames(menulength)
+
+        #numframes should be the number of preview images that have been created
+
+        if haspreview == True:
+            # only generate the preview video if required.
+
+            write( "Generation the chapter images" )
+            framenum = 0
+            while framenum < numframes:
+                previewitem = savedpreviewitem
+                itemsonthispage = 0
+                while previewitem <= numberofitems and itemsonthispage < itemsperpage:
+                    itemsonthispage+=1
+                    if previewx[itemsonthispage-1] != 9999:
+                        previewpath = os.path.join(getItemTempPath(previewitem), "preview")
+                        previewfile = "preview-i%d-f%06d.png" % (itemsonthispage, framenum)
+                        imagefile = os.path.join(previewpath, previewfile)
+
+                        if doesFileExist(imagefile):
+                            picture = Image.open(imagefile, "r")
+                            picture = picture.convert("RGBA")
+                            imagemaskfile = os.path.join(previewpath, "mask-i%d.png" % itemsonthispage)
+                            if previewmask[itemsonthispage-1] != None:
+                                bgimage.paste(picture, (previewx[itemsonthispage-1], previewy[itemsonthispage-1]), previewmask[itemsonthispage-1])
+                            else:
+                                bgimage.paste(picture, (previewx[itemsonthispage-1], previewy[itemsonthispage-1]))
+                            del picture
+                    previewitem+=1
+                #-> slow bgimage.save(os.path.join(getTempPath(),"background-%s-f%06d.png" % (page, framenum)),"PNG",quality=100,optimize=0,dpi=screendpi)
+                bgimage.save(os.path.join(getTempPath(),"background-%s-f%06d.jpg" % (page, framenum)),"JPEG",dpi=screendpi)
+                framenum+=1
+
 ## Experimental!
 ##        for i in range(1,750):
 ##            bgimage.save(os.path.join(getTempPath(),"background-%s-%s.ppm" % (page,i)),"PPM",quality=99,optimize=0)
@@ -2515,6 +2687,10 @@
         del bgimage
         del drawmask
         del bgimagemask
+        del overlayimage
+        del previewx
+        del previewy
+        del previewmask
 
         #write( spumuxdom.toprettyxml())
         WriteXMLToFile (spumuxdom,os.path.join(getTempPath(),"spumux-%s.xml" % page))
@@ -2525,14 +2701,26 @@
             aspect_ratio = 3
 
         write("Encoding Menu Page %s using aspect ratio '%s'" % (page, mainmenuAspectRatio))
-        encodeMenu(os.path.join(getTempPath(),"background-%s.png" % page),
-                    os.path.join(getTempPath(),"temp.m2v"),
-                    getThemeFile(themeName,menumusic),
-                    menulength,
-                    os.path.join(getTempPath(),"temp.mpg"),
-                    os.path.join(getTempPath(),"spumux-%s.xml" % page),
-                    os.path.join(getTempPath(),"menu-%s.mpg" % page),
-                    aspect_ratio)
+        if haspreview == True:
+            encodeMenu(os.path.join(getTempPath(),"background-%s-f%%06d.jpg" % page),
+                        os.path.join(getTempPath(),"temp.m2v"),
+                        getThemeFile(themeName,menumusic),
+                        menulength,
+                        os.path.join(getTempPath(),"temp.mpg"),
+                        os.path.join(getTempPath(),"spumux-%s.xml" % page),
+                        os.path.join(getTempPath(),"menu-%s.mpg" % page),
+                        aspect_ratio,
+                        True)
+        else:
+            encodeMenu(os.path.join(getTempPath(),"background-%s.png" % page),
+                        os.path.join(getTempPath(),"temp.m2v"),
+                        getThemeFile(themeName,menumusic),
+                        menulength,
+                        os.path.join(getTempPath(),"temp.mpg"),
+                        os.path.join(getTempPath(),"spumux-%s.xml" % page),
+                        os.path.join(getTempPath(),"menu-%s.mpg" % page),
+                        aspect_ratio,
+                        False)
 
         #Tidy up temporary files
 ####        os.remove(os.path.join(getTempPath(),"spumux-%s.xml" % page))
@@ -2593,11 +2781,19 @@
         #Default settings for this page
 
         #Load background image
-        bgimage=Image.open(backgroundfilename,"r").resize(screensize)
-        draw=ImageDraw.Draw(bgimage)
+        #bgimage=Image.open(backgroundfilename,"r").resize(screensize)
 
+        #instead of loading the background image and drawing on it we now
+        #make a transparent image and draw all items on it. This overlay
+        #image is then added to the required background image when the
+        #preview items are added (the reason for this is it will assist
+        #if the background image is actually a video)
+
+        overlayimage=Image.new("RGBA",screensize)
+        draw=ImageDraw.Draw(overlayimage)
+
         #Create image to hold button masks (same size as background)
-        bgimagemask=Image.new("RGBA",bgimage.size)
+        bgimagemask=Image.new("RGBA",overlayimage.size)
         drawmask=ImageDraw.Draw(bgimagemask)
 
         spumuxdom = xml.dom.minidom.parseString('<subpictures><stream><spu force="yes" start="00:00:00.0" highlight="" select="" ></spu></stream></subpictures>')
@@ -2605,26 +2801,88 @@
 
         #Extracting the thumbnails for the video takes an incredibly long time
         #need to look at a switch to disable this. or not use FFMPEG
+
         chapterlist=createVideoChapters(page,itemsperpage,getLengthOfVideo(page),True)
         chapterlist=string.split(chapterlist,",")
 
+        #now need to preprocess the menu to see if any preview videos are required
+        #This must be done on an individual basis since we do the resize as the
+        #images are extracted.
+
+        #first make sure the preview folder is empty and present
+
+        previewfolder = createEmptyPreviewFolder(page)
+
+        haspreview = False
+
+        previewsegment=int(getLengthOfVideo(page) / itemsperpage)
+        previewtime = 0
+        previewchapter = 0
+        previewx = []
+        previewy = []
+        previewmask = []
+        while previewchapter < itemsperpage:
+            menuitem=menuitems[ previewchapter ]
+
+            #generate the preview if required (px=9999 means not required)
+
+            px, py, maskimage = generateVideoPreview(page, previewchapter, menuitem, previewtime, menulength, previewfolder)
+            previewx.append(px)
+            previewy.append(py)
+            previewmask.append(maskimage)
+            if px != 9999:
+                haspreview = True
+
+            previewchapter+=1
+            previewtime+=previewsegment
+
         #Loop through all the items on this menu page
         chapter=0
         while chapter < itemsperpage:  # and itemsonthispage < itemsperpage:
             menuitem=menuitems[ chapter ]
             chapter+=1
 
-            drawThemeItem(page, itemsperpage, page, menuitem, 
-                        bgimage, draw, 
+            drawThemeItem(page, itemsperpage, page, menuitem,
+                        overlayimage, draw,
                         bgimagemask, drawmask, highlightcolor,
-                        spumuxdom, spunode, 
+                        spumuxdom, spunode,
                         999, chapter, chapterlist)
 
         #Save this menu image and its mask
+        bgimage=Image.open(backgroundfilename,"r").resize(screensize)
+        bgimage.paste(overlayimage, (0,0), overlayimage)
         bgimage.save(os.path.join(getTempPath(),"chaptermenu-%s.png" % page),"PNG",quality=99,optimize=0,dpi=screendpi)
 
         bgimagemask.save(os.path.join(getTempPath(),"chaptermenumask-%s.png" % page),"PNG",quality=99,optimize=0,dpi=screendpi)
 
+        if haspreview == True:
+            numframes=secondsToFrames(menulength)
+
+            #numframes should be the number of preview images that have been created
+
+            write( "Generation the sub-menu images" )
+            framenum = 0
+            while framenum < numframes:
+                previewchapter = 0
+                while previewchapter < itemsperpage:
+                    if previewx[previewchapter] != 9999:
+                        previewpath = os.path.join(getItemTempPath(page), "preview")
+                        previewfile = "preview-i%d-f%06d.png" % (previewchapter, framenum)
+                        imagefile = os.path.join(previewpath, previewfile)
+
+                        if doesFileExist(imagefile):
+                            picture = Image.open(imagefile, "r")
+                            picture = picture.convert("RGBA")
+                            imagemaskfile = os.path.join(previewpath, "mask-i%d.png" % previewchapter)
+                            if previewmask[previewchapter] != None:
+                                bgimage.paste(picture, (previewx[previewchapter], previewy[previewchapter]), previewmask[previewchapter])
+                            else:
+                                bgimage.paste(picture, (previewx[previewchapter], previewy[previewchapter]))
+                            del picture
+                    previewchapter+=1
+                bgimage.save(os.path.join(getTempPath(),"chaptermenu-%s-f%06d.jpg" % (page, framenum)),"JPEG",dpi=screendpi)
+                framenum+=1
+
         spumuxdom.documentElement.firstChild.firstChild.setAttribute("select",os.path.join(getTempPath(),"chaptermenumask-%s.png" % page))
         spumuxdom.documentElement.firstChild.firstChild.setAttribute("highlight",os.path.join(getTempPath(),"chaptermenumask-%s.png" % page))
 
@@ -2633,6 +2891,10 @@
         del bgimage
         del drawmask
         del bgimagemask
+        del overlayimage
+        del previewx
+        del previewy
+        del previewmask
 
         #write( spumuxdom.toprettyxml())
         WriteXMLToFile (spumuxdom,os.path.join(getTempPath(),"chapterspumux-%s.xml" % page))
@@ -2648,15 +2910,28 @@
                 aspect_ratio = '2'
 
         write("Encoding Chapter Menu Page %s using aspect ratio '%s'" % (page, chaptermenuAspectRatio))
-        encodeMenu(os.path.join(getTempPath(),"chaptermenu-%s.png" % page),
-                    os.path.join(getTempPath(),"temp.m2v"),
-                    getThemeFile(themeName,menumusic),
-                    menulength,
-                    os.path.join(getTempPath(),"temp.mpg"),
-                    os.path.join(getTempPath(),"chapterspumux-%s.xml" % page),
-                    os.path.join(getTempPath(),"chaptermenu-%s.mpg" % page),
-                    aspect_ratio)
 
+        if haspreview == True:
+            encodeMenu(os.path.join(getTempPath(),"chaptermenu-%s-f%%06d.jpg" % page),
+                        os.path.join(getTempPath(),"temp.m2v"),
+                        getThemeFile(themeName,menumusic),
+                        menulength,
+                        os.path.join(getTempPath(),"temp.mpg"),
+                        os.path.join(getTempPath(),"chapterspumux-%s.xml" % page),
+                        os.path.join(getTempPath(),"chaptermenu-%s.mpg" % page),
+                        aspect_ratio,
+                        True)
+        else:
+            encodeMenu(os.path.join(getTempPath(),"chaptermenu-%s.png" % page),
+                        os.path.join(getTempPath(),"temp.m2v"),
+                        getThemeFile(themeName,menumusic),
+                        menulength,
+                        os.path.join(getTempPath(),"temp.mpg"),
+                        os.path.join(getTempPath(),"chapterspumux-%s.xml" % page),
+                        os.path.join(getTempPath(),"chaptermenu-%s.mpg" % page),
+                        aspect_ratio,
+                        False)
+
         #Tidy up
 ####        os.remove(os.path.join(getTempPath(),"chaptermenu-%s.png" % page))
 ####        os.remove(os.path.join(getTempPath(),"chaptermenumask-%s.png" % page))
@@ -2703,19 +2978,66 @@
     while itemnum <= numberofitems:
         write( "Creating details page for %s" % itemnum)
 
+        #make sure the preview folder is empty and present
+
+        previewfolder = createEmptyPreviewFolder(itemnum)
+        haspreview = False
+
+        #and then generate the preview if required (px=9999 means not required)
+
+        previewx, previewy, previewmask = generateVideoPreview(itemnum, 1, detailnode, 0, menulength, previewfolder)
+        if previewx != 9999:
+            haspreview = True
+
         #Load background image
-        bgimage=Image.open(backgroundfilename,"r").resize(screensize)
-        draw=ImageDraw.Draw(bgimage)
+        #bgimage=Image.open(backgroundfilename,"r").resize(screensize)
 
+        #instead of loading the background image and drawing on it we now
+        #make a transparent image and draw all items on it. This overlay
+        #image is then added to the required background image when the
+        #preview items are added (the reason for this is it will assist
+        #if the background image is actually a video)
+
+        overlayimage=Image.new("RGBA",screensize)
+        draw=ImageDraw.Draw(overlayimage)
+
         spumuxdom = xml.dom.minidom.parseString('<subpictures><stream><spu force="yes" start="00:00:00.0" highlight="" select="" ></spu></stream></subpictures>')
         spunode = spumuxdom.documentElement.firstChild.firstChild
 
-        drawThemeItem(0, 0, itemnum, detailnode, bgimage, draw, None, None,
+        drawThemeItem(0, 0, itemnum, detailnode, overlayimage, draw, None, None,
                       "", spumuxdom, spunode, numberofitems, 0, "")
 
         #Save this details image
+        bgimage=Image.open(backgroundfilename,"r").resize(screensize)
+        bgimage.paste(overlayimage, (0,0), overlayimage)
         bgimage.save(os.path.join(getTempPath(),"details-%s.png" % itemnum),"PNG",quality=99,optimize=0,dpi=screendpi)
 
+        if haspreview == True:
+            numframes=secondsToFrames(menulength)
+
+            #numframes should be the number of preview images that have been created
+
+            write( "Generation the detail images" )
+            framenum = 0
+            while framenum < numframes:
+                if previewx != 9999:
+                    previewpath = os.path.join(getItemTempPath(itemnum), "preview")
+                    previewfile = "preview-i%d-f%06d.png" % (1, framenum)
+                    imagefile = os.path.join(previewpath, previewfile)
+
+                    if doesFileExist(imagefile):
+                        picture = Image.open(imagefile, "r")
+                        picture = picture.convert("RGBA")
+                        imagemaskfile = os.path.join(previewpath, "mask-i%d.png" % 1)
+                        if previewmask != None:
+                            bgimage.paste(picture, (previewx, previewy), previewmask)
+                        else:
+                            bgimage.paste(picture, (previewx, previewy))
+                        del picture
+                bgimage.save(os.path.join(getTempPath(),"details-%s-f%06d.jpg" % (itemnum, framenum)),"JPEG",dpi=screendpi)
+                framenum+=1
+
+
         #Release large amounts of memory ASAP !
         del draw
         del bgimage
@@ -2729,14 +3051,26 @@
         WriteXMLToFile (spumuxdom,os.path.join(getTempPath(),"detailsspumux-%s.xml" % itemnum))
 
         write("Encoding Details Page %s" % itemnum)
-        encodeMenu(os.path.join(getTempPath(),"details-%s.png" % itemnum),
-                    os.path.join(getTempPath(),"temp.m2v"),
-                    getThemeFile(themeName,menumusic),
-                    menulength,
-                    os.path.join(getTempPath(),"temp.mpg"),
-                    "",
-                    os.path.join(getTempPath(),"details-%s.mpg" % itemnum),
-                    aspect_ratio)
+        if haspreview == True:
+            encodeMenu(os.path.join(getTempPath(),"details-%s-f%%06d.jpg" % itemnum),
+                        os.path.join(getTempPath(),"temp.m2v"),
+                        getThemeFile(themeName,menumusic),
+                        menulength,
+                        os.path.join(getTempPath(),"temp.mpg"),
+                        "",
+                        os.path.join(getTempPath(),"details-%s.mpg" % itemnum),
+                        aspect_ratio,
+                        True)
+        else:
+            encodeMenu(os.path.join(getTempPath(),"details-%s.png" % itemnum),
+                        os.path.join(getTempPath(),"temp.m2v"),
+                        getThemeFile(themeName,menumusic),
+                        menulength,
+                        os.path.join(getTempPath(),"temp.mpg"),
+                        "",
+                        os.path.join(getTempPath(),"details-%s.mpg" % itemnum),
+                        aspect_ratio,
+                        False)
 
         #On to the next item
         itemnum+=1
@@ -3371,6 +3705,10 @@
                     if os.path.exists(folder):
                         #Remove all the files first
                         deleteAllFilesInFolder(folder)
+                        previewfolder = os.path.join(folder, "preview")
+                        if os.path.exists(previewfolder):
+                            deleteAllFilesInFolder(previewfolder)
+                            os.rmdir(previewfolder)
                         #Remove the folder
                         os.rmdir (folder)
                     os.makedirs(folder)
@@ -3566,6 +3904,8 @@
 path_png2yuv = [defaultsettings["MythArchivePng2yuvCmd"], os.path.split(defaultsettings["MythArchivePng2yuvCmd"])[1]]
 path_spumux = [defaultsettings["MythArchiveSpumuxCmd"], os.path.split(defaultsettings["MythArchiveSpumuxCmd"])[1]]
 path_mpeg2enc = [defaultsettings["MythArchiveMpeg2encCmd"], os.path.split(defaultsettings["MythArchiveMpeg2encCmd"])[1]]
+path_jpeg2yuv = [defaultsettings["MythArchiveJpeg2yuvCmd"], os.path.split(defaultsettings["MythArchiveJpeg2yuvCmd"])[1]]
+path_transcode = [defaultsettings["MythArchiveTranscodeCmd"], os.path.split(defaultsettings["MythArchiveTranscodeCmd"])[1]]
 
 try:
     try:
