-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrectovid.py
executable file
·1272 lines (1107 loc) · 45.7 KB
/
rectovid.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 python3
""" Transcodes a MythTV recording and puts it into the video storage """
import argparse
import sys
import os
import subprocess
import logging
import logging.handlers
import math
import urllib.parse
import re
import json
import time
import configparser
import shlex
from threading import Timer
from MythTV import Job
from MythTV.services_api import send as api
sys.path.append("/usr/bin")
class Status:
""" Manages status reporting """
_myth_job = None
_myth_job_id = 0
_subprogresses = []
_cur_subprogress = 0
_progress_start = None
_last_progress = None
def __init__(self, job_id=0):
if job_id and not Status._myth_job:
Status._myth_job_id = job_id
Status._myth_job = Job(job_id)
Status._myth_job.update(status=Job.STARTING)
self.set_comment('Starting job...')
@staticmethod
def set_error(msg):
""" Set an error state to the myth job object """
logging.error(msg)
Status.set_comment(msg, log=False)
Status.set_status(Job.ERRORED)
@staticmethod
def set_comment(msg, log=True):
""" Sets a comment text to the myth job object """
if log:
logging.info(msg)
if Status._myth_job:
Status._myth_job.setComment(msg)
@staticmethod
def add_subprogress(duration):
""" Adds a subprogress """
Status._subprogresses.append({'Duration': duration, 'Start': 0, 'End': 0})
total_duration = 0.0
for sub in Status._subprogresses:
total_duration += float(sub['Duration'])
current_duration = 0.0
for sub in Status._subprogresses:
sub['Start'] = current_duration / total_duration
current_duration += float(sub['Duration'])
sub['End'] = current_duration / total_duration
@staticmethod
def next_subprogress():
""" Switches to next subprogress """
if Status._subprogresses:
Status._cur_subprogress += 1
@staticmethod
def reset_progress():
""" Clears subprogress list and resets start time """
Status._subprogresses = []
Status._cur_subprogress = 0
Status._progress_start = None
Status._last_progress = None
@staticmethod
def init_progress():
""" Initializes progress start time """
Status._progress_start = time.time()
logging.debug(Status._subprogresses)
@staticmethod
def set_progress(progress):
""" Sets progress as a comment to the myth job object """
if not progress:
return
if Status._subprogresses and Status._cur_subprogress < len(Status._subprogresses):
sub = Status._subprogresses[Status._cur_subprogress]
progress = sub['Start']*100.0 + (sub['End'] - sub['Start']) * progress
if Status._last_progress and Status._last_progress == int(progress):
return
Status._last_progress = int(progress)
eta = None
if Status._progress_start and progress > 0.0:
time_spent = time.time() - Status._progress_start
time_left = (100.0 - progress) * time_spent / progress
eta = time.strftime('%H:%M:%S', time.gmtime(time_left))
if Status._myth_job:
if eta:
Status._myth_job.setComment(f'Progress: {int(progress)} %\nRemaining time: {eta}')
else:
Status._myth_job.setComment(f'Progress: {int(progress)} %')
@staticmethod
def set_status(new_status):
""" Sets a state to the myth job object """
if Status._myth_job:
logging.debug('Setting job status to %s', new_status)
Status._myth_job.setStatus(new_status)
@staticmethod
def get_status():
""" Gets state of the myth job object """
if Status._myth_job:
return Status._myth_job.status
return Job.UNKNOWN
@staticmethod
def get_cmd():
""" Reads the current myth job state from the database """
if Status._myth_job_id == 0:
return Job.UNKNOWN
# create new job object to pull current state from database
return Job(Status._myth_job_id).cmds
@staticmethod
def canceled():
""" Checks if myth job object has been stopped/canceled """
return Status.get_cmd() == Job.STOP or Status.get_status() == Job.CANCELLED
@staticmethod
def failed():
""" Checks if myth job object has error state """
return Status.get_status() == Job.ERRORED
class VideoFilePath:
""" Build video file name from title, subtitle and season metadata
Also finds best matching storage group from different criteria.
"""
def __init__(self, recording):
self.recording = recording
self.storage_dir, self.video_dir = self._find_dir()
self.path = None
if self.storage_dir:
self.video_file = self._build_name()
self.path = os.path.join(os.path.join(self.storage_dir, self.video_dir), self.video_file)
def __str__(self):
return self.path if self.path else ''
def _find_dir(self):
""" Builds the video file directory.
It scans all video storage dirs to find the best
one using the following criteria by ascending priority:
1. Storage dir with maximum free space
2. Directory matching recording title (useful for series)
3. Directory containing files matching the title
"""
mbe = Backend()
matched_dir_name = None
matched_storage_dir = None
max_free_space = 0
max_space_storage_dir = None
rec_size = int(Util.get_file_size(self.recording.path) / 1000.0)
logging.debug("Recording %s -> size %s KiB", self.recording.path, rec_size)
for storage_group in mbe.get_storage_group_data(group_name='Videos'):
if storage_group['HostName'] != mbe.host_name:
continue
if storage_group['DirWrite'] != True:
continue
storage_dir = storage_group['DirName']
# search given group
if not os.path.isdir(storage_dir):
continue
# get avaliable space of storage group partition
# and use storage group with max. available space
free_space = int(storage_group['KiBFree'])
logging.debug('Storage group %s -> space %s KiB', storage_dir, free_space)
# check if recording fits into storage group
if rec_size > free_space:
logging.warning('Recording size exceeds free space on storage group, skipping')
continue
if free_space > max_free_space:
max_space_storage_dir = storage_dir
max_free_space = free_space
for sg_root, sg_dirs, sg_files in os.walk(storage_dir, followlinks=True):
# first check subdir for match
for sg_dir in sg_dirs:
if self._match_title(sg_dir):
matched_dir_name = os.path.join(sg_root, sg_dir)
matched_storage_dir = storage_dir
# check file names for match
for sg_file in sg_files:
if self._match_title(sg_file):
logging.debug('Using storage dir with files matching title')
if sg_root == storage_dir:
return storage_dir, ''
return storage_dir, os.path.relpath(sg_root, storage_dir)
# return directory matching title if found
if matched_dir_name:
logging.debug('Using storage dir matching title')
return matched_storage_dir, os.path.relpath(matched_dir_name, matched_storage_dir)
# return storage directory with max free space
if max_space_storage_dir:
logging.debug('Using storage dir with max. space')
return max_space_storage_dir, ''
return None, None
def _build_name(self):
""" Builds video file name: "The_title(_-_|_SxxEyy_][The_Subtitle].[mkv]" """
parts = []
title = self.recording.get_title()
subtitle = self.recording.get_subtitle()
season = self.recording.get_season()
episode = self.recording.get_episode()
if title and title != '':
parts.append(title)
if season > 0 and episode > 0:
parts.append(f'S{season:02}E{episode:02}')
elif subtitle and subtitle != "":
parts.append('-')
if subtitle and subtitle != "":
parts.append(subtitle)
name = "_".join(' '.join(parts).split()) + '.mkv'
for char in ('\''):
name = name.replace(char, '')
return name
def _match_title(self, name):
""" Checks if file or directory name starts with specified title """
simplified_title = self.recording.get_title().lower()
simplified_name = name.lower()
for char in (' ', '_', '-'):
simplified_name = simplified_name.replace(char, '')
simplified_title = simplified_title.replace(char, '')
return simplified_name.startswith(simplified_title)
class Recording:
""" Handles recording data """
def __init__(self, rec_path):
self.path = rec_path
# first determine video stream of recording
streams = Util.get_video_streams(self.path)
self.video_stream = None
for stream in streams:
if 'codec_type' in stream and stream['codec_type'] == 'video':
self.video_stream = stream
break
self.metadata = None
def get_video_codec(self):
""" Return video stream codec name """
return self.video_stream['codec_name']
def get_video_fps(self):
""" Return video stream FPS """
return float(self.video_stream['r_frame_rate'].split('/')[0])
def get_uncut_list(self):
""" Returns uncut parts of the recording """
mbe = Backend()
rec_id = mbe.get_recording_id(self.path)
if rec_id is None:
return None
return mbe.get_recording_uncutlist(rec_id)
def _get_metadata(self):
if not self.metadata:
mbe = Backend()
rec_id = mbe.get_recording_id(self.path)
if rec_id is None:
return False
self.metadata = mbe.get_recording_metadata(rec_id)
return self.metadata is not None
def get_title(self):
""" Returns recording title """
if self._get_metadata():
return self.metadata['Title']
return ''
def get_subtitle(self):
""" Returns recording subtitle """
if self._get_metadata():
return self.metadata['SubTitle']
return ''
def get_season(self):
""" Returns recording season """
if self._get_metadata():
return int(self.metadata['Season'])
return 0
def get_episode(self):
""" Returns recording episode """
if self._get_metadata():
return int(self.metadata['Episode'])
return 0
class Transcoder:
""" Handles transcoding a recording to a video file """
def __init__(self, recording, preset, preset_file, timeout):
self.timer = None
self.recording = recording
self.preset = preset
self.preset_file = preset_file
self.timeout = timeout
@staticmethod
def _abort(process):
""" Abort transcoding after timeout """
Status.set_error('Aborting transcode due to timeout')
process.kill()
def _start_timer(self, process):
""" Start timer to abort transcode process if it hangs """
self._stop_timer()
self.timer = Timer(self.timeout, self._abort, [process])
self.timer.start()
def _stop_timer(self):
""" Stop the abort transcoding timer """
if self.timer is not None:
self.timer.cancel()
self.timer = None
def transcode(self, dst_file):
""" Transcode the source file to the destination file using the specified preset
The cutlist of the recording (source file) is used to transcode
multiple parts of the recording if neccessary and then merged into the final
destination file.
"""
# obtain recording parts to transcode
parts = self.recording.get_uncut_list()
if parts is None:
return 1
if parts:
logging.debug('Found %s parts: %s', len(parts), parts)
Status.init_progress()
if not parts:
# transcode whole file directly
res = self._transcode_part(dst_file)
elif len(parts) == 1:
# transcode single part directly
res = self._transcode_part(dst_file, parts[0])
else:
# transcode each part on its own
res = self._transcode_multiple(dst_file, parts)
Status.reset_progress()
return res
def copy(self, dst_file):
""" Copies streams of the source file to the destination file using mkvmerge
The cutlist of the recording (source file) is used to copy
multiple parts of the recording if neccessary and then merged into the final
destination file.
"""
# obtain recording parts to transcode
parts = self.recording.get_uncut_list()
if parts is None:
return 1
if parts:
logging.debug('Found %s parts: %s', len(parts), parts)
Status.init_progress()
# workaround bug in mkvmerge producing an mkv file where the
# audio has a big offset after compile
# convert first into mkv file using ffmpeg, then split and merge
dst_dir, dst_name = os.path.split(dst_file)
tmp_file = os.path.join(dst_dir, "tmp_" + dst_name)
res = self._extract_part(tmp_file)
if res != 0:
Util.remove_file(tmp_file)
return res
res = self._copy_and_merge(tmp_file, dst_file, parts)
Util.remove_file(tmp_file)
Status.reset_progress()
return res
def extract(self, dst_file):
""" Copies streams of the source file to the destination file using ffmpeg
The cutlist of the recording (source file) is used to extract
multiple parts of the recording if neccessary and then merged into the final
destination file.
"""
# obtain recording parts to extract
parts = self.recording.get_uncut_list()
if parts is None:
return 1
if parts:
logging.debug('Found %s parts: %s', len(parts), parts)
Status.init_progress()
if not parts:
# extract whole file directly
res = self._extract_part(dst_file)
elif len(parts) == 1:
# extract single part directly
res = self._extract_part(dst_file, parts[0])
else:
# extract each part on its own
res = self._extract_multiple(dst_file, parts)
Status.reset_progress()
return res
def _extract_multiple(self, dst_file, parts):
# initialize progress ranges
for part in parts:
Status.add_subprogress(part[1]-part[0])
# transcode each part on its own
part_number = 1
tmp_files = []
dst_file_base_name, dst_file_ext = os.path.splitext(dst_file)
for part in parts:
dst_file_part = f'{dst_file_base_name}_part_{part_number}{dst_file_ext}'
logging.info('Processing part %s/%s to %s', part_number, len(parts), dst_file_part)
res = self._extract_part(dst_file_part, part)
if res != 0:
break
part_number += 1
tmp_files.append(dst_file_part)
Status.next_subprogress()
# merge transcoded parts
if len(parts) == len(tmp_files):
res = self._merge_parts(tmp_files, dst_file)
# delete transcoded parts
for tmp_file in tmp_files:
Util.remove_file(tmp_file)
return res
def _transcode_multiple(self, dst_file, parts):
# initialize progress ranges
for part in parts:
Status.add_subprogress(part[1]-part[0])
# transcode each part on its own
part_number = 1
tmp_files = []
dst_file_base_name, dst_file_ext = os.path.splitext(dst_file)
for part in parts:
dst_file_part = f'{dst_file_base_name}_part_{part_number}{dst_file_ext}'
logging.info('Processing part %s/%s to %s', part_number, len(parts), dst_file_part)
res = self._transcode_part(dst_file_part, part)
if res != 0:
break
part_number += 1
tmp_files.append(dst_file_part)
Status.next_subprogress()
# merge transcoded parts
if len(parts) == len(tmp_files):
res = self._merge_parts(tmp_files, dst_file)
# delete transcoded parts
for tmp_file in tmp_files:
Util.remove_file(tmp_file)
return res
def _copy_and_merge(self, src_file, dst_file, parts):
# start the copying process
args = []
args.append('mkvmerge')
args.append('--verbose')
args.append('-o')
args.append(dst_file)
split_spec = ''
for part in parts:
split_spec += f'{"parts-frames:" if not split_spec else ",+"}{part[0]}-{part[1]}'
if split_spec:
args.append('--append-mode')
args.append('track')
args.append('--split')
args.append(split_spec)
args.append(src_file)
logging.debug('Executing \"%s\"', ' '.join(args))
proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
# start timer to abort transcode process if it hangs
self._start_timer(proc)
# regex pattern to find prograss and ETA in output line
pattern = re.compile(r"^Progress:([ ]*[\d]*)")
while True:
line = proc.stdout.readline()
if line == '' and proc.poll() is not None:
break # Aborted, no characters available, process died.
if line:
# new line, restart abort timer
self._start_timer(proc)
if line.startswith('Warning:'):
logging.warning(line)
progress = None
try:
if matched := re.search(pattern, line):
progress = float(matched.group(1))
except IndexError:
pass
else:
Status.set_progress(progress)
# check if job was stopped externally
if Status.canceled():
proc.kill()
break
# remove video file on failure
if proc.wait() == 2 or Status.canceled() or Status.failed():
# print transcoding error output
logging.error(proc.stderr.read())
Util.remove_file(dst_file)
self._stop_timer()
if proc.returncode == 1:
# a warning has occured
logging.info('Finished with warning(s)')
return 0
return proc.returncode
def _transcode_part(self, dst_file, frames=None):
""" Start HandBrake to transcodes all or a single part (identified by
start and end frame) of the source file
A timer is used to abort the transcoding if there was no progress
detected within a specfied timeout period.
"""
# start the transcoding process
args = []
args.append('HandBrakeCLI')
if self.preset_file:
args.append('--presetfile')
args.append(self.preset_file)
args.append('--preset')
args.append(self.preset)
args.append('-i')
args.append(self.recording.path)
args.append('-o')
args.append(dst_file)
if frames:
logging.debug('Processing frame %s to %s (%s frames)',
frames[0], frames[1], frames[1]-frames[0])
# pass start and end position of remaining part to handbrake
args.append('--start-at')
args.append(f'frame:{frames[0]}')
# stop it relative to start position
args.append('--stop-at')
args.append(f'frame:{frames[1]-frames[0]}')
logging.debug('Executing \"%s\"', ' '.join(args))
proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
# start timer to abort transcode process if it hangs
self._start_timer(proc)
# regex pattern to find prograss and ETA in output line
pattern = re.compile(r"([\d]*\.[\d]*)(?=\s\%.*fps)")
while True:
line = proc.stdout.readline()
if line == '' and proc.poll() is not None:
break # Aborted, no characters available, process died.
if line:
# new line, restart abort timer
self._start_timer(proc)
progress = None
try:
if matched := re.search(pattern, line):
progress = float(matched.group(1))
except IndexError:
pass
else:
Status.set_progress(progress)
# check if job was stopped externally
if Status.canceled():
proc.kill()
break
# remove video file on failure
if proc.wait() != 0 or Status.canceled() or Status.failed():
# print transcoding error output
logging.error(proc.stderr.read())
Util.remove_file(dst_file)
self._stop_timer()
return proc.returncode
def _extract_part(self, dst_file, frames=None):
""" Use ffmpeg to copy video part. """
if frames:
fps = self.recording.get_video_fps()
logging.debug('Using %s fps', fps)
frame_count = float(frames[1]-frames[0]) if frames else 0
streams = Util.get_video_streams(self.recording.path)
# start the copying process
args = []
args.append('ffmpeg')
if frames:
args.append('-ss')
args.append(f'{float(frames[0]) / fps}')
args.append('-i')
args.append(self.recording.path)
if frames:
args.append('-t')
args.append(f'{float(frames[1]-frames[0]) / fps}')
args.append('-vcodec')
args.append('copy')
args.append('-acodec')
args.append('copy')
args.append('-scodec')
args.append('dvdsub')
# select all video streams
args.append('-map')
args.append('0:v')
# select all audio streams
args.append('-map')
args.append('0:a')
sub_stream_index = 0
for stream in streams:
if not 'codec_type' in stream or not 'codec_name' in stream:
continue
if stream['codec_type'] != 'subtitle':
continue
if stream['codec_name'] == 'dvb_subtitle':
args.append('-map')
args.append(f'0:s:{sub_stream_index}')
sub_stream_index += 1
args.append(dst_file)
logging.debug('Executing \"%s\"', ' '.join(args))
proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
# start timer to abort transcode process if it hangs
self._start_timer(proc)
# regex pattern to find prograss and ETA in output line
pattern = re.compile(r"^frame=([ ]*[\d]*)")
while True:
line = proc.stderr.readline()
if line == '' and proc.poll() is not None:
break # Aborted, no characters available, process died.
if line:
# new line, restart abort timer
self._start_timer(proc)
progress = None
try:
if matched := re.search(pattern, line):
frame = float(matched.group(1))
progress = 100.0 * frame / frame_count
except IndexError:
pass
else:
Status.set_progress(progress)
# check if job was stopped externally
if Status.canceled():
proc.kill()
break
# remove video file on failure
if proc.wait() != 0 or Status.canceled() or Status.failed():
# print transcoding error output
logging.error(proc.stderr.read())
Util.remove_file(dst_file)
self._stop_timer()
return proc.returncode
@staticmethod
def _merge_parts(parts, dst_file):
logging.debug('Merging transcoded parts %s', parts)
list_file = f'{os.path.splitext(dst_file)[0]}_partlist.txt'
with open(list_file, "w") as text_file:
for part in parts:
text_file.write(f'file {os.path.basename(part)}\n')
Status.set_comment('Merging transcoded parts')
args = []
args.append('ffmpeg')
args.append('-f')
args.append('concat')
args.append('-safe')
args.append('0')
args.append('-i')
args.append(list_file)
args.append('-c')
args.append('copy')
args.append(dst_file)
logging.debug('Executing \"%s\"', ' '.join(args))
try:
proc = subprocess.run(args, capture_output=True, text=True, check=True)
except subprocess.CalledProcessError as error:
logging.error(error.stderr)
Util.remove_file(dst_file)
finally:
Util.remove_file(list_file)
return proc.returncode
class Backend:
""" Handles sending and receiving data to/from the Mythtv backend """
def __init__(self, debug=None):
try:
self.mbe = api.Send(host='localhost')
result = self.mbe.send(
endpoint='Myth/GetHostName'
)
logging.debug('Myth/GetHostName received: %s', result)
self.host_name = result['String']
except RuntimeError as error:
logging.error('\nFatal error: "%s"', error)
self.post_opts = {'wrmi': True}
if debug is not None:
self.post_opts['debug'] = debug
elif logging.getLogger().getEffectiveLevel() == logging.DEBUG:
self.post_opts['debug'] = True
def get_storage_group_data(self, group_name=None):
""" Retrieve storage group data from backend """
if group_name:
data = f'HostName={self.host_name}&GroupName={group_name}'
else:
data = f'HostName={self.host_name}'
try:
result = self.mbe.send(
endpoint='Myth/GetStorageGroupDirs', rest=data
)
logging.debug('Myth/GetStorageGroupDirs received: %s', result)
return result['StorageGroupDirList']['StorageGroupDirs']
except RuntimeError as error:
logging.error('\nFatal error: "%s"', error)
return None
def get_storage_dirs(self, group_name=None, host_name=None, writable=None):
""" Returns list of storage group directories """
storage_groups = self.get_storage_group_data(group_name)
if not storage_groups:
return []
dirs = []
for sg_data in storage_groups:
if writable and sg_data["DirWrite"] != 'true':
continue
if not host_name or sg_data['HostName'] == host_name:
dirs.append(sg_data['DirName'])
return dirs
def get_recording_id(self, rec_path):
""" Retrieves recording id of specified recording file """
try:
data = f'Pathname={urllib.parse.quote(rec_path)}'
result = self.mbe.send(
endpoint='Dvr/RecordedIdForPathname', rest=data
)
logging.debug('Dvr/RecordedIdForPathname received: %s', result)
return result['int']
except RuntimeError as error:
logging.error('\nFatal error: "%s"', error)
return None
def get_recording_metadata(self, rec_id):
""" Retrieves metadata of the specified recording """
try:
data = f'RecordedId={rec_id}'
result = self.mbe.send(
endpoint='Dvr/GetRecorded', rest=data
)
logging.debug('Dvr/GetRecorded received: %s', result)
return result['Program']
except RuntimeError as error:
logging.error('\nFatal error: "%s"', error)
return None
def get_recording_uncutlist(self, rec_id):
""" Retrives cutlist of specified recording """
try:
data = f'RecordedId={rec_id}&OffsetType=Frames'
result = self.mbe.send(
endpoint='Dvr/GetRecordedCutList', rest=data
)
logging.debug('Dvr/GetRecordedCutList received: %s', result)
# create negated (uncut) list from cut list
start = 0
stop = 0
cuts = []
for cut in result['CutList']['Cuttings']:
if int(cut['Mark']) == 1: # start of cut
stop = int(cut['Offset'])
cuts.append((start, stop))
elif int(cut['Mark']) == 0: # end of cut
start = int(cut['Offset'])
stop = 9999999
if stop == 9999999:
cuts.append((start, stop))
return cuts
except RuntimeError as error:
logging.error('\nFatal error: "%s"', error)
return None
def add_video(self, vid_path):
""" Adds specified video to the database
The path must be an absolute path.
"""
if not vid_path:
return False
try:
data = {'HostName': self.host_name, 'FileName': vid_path}
result = self.mbe.send(
endpoint='Video/AddVideo', postdata=data, opts=self.post_opts
)
logging.debug('Video/AddVideo received: %s', result)
return result['bool']
except RuntimeError as error:
logging.error('\nFatal error: "%s"', error)
return False
def get_video_id(self, vid_file):
""" Retrieves the video id of the specified video file
The video file must be relative to one of the video
storage dirs.
"""
try:
data = f'FileName={urllib.parse.quote(vid_file)}'
result = self.mbe.send(
endpoint='Video/GetVideoByFileName', rest=data
)
logging.debug('Video/GetVideoByFileName received: %s', result)
return result['VideoMetadataInfo']['Id']
except RuntimeError as error:
logging.error('\nFatal error: "%s"', error)
return None
def get_video_metadata(self, vid_id):
""" Retrieves the metadata of the specified video file """
try:
data = f'Id={vid_id}'
result = self.mbe.send(
endpoint='Video/GetVideo', rest=data
)
logging.debug('Video/GetVideo received: %s', result)
return result['VideoMetadataInfo']
except RuntimeError as error:
logging.error('\nFatal error: "%s"', error)
return None
def update_video_metadata(self, vid_id, data):
""" Updates metadata of the specified video """
try:
if not data:
return False
data['Id'] = vid_id
result = self.mbe.send(
endpoint='Video/UpdateVideoMetadata', postdata=data, opts=self.post_opts
)
logging.debug('Video/UpdateVideoMetadata received: %s', result)
return result['bool']
except RuntimeError as error:
logging.error('\nFatal error: "%s"', error)
return False
def show_notification(self, msg, msg_type):
""" Displays a visual notification on active frontends """
try:
data = {
'Message': msg,
'Origin': '\"' + __file__ + '\"',
'TimeOut': 60,
'Type': msg_type,
'Progress': -1
}
self.mbe.send(
endpoint='Myth/SendNotification', postdata=data, opts=self.post_opts
)
except RuntimeError as error:
logging.error('\nFatal error: "%s"', error)
if msg_type == 'error':
logging.error(msg)
elif msg_type == "warning":
logging.warning(msg)
elif msg_type == "normal":
logging.info(msg)
class Util:
""" Utility class """
@staticmethod
def get_file_size(file_name):
""" Return size of specified file """
return os.stat(file_name).st_size
@staticmethod
def format_file_size(num):
""" Formats the given number as a file size """
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if abs(num) < 1000.0:
return "%3.1f %s" % (num, unit)
num /= 1000.0
return "%.1f %s" % (num, 'PB')
@staticmethod
def get_free_space(file_name):
""" Returns the free space of the partition of the specified file/directory """
stats = os.statvfs(file_name)
return stats.f_bfree * stats.f_frsize
@staticmethod
def get_video_streams(filename):
""" Determines all streams of the video file using ffprobe
Returns list of streams.
"""
args = []
args.append('ffprobe')
args.append('-hide_banner')
args.append('-v')
args.append('error')
args.append('-show_streams')
args.append('-of')
args.append('json')
args.append(filename)
logging.debug('Executing \"%s\"', ' '.join(args))
try:
proc = subprocess.run(args, capture_output=True, text=True, check=True)
return json.loads(proc.stdout)['streams']
except subprocess.CalledProcessError as error:
logging.error(error.stderr)
return {}
except ValueError:
return {}
@staticmethod
def get_video_length(filename):
""" Determines the video length using ffprobe
Returns the video length in minutes.
"""
streams = Util.get_video_streams(filename)
if not streams:
return 0
for stream in streams:
if 'codec_type' in stream and stream['codec_type'] == 'video':
if 'duration' in stream:
return int(math.ceil(float(stream['duration']) / 60.0))
if 'tags' in stream and 'DURATION' in stream['tags']:
tokens = stream['tags']['DURATION'].split(':')
if tokens:
return int(tokens[0]) * 60 + int(tokens[1])
if 'tags' in stream and 'DURATION-eng' in stream['tags']:
tokens = stream['tags']['DURATION-eng'].split(':')
if tokens:
return int(tokens[0]) * 60 + int(tokens[1])
return 0
@staticmethod