-
Notifications
You must be signed in to change notification settings - Fork 29
/
player.py
1331 lines (1101 loc) · 51 KB
/
player.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
# -*- coding: utf-8 -*-
import subprocess, sys, json, time, re, os, atexit
import logging
import tempfile
import traceback
try:
from aqt.sound import play, _packagedCmd, si
import aqt.sound as sound # Anki 2.1.17+
except ImportError:
from anki.sound import play, _packagedCmd, si
import anki.sound as sound
from anki import hooks
from anki.lang import _, ngettext
from anki.hooks import addHook, wrap
from anki.template import TemplateRenderContext
from anki.utils import no_bundled_libs, strip_html, tmpdir
from aqt.reviewer import Reviewer
from aqt import mw, browser, gui_hooks
from aqt.utils import getFile, showWarning, showInfo, showText, tooltip, is_win, is_mac
from aqt.qt import *
from subprocess import check_output, CalledProcessError
from . import media
from .utils import format_filename
# ------------- ADDITIONAL OPTIONS -------------
NORMALIZE_AUDIO = False
NORMALIZE_AUDIO_FILTER = "I=-18:LRA=11"
NORMALIZE_AUDIO_WITH_MP3GAIN = True
ADJUST_AUDIO_STEP = 0.25
ADJUST_AUDIO_REPLAY_TIME = 2.5
VLC_DIR = ""
IINA_DIR = "/Applications/IINA.app/Contents/MacOS/IINA"
# ----------------------------------------------
info = None
if is_win:
info = subprocess.STARTUPINFO()
info.wShowWindow = subprocess.SW_HIDE
info.dwFlags = subprocess.STARTF_USESHOWWINDOW
p = None
from distutils.spawn import find_executable
if is_mac and '/usr/local/bin' not in os.environ['PATH'].split(':'):
# https://docs.brew.sh/FAQ#my-mac-apps-dont-find-usrlocalbin-utilities
os.environ['PATH'] = "/usr/local/bin:" + os.environ['PATH']
if is_mac and '/opt/homebrew/bin' not in os.environ['PATH'].split(':'):
# https://docs.brew.sh/FAQ#my-mac-apps-dont-find-usrlocalbin-utilities
os.environ['PATH'] = "/opt/homebrew/bin:" + os.environ['PATH']
mpv_executable, env = find_executable("mpv"), os.environ
if mpv_executable is None and is_mac:
mpv_executable = "/Applications/mpv.app/Contents/MacOS/mpv"
if not os.path.exists(mpv_executable):
mpv_executable = None
with_bundled_libs = False
if mpv_executable is None:
mpv_path, env = _packagedCmd(["mpv"])
mpv_executable = mpv_path[0]
with_bundled_libs = True
ffmpeg_executable = find_executable("ffmpeg")
ffprobe_executable = find_executable("ffprobe")
# maybe a fix for macOS
if ffprobe_executable is None:
ffprobe_executable = '/usr/local/bin/ffprobe'
if not os.path.exists(ffprobe_executable):
ffprobe_executable = None
if ffmpeg_executable is None:
ffmpeg_executable = '/usr/local/bin/ffmpeg'
if not os.path.exists(ffmpeg_executable):
ffmpeg_executable = None
logger = logging.getLogger()
ch = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
logger.handlers = []
logger.addHandler(ch)
def timeToSeconds(t):
hours, minutes, seconds, milliseconds = t.split('.')
return int(hours) * 3600 + int(minutes) * 60 + int(seconds) + int(milliseconds) * 0.001
def secondsToTime(seconds, sep="."):
ms = (seconds * 1000) % 1000
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
return "%d%s%02d%s%02d.%03d" % (h, sep, m, sep, s, ms)
def playVideoClip(path=None, state=None, shift=None, isEnd=True, isPrev=False, isNext=False):
global p, _player
fields = {}
for item in mw.reviewer.card.note().items():
fields[item[0]] = item[1]
# if path is not None and os.path.exists(path):
# _player(path)
# return
if not path:
if state is not None:
path = fields["Audio"]
else:
path = fields["Video"]
path = strip_html(path)
path = path.replace('[sound:', '')
path = path.replace(']', '')
# elif path.endswith(".mp3"): # workaround to fix replay button (R) without refreshing webview.
# path = fields["Audio"]
# else:
# path = fields["Video"]
# if mw.reviewer.state == "question" and mw.reviewer.card.note_type()["name"] == "movies2anki - subs2srs (video)":
# path = fields["Video"]
m = re.fullmatch(r"(.*?)_(\d+\.\d\d\.\d\d\.\d+)-(\d+\.\d\d\.\d\d\.\d+).*", path)
if not m:
return False
card_prefix, time_start, time_end = m.groups()
time_start = timeToSeconds(time_start)
time_end = timeToSeconds(time_end)
if state == None and (isPrev or isNext):
cards = sorted(mw.col.findCards('"Id:{}_*"'.format(card_prefix), order=True))
card_idx = cards.index(mw.reviewer.card.id)
prev_card_idx = card_idx - 1 if card_idx - 1 > 0 else 0
next_card_idx = card_idx + 1
if next_card_idx >= len(cards):
next_card_idx = len(cards) - 1
if (isPrev and mw.col.getCard(cards[prev_card_idx]).id == mw.reviewer.card.id):
tooltip("It's the first card.")
return
if (isNext and mw.col.getCard(cards[next_card_idx]).id == mw.reviewer.card.id):
tooltip("It's the last card.")
return
curr_card = mw.col.getCard(cards[card_idx])
prev_card = mw.col.getCard(cards[prev_card_idx])
next_card = mw.col.getCard(cards[next_card_idx])
prev_card_audio = prev_card.note()["Audio"]
next_card_audio = next_card.note()["Audio"]
# TODO compare Id field prefix or Path field or limit search by Path or maybe something else
m = re.fullmatch(r".*?_(\d+\.\d\d\.\d\d\.\d+)-(\d+\.\d\d\.\d\d\.\d+).*", prev_card_audio)
prev_time_start, prev_time_end = m.groups()
prev_time_start = timeToSeconds(prev_time_start)
prev_time_end = timeToSeconds(prev_time_end)
m = re.fullmatch(r".*?_(\d+\.\d\d\.\d\d\.\d+)-(\d+\.\d\d\.\d\d\.\d+).*", next_card_audio)
next_time_start, next_time_end = m.groups()
next_time_start = timeToSeconds(next_time_start)
next_time_end = timeToSeconds(next_time_end)
if isPrev:
time_start = prev_time_start
if isNext:
time_end = next_time_end
if state != None:
if state == "start":
time_start = time_start - shift
elif state == "end":
time_end = time_end + shift
# elif state == "start reset":
# m = re.match(r"^.*?_(\d+\.\d\d\.\d\d\.\d+)-(\d+\.\d\d\.\d\d\.\d+).*$", fields["Id"])
# id_time_start, id_time_end = m.groups()
# id_time_start = timeToSeconds(id_time_start)
# time_start = id_time_start
# elif state == "end reset":
# m = re.match(r"^.*?_(\d+\.\d\d\.\d\d\.\d+)-(\d+\.\d\d\.\d\d\.\d+).*$", fields["Id"])
# id_time_start, id_time_end = m.groups()
# id_time_end = timeToSeconds(id_time_end)
# time_end = id_time_end
time_interval = "%s-%s" % (secondsToTime(time_start), secondsToTime(time_end))
mw.reviewer.card.note()["Id"] = re.sub(r"_\d+\.\d\d\.\d\d\.\d+-\d+\.\d\d\.\d\d\.\d+\.", "_%s." % time_interval, fields["Id"])
mw.reviewer.card.note()["Audio"] = re.sub(r"_\d+\.\d\d\.\d\d\.\d+-\d+\.\d\d\.\d\d\.\d+\.", "_%s." % time_interval, fields["Audio"])
if "Video" in mw.reviewer.card.note():
mw.reviewer.card.note()["Video"] = re.sub(r"_\d+\.\d\d\.\d\d\.\d+-\d+\.\d\d\.\d\d\.\d+\.", "_%s." % time_interval, fields["Video"])
mw.reviewer.card.note().flush()
if VLC_DIR:
default_args = ["-I", "dummy", "--play-and-exit", "--no-video-title", "--video-on-top", "--sub-track=8"]
if is_win:
default_args += ["--dummy-quiet"]
default_args += ["--no-sub-autodetect-file"]
else:
default_args = ["--pause=no", "--script=%s" % os.path.join(os.path.dirname(os.path.abspath(__file__)), "settings.lua")]
default_args += ["--sub-visibility=no", "--no-resume-playback", "--save-position-on-quit=no"]
if path.endswith(".mp3"):
if VLC_DIR:
default_args += ["--no-video"]
else:
default_args += ["--force-window=no", "--video=no"]
args = list(default_args)
if state == None:
if VLC_DIR:
args += ["--start-time={}".format(time_start)]
if isEnd:
args += ["--stop-time={}".format(time_end)]
else:
args += ["--start={}".format(time_start)]
if isEnd:
args += ["--end={}".format(time_end)]
elif state == "start" or state == "start reset":
if VLC_DIR:
args += ["--start-time={}".format(time_start), "--stop-time={}".format(time_end)]
else:
args += ["--start={}".format(time_start), "--end={}".format(time_end)]
elif state == "end" or state == "end reset":
if VLC_DIR:
args += ["--start-time={}".format(time_end - ADJUST_AUDIO_REPLAY_TIME), "--stop-time={}".format(time_end)]
else:
args += ["--start={}".format(time_end - ADJUST_AUDIO_REPLAY_TIME), "--end={}".format(time_end)]
config = mw.addonManager.getConfig(__name__)
af_d = float(config["audio fade in/out"])
if (path.endswith(".mp3") and not isPrev and not isNext) or state != None:
if VLC_DIR:
pass
else:
if af_d:
args += ["--af=afade=t=out:st=%s:d=%s" % (time_end - af_d, af_d)]
else:
if VLC_DIR:
pass
else:
if not (state == None and isEnd == False):
if af_d:
args += ["--af=afade=t=out:st=%s:d=%s" % (time_end - af_d, af_d)]
if "Path" in fields and fields["Path"] != '':
fullpath = fields["Path"]
else:
try:
m = re.match(r"^(.*?)_(\d+\.\d\d\.\d\d\.\d+)-(\d+\.\d\d\.\d\d\.\d+).*$", fields["Id"])
video_id = m.group(1)
fullpath = media.get_path_in_media_db(video_id, ask=False)
except:
fullpath = path
if path is not None and os.path.exists(path) and isEnd == True and not any([state, isPrev, isNext]):
fullpath = path
args = list(default_args)
if not os.path.exists(fullpath):
if fullpath.endswith('.mp4') or fullpath.endswith('.webm'):
tooltip("video can't be found")
else:
tooltip("audio can't be found")
return
aid = "auto"
if fullpath != path:
try:
m = re.match(r"^(.*?)_(\d+\.\d\d\.\d\d\.\d+)-(\d+\.\d\d\.\d\d\.\d+).*$", fields["Id"])
video_id = m.group(1)
aid = media.getAudioId(video_id)
except:
pass
if VLC_DIR:
cmd = [VLC_DIR] + args + [os.path.normpath(fullpath)]
else:
if aid != "auto":
args += ["--aid={}".format(aid)]
else:
alang = config["preferred languages for audio"]
if alang != "":
args += ["--alang={}".format(alang)]
if is_mac and os.path.exists(IINA_DIR):
args = [o.replace("--", "--mpv-") for o in args]
cmd = [IINA_DIR] + args + [fullpath]
else:
cmd = [mpv_executable] + args + [fullpath]
if p != None and p.poll() is None:
p.kill()
if with_bundled_libs:
p = subprocess.Popen(cmd, cwd=mw.col.media.dir())
return
with no_bundled_libs():
p = subprocess.Popen(cmd, cwd=mw.col.media.dir())
def queueExternalAV(self, path):
if mw.state == "review" and mw.reviewer.card != None and (mw.reviewer.card.note_type()["name"] == "movies2anki (add-on)" or mw.reviewer.card.note_type()["name"].startswith("movies2anki - subs2srs")):
queueExternal(path)
else:
_player(path)
def queueExternal(path):
global p, _player
if mw.state == "review" and mw.reviewer.card != None and (mw.reviewer.card.note_type()["name"] == "movies2anki (add-on)" or mw.reviewer.card.note_type()["name"].startswith("movies2anki - subs2srs")):
# if mw.reviewer.state == "answer" and path.endswith(".mp4"):
# return
try:
clearExternalQueue()
oldcwd = os.getcwd()
os.chdir(mw.col.media.dir())
ret = playVideoClip(path.filename if av_player else path)
os.chdir(oldcwd)
if ret == False:
_player(path)
except OSError:
return showWarning(r"""<p>Please install <a href='https://mpv.io'>mpv</a>.</p>
On Windows download mpv and either update PATH environment variable or put mpv.exe in Anki installation folder (C:\Program Files\Anki).""", parent=mw)
else:
_player(path)
def _stopPlayer():
global p
if p != None and p.poll() is None:
p.kill()
addHook("unloadProfile", _stopPlayer)
atexit.register(_stopPlayer)
def clearExternalQueue():
global _queueEraser
_stopPlayer()
_queueEraser()
_player = sound._player
sound._player = queueExternal
try:
import types
from aqt.sound import av_player # Anki 2.1.20+
from anki.sound import SoundOrVideoTag
_player = av_player._play
av_player._play = types.MethodType(queueExternalAV, av_player)
except Exception as e:
av_player = None
pass
_queueEraser = sound._queueEraser
sound._queueEraser = clearExternalQueue
def adjustAudio(state, shift=None):
if mw.state == "review" and mw.reviewer.card != None and (mw.reviewer.card.note_type()["name"] == "movies2anki (add-on)" or mw.reviewer.card.note_type()["name"].startswith("movies2anki - subs2srs")):
try:
clearExternalQueue()
oldcwd = os.getcwd()
os.chdir(mw.col.media.dir())
playVideoClip(state=state, shift=shift)
os.chdir(oldcwd)
except OSError:
return showWarning(r"""<p>Please install <a href='https://mpv.io'>mpv</a>.</p>
On Windows download mpv and either update PATH environment variable or put mpv.exe in Anki installation folder (C:\Program Files\Anki).""", parent=mw)
def selectVideoPlayer():
global VLC_DIR
try:
if is_mac and os.path.exists(IINA_DIR):
return
if mpv_executable is None:
raise OSError()
if with_bundled_libs:
p = subprocess.Popen([mpv_executable, "--version"], startupinfo=info)
else:
with no_bundled_libs():
p = subprocess.Popen([mpv_executable, "--version"], startupinfo=info)
if p != None and p.poll() is None:
p.kill()
except OSError:
if VLC_DIR != "":
return
if is_win:
VLC_DIR = r"C:\Program Files\VideoLAN\VLC\vlc.exe"
if os.path.exists(VLC_DIR):
return
VLC_DIR = r"C:\Program Files (x86)\VideoLAN\VLC\vlc.exe"
if os.path.exists(VLC_DIR):
return
elif is_mac:
VLC_DIR = r"/Applications/VLC.app/Contents/MacOS/VLC"
if os.path.exists(VLC_DIR):
return
VLC_DIR = ""
return showWarning(r"""<p>Neither mpv nor VLC were found.</p>
<p>Please install <a href='https://mpv.io'>mpv</a>.</p>
On Windows download mpv and either update PATH environment variable or put mpv.exe in Anki installation folder (C:\Program Files\Anki).""", parent=mw)
addHook("profileLoaded", selectVideoPlayer)
def addShortcutKeys(state, shortcuts):
if state != "review":
return
shortcuts.extend([
(",", lambda: adjustAudio("start", ADJUST_AUDIO_STEP)),
(".", lambda: adjustAudio("start", -1.0 * ADJUST_AUDIO_STEP)),
("Shift+,", lambda: adjustAudio("end", -1.0 * ADJUST_AUDIO_STEP)),
("Shift+.", lambda: adjustAudio("end", ADJUST_AUDIO_STEP)),
# ("Ctrl+Shift+,", lambda: adjustAudio("start reset")),
# ("Ctrl+Shift+.", lambda: adjustAudio("end reset")),
("Ctrl+R", replayVideo),
("Shift+R", lambda: replayVideo(isEnd=False)),
("[", lambda: replayVideo(isPrev=True)),
("]", lambda: replayVideo(isNext=True)),
("Shift+[", lambda: joinCard(isPrev=True)),
("Shift+]", lambda: joinCard(isNext=True)),
("б", lambda: adjustAudio("start", ADJUST_AUDIO_STEP)),
("ю", lambda: adjustAudio("start", -1.0 * ADJUST_AUDIO_STEP)),
("Shift+Б", lambda: adjustAudio("end", -1.0 * ADJUST_AUDIO_STEP)),
("Shift+Ю", lambda: adjustAudio("end", ADJUST_AUDIO_STEP)),
("х", lambda: replayVideo(isPrev=True)),
("ъ", lambda: replayVideo(isNext=True)),
("Shift+Х", lambda: joinCard(isPrev=True)),
("Shift+Ъ", lambda: joinCard(isNext=True)),
])
gui_hooks.state_shortcuts_will_change.append(addShortcutKeys)
def replayVideo(isEnd=True, isPrev=False, isNext=False):
if mw.state == "review" and mw.reviewer.card != None and (mw.reviewer.card.note_type()["name"] == "movies2anki (add-on)" or mw.reviewer.card.note_type()["name"].startswith("movies2anki - subs2srs")):
clearExternalQueue()
oldcwd = os.getcwd()
os.chdir(mw.col.media.dir())
playVideoClip(isEnd=isEnd, isPrev=isPrev, isNext=isNext)
os.chdir(oldcwd)
def joinCard(isPrev=False, isNext=False):
config = mw.addonManager.getConfig(__name__)
if mw.state == "review" and mw.reviewer.card != None and (mw.reviewer.card.note_type()["name"] == "movies2anki (add-on)" or mw.reviewer.card.note_type()["name"].startswith("movies2anki - subs2srs")):
audio_filename = mw.reviewer.card.note()["Audio"]
m = re.search(r'\[sound:(.+?)\]', audio_filename)
if m:
audio_filename = m.group(1)
audio_filename = audio_filename.replace('[sound:', '')
audio_filename = audio_filename.replace(']', '')
m = re.match(r"^(.*?)_(\d+\.\d\d\.\d\d\.\d+)-(\d+\.\d\d\.\d\d\.\d+).*$", audio_filename)
card_prefix, time_start, time_end = m.groups()
time_start = timeToSeconds(time_start)
time_end = timeToSeconds(time_end)
cards = sorted(mw.col.findCards('"Id:{}_*"'.format(card_prefix), order=True))
card_idx = cards.index(mw.reviewer.card.id)
prev_card_idx = card_idx - 1 if card_idx - 1 > 0 else 0
next_card_idx = card_idx + 1
if next_card_idx >= len(cards):
next_card_idx = len(cards) - 1
if (isPrev and mw.col.getCard(cards[prev_card_idx]).id == mw.reviewer.card.id) or \
(isNext and mw.col.getCard(cards[next_card_idx]).id == mw.reviewer.card.id):
tooltip("Nothing to do.")
return
curr_card = mw.col.getCard(cards[card_idx]).note()
prev_card = mw.col.getCard(cards[prev_card_idx]).note()
next_card = mw.col.getCard(cards[next_card_idx]).note()
prev_card_path = ''
curr_card_path = ''
next_card_path = ''
if "Path" in prev_card and prev_card["Path"] != "":
prev_card_path = prev_card["Path"]
else:
try:
m = re.match(r"^(.*?)_(\d+\.\d\d\.\d\d\.\d+)-(\d+\.\d\d\.\d\d\.\d+).*$", prev_card['Id'])
prev_card_path = media.get_path_in_media_db(m.group(1))
except:
return
if "Path" in curr_card and curr_card["Path"] != "":
curr_card_path = curr_card["Path"]
else:
try:
m = re.match(r"^(.*?)_(\d+\.\d\d\.\d\d\.\d+)-(\d+\.\d\d\.\d\d\.\d+).*$", curr_card['Id'])
curr_card_path = media.get_path_in_media_db(m.group(1))
except:
return
if "Path" in next_card and next_card["Path"] != "":
next_card_path = next_card["Path"]
else:
try:
m = re.match(r"^(.*?)_(\d+\.\d\d\.\d\d\.\d+)-(\d+\.\d\d\.\d\d\.\d+).*$", next_card['Id'])
next_card_path = media.get_path_in_media_db(m.group(1))
except:
return
if (isPrev and prev_card_path != curr_card_path) or (isNext and curr_card_path != next_card_path):
showInfo("Cards can't be joined due to the difference in Path.")
return
curr_card_audio = curr_card["Audio"]
prev_card_audio = prev_card["Audio"]
next_card_audio = next_card["Audio"]
m = re.match(r"^.*?_(\d+\.\d\d\.\d\d\.\d+)-(\d+\.\d\d\.\d\d\.\d+).*$", curr_card_audio)
curr_time_start, curr_time_end = m.groups()
curr_time_start = timeToSeconds(curr_time_start)
curr_time_end = timeToSeconds(curr_time_end)
m = re.match(r"^.*?_(\d+\.\d\d\.\d\d\.\d+)-(\d+\.\d\d\.\d\d\.\d+).*$", prev_card_audio)
prev_time_start, prev_time_end = m.groups()
prev_time_start = timeToSeconds(prev_time_start)
prev_time_end = timeToSeconds(prev_time_end)
m = re.match(r"^.*?_(\d+\.\d\d\.\d\d\.\d+)-(\d+\.\d\d\.\d\d\.\d+).*$", next_card_audio)
next_time_start, next_time_end = m.groups()
next_time_start = timeToSeconds(next_time_start)
next_time_end = timeToSeconds(next_time_end)
if isPrev:
time_start = prev_time_start
if isNext:
time_end = next_time_end
config = mw.addonManager.getConfig(__name__)
c = mw.reviewer.card.note()
for name, val in c.items():
if name == "Id":
c[name] = "%s_%s-%s" % (card_prefix, secondsToTime(time_start), secondsToTime(time_end))
elif name == "Audio":
c[name] = "%s_%s-%s.mp3" % (card_prefix, secondsToTime(time_start), secondsToTime(time_end))
elif name == "Video":
c[name] = "%s_%s-%s.%s" % (card_prefix, secondsToTime(time_start), secondsToTime(time_end), config['video extension'])
elif name == "Path":
pass
elif name == "Audio Sound":
c["Audio Sound"] = ""
elif name == "Video Sound":
c["Video Sound"] = ""
elif name == "Snapshot":
pass
else:
if isPrev:
c[name] = prev_card[name] + "<br>" + c[name]
else:
c[name] = c[name] + "<br>" + next_card[name]
mw.checkpoint(_("Delete"))
c.flush()
if isPrev:
cd = prev_card
else:
cd = next_card
cnt = len(cd.cards())
mw.col.remNotes([cd.id])
mw.reset()
tooltip(ngettext(
"Notes joined and %d card deleted.",
"Notes joined and %d cards deleted.",
cnt) % cnt)
def join_and_add_double_quotes(cmd):
return '[' + ' '.join(['"{}"'.format(s) if ' ' in s else s for s in cmd]) + ']'
class MediaWorker(QThread):
updateProgress = pyqtSignal(int)
updateProgressText = pyqtSignal(str)
updateNote = pyqtSignal(str, str, str)
jobFinished = pyqtSignal(float)
def __init__(self, data, map_ids):
QThread.__init__(self)
self.data = data
self.canceled = False
self.fp = None
self.map_ids = map_ids
if os.environ.get("ADDON_DEBUG"):
logger.setLevel(logging.DEBUG)
def cancel(self):
self.canceled = True
if self.fp != None:
self.fp.terminate()
def run(self):
job_start = time.time()
mp3gain_executable = find_executable("mp3gain")
logger.debug('mpv_executable: {}'.format(mpv_executable))
config = mw.addonManager.getConfig(__name__)
for idx, note in enumerate(self.data):
if self.canceled:
break
self.updateProgress.emit((idx * 1.0 / len(self.data)) * 100)
fld = note["Audio"]
time_start, time_end = re.match(r"^.*?_(\d+\.\d\d\.\d\d\.\d+)-(\d+\.\d\d\.\d\d\.\d+).*$", fld).groups()
time_start_seconds = timeToSeconds(time_start)
time_end_seconds = timeToSeconds(time_end)
if time_start_seconds == time_end_seconds:
continue
ss = secondsToTime(timeToSeconds(time_start), sep=":")
se = secondsToTime(timeToSeconds(time_end), sep=":")
t = timeToSeconds(time_end) - timeToSeconds(time_start)
if config["audio fade in/out"]:
af_d = float(config["audio fade in/out"])
af_st = 0
af_to = t - af_d
default_af_params = "afade=t=in:st={:.3f}:d={:.3f},afade=t=out:st={:.3f}:d={:.3f}".format(af_st, af_d, af_to, af_d)
else:
default_af_params = ""
if "Path" in note and note["Path"] != "":
note_video_path = note["Path"]
else:
try:
m = re.match(r"^(.*?)_(\d+\.\d\d\.\d\d\.\d+)-(\d+\.\d\d\.\d\d\.\d+).*$", note["Id"])
video_id = m.group(1)
note_video_path = media.get_path_in_media_db(video_id)
except:
continue
audio_id = self.map_ids[note_video_path]
video_width = config["video width"]
video_height = config["video height"]
video_source = os.path.splitext(os.path.basename(note_video_path))[0]
self.updateProgressText.emit(video_source + " " + ss)
audio_filename = note["Audio"]
m = re.search(r'\[sound:(.+?)\]', audio_filename)
if m:
audio_filename = m.group(1)
audio_filename = audio_filename.replace('[sound:', '')
audio_filename = audio_filename.replace(']', '')
if os.path.exists(os.path.join(mw.col.media.dir(), audio_filename)):
if "Audio Sound" in note:
if '[sound:' not in note["Audio Sound"]:
self.updateNote.emit(str(note.id), "Audio Sound", "[sound:%s]" % audio_filename)
elif '[sound:' not in note["Audio"]:
self.updateNote.emit(str(note.id), "Audio", "[sound:%s]" % audio_filename)
af_params = default_af_params
if NORMALIZE_AUDIO and not (NORMALIZE_AUDIO_WITH_MP3GAIN and mp3gain_executable):
cmd = [ffmpeg_executable, "-ss", ss, "-i", note_video_path, "-t", str(t), "-af", "loudnorm=%s:print_format=json" % NORMALIZE_AUDIO_FILTER, "-f", "null", "-"]
logger.debug('normalize_audio: {}'.format('Started'))
logger.debug('normalize_audio: {}'.format(join_and_add_double_quotes(cmd)))
with no_bundled_libs():
output = check_output(cmd, startupinfo=info, encoding='utf-8')
logger.debug('normalize_audio: {}'.format('Finished'))
# https://github.com/slhck/ffmpeg-normalize/blob/5fe6b3df5f4b36b398fa08c11a9001b1e67cec10/ffmpeg_normalize/_streams.py#L171
output_lines = [line.strip() for line in output.split('\n')]
loudnorm_start = False
loudnorm_end = False
for index, line in enumerate(output_lines):
if line.startswith('[Parsed_loudnorm'):
loudnorm_start = index + 1
continue
if loudnorm_start and line.startswith('}'):
loudnorm_end = index + 1
break
stats = json.loads('\n'.join(output_lines[loudnorm_start:loudnorm_end]))
nf_params = "loudnorm={}:measured_I={}:measured_LRA={}:measured_TP={}:measured_thresh={}:offset={}:linear=true".format(NORMALIZE_AUDIO_FILTER, stats["input_i"], stats["input_lra"], stats["input_tp"], stats["input_thresh"], stats["target_offset"])
if af_params:
af_params = "%s,%s" % (nf_params, af_params)
else:
af_params = nf_params
if ("Audio Sound" in note and note["Audio Sound"] == "") or not os.path.exists(os.path.join(mw.col.media.dir(), audio_filename)):
self.fp = None
audio_temp_filepath = os.path.join(tmpdir(), audio_filename)
if ffmpeg_executable:
cmd = [ffmpeg_executable, "-y", "-ss", ss, "-i", note_video_path, "-loglevel", "quiet", "-t", "{:.3f}".format(t)]
if af_params:
cmd += ["-af", af_params]
cmd += ["-sn"]
cmd += ["-map_metadata", "-1"]
if audio_filename.endswith('.mp3'):
cmd += ["-c:a", "libmp3lame"]
cmd += ["-map", "0:a:{}".format(audio_id-1)]
cmd += [audio_temp_filepath]
else:
cmd = [mpv_executable, note_video_path]
# cmd += ["--include=%s" % self.mpvConf]
cmd += ["--start=%s" % ss, "--length=%s" % "{:.3f}".format(t)]
cmd += ["--aid=%d" % (audio_id)]
cmd += ["--video=no"]
cmd += ["--no-ocopy-metadata"]
cmd += ["--af=afade=t=in:st={:.3f}:d={:.3f},afade=t=out:st={:.3f}:d={:.3f}".format(time_start_seconds, af_d, time_end_seconds - af_d, af_d)]
cmd += ["--o=%s" % audio_temp_filepath]
logger.debug('export_audio: {}'.format('Started'))
logger.debug('export_audio: {}'.format(join_and_add_double_quotes(cmd)))
if with_bundled_libs:
self.fp = subprocess.Popen(cmd, startupinfo=info, cwd=mw.col.media.dir())
self.fp.wait()
else:
with no_bundled_libs():
self.fp = subprocess.Popen(cmd, startupinfo=info, cwd=mw.col.media.dir())
self.fp.wait()
logger.debug('export_audio: {}'.format('Finished'))
if NORMALIZE_AUDIO and NORMALIZE_AUDIO_WITH_MP3GAIN and mp3gain_executable:
cmd = [mp3gain_executable, "/f", "/q", "/r", "/k", audio_temp_filepath]
with no_bundled_libs():
self.fp = subprocess.Popen(cmd, startupinfo=info, cwd=mw.col.media.dir())
self.fp.wait()
if self.canceled:
break
if os.path.exists(audio_temp_filepath):
with open(audio_temp_filepath, "rb") as file:
fdata = file.read()
mw.col.media.write_data(audio_filename, fdata)
if "Audio Sound" in note:
self.updateNote.emit(str(note.id), "Audio Sound", "[sound:%s]" % audio_filename)
else:
self.updateNote.emit(str(note.id), "Audio", "[sound:%s]" % audio_filename)
video_filename = ""
if "Video" in note:
video_filename = note["Video"]
m = re.search(r'\[sound:(.+?)\]', video_filename)
if m:
video_filename = m.group(1)
video_filename = video_filename.replace('[sound:', '')
video_filename = video_filename.replace(']', '')
if os.path.exists(os.path.join(mw.col.media.dir(), video_filename)):
if "Video Sound" in note:
if '[sound:' not in note["Video Sound"]:
self.updateNote.emit(str(note.id), "Video Sound", "[sound:%s]" % video_filename)
elif '[sound:' not in note["Video"]:
self.updateNote.emit(str(note.id), "Video", "[sound:%s]" % video_filename)
if ("Video Sound" in note and (note["Video Sound"] == "") or (video_filename != "" and not os.path.exists(os.path.join(mw.col.media.dir(), video_filename)))):
self.fp = None
video_temp_filepath = os.path.join(tmpdir(), video_filename)
if ffmpeg_executable:
cmd = [ffmpeg_executable, "-y", "-ss", ss, "-i", note_video_path, "-loglevel", "quiet", "-t", "{:.3f}".format(t)]
if af_params:
cmd += ["-af", af_params]
cmd += ["-map", "0:v:0", "-map", "0:a:{}".format(audio_id-1), "-ac", "2", "-vf", "scale='min(%s,iw)':'min(%s,ih)',setsar=1" % (video_width, video_height)]
cmd += ["-pix_fmt", "yuv420p"]
cmd += ["-sn"]
cmd += ["-map_metadata", "-1"]
if video_filename.endswith('.webm'):
cmd += config["video encoding settings (webm)"].split()
else:
cmd += ["-c:v", "libx264"]
cmd += ["-profile:v", "main", "-level:v", "3.1"]
cmd += ['-movflags', '+faststart']
cmd += [video_temp_filepath]
else:
cmd = [mpv_executable, note_video_path]
# cmd += ["--include=%s" % self.mpvConf]
cmd += ["--start=%s" % ss, "--length=%s" % "{:.3f}".format(t)]
cmd += ["--sub=no"]
cmd += ["--no-ocopy-metadata"]
cmd += ["--aid=%d" % (audio_id)]
cmd += ["--af=afade=t=in:st={:.3f}:d={:.3f},afade=t=out:st={:.3f}:d={:.3f}".format(time_start_seconds, af_d, time_end_seconds - af_d, af_d)]
cmd += ["--vf-add=lavfi=[scale='min(%s,iw)':'min(%s,ih)',setsar=1]" % (video_width, video_height)]
if video_filename.endswith('.webm'):
cmd += ["--ovc=libvpx-vp9"]
cmd += ["--ovcopts=b=1400K,threads=4,crf=23,qmin=0,qmax=36,speed=2"]
else:
cmd += ["--ovc=libx264"]
cmd += ["--ovcopts=profile=main,level=31"]
cmd += ["--vf-add=format=yuv420p"]
cmd += ["--oac=aac"]
cmd += ["--ofopts=movflags=+faststart"]
cmd += ["--o=%s" % video_temp_filepath]
logger.debug('export_video: {}'.format('Started'))
logger.debug('export_video: {}'.format(join_and_add_double_quotes(cmd)))
if with_bundled_libs:
self.fp = subprocess.Popen(cmd, startupinfo=info, cwd=mw.col.media.dir())
self.fp.wait()
else:
with no_bundled_libs():
self.fp = subprocess.Popen(cmd, startupinfo=info, cwd=mw.col.media.dir())
self.fp.wait()
logger.debug('export_video: {}'.format('Finished'))
retcode = self.fp.returncode
logger.debug('return code: {}'.format(retcode))
if retcode != 0 and not self.canceled:
cmd_debug = ' '.join(['"' + c + '"' for c in cmd])
cmd_debug = cmd_debug.replace(' "-loglevel" "quiet" ', ' ')
cmd_debug = [cmd_debug]
raise CalledProcessError(retcode, cmd_debug)
if self.canceled:
break
if os.path.exists(video_temp_filepath):
with open(video_temp_filepath, "rb") as file:
fdata = file.read()
mw.col.media.write_data(video_filename, fdata)
if "Video Sound" in note:
self.updateNote.emit(str(note.id), "Video Sound", "[sound:%s]" % video_filename)
else:
self.updateNote.emit(str(note.id), "Video", "[sound:%s]" % video_filename)
job_end = time.time()
time_diff = (job_end - job_start)
if not self.canceled:
self.updateProgress.emit(100)
self.jobFinished.emit(time_diff)
def cancelProgressDialog():
global is_cancel
is_cancel = True
if hasattr(mw, 'worker'):
mw.worker.cancel()
del mw.worker
if hasattr(mw, 'progressDialog'):
mw.progressDialog.cancel()
del mw.progressDialog
gui_hooks.profile_will_close.append(cancelProgressDialog)
def setProgress(progress):
logger.debug('progress: {:.2f}%'.format(progress))
mw.progressDialog.setValue(progress)
def setProgressText(text):
logger.debug('file: {}'.format(text))
mw.progressDialog.setLabelText(text)
def saveNote(nid, fld, val):
note = mw.col.get_note(int(nid))
note[fld] = val
note.flush()
def finishProgressDialog(time_diff, errors, parent=mw):
mw.progressDialog.done(0)
minutes = int(time_diff / 60)
seconds = int(time_diff % 60)
message = "Processing completed in %s minutes %s seconds." % (minutes, seconds)
if not errors:
QMessageBox.information(parent, "movies2anki", message)
else:
msg = "The following notes were skipped because the Id field doesn't match the regular expression: ^(.*?)_(\d+\.\d\d\.\d\d\.\d+)-(\d+\.\d\d\.\d\d\.\d+).*$"
msg += "\n"
msg += "\n"
msg += ' or '.join(['nid:{}'.format(str(e)) for e in errors])
showText(message + '\n\n' + msg, parent=mw)
class AudioInfo(QDialog):
def __init__(self, map_ids, map_data, parent=None):
super(AudioInfo, self).__init__(parent)
self.map_data = map_data
self.map_ids = map_ids
self.initUI()
def initUI(self):
okButton = QPushButton("OK")
okButton.clicked.connect(self.ok)
vbox = QVBoxLayout()
hbox = QHBoxLayout()
grid = QGridLayout()
grid.setSpacing(10)
# grid.addWidget(reviewEdit, 1, 1, 1, 3)
hbox.addStretch(1)
hbox.addWidget(okButton)
for idx, video_path in enumerate(self.map_data):
video_filename = os.path.basename(video_path)
audio_tracks = self.map_data[video_path]
i_selected = 0
btn_label = QLabel(video_filename)
btn_cbox = QComboBox()
# btn_cbox.setSizeAdjustPolicy(QComboBox.SizeAdjustPolicy.AdjustToContents)
for i in audio_tracks:
title = audio_tracks[i]['title']
if title == '(unavailable)':
title = ''
lang = audio_tracks[i]['lang']
if not lang:
lang = 'und'
if audio_tracks[i]['selected'] == 'yes':
self.map_ids[video_path] = i
i_selected = i - 1
item_title = '{}: {}'.format(i, lang)
if title:
item_title += ' ({})'.format(title)
btn_cbox.addItem(item_title)
btn_cbox.setCurrentIndex(i_selected)
btn_cbox.currentIndexChanged.connect(lambda x, vp=video_path: self.setAudioStream(vp, x))
grid.addWidget(btn_label, idx + 1, 1)
grid.addWidget(btn_cbox, idx + 1, 2)
grid.setColumnStretch(1,1)
grid.setRowMinimumHeight(len(self.map_data)+1, 30)
vbox.addLayout(grid)
vbox.addLayout(hbox)
self.setLayout(vbox)
self.setWindowTitle('[movies2anki] Select Audio Streams')
self.setModal(True)
# self.setMinimumSize(400, 300)
self.adjustSize()
self.setMinimumWidth(450)
def setAudioStream(self, video_path, i):
self.map_ids[video_path] = i+1
def ok(self):
self.done(1)
def cancel(self):
self.done(0)
def on_play_filter(text, field, filter, context: TemplateRenderContext):
if filter != "play":
return text
if '[sound:' in text:
return text
text = text.strip()
if text == '':
return text
return '[sound:{}]'.format(text)
hooks.field_filter.append(on_play_filter)
ADDON_MODELS = [
"movies2anki (add-on)",
"movies2anki - subs2srs (image)",
"movies2anki - subs2srs (video)",
"movies2anki - subs2srs (audio)"
]
ADDON_MODELS += ["movies2anki - subs2srs"] # legacy model name
def get_addon_nids():
nids = []