/
mythburn.py
executable file
·5289 lines (4233 loc) · 206 KB
/
mythburn.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
# mythburn.py
# The ported MythBurn scripts which feature:
# Burning of recordings (including HDTV) and videos
# of ANY format to DVDR. Menus are created using themes
# and are easily customised.
# See mydata.xml for format of input file
# spit2k1
# 11 January 2006
# 6 Feb 2006 - Added into CVS for the first time
# paulh
# 4 May 2006 - Added into mythtv svn
# For this script to work you need to have...
# Python - v2.6 or later
# mythtv python bindings installed
# python-imaging (PIL) or Pillow the fork of PIL
# dvdauthor - v0.6.14
# dvd+rw-tools - v7.1
# cdrtools - v3.01
# Optional for shrink-to-fit requantisation
# M2VRequantiser (from flexion, based on the newer code from Metakine)
# Optional (for Right To Left languages)
# pyfribidi
# Optional (alternate demuxer)
# ProjectX - >=0.91
# Optional (to lower the ionice level)
# psutil
#******************************************************************************
#******************************************************************************
#******************************************************************************
# All strings in this file should be unicode, not byte string!! They get converted to utf-8 only
# version of script - change after each update
VERSION="0.1.20130911-5"
# keep all temporary files for debugging purposes
# set this to True before a first run through when testing
# out new themes (see below)
debug_keeptempfiles = False
##You can use this debug flag when testing out new themes
##pick some small recordings, run them through as normal
##with debug_keeptempfiles = True (see above)
##set this variable to True and then re-run the scripts
##the temp. files will not be deleted and it will run through
##very much quicker!
debug_secondrunthrough = False
# default encoding profile to use
defaultEncodingProfile = "SP"
# add audio sync offset when re-muxing
useSyncOffset = True
# if the theme doesn't have a chapter menu and this is set to true then the
# chapter marks will be set to the cut point end marks
addCutlistChapters = False
# change this to True to always convert any audio tracks to ac3 for better compatibility
encodetoac3 = False
#*********************************************************************************
#Dont change the stuff below!!
#*********************************************************************************
import os
import sys
import string
import codecs
import getopt
import traceback
import signal
import xml.dom.minidom
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from PIL import ImageColor
import unicodedata
import time
import tempfile
from fcntl import ioctl
import CDROM
from shutil import copy
import MythTV
from MythTV import datetime
from MythTV.altdict import OrdDict
# media types (should match the enum in mytharchivewizard.h)
DVD_SL = 0
DVD_DL = 1
DVD_RW = 2
FILE = 3
dvdPAL=(720,576)
dvdNTSC=(720,480)
dvdPALdpi=(75,80)
dvdNTSCdpi=(81,72)
dvdPALHalfD1="352x576"
dvdNTSCHalfD1="352x480"
dvdPALD1="%sx%s" % (dvdPAL[0],dvdPAL[1])
dvdNTSCD1="%sx%s" % (dvdNTSC[0],dvdNTSC[1])
#Single and dual layer recordable DVD free space in MBytes
dvdrsize=(4482,8106)
frameratePAL=25
framerateNTSC=29.97
#any aspect ratio above this value is assumed to be 16:9
aspectRatioThreshold = 1.4
#Just blank globals at startup
temppath=""
logpath=""
scriptpath=""
sharepath=""
videopath=""
defaultsettings=""
videomode=""
gallerypath=""
musicpath=""
dateformat=""
timeformat=""
dbVersion=""
preferredlang1=""
preferredlang2=""
useFIFO = True
alwaysRunMythtranscode = False
copyremoteFiles = False
thumboffset = 10
usebookmark = True
clearArchiveTable = True
nicelevel = 17;
drivespeed = 0;
#main menu aspect ratio (4:3 or 16:9)
mainmenuAspectRatio = "16:9"
#chapter menu aspect ratio (4:3, 16:9 or Video)
#video means same aspect ratio as the video title
chaptermenuAspectRatio = "Video"
#default chapter length in seconds
chapterLength = 5 * 60;
#name of the default job file
jobfile="mydata.xml"
#progress log filename and file object
progresslog = ""
progressfile = codecs.open("/dev/null", 'w', 'utf-8')
#default location of DVD drive
dvddrivepath = "/dev/dvd"
#default option settings
docreateiso = False
doburn = True
erasedvdrw = False
mediatype = DVD_SL
savefilename = ''
installPrefix = ""
# job xml file
jobDOM = None
# theme xml file
themeDOM = None
themeName = ''
#dictionary of font definitions used in theme
themeFonts = {}
# no. of processors we have access to
cpuCount = 1
DB = MythTV.MythDB()
MVID = MythTV.MythVideo(db=DB)
Video = MythTV.Video
configHostname = DB.gethostname()
#############################################################
# mytharchivehelper needes this locale to work correctly
try:
oldlocale = os.environ["LC_ALL"]
except:
oldlocale = ""
os.putenv("LC_ALL", "en_US.UTF-8")
# fix rtl text where pyfribidi is not available
# should write a simple algorithm, meanwhile just return the original string
def simple_fix_rtl(str):
return str
# Bind the name fix_rtl to the appropriate function
try:
import pyfribidi
except ImportError:
sys.stdout.write("Using simple_fix_rtl\n")
fix_rtl = simple_fix_rtl
else:
sys.stdout.write("Using pyfribidi.log2vis\n")
fix_rtl = pyfribidi.log2vis
#############################################################
# class to hold a font definition
class FontDef(object):
def __init__(self, name=None, fontFile=None, size=19, color="white", effect="normal", shadowColor="black", shadowSize=1):
self.name = name
self.fontFile = fontFile
self.size = size
self.color = color
self.effect = effect
self.shadowColor = shadowColor
self.shadowSize = shadowSize
self.font = None
def getFont(self):
if self.font == None:
self.font = ImageFont.truetype(self.fontFile, int(self.size))
return self.font
def drawText(self, text, color=None):
if self.font == None:
self.font = ImageFont.truetype(self.fontFile, int(self.size))
if color == None:
color = self.color
textwidth, textheight = self.font.getsize(text)
image = Image.new("RGBA", (textwidth + (self.shadowSize * 2), textheight), (0,0,0,0))
draw = ImageDraw.ImageDraw(image)
if self.effect == "shadow":
draw.text((self.shadowSize,self.shadowSize), text, font=self.font, fill=self.shadowColor)
draw.text((0,0), text, font=self.font, fill=color)
elif self.effect == "outline":
for x in range(0, self.shadowSize * 2 + 1):
for y in range(0, self.shadowSize * 2 + 1):
draw.text((x, y), text, font=self.font, fill=self.shadowColor)
draw.text((self.shadowSize,self.shadowSize), text, font=self.font, fill=color)
else:
draw.text((0,0), text, font=self.font, fill=color)
bbox = image.getbbox()
image = image.crop(bbox)
return image
#############################################################
# Write a string to stdout and optionaly to a progress log file
def write(text, progress=True):
"""Simple place to channel all text output through"""
sys.stdout.write((text + "\n").encode("utf-8", "replace"))
sys.stdout.flush()
if progress == True and progresslog != "":
progressfile.write(time.strftime("%Y-%m-%d %H:%M:%S ") + text + "\n")
progressfile.flush()
#############################################################
# Display an error message and exit
def fatalError(msg):
"""Display an error message and exit app"""
write("*"*60)
write("ERROR: " + msg)
write("See mythburn.log for more information.")
write("*"*60)
write("")
saveSetting("MythArchiveLastRunResult", "Failed: " + quoteString(msg));
saveSetting("MythArchiveLastRunEnd", time.strftime("%Y-%m-%d %H:%M:%S "))
sys.exit(0)
# ###########################################################
# Display a warning message
def nonfatalError(msg):
"""Display a warning message"""
write("*"*60)
write("WARNING: " + msg)
write("*"*60)
write("")
#############################################################
# Return the input string with single quotes escaped.
def quoteString(str):
"""Return the input string with single quotes escaped."""
return str.replace("'", "'\"'\"'")
#############################################################
# Directory where all temporary files will be created.
def getTempPath():
"""This is the folder where all temporary files will be created."""
return temppath
#############################################################
# Try to work out how many cpus we have available
def getCPUCount():
"""return the number of CPUs"""
# /proc/cpuinfo
cpustat = codecs.open("/proc/cpuinfo", 'r', 'utf-8')
cpudata = cpustat.readlines()
cpustat.close()
cpucount = 0
for line in cpudata:
tokens = line.split()
if len(tokens) > 0:
if tokens[0] == "processor":
cpucount += 1
if cpucount == 0:
cpucount = 1
write("Found %d CPUs" % cpucount)
return cpucount
#############################################################
# Get the directory where all encoder profile files are located.
def getEncodingProfilePath():
"""This is the folder where all encoder profile files are located."""
return os.path.join(sharepath, "mytharchive", "encoder_profiles")
#############################################################
# Returns true/false if a given file or path exists.
def doesFileExist(file):
"""Returns true/false if a given file or path exists."""
return os.path.exists( file )
#############################################################
# Escape quotes in a command line argument
def quoteCmdArg(arg):
arg = arg.replace('"', '\\"')
arg = arg.replace('`', '\\`')
return '"%s"' % arg
#############################################################
# Returns the text contents from a given XML element.
def getText(node):
"""Returns the text contents from a given XML element."""
if node.childNodes.length>0:
return node.childNodes[0].data
else:
return ""
#############################################################
# Try to find a theme file
def getThemeFile(theme,file):
"""Find a theme file - first look in the specified theme directory then look in the
shared music and image directories"""
if os.path.exists(os.path.join(sharepath, "mytharchive", "themes", theme, file)):
return os.path.join(sharepath, "mytharchive", "themes", theme, file)
if os.path.exists(os.path.join(sharepath, "mytharchive", "images", file)):
return os.path.join(sharepath, "mytharchive", "images", file)
if os.path.exists(os.path.join(sharepath, "mytharchive", "intro", file)):
return os.path.join(sharepath, "mytharchive", "intro", file)
if os.path.exists(os.path.join(sharepath, "mytharchive", "music", file)):
return os.path.join(sharepath, "mytharchive", "music", file)
fatalError("Cannot find theme file '%s' in theme '%s'" % (file, theme))
#############################################################
# Returns the path where we can find our fonts
def getFontPathName(fontname):
return os.path.join(sharepath, "fonts", fontname)
#############################################################
# Creates a file path where the temp files for a video file can be created
def getItemTempPath(itemnumber):
return os.path.join(getTempPath(),"%s" % itemnumber)
#############################################################
# Returns True if the theme.xml file can be found for the given theme
def validateTheme(theme):
#write( "Checking theme", theme
file = getThemeFile(theme,"theme.xml")
write("Looking for: " + file)
return doesFileExist( getThemeFile(theme,"theme.xml") )
#############################################################
# Returns True if the given resolution is a DVD compliant one
def isResolutionOkayForDVD(videoresolution):
if videomode=="ntsc":
return videoresolution==(720,480) or videoresolution==(704,480) or videoresolution==(352,480) or videoresolution==(352,240)
else:
return videoresolution==(720,576) or videoresolution==(704,576) or videoresolution==(352,576) or videoresolution==(352,288)
#############################################################
# Removes all the files from a directory
def deleteAllFilesInFolder(folder):
"""Does what it says on the tin!."""
for root, dirs, deletefiles in os.walk(folder, topdown=False):
for name in deletefiles:
os.remove(os.path.join(root, name))
#############################################################
# Romoves all the objects from a directory
def deleteEverythingInFolder(folder):
for root, dirs, files in os.walk(folder, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
if os.path.islink(os.path.join(root, name)):
os.remove(os.path.join(root, name))
else:
os.rmdir(os.path.join(root, name))
#############################################################
# Check to see if the user has cancelled the DVD creation process
def checkCancelFlag():
"""Checks to see if the user has cancelled this run"""
if os.path.exists(os.path.join(logpath, "mythburncancel.lck")):
os.remove(os.path.join(logpath, "mythburncancel.lck"))
write('*'*60)
write("Job has been cancelled at users request")
write('*'*60)
sys.exit(1)
#############################################################
# Runs an external command checking to see if the user has cancelled
# the DVD creation process
def runCommand(command):
checkCancelFlag()
result = os.system(command.encode('utf-8'))
if os.WIFEXITED(result):
result = os.WEXITSTATUS(result)
checkCancelFlag()
return result
#############################################################
# Convert a time in seconds to a frame number
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
#############################################################
# Creates a short mpeg file from a jpeg image and an ac3 sound track
def encodeMenu(background, tempvideo, music, musiclength, tempmovie, xmlfile, finaloutput, aspectratio):
if videomode=="pal":
framespersecond=frameratePAL
else:
framespersecond=framerateNTSC
totalframes=int(musiclength * framespersecond)
command = quoteCmdArg(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, quoteCmdArg(background), quoteCmdArg(path_mpeg2enc[0]), aspectratio, quoteCmdArg(tempvideo))
result = runCommand(command)
if result<>0:
fatalError("Failed while running jpeg2yuv - %s" % command)
command = quoteCmdArg(path_mplex[0]) + " -f 8 -v 0 -o %s %s %s" % (quoteCmdArg(tempmovie), quoteCmdArg(tempvideo), quoteCmdArg(music))
result = runCommand(command)
if result<>0:
fatalError("Failed while running mplex - %s" % command)
if xmlfile != "":
command = quoteCmdArg(path_spumux[0]) + " -m dvd -s 0 %s < %s > %s" % (quoteCmdArg(xmlfile), quoteCmdArg(tempmovie), quoteCmdArg(finaloutput))
result = runCommand(command)
if result<>0:
fatalError("Failed while running spumux - %s" % command)
else:
os.rename(tempmovie, finaloutput)
if os.path.exists(tempvideo):
os.remove(tempvideo)
if os.path.exists(tempmovie):
os.remove(tempmovie)
#############################################################
# Return an xml node from a re-encoding profile xml file for
# a given profile name
def findEncodingProfile(profile):
"""Returns the XML node for the given encoding profile"""
# which encoding file do we need
# first look for a custom profile file in ~/.mythtv/MythArchive/
if videomode == "ntsc":
filename = os.path.expanduser("~/.mythtv/MythArchive/ffmpeg_dvd_ntsc.xml")
else:
filename = os.path.expanduser("~/.mythtv/MythArchive/ffmpeg_dvd_pal.xml")
if not os.path.exists(filename):
# not found so use the default profiles
if videomode == "ntsc":
filename = getEncodingProfilePath() + "/ffmpeg_dvd_ntsc.xml"
else:
filename = getEncodingProfilePath() + "/ffmpeg_dvd_pal.xml"
write("Using encoder profiles from %s" % filename)
DOM = xml.dom.minidom.parse(filename)
#Error out if its the wrong XML
if DOM.documentElement.tagName != "encoderprofiles":
fatalError("Profile xml file doesn't look right (%s)" % filename)
profiles = DOM.getElementsByTagName("profile")
for node in profiles:
if getText(node.getElementsByTagName("name")[0]) == profile:
write("Encoding profile (%s) found" % profile)
return node
write('WARNING: Encoding profile "' + profile + '" not found.')
write('Using default profile "' + defaultEncodingProfile + '".')
for node in profiles:
if getText(node.getElementsByTagName("name")[0]) == defaultEncodingProfile:
write("Encoding profile (%s) found" % defaultEncodingProfile)
return node
fatalError('Neither encoding profile "' + profile + '" nor default enocding profile "' + defaultEncodingProfile + '" found. Giving up.')
return None
#############################################################
# Load the theme.xml file for a DVD theme
def getThemeConfigurationXML(theme):
"""Loads the XML file from disk for a specific theme"""
#Load XML input file from disk
themeDOM = xml.dom.minidom.parse( getThemeFile(theme,"theme.xml") )
#Error out if its the wrong XML
if themeDOM.documentElement.tagName != "mythburntheme":
fatalError("Theme xml file doesn't look right (%s)" % theme)
return themeDOM
#############################################################
# Gets the duration of a video file from its stream info file
def getLengthOfVideo(index):
"""Returns the length of a video file (in seconds)"""
#open the XML containing information about this file
infoDOM = xml.dom.minidom.parse(os.path.join(getItemTempPath(index), 'streaminfo.xml'))
#error out if its the wrong XML
if infoDOM.documentElement.tagName != "file":
fatalError("Stream info file doesn't look right (%s)" % os.path.join(getItemTempPath(index), 'streaminfo.xml'))
file = infoDOM.getElementsByTagName("file")[0]
if file.attributes["cutduration"].value != 'N/A':
duration = int(file.attributes["cutduration"].value)
else:
duration = 0;
return duration
#############################################################
# Gets the audio sample rate and number of channels of a video file
# from its stream info file
def getAudioParams(folder):
"""Returns the audio bitrate and no of channels for a file from its streaminfo.xml"""
#open the XML containing information about this file
infoDOM = xml.dom.minidom.parse(os.path.join(folder, 'streaminfo.xml'))
#error out if its the wrong XML
if infoDOM.documentElement.tagName != "file":
fatalError("Stream info file doesn't look right (%s)" % os.path.join(folder, 'streaminfo.xml'))
audio = infoDOM.getElementsByTagName("file")[0].getElementsByTagName("streams")[0].getElementsByTagName("audio")[0]
samplerate = audio.attributes["samplerate"].value
channels = audio.attributes["channels"].value
return (samplerate, channels)
#############################################################
# Gets the video resolution, frames per second and aspect ratio
# of a video file from its stream info file
def getVideoParams(folder):
"""Returns the video resolution, fps and aspect ratio for the video file from the streaminfo.xml file"""
#open the XML containing information about this file
infoDOM = xml.dom.minidom.parse(os.path.join(folder, 'streaminfo.xml'))
#error out if its the wrong XML
if infoDOM.documentElement.tagName != "file":
fatalError("Stream info file doesn't look right (%s)" % os.path.join(getItemTempPath(index), 'streaminfo.xml'))
video = infoDOM.getElementsByTagName("file")[0].getElementsByTagName("streams")[0].getElementsByTagName("video")[0]
if video.attributes["aspectratio"].value != 'N/A':
aspect_ratio = video.attributes["aspectratio"].value
else:
aspect_ratio = "1.77778"
videores = video.attributes["width"].value + 'x' + video.attributes["height"].value
fps = video.attributes["fps"].value
#sanity check the fps
if videomode=="pal":
fr=frameratePAL
else:
fr=framerateNTSC
if float(fr) != float(fps):
write("WARNING: frames rates do not match")
write("The frame rate for %s should be %s but the stream info file "
"report a fps of %s" % (videomode, fr, fps))
fps = fr
return (videores, fps, aspect_ratio)
#############################################################
# Gets the aspect ratio of a video file from its stream info file
def getAspectRatioOfVideo(index):
"""Returns the aspect ratio of the video file (1.333, 1.778, etc)"""
#open the XML containing information about this file
infoDOM = xml.dom.minidom.parse(os.path.join(getItemTempPath(index), 'streaminfo.xml'))
#error out if its the wrong XML
if infoDOM.documentElement.tagName != "file":
fatalError("Stream info file doesn't look right (%s)" % os.path.join(getItemTempPath(index), 'streaminfo.xml'))
video = infoDOM.getElementsByTagName("file")[0].getElementsByTagName("streams")[0].getElementsByTagName("video")[0]
if video.attributes["aspectratio"].value != 'N/A':
aspect_ratio = float(video.attributes["aspectratio"].value)
else:
aspect_ratio = 1.77778; # default
write("aspect ratio is: %s" % aspect_ratio)
return aspect_ratio
#############################################################
# Calculates the sync offset between the video and first audio stream
def calcSyncOffset(index):
"""Returns the sync offset between the video and first audio stream"""
#open the XML containing information about this file
#infoDOM = xml.dom.minidom.parse(os.path.join(getItemTempPath(index), 'streaminfo_orig.xml'))
infoDOM = xml.dom.minidom.parse(os.path.join(getItemTempPath(index), 'streaminfo.xml'))
#error out if its the wrong XML
if infoDOM.documentElement.tagName != "file":
fatalError("Stream info file doesn't look right (%s)" % os.path.join(getItemTempPath(index), 'streaminfo_orig.xml'))
video = infoDOM.getElementsByTagName("file")[0].getElementsByTagName("streams")[0].getElementsByTagName("video")[0]
video_start = float(video.attributes["start_time"].value)
audio = infoDOM.getElementsByTagName("file")[0].getElementsByTagName("streams")[0].getElementsByTagName("audio")[0]
audio_start = float(audio.attributes["start_time"].value)
# write("Video start time is: %s" % video_start)
# write("Audio start time is: %s" % audio_start)
sync_offset = int((video_start - audio_start) * 1000)
# write("Sync offset is: %s" % sync_offset)
return sync_offset
#############################################################
# Gets the length of a video file and returns it as a string
def getFormatedLengthOfVideo(index):
duration = getLengthOfVideo(index)
minutes = int(duration / 60)
seconds = duration % 60
hours = int(minutes / 60)
minutes %= 60
return '%02d:%02d:%02d' % (hours, minutes, seconds)
#############################################################
# Convert a frame number to a time string
def frameToTime(frame, fps):
sec = int(frame / fps)
frame = frame - int(sec * fps)
mins = sec / 60
sec %= 60
hour = mins / 60
mins %= 60
return '%02d:%02d:%02d' % (hour, mins, sec)
#############################################################
# Convert a time string of format 00:00:00 to number of seconds
def timeStringToSeconds(formatedtime):
parts = string.split(formatedtime, ':')
if len(parts) != 3:
return 0
sec = int(parts[2])
mins = int(parts[1])
hour = int(parts[0])
return sec + (mins * 60) + (hour * 60 * 60)
#############################################################
# Creates a set of chapter points evenly spread thoughout a file
# Optionally grabs the thumbnails from the file
def createVideoChapters(itemnum, numofchapters, lengthofvideo, getthumbnails):
"""Returns numofchapters chapter marks even spaced through a certain time period"""
# if there are user defined thumb images already available use them
infoDOM = xml.dom.minidom.parse(os.path.join(getItemTempPath(itemnum),"info.xml"))
thumblistNode = infoDOM.getElementsByTagName("thumblist")
if thumblistNode.length > 0:
thumblist = getText(thumblistNode[0])
write("Using user defined thumb images - %s" % thumblist)
return thumblist
# no user defined thumbs so create them
segment=int(lengthofvideo / numofchapters)
write( "Video length is %s seconds. Each chapter will be %s seconds" % (lengthofvideo,segment))
chapters=[]
thumbList=[]
starttime=0
count=1
while count<=numofchapters:
chapters.append(time.strftime("%H:%M:%S",time.gmtime(starttime)))
if starttime==0:
if thumboffset < segment:
thumbList.append(str(thumboffset))
else:
thumbList.append(str(starttime))
else:
thumbList.append(str(starttime))
starttime+=segment
count+=1
chapters = ','.join(chapters)
thumbList = ','.join(thumbList)
if getthumbnails==True:
extractVideoFrames( os.path.join(getItemTempPath(itemnum),"stream.mv2"),
os.path.join(getItemTempPath(itemnum),"chapter-%1.jpg"), thumbList)
return chapters
#############################################################
# Creates some fixed length chapter marks
def createVideoChaptersFixedLength(itemnum, segment, lengthofvideo):
"""Returns chapter marks at cut list ends,
or evenly spaced chapters 'segment' seconds through the file"""
if addCutlistChapters == True:
# we've been asked to use the cut list as chapter marks
# so if there is a cut list available, use it
infoDOM = xml.dom.minidom.parse(os.path.join(getItemTempPath(itemnum),"info.xml"))
chapterlistNode = infoDOM.getElementsByTagName("chapterlist")
if chapterlistNode.length > 0:
chapterlist = getText(chapterlistNode[0])
write("Using commercial end marks - %s" % chapterlist)
return chapterlist
if lengthofvideo < segment:
return "00:00:00"
numofchapters = lengthofvideo / segment + 1;
chapters = "00:00:00"
starttime = 0
count = 2
while count <= numofchapters:
starttime += segment
chapters += "," + time.strftime("%H:%M:%S", time.gmtime(starttime))
count += 1
write("Fixed length chapters: %s" % chapters)
return chapters
#############################################################
# Reads a load of settings from DB
def getDefaultParametersFromMythTVDB():
"""Reads settings from MythTV database"""
write( "Obtaining MythTV settings from MySQL database for hostname " + configHostname)
#DBSchemaVer, ISO639Language0 ISO639Language1 are not dependant upon the hostname.
sqlstatement="""SELECT value, data FROM settings WHERE value IN(
'DBSchemaVer',
'ISO639Language0',
'ISO639Language1')
OR (hostname=%s AND value IN(
'VideoStartupDir',
'GalleryDir',
'MusicLocation',
'MythArchiveVideoFormat',
'MythArchiveTempDir',
'MythArchiveMplexCmd',
'MythArchiveDvdauthorCmd',
'MythArchiveMkisofsCmd',
'MythArchiveM2VRequantiserCmd',
'MythArchiveMpg123Cmd',
'MythArchiveProjectXCmd',
'MythArchiveDVDLocation',
'MythArchiveGrowisofsCmd',
'MythArchiveJpeg2yuvCmd',
'MythArchiveSpumuxCmd',
'MythArchiveMpeg2encCmd',
'MythArchiveCopyRemoteFiles',
'MythArchiveAlwaysUseMythTranscode',
'MythArchiveUseProjectX',
'MythArchiveAddSubtitles',
'MythArchiveUseFIFO',
'MythArchiveMainMenuAR',
'MythArchiveChapterMenuAR',
'MythArchiveDateFormat',
'MythArchiveTimeFormat',
'MythArchiveClearArchiveTable',
'MythArchiveDriveSpeed',
'JobQueueCPU'
)) ORDER BY value"""
# create a cursor
cursor = DB.cursor()
# execute SQL statement
cursor.execute(sqlstatement, configHostname)
# get the resultset as a tuple
result = cursor.fetchall()
cfg = {}
for i in range(len(result)):
cfg[result[i][0]] = result[i][1]
#bail out if we can't find the temp dir setting
if not "MythArchiveTempDir" in cfg:
fatalError("Can't find the setting for the temp directory. \nHave you run setup in the frontend?")
return cfg
#############################################################
# Save a setting to the settings table in the DB
def saveSetting(name, data):
host = DB.gethostname()
DB.settings[host][name] = data
#############################################################
# Remove all archive items from the archiveitems DB table
def clearArchiveItems():
''' Remove all archive items from the archiveitems DB table'''
write("Removing all archive items from the archiveitems DB table")
with DB as cursor:
cursor.execute("DELETE FROM archiveitems")
#############################################################
# Load the options from the options node passed in the job file
def getOptions(options):
global doburn
global docreateiso
global erasedvdrw
global mediatype
global savefilename
if options.length == 0:
fatalError("Trying to read the options from the job file but none found?")
options = options[0]
doburn = options.attributes["doburn"].value != '0'
docreateiso = options.attributes["createiso"].value != '0'
erasedvdrw = options.attributes["erasedvdrw"].value != '0'
mediatype = int(options.attributes["mediatype"].value)
savefilename = options.attributes["savefilename"].value
write("Options - mediatype = %d, doburn = %d, createiso = %d, erasedvdrw = %d" \
% (mediatype, doburn, docreateiso, erasedvdrw))
write(" savefilename = '%s'" % savefilename)
#############################################################
# Substitutes some text from a theme file with the required values
def expandItemText(infoDOM, text, itemnumber, pagenumber, keynumber,chapternumber, chapterlist ):
"""Replaces keywords in a string with variables from the XML and filesystem"""
text=string.replace(text,"%page","%s" % pagenumber)
#See if we can use the thumbnail/cover file for videos if there is one.
if getText( infoDOM.getElementsByTagName("coverfile")[0]) =="":
text=string.replace(text,"%thumbnail", os.path.join( getItemTempPath(itemnumber), "title.jpg"))
else:
text=string.replace(text,"%thumbnail", getText( infoDOM.getElementsByTagName("coverfile")[0]) )
text=string.replace(text,"%itemnumber","%s" % itemnumber )
text=string.replace(text,"%keynumber","%s" % keynumber )
text=string.replace(text,"%title",getText( infoDOM.getElementsByTagName("title")[0]) )
text=string.replace(text,"%subtitle",getText( infoDOM.getElementsByTagName("subtitle")[0]) )
text=string.replace(text,"%description",getText( infoDOM.getElementsByTagName("description")[0]) )
text=string.replace(text,"%type",getText( infoDOM.getElementsByTagName("type")[0]) )
text=string.replace(text,"%recordingdate",getText( infoDOM.getElementsByTagName("recordingdate")[0]) )
text=string.replace(text,"%recordingtime",getText( infoDOM.getElementsByTagName("recordingtime")[0]) )
text=string.replace(text,"%duration", getFormatedLengthOfVideo(itemnumber))
text=string.replace(text,"%myfolder",getThemeFile(themeName,""))
if chapternumber>0:
text=string.replace(text,"%chapternumber","%s" % chapternumber )
text=string.replace(text,"%chaptertime","%s" % chapterlist[chapternumber - 1] )
text=string.replace(text,"%chapterthumbnail", os.path.join( getItemTempPath(itemnumber), "chapter-%s.jpg" % chapternumber))
return text
#############################################################
# Scale a theme position/size depending on the current video mode
def getScaledAttribute(node, attribute):
""" Returns a value taken from attribute in node scaled for the current video mode"""
if videomode == "pal" or attribute == "x" or attribute == "w":
return int(node.attributes[attribute].value)
else:
return int(float(node.attributes[attribute].value) / 1.2)
#############################################################
# Splits some text into lines so it will fit into a given container
def intelliDraw(drawer, text, font, containerWidth):
"""Based on http://mail.python.org/pipermail/image-sig/2004-December/003064.html"""
#Args:
# drawer: Instance of "ImageDraw.Draw()"
# text: string of long text to be wrapped
# font: instance of ImageFont (I use .truetype)
# containerWidth: number of pixels text lines have to fit into.
#write("containerWidth: %s" % containerWidth)
words = text.split()
lines = [] # prepare a return argument
lines.append(words)
finished = False
line = 0
while not finished: