-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathtboplayer.py
2304 lines (1916 loc) · 95.5 KB
/
tboplayer.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
"""
A GUI interface using jbaiter's pyomxplayer to control omxplayer
INSTALLATION
***
* TBOPlayer requires avconv, youtube-dl, and also the python libraries requests, gobject2, gtk2, pexpect and ptyprocess to be installed in order to work.
*
* -------------------------
*
* To install TBOPlayer and all required libraries, you can simply use the following command from tboplayer directory:
*
* chmod +x setup.sh
* ./setup.sh
*
* -------------------------
*
* See README.md file for more details on installation
*
OPERATION
Menus
====
Track - Track - add tracks (for selecting multiple tracks, hold ctrl when clicking) or directories or URLs, edit or remove tracks from the current playlist
Playlist - save the current playlist or open a saved one or load youtube playlist
OMX - display the track information for the last played track (needs to be enabled in options)
Options -
Audio Output - play sound to hdmi or local output, auto does not send an audio option to omxplayer.
Mode - play the Single selected track, Repeat the single track, rotate around the Playlist starting from the selected track, randomly play a track from the Playlist.
Initial directory for tracks - where Add Track starts looking.
Initial directory for playlists - where Open Playlist starts looking
Enable subtitles
OMXPlayer location - path to omxplayer binary
OMXplayer options - add your own (no validation so be careful)
Download from Youtube - defines whether to download video and audio or audio only from Youtube (other online video services will always be asked for "video and audio")
Download actual media URL [when] - defines when to extract the actual media from the given URL, either upon adding the URL or when playing it
Youtube video quality - lets you choose between "small", "medium" and "high" qualities (Youtube only feature)
youtube-dl location - path to youtube-dl binary
Start/End track paused - Pauses the track both in the beginning and in the end of the track
Autoplay on start up - If TBOPlayer has just been opened and has some file in the playlist, automatically satrt playing the first file in the list
Forbid windowed mode - if enabled will make videos always show in full screen, disabling the video window mode and video progress bar - useful if you're using tboplayer through a remote desktop
Debug - prints some debug text to the command line
* See README.md file for more details on operation in the OPERATION section
TODO (maybe)
--------
sort out black border around some videos
gapless playback, by running two instances of pyomxplayer
read and write m3u and pls playlists
PROBLEMS
---------------
I think I might have fixed this but two tracks may play at the same time if you use the controls quickly, you may need to SSH in form another computer and use top -upi and k to kill the omxplayer.bin
"""
from options import *
from ytdl import *
from omxplayer import *
from playlist import *
from dnd import *
from dbusinterface import *
from htmlparsers import *
from scrolledframe import *
from debugging import *
from threading import Thread
from time import sleep
from pprint import ( pformat, pprint )
from random import randint
from math import log10
from magic import from_file
from youtubesearchpython import SearchVideos
import gettext
import json
import re
import string
import sys
from Tkinter import *
from ttk import ( Progressbar, Style, Sizegrip )
from gtk.gdk import ( screen_width, screen_height )
import Tkinter as tk
import tkFileDialog
import tkMessageBox
import tkSimpleDialog
import tkFont
options = Options()
try:
gettext.translation('tboplayer', localedir=sys.path[0] + '/locale', languages=[options.lang]).install()
except:
_ = lambda x:x
#**************************
# TBOPLAYER CLASS
# *************************
class TBOPlayer:
# regular expression patterns
RE_RESOLUTION = re.compile("^([0-9]+)x([0-9]+)$")
RE_COORDS = re.compile("^([\+-][0-9]+)([\+-][0-9]+)$")
_SUPPORTED_MIME_TYPES = ('video/x-msvideo', 'video/quicktime', 'video/mp4', 'video/x-flv', 'video/x-matroska', 'audio/x-matroska',
'video/3gpp', 'audio/x-aac', 'video/h264', 'video/h263', 'video/x-m4v', 'audio/midi',
'audio/mid', 'audio/vnd.qcelp', 'audio/mpeg', 'video/mpeg', 'audio/rmf', 'audio/x-rmf',
'audio/mp4', 'video/mj2', 'audio/x-tta', 'audio/tta', 'application/mp4', 'audio/ogg',
'video/ogg', 'audio/wav', 'audio/wave' ,'audio/x-pn-aiff', 'audio/x-pn-wav', 'audio/x-wav',
'audio/flac', 'audio/x-flac', 'video/h261', 'application/adrift', 'video/3gpp2', 'video/x-f4v',
'application/ogg', 'audio/mpeg3', 'audio/x-mpeg-3', 'audio/x-gsm', 'audio/x-mpeg', 'audio/mod',
'audio/x-mod', 'video/x-ms-asf', 'audio/x-pn-realaudio', 'audio/x-realaudio' ,'video/vnd.rn-realvideo', 'video/fli',
'video/x-fli', 'audio/x-ms-wmv', 'video/avi', 'video/msvideo', 'video/m4v', 'audio/x-ms-wma',
'application/octet-stream', 'application/x-url', 'text/url', 'text/x-url', 'application/vnd.rn-realmedia', 'video/webm',
'audio/webm', 'audio/vnd.rn-realaudio', 'audio/x-pn-realaudio', 'audio/x-realaudio', 'audio/aiff', 'audio/x-aiff')
YTDL_MSGS = (_("Problem retreiving content. Do you have up-to-date dependencies?"),
_("Problem retreiving content. Content may be copyrighted or the link may be invalid."),
_("Problem retrieving content. Content may have been truncated."))
YTDL_WAIT_TAG = "[" + _("wait") + "]"
progress_bar_total_steps = 200
progress_bar_step_rate = 0
volume_max = 60
volume_normal_step = 40
volume_critical_step = 49
# ***************************************
# # PLAYING STATE MACHINE
# ***************************************
"""self. play_state controls the playing sequence, it has the following values.
I am not entirely sure the startign and ending states are required.
- omx_closed - the omx process is not running, omx process can be initiated
- omx_starting - omx process is running but is not yet able to receive commands
- omx_playing - playing a track, commands can be sent
- omx_ending - omx is doing its termination, commands cannot be sent
"""
def init_play_state_machine(self):
self._OMX_CLOSED = "omx_closed"
self._OMX_STARTING = "omx_starting"
self._OMX_PLAYING = "omx_playing"
self._OMX_ENDING = "omx_ending"
self._YTDL_CLOSED = "ytdl_closed"
self._YTDL_STARTING = "ytdl_starting"
self._YTDL_WORKING = "ytdl_working"
self._YTDL_ENDING = "ytdl_ending"
# what to do next signals
self.break_required_signal=False # signal to break out of Repeat or Playlist loop
self.play_previous_track_signal = False
self.play_next_track_signal = False
# playing a track signals
self.stop_required_signal=False
self.play_state=self._OMX_CLOSED
self.quit_sent_signal = False # signal that q has been sent
self.paused=False
# playing a track signals
self.ytdl_state=self._YTDL_CLOSED
self.quit_ytdl_sent_signal = False # signal that q has been sent
# whether omxplayer dbus is connected
self.dbus_connected = False
self.start_track_index = None
self.omx = None
self.autolyrics = None
# kick off the state machine by playing a track
def play(self):
#initialise all the state machine variables
if self.play_state==self._OMX_CLOSED and self.playlist.track_is_selected():
self.ytdl.reset_subtitle_attributes()
self.iteration = 0 # for debugging
self.paused = False
self.stop_required_signal=False # signal that user has pressed stop
self.quit_sent_signal = False # signal that q has been sent
self.playing_location = self.playlist.selected_track_location
self.play_state=self._OMX_STARTING
self.dbus_connected = False
self._cued = False
#play the selelected track
index = self.playlist.selected_track_index()
self.display_selected_track(index)
self.start_omx(self.playlist.selected_track_location)
self.play_state_machine()
self.set_play_button_state(1)
def play_state_machine(self):
# self.monitor ("******Iteration: " + str(self.iteration))
self.iteration +=1
if self.play_state == self._OMX_CLOSED:
self.monitor(" State machine: " + self.play_state)
self.what_next()
return
elif self.play_state == self._OMX_STARTING:
self.monitor(" State machine: " + self.play_state)
# if omxplayer is playing the track change to play state
if self.omx and self.omx.start_play_signal==True:
self.monitor(" <start play signal received from omx")
self.omx.start_play_signal=False
self.play_state=self._OMX_PLAYING
self.monitor(" State machine: omx_playing started")
self.dbus_connected = self.omx.init_dbus_link()
self.show_progress_bar()
self.set_progress_bar()
if self.media_is_video() and not self.options.forbid_windowed_mode:
self.create_vprogress_bar()
if self.dbus_connected:
self.omx.set_aspect_mode(OMXPlayer.AM_LETTERBOX)
if self.options.cue_track_mode:
self.toggle_pause()
if self.options.find_lyrics:
self.grab_lyrics()
else:
if self.ytdl_state == self._YTDL_CLOSED:
self.play_state=self._OMX_CLOSED
self.monitor(" youtube-dl failed, stopping omx state machine")
else:
self.monitor(" OMXPlayer did not start yet.")
self.root.after(350, self.play_state_machine)
elif self.play_state == self._OMX_PLAYING :
# service any queued stop signals
if self.stop_required_signal==True :#or (self.omx and (self.omx.end_play_signal or self.omx.failed_play_signal)):
self.monitor(" Service stop required signal")
self.stop_omx()
self.stop_required_signal=False
else:
# quit command has been sent or omxplayer reports it is terminating so change to ending state
if self.quit_sent_signal == True or self.omx.end_play_signal== True or not self.omx.is_running():
if self.quit_sent_signal:
self.monitor(" quit sent signal received")
self.quit_sent_signal = False
if self.omx.end_play_signal:
self.monitor(" <end play signal received")
self.monitor(" <end detected at: " + str(self.omx.position))
self.play_state =self._OMX_ENDING
self.reset_progress_bar()
if self.media_is_video():
self.destroy_vprogress_bar()
self.do_playing()
self.root.after(350, self.play_state_machine)
elif self.play_state == self._OMX_ENDING:
self.monitor(" State machine: " + self.play_state)
# if spawned process has closed can change to closed state
self.monitor (" State machine : is omx process running - " + str(self.omx.is_running()))
if self.omx.is_running() ==False:
#if self.omx.end_play_signal==True: #this is not as safe as process has closed.
self.monitor(" <omx process is dead")
self.play_state = self._OMX_CLOSED
self.dbus_connected = False
self.do_ending()
if self.autolyrics:
self.autolyrics.destroy()
self.autolyrics = None
self.root.after(350, self.play_state_machine)
# do things in each state
def do_playing(self):
# we are playing so just update time display
# self.monitor("Position: " + str(self.omx.position))
if self.paused == False:
time_string = self.time_string(self.omx.position)
if self.omx.timenf:
time_string += "\n/ " + self.time_string(self.omx.timenf['duration'])
self.display_time.set(time_string)
if abs(self.omx.position - self.progress_bar_var.get()) > self.progress_bar_step_rate:
self.set_progress_bar_step()
if self.options.cue_track_mode and not self._cued and self.omx.timenf and self.omx.position >= self.omx.timenf['duration'] - 1:
self.toggle_pause()
self._cued = True
else:
self.display_time.set(_("Paused"))
def do_starting(self):
self.display_time.set(_("Starting"))
return
def do_ending(self):
# we are ending so just write End to the time display
self.display_time.set(_("End"))
self.hide_progress_bar()
# respond to asynchrous user input and send signals if necessary
def play_track(self):
""" respond to user input to play a track, ignore it if already playing
needs to start playing and not send a signal as it is this that triggers the state machine.
"""
self.monitor(">play track received")
if self.play_state == self._OMX_CLOSED:
self.start_track_index = self.playlist.selected_track_index()
self.play()
elif self.play_state == self._OMX_PLAYING and not (self.stop_required_signal or self.break_required_signal):
self.toggle_pause()
def play_track_by_index(self, track_index=0):
if self.play_state == self._OMX_CLOSED:
self.playlist.select(track_index)
self.play_track()
return
elif (track_index == self.start_track_index
and self.play_state == self._OMX_PLAYING):
self.toggle_pause()
return
self.stop_track()
def play_after():
self.playlist.select(track_index)
self.play_track()
self.root.after(1200, play_after)
def skip_to_next_track(self):
# send signals to stop and then to play the next track
if self.play_state == self._OMX_PLAYING:
self.monitor(">skip to next received")
self.monitor(">stop received for next track")
self.stop_required_signal=True
self.play_next_track_signal=True
def skip_to_previous_track(self):
# send signals to stop and then to play the previous track
if self.play_state == self._OMX_PLAYING:
self.monitor(">skip to previous received")
self.monitor(">stop received for previous track")
self.stop_required_signal=True
self.play_previous_track_signal=True
def stop_track(self):
# send signals to stop and then to break out of any repeat loop
if self.play_state == self._OMX_PLAYING:
self.monitor(">stop received")
self.start_track_index=None
self.stop_required_signal=True
self.break_required_signal=True
self.hide_progress_bar()
self.set_play_button_state(0)
def toggle_pause(self):
"""pause clicked Pauses or unpauses the track"""
if self.play_state == self._OMX_PLAYING:
self.send_command('p')
if self.paused == False:
self.paused=True
self.set_play_button_state(0)
else:
if(self.options.cue_track_mode and self._cued):
self.stop_omx()
self.paused=False
self.set_play_button_state(1)
def set_play_button_state(self, state):
if state == 0:
self.play_button['text'] = _('Play')
elif state == 1:
self.play_button['text'] = _('Pause')
def volminusplus(self, event):
if event.x < event.widget.winfo_width()/2:
self.volminus()
else:
self.volplus()
def volplus(self):
self.send_command('+')
def volminus(self):
self.send_command('-')
def time_string(self,secs):
minu = int(secs/60)
sec = secs-(minu*60)
return str(minu)+":"+str(int(sec))
def what_next(self):
if self.break_required_signal==True:
self.hide_progress_bar()
self.monitor("What next, break_required so exit")
self.set_play_button_state(0)
def break_required_signal_false():
self.break_required_signal=False
self.root.after(650, break_required_signal_false)
# fall out of the state machine
return
elif self.play_next_track_signal ==True:
# called when state machine is in the omx_closed state in order to decide what to do next.
self.monitor("What next, skip to next track")
self.play_next_track_signal=False
if self.options.mode=='shuffle':
self.random_next_track()
self.play()
else:
self.select_next_track()
self.play()
return
elif self.play_previous_track_signal ==True:
self.monitor("What next, skip to previous track")
self.select_previous_track()
self.play_previous_track_signal=False
self.play()
return
elif self.options.mode=='single':
self.monitor("What next, single track so exit")
self.set_play_button_state(0)
# fall out of the state machine
return
elif self.options.mode=='repeat':
self.monitor("What next, Starting repeat track")
self.play()
return
elif 'playlist' in self.options.mode:
if not 'repeat' in self.options.mode and self.start_track_index == self.playlist.length() - 1:
self.stop_required_signal=True
self.set_play_button_state(0)
self.monitor("What next, reached end of playlist, so exit")
return
self.monitor("What next, Starting playlist track")
self.select_next_track()
self.play()
return
elif self.options.mode=='shuffle':
self.monitor("What next, Starting random track")
self.random_next_track()
self.play()
return
# ***************************************
# YTDL STATE MACHINE
# ***************************************
def go_ytdl(self, url, playlist=False):
self.quit_ytdl_sent_signal = False
if self.ytdl_state in (self._YTDL_CLOSED, self._YTDL_ENDING):
self.ytdl_state=self._YTDL_STARTING
self.ytdl.start_signal=True
youtube_media_format = self.options.youtube_media_format
if not playlist:
self.ytdl.retrieve_media_url(url, youtube_media_format)
else:
self.ytdl.retrieve_youtube_playlist(url, youtube_media_format)
if self.ytdl_state==self._YTDL_STARTING:
self.ytdl_state_machine()
def go_ytdl_subtitles(self, track):
self.ytdl.download_subtitles(self.options.subtitles_lang, track[2])
while (not self.ytdl.subtitle_ready_signal and
not self.ytdl.download_subtitle_failed_signal):
sleep(0.2)
self.start_omx(track[0], skip_ytdl_check = True)
def ytdl_state_machine(self):
if self.ytdl_state == self._YTDL_CLOSED:
self.monitor(" Ytdl state machine: " + self.ytdl_state)
return
elif self.ytdl_state == self._YTDL_STARTING:
self.monitor(" Ytdl state machine: " + self.ytdl_state)
if self.ytdl.start_signal==True:
self.monitor(" <start play signal received from youtube-dl")
self.ytdl.start_signal=False
self.ytdl_state=self._YTDL_WORKING
self.monitor(" Ytdl state machine: "+self.ytdl_state)
self.root.after(500, self.ytdl_state_machine)
elif self.ytdl_state == self._YTDL_WORKING:
try:
if len(self.ytdl.finished_processes):
for url in self.ytdl.finished_processes:
process = self.ytdl.finished_processes[url]
self.treat_ytdl_result(url, process[1])
self.ytdl.finished_processes = {}
if not self.ytdl.is_running():
self.ytdl_state = self._YTDL_ENDING
except Exception:
log.logException()
sys.exc_clear()
self.root.after(500, self.ytdl_state_machine)
elif self.ytdl_state == self._YTDL_ENDING:
self.ytdl.reset_processes()
self.monitor(" Ytdl state machine: " + self.ytdl_state)
self.monitor(" Ytdl state machine: is process running - " + str(self.ytdl.is_running()))
self.ytdl_state = self._YTDL_CLOSED
self.root.after(500, self.ytdl_state_machine)
def treat_ytdl_result(self, url, res):
if res[0] == 1:
try:
result = json.loads(res[1])
except Exception:
log.logException()
sys.exc_clear()
self.remove_waiting_track(url)
return
if 'entries' in result:
self.treat_youtube_playlist_data(result)
else:
self.treat_video_data(url, result)
else:
self.remove_waiting_track(url)
if self.play_state==self._OMX_STARTING:
self.quit_sent_signal = True
self.display_selected_track_title.set(self.YTDL_MSGS[res[1]])
self.root.after(3000, lambda: self.display_selected_track())
return
def treat_video_data(self, url, data):
media_url = self._treat_video_data(data, data['extractor'])
if not media_url and self.options.youtube_video_quality == "small":
media_url = self._treat_video_data(data, data['extractor'], "medium")
if not media_url:
media_url = data['url']
tracks = self.playlist.waiting_tracks()
if tracks:
for track in tracks:
if track[1][0] == url:
self.playlist.replace(track[0],[media_url, data['title'], url])
if self.play_state == self._OMX_STARTING:
self.start_omx(media_url,skip_ytdl_check=True)
self.refresh_playlist_display()
self.playlist.select(track[0])
break
def treat_youtube_playlist_data(self, data):
for entry in data['entries']:
media_url = self._treat_video_data(entry, data['extractor'])
if not media_url and self.options.youtube_video_quality == "small":
media_url = self._treat_video_data(entry, data['extractor'], "medium")
if not media_url:
media_url = entry['url']
self.playlist.append([media_url,entry['title'],''])
self.playlist.select(self.playlist.length() - len(data['entries']))
self.refresh_playlist_display()
self.root.after(3000, lambda: self.display_selected_track())
def _treat_video_data(self, data, extractor, force_quality=False):
media_url = None
media_format = self.options.youtube_media_format
quality = self.options.youtube_video_quality if not force_quality else force_quality
if extractor != "youtube" or (media_format == "mp4" and quality == "high"):
media_url = data['url']
else:
preference = -100
for format in data['formats']:
if ((media_format == format['ext'] == "m4a" and
((quality == "high" and format['abr'] == 256) or
(quality in ("medium", "small") and format['abr'] == 128))) or
(media_format == format['ext'] == "mp4" and
quality == format['format_note'])):
if 'preference' in format and format['preference'] > preference:
preference = format['preference']
media_url = format['url']
else:
media_url = format['url']
return media_url
def ytdl_update_messages_loop(self):
if not self.ytdl.updating_signal:
if self.ytdl.updated_signal:
tkMessageBox.showinfo("",_("youtube-dl has been updated."))
elif self.ytdl.update_failed_signal:
tkMessageBox.showinfo("",_("Failed to update youtube-dl."))
else:
if self.ytdl.password_requested_signal and not self.ytdl.has_password_signal:
password = tkSimpleDialog.askstring("", _("youtube-dl needs to be updated.\nPlease inform your password."), parent=self.root, show="*")
if password: self.ytdl.set_password(password)
else: return
self.root.after(500, self.ytdl_update_messages_loop)
# ***************************************
# WRAPPER FOR JBAITER'S PYOMXPLAYER
# ***************************************
def start_omx(self, track, skip_ytdl_check=False):
""" Loads and plays the track"""
if not skip_ytdl_check and self.ytdl.whether_to_use_youtube_dl(track):
self.go_ytdl(track)
index = self.playlist.selected_track_index()
track = self.playlist.selected_track()
track = (track[0], self.YTDL_WAIT_TAG+track[1])
self.playlist.replace(index, track)
self.playlist.select(index)
self.refresh_playlist_display()
return
if ("http" in track and
self.options.omx_subtitles and
not self.ytdl.subtitle_ready_signal and
not self.ytdl.download_subtitle_failed_signal):
track = self.playlist.selected_track()
self.go_ytdl_subtitles(track)
return
track= "'"+ track.replace("'","'\\''") + "'"
opts= (self.options.omx_user_options + " " + self.options.omx_audio_output + " " +
" --vol " + str(self.get_mB()) + " " + self.options.omx_subtitles + " " +
(" --subtitles " + self.ytdl._YTLAUNCH_SUB_DIR + "/subtitle." + self.options.subtitles_lang + ".srt" if self.ytdl.subtitle_ready_signal else ""))
#print(639, "self.media_is_video()",self.media_is_video())
#print(hasattr(self,"omx"), hasattr(self.omx, "video"), len(self.omx.video) > 0)
#if self.media_is_video():
if not self.options.forbid_windowed_mode and not self.options.full_screen and '--win' not in opts:
mc = self.RE_COORDS.match(self.options.windowed_mode_coords)
mg = self.RE_RESOLUTION.match(self.options.windowed_mode_resolution)
if mc and mg:
w, h, x, y = [int(v) for v in mg.groups()+mc.groups()]
opts += ' --win %d,%d,%d,%d' % (x, y, x+w, y+h)
if not '--aspect-mode' in opts:
opts += ' --aspect-mode letterbox'
if not '--no-osd' in opts:
opts += ' --no-osd'
self.monitor('starting omxplayer with args: "%s"' % (opts,))
self.omx = OMXPlayer(track, args=opts, start_playback=True)
self.monitor(" >Play: " + track + " with " + opts)
def stop_omx(self):
if self.play_state == self._OMX_PLAYING:
self.monitor(" >Send stop to omx")
self.omx.stop()
else:
self.monitor (" !>stop not sent to OMX because track not playing")
def send_command(self,command):
if command in "+=-pz12jkionms" and self.play_state == self._OMX_PLAYING:
self.monitor(" >Send Command: "+command)
self.omx.send_command(command)
if self.dbus_connected and command in ('+' , '=', '-'):
sleep(0.1)
try:
self.set_volume_bar_step(int(self.vol2dB(self.omx.volume())+self.volume_normal_step))
except Exception:
log.logException()
sys.exc_clear()
self.monitor("Failed to set volume bar step")
return True
else:
if command in "+=":
self.set_volume_bar_step(self.volume_var.get() + 3)
elif command == '-':
self.set_volume_bar_step(self.volume_var.get() - 3)
self.monitor (" !>Send command: illegal control or track not playing")
return False
def send_special(self,command):
if self.play_state == self._OMX_PLAYING:
self.monitor(" >Send special")
self.omx.send_command(command)
return True
else:
self.monitor (" !>Send special: track not playing")
return False
# ***************************************
# INIT
# ***************************************
def __init__(self, options):
# initialise options class and do initial reading/creation of options
self.options=options
if self.options.debug:
log.setLogFile(self.options.log_file)
log.enableLogging()
self.monitor('started logging to file "%s"' % (self.options.log_file,))
else:
log.disableLogging()
#initialise the play state machine
self.init_play_state_machine()
# start and configure ytdl object
self.ytdl = Ytdl(self.options,
lambda: tkMessageBox.showinfo("",_("youtube-dl binary is not in the path configured in the Options, please check your configuration")))
#create the internal playlist
self.playlist = PlayList(self.YTDL_WAIT_TAG)
#root is the Tkinter root widget
self.root = tk.Tk()
icon_photo = tk.PhotoImage(file=os.path.dirname(os.path.realpath(__file__)) + '/ico/48x48.png')
self.root.call('wm', 'iconphoto', self.root._w, icon_photo)
#self.root.iconphoto()
self.root.title("GUI for OMXPlayer")
self.root.configure(background='grey')
# width, height, xoffset, yoffset
self.root.geometry(self.options.geometry)
self.root.resizable(True,True)
OMXPlayer.set_omx_location(self.options.omx_location)
# bind some display fields
self.filename = tk.StringVar()
self.display_selected_track_title = tk.StringVar()
self.display_time = tk.StringVar()
self.volume_var = tk.IntVar()
self.progress_bar_var = tk.IntVar()
self.root.bind("<Configure>", self.save_geometry)
#Keys
self.root.bind("<Left>", self.key_left)
self.root.bind("<Right>", self.key_right)
self.root.bind("<Up>", self.key_up)
self.root.bind("<Down>", self.key_down)
self.root.bind("<Shift-Right>", self.key_shiftright) #forward 600
self.root.bind("<Shift-Left>", self.key_shiftleft) #back 600
self.root.bind("<Control-Right>", self.key_ctrlright) #next track
self.root.bind("<Control-Left>", self.key_ctrlleft) #previous track
self.root.bind("<Control-v>", self.add_url)
self.root.bind("<Escape>", self.key_escape)
self.root.bind("<F11>", self.toggle_full_screen)
self.root.bind("<Control_L>", self.vwindow_start_resize)
self.root.bind("<KeyRelease-Control_L>", self.vwindow_stop_resize)
self.root.bind('<Button-3>', self.add_url)
self.root.bind("<Key>", self.key_pressed)
self.style = Style()
self.style.theme_use("alt")
# define menu
menubar = Menu(self.root)
filemenu = Menu(menubar, tearoff=0, background="grey", foreground="black")
menubar.add_cascade(label=_('Track'), menu = filemenu)
filemenu.add_command(label=_('Add'), command = self.add_track)
filemenu.add_command(label=_('Add Dir'), command = self.add_dir)
filemenu.add_command(label=_('Add Dirs'), command = self.add_dirs)
filemenu.add_command(label=_('Add URL'), command = self.add_url)
filemenu.add_command(label=_('Youtube search'), command = self.youtube_search)
filemenu.add_command(label=_('Remove'), command = self.remove_track)
filemenu.add_command(label=_('Edit'), command = self.edit_track)
listmenu = Menu(menubar, tearoff=0, background="grey", foreground="black")
menubar.add_cascade(label=_('Playlists'), menu = listmenu)
listmenu.add_command(label=_('Open playlist'), command = self.open_list_dialog)
listmenu.add_command(label=_('Save playlist'), command = self.save_list)
listmenu.add_command(label=_('Load Youtube playlist'), command = self.load_youtube_playlist)
listmenu.add_command(label=_('Clear'), command = self.clear_list)
omxmenu = Menu(menubar, tearoff=0, background="grey", foreground="black")
menubar.add_cascade(label='OMX', menu = omxmenu)
omxmenu.add_command(label=_('Track Info'), command = self.show_omx_track_info)
optionsmenu = Menu(menubar, tearoff=0, background="grey", foreground="black")
menubar.add_cascade(label=_('Options'), menu = optionsmenu)
optionsmenu.add_command(label=_('Edit'), command = self.edit_options)
helpmenu = Menu(menubar, tearoff=0, background="grey", foreground="black")
menubar.add_cascade(label=_('Help'), menu = helpmenu)
helpmenu.add_command(label=_('Help'), command = self.show_help)
helpmenu.add_command(label=_('About'), command = self.about)
self.root.config(menu=menubar)
# define buttons
# add track button
Button(self.root, width = 5, height = 1, text=_('Add'),
foreground='black', command = self.add_track,
background="light grey").grid(row=0, column=1, rowspan=2, sticky=N+W+E+S)
# add dir button
Button(self.root, width = 5, height = 1, text=_('Add Dir'),
foreground='black', command = self.add_dir,
background="light grey").grid(row=0, column=2, rowspan=2, sticky=N+W+E+S)
# add url button
Button(self.root, width = 5, height = 1, text=_('Add URL'),
foreground='black', command = self.add_url,
background="light grey").grid(row=0, column=3, rowspan=2, sticky=N+W+E+S)
# open list button
Button(self.root, width = 5, height = 1, text=_('Open List'),
foreground='black', command = self.open_list_dialog,
background="light grey").grid(row=0, column=4, rowspan=2, sticky=N+W+E+S)
# save list button
Button(self.root, width = 5, height = 1, text =_('Save List'),
foreground='black', command = self.save_list,
background='light grey').grid(row=0, column=5, rowspan=2, sticky=N+W+E+S)
# clear list button;
Button(self.root, width = 5, height = 1, text =_('Clear List'),
foreground='black', command = self.clear_list,
background='light grey').grid(row=0, column=6, rowspan=2, sticky=N+W+E+S)
# play/pause button
self.play_button = Button(self.root, width = 5, height = 1, text=_('Play'),
foreground='black', command = self.play_track,
background="light grey")
self.play_button.grid(row=7, column=1, sticky=N+W+E+S)
# stop track button
Button(self.root, width = 5, height = 1, text=_('Stop'),
foreground='black', command = self.stop_track,
background="light grey").grid(row=7, column=2, sticky=N+W+E+S)
# previous track button
Button(self.root, width = 5, height = 1, text=_('Previous'),
foreground='black', command = self.skip_to_previous_track,
background="light grey").grid(row=7, column=3, sticky=N+W+E+S)
# next track button
Button(self.root, width = 5, height = 1, text=_('Next'),
foreground='black', command = self.skip_to_next_track,
background="light grey").grid(row=7, column=4, sticky=N+W+E+S)
# vol button
minusplus_button = Button(self.root, width = 5, height = 1, text = '- Vol +',
foreground='black', background='light grey')
minusplus_button.grid(row=7, column=5, sticky=N+W+E+S)#, sticky=E)
minusplus_button.bind("<ButtonRelease-1>", self.volminusplus)
# define display of file that is selected
Label(self.root, font=('Comic Sans', 10),
fg = 'black', wraplength = 400, height = 2,
textvariable=self.display_selected_track_title,
background="grey").grid(row=2, column=1, columnspan=6, sticky=N+W+E)
# define time/status display for selected track
Label(self.root, font=('Comic Sans', 9),
fg = 'black', wraplength = 100,
textvariable=self.display_time,
background="grey").grid(row=2, column=6, columnspan=1, sticky=N+W+E+S)
# define display of playlist
self.track_titles_display = Listbox(self.root, background="white", height = 15,
foreground="black", takefocus=0)
self.track_titles_display.grid(row=3, column=1, columnspan=7,rowspan=3, sticky=N+S+E+W)
self.track_titles_display.bind("<ButtonRelease-1>", self.select_track)
self.track_titles_display.bind("<Delete>", self.remove_track)
self.track_titles_display.bind("<Return>", self.key_return)
self.track_titles_display.bind("<Double-1>", self.select_and_play)
# scrollbar for displaylist
scrollbar = Scrollbar(self.root, command=self.track_titles_display.yview, orient=tk.VERTICAL)
scrollbar.grid(row = 3, column=6, rowspan=3, sticky=N+S+E)
self.track_titles_display.config(yscrollcommand=scrollbar.set)
# progress bar
self.style.configure("progressbar.Horizontal.TProgressbar", foreground='medium blue', background='medium blue')
self.progress_bar = Progressbar(orient=HORIZONTAL, length=self.progress_bar_total_steps, mode='determinate',
maximum=self.progress_bar_total_steps, variable=self.progress_bar_var,
style="progressbar.Horizontal.TProgressbar")
self.progress_bar.grid(row=6, column=1, columnspan=6, sticky=N+W+E+S)
self.progress_bar.grid_remove()
self.progress_bar.bind("<ButtonRelease-1>", self.set_track_position)
self.progress_bar_var.set(0)
# volume bar, volume meter is 0.0 - 16.0, being normal volume 1.0
self.style.configure("volumebar.Horizontal.TProgressbar", foreground='cornflower blue', background='cornflower blue')
self.volume_bar = Progressbar(orient=HORIZONTAL, length=self.volume_max, mode='determinate',
maximum=self.volume_max, variable=self.volume_var,
style="volumebar.Horizontal.TProgressbar")
self.volume_bar.grid(row=7, column=6, stick=W+E)
self.volume_bar.bind("<ButtonRelease-1>", self.set_volume_bar)
self.volume_var.set(self.volume_normal_step)
# configure grid
self.root.grid_columnconfigure(1, weight=1)
self.root.grid_columnconfigure(2, weight=1)
self.root.grid_columnconfigure(3, weight=1)
self.root.grid_columnconfigure(4, weight=1)
self.root.grid_columnconfigure(5, weight=1)
self.root.grid_columnconfigure(6, weight=1)
self.root.grid_rowconfigure(1, weight=0)
self.root.grid_rowconfigure(2, weight=0)
self.root.grid_rowconfigure(3, weight=1, minsize=40)
self.root.grid_rowconfigure(4, weight=0)
self.root.grid_rowconfigure(5, weight=0)
self.root.grid_rowconfigure(6, weight=0)
self.root.grid_rowconfigure(7, weight=0)
# if files were passed in the command line, add them to the playlist
for f in sys.argv[1:]:
if os.path.isfile(f) and self.is_file_supported(f):
self.file = f
self.file_pieces = self.file.split("/")
self.playlist.append([self.file, self.file_pieces[-1],'',''])
self.track_titles_display.insert(END, self.file_pieces[-1])
elif os.path.isfile(f) and f[f.rfind('.')+1:]=="csv":
self._open_list(f)
if self.playlist.length() > 0 and self.options.autoplay:
if self.options.mode=='shuffle':
self.random_next_track()
else:
self.select_track(False)
self.play_track()
self.dnd = DnD(self.root)
self.dnd.bindtarget(self.root, 'text/uri-list', '<Drop>', self.add_drag_drop)
if self.options.ytdl_update:
self.ytdl.check_for_update()
self.ytdl_update_messages_loop()
def shutdown(self):
self.root.quit()
self.ytdl.quit()
if self.omx is not None:
self.omx.stop()
self.omx.kill()
# ***************************************
# MISCELLANEOUS
# ***************************************
def edit_options(self):
"""edit the options then read them from file"""
eo = OptionsDialog(self.root, self.options.options_file,_('Edit Options'))
self.options.read(self.options.options_file)
self.ytdl.set_options(self.options)
OMXPlayer.set_omx_location(self.options.omx_location)
def show_help (self):
tkMessageBox.showinfo(_("Help"),
_("To control playing, type a key\np - pause/play\nspacebar - pause/play\nq - quit\n")
+ _("+ - increase volume\n- - decrease volume\nz - tv show info\n1 - reduce speed\no - forward a chapter\n")
+ _("2 - increase speed\nj - previous audio index\nk - next audio index\ni - back a chapter\nn - previous subtitle index\n")
+ _("m - next subtitle index\ns - toggle subtitles\n>cursor - seek forward 30\n<cursor - seek back 30\n")
+ _("SHIFT >cursor - seek forward 600\nSHIFT <cursor - seek back 600\nCTRL >cursor - next track\nCTRL <cursor - previous track\n")
+ _("F11 - toggle full screen/windowed mode\n\nFor more help, consult the 'Operation' section of the README file"))
def about (self):
tkMessageBox.showinfo(_("About"),_("GUI for omxplayer using jbaiter's pyomxplayer wrapper\n")
+((_("Version dated: %s \nAuthor:\n Ken Thompson - KenT2\n")) % datestring)
+_("Contributors:\n eysispeisi\n heniotierra\n krugg\n popiazaza"))
def monitor(self,text):
if self.options.debug:
log.debug(text)
# Key Press callbacks
def key_right(self,event):
self.send_special('\x1b\x5b\x43')
self.monitor("Seek forward 30")
def key_left(self,event):
self.send_special('\x1b\x5b\x44')
self.monitor("Seek back 30")
def key_shiftright(self,event):
self.send_special('\x1b\x5b\x42')
self.monitor("Seek forward 600")
def key_shiftleft(self,event):
self.send_special('\x1b\x5b\x41')
self.monitor("Seek back 600")