-
Notifications
You must be signed in to change notification settings - Fork 10
/
nrsc5-dui.py
2312 lines (2026 loc) · 115 KB
/
nrsc5-dui.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/python
# -*- coding: utf-8 -*-
# NRSC5 DUI - A graphical interface for nrsc5
# Copyright (C) 2017-2019 Cody Nybo & Clayton Smith, 2019 zefie, 2021-24 Mark J. Fine
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Updated by zefie for modern nrsc5 ~ 2019
# Updated and enhanced by markjfine ~ 2021-24
import os, pty, select, sys, shutil, re, json, datetime, numpy, glob, time, platform, io
from subprocess import Popen, PIPE
from threading import Timer, Thread
from dateutil import tz
from PIL import Image, ImageFont, ImageDraw, __version__
print('Using Pillow v'+__version__)
if (int(__version__[0]) < 9):
imgLANCZOS = Image.LANCZOS
else:
imgLANCZOS = Image.Resampling.LANCZOS
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, GObject, Gdk, GdkPixbuf, GLib
import urllib3
from OpenSSL import SSL
import musicbrainzngs
# print debug messages to stdout (if debugger is attached)
debugMessages = (sys.gettrace() != None)
debugAutoStart = True
if hasattr(sys, 'frozen'):
runtimeDir = os.path.dirname(sys.executable) # for py2exe
else:
runtimeDir = sys.path[0]
if "NRSC5DUI_DATA" in os.environ:
userDataDir = os.environ["NRSC5DUI_DATA"]
os.makedirs(userDataDir, exist_ok=True)
else:
userDataDir = runtimeDir
aasDir = os.path.join(userDataDir, "aas") # aas (data from nrsc5) file directory
mapDir = os.path.join(userDataDir, "map") # map (data we process) file directory
resDir = os.path.join(runtimeDir, "res") # resource (application dependencies) file directory
cfgDir = os.path.join(userDataDir, "cfg") # config file directory
class NRSC5_DUI(object):
def __init__(self):
global runtimeDir, userDataDir, resDir, imgLANCZOS
self.windowsOS = False # save our determination as a var in case we change how we determine.
self.getControls() # get controls and windows
self.initStreamInfo() # initilize stream info and clear status widgets
self.http = urllib3.PoolManager()
self.debugLog("Local path determined as " + runtimeDir)
self.debugLog("User data base directory: " + userDataDir)
if (platform.system() == 'Windows'):
# Windows release layout
self.windowsOS = True
self.binDir = os.path.join(runtimeDir, "bin") # windows binaries directory
self.nrsc5Path = os.path.join(self.binDir,'nrsc5.exe')
else:
# Linux/Mac/proper posix
# if nrsc5 and transcoder are not in the system path, set the full path here
arg1 = ""
if (len(sys.argv[1:]) > 0):
arg1 = sys.argv[1].strip()
self.nrsc5Path = arg1+"nrsc5"
self.debugLog("OS Determination: Windows = {}".format(self.windowsOS))
self.app_name = "NRSC5-DUI"
self.version = "2.2.4"
self.web_addr = "https://github.com/markjfine/nrsc5-dui"
self.copyright = "Copyright © 2017-2019 Cody Nybo & Clayton Smith, 2019 zefie, 2021-24 Mark J. Fine"
musicbrainzngs.set_useragent(self.app_name,self.version,self.web_addr)
self.width = 0 # window width
self.height = 0 # window height
self.mapFile = os.path.join(resDir, "map.png")
self.defaultSize = [490,250] # default width,height of main app
self.nrsc5 = None # nrsc5 process
self.nrsc5master = None # required for pipe
self.nrsc5slave = None # required for pipe
self.playerThread = None # player thread
self.playing = False # currently playing
self.statusTimer = None # status update timer
self.imageChanged = False # has the album art changed
self.xhdrChanged = False # has the HDDR data changed
self.nrsc5Args = [] # arguments for nrsc5
self.logFile = None # nrsc5 log file
self.lastImage = "" # last image file displayed
self.coverImage = "" # cover image to display
self.id3Changed = False # if the track info changed
self.lastXHDR = "" # the last XHDR data received
self.lastLOT = "" # the last LOT received with XHDR
self.stationStr = "" # current station frequency (string)
self.streamNum = 0 # current station stream number
self.nrsc5msg = "" # send key command to nrsc5 (streamNum)
self.update_btns = True # whether to update the stream buttons
self.set_program_btns() # whether to set the stream buttons
self.bookmarks = [] # station bookmarks
self.booknames = ["","","","","","","",""] # station bookmark names
self.stationLogos = {} # station logos
self.coverMetas = {} # cover metadata
self.bookmarked = False # is current station bookmarked
self.mapViewer = None # map viewer window
self.weatherMaps = [] # list of current weathermaps sorted by time
self.waittime = 10 # time in seconds to wait for file to exist
self.waitdivider = 4 # check this many times per second for file
self.pixbuf = None # store image buffer for rescaling on resize
self.mimeTypes = { # as defined by iHeartRadio anyway, defined here for possible future use
"4F328CA0":["image/png","png"],
"1E653E9C":["image/jpg","jpg"],
"BB492AAC":["text/plain","txt"]
}
self.mapData = {
"mapMode" : 1,
"mapTiles" : [[0,0,0],[0,0,0],[0,0,0]],
"mapComplete" : False,
"weatherTime" : 0,
"weatherPos" : [0,0,0,0],
"weatherNow" : "",
"weatherID" : "",
"viewerConfig" : {
"mode" : 1,
"animate" : False,
"scale" : True,
"windowPos" : (0,0),
"windowSize" : (764,632),
"animationSpeed" : 0.5
}
}
self.slPopup = None # entry for external station logo URL
self.slData = {
"externalURL" : ""
}
self.ServiceDataType = {
0 : "Non_Specific",
1 : "News",
3 : "Sports",
29 : "Weather",
31 : "Emergency",
65 : "Traffic",
66 : "Image Maps",
80 : "Text",
256 : "Advertising",
257 : "Financial",
258 : "Stock Ticker",
259 : "Navigation",
260 : "Electronic Program Guide",
261 : "Audio",
262 : "Private Data Network",
263 : "Service Maintenance",
264 : "HD Radio System Services",
265 : "Audio-Related Objects",
511 : "Reserved for Special Tests"
}
self.ProgramType = {
0 : "None",
1 : "News",
2 : "Information",
3 : "Sports",
4 : "Talk",
5 : "Rock",
6 : "Classic Rock",
7 : "Adult Hits",
8 : "Soft Rock",
9 : "Top 40",
10 : "Country",
11 : "Oldies",
12 : "Soft",
13 : "Nostalgia",
14 : "Jazz",
15 : "Classical",
16 : "Rhythm and Blues",
17 : "Soft Rhythm and Blues",
18 : "Foreign Language",
19 : "Religious Music",
20 : "Religious Talk",
21 : "Personality",
22 : "Public",
23 : "College",
24 : "Spanish Talk",
25 : "Spanish Music",
26 : "Hip-Hop",
29 : "Weather",
30 : "Emergency Test",
31 : "Emergency",
65 : "Traffic",
76 : "Special Reading Services"
}
self.MIMETypes = {
0x1E653E9C : "JPEG",
0x2D42AC3E : "NavTeq",
0x4F328CA0 : "PNG",
0x4DC66C5A : "HDC",
0x4EB03469 : "TTN TPEG 2",
0x52103469 : "TTN TPEG 3",
0x82F03DFC : "HERE TPEG",
0xB39EBEB2 : "TTN TPEG 1",
0xB7F03DFC : "HERE Image",
0xB81FFAA8 : "Unknown Test",
0xBB492AAC : "Text",
0xBE4B7536 : "Primary Image",
0xD9C72536 : "Station Logo",
0xEECB55B6 : "HD TMC",
0xEF042E96 : "TTN STM Weather",
0xFF8422D7 : "TTN STM Traffic"
}
self.pointer_cursor = Gdk.Cursor(Gdk.CursorType.LEFT_PTR)
self.hand_cursor = Gdk.Cursor(Gdk.CursorType.HAND2)
# set events on info labels
self.set_tuning_actions(self.btnAudioPrgs0, "btn_prg0", False, False)
self.set_tuning_actions(self.btnAudioPrgs1, "btn_prg1", False, False)
self.set_tuning_actions(self.btnAudioPrgs2, "btn_prg2", False, False)
self.set_tuning_actions(self.btnAudioPrgs3, "btn_prg3", False, False)
self.set_tuning_actions(self.btnAudioPrgs4, "btn_prg4", False, False)
self.set_tuning_actions(self.btnAudioPrgs5, "btn_prg5", False, False)
self.set_tuning_actions(self.btnAudioPrgs6, "btn_prg6", False, False)
self.set_tuning_actions(self.btnAudioPrgs7, "btn_prg7", False, False)
self.set_tuning_actions(self.lblAudioPrgs0, "prg0", True, True)
self.set_tuning_actions(self.lblAudioPrgs1, "prg1", True, True)
self.set_tuning_actions(self.lblAudioPrgs2, "prg2", True, True)
self.set_tuning_actions(self.lblAudioPrgs3, "prg3", True, True)
self.set_tuning_actions(self.lblAudioPrgs4, "prg4", True, True)
self.set_tuning_actions(self.lblAudioPrgs5, "prg5", True, True)
self.set_tuning_actions(self.lblAudioPrgs6, "prg6", True, True)
self.set_tuning_actions(self.lblAudioPrgs7, "prg7", True, True)
self.set_tuning_actions(self.lblAudioSvcs0, "svc0", True, True)
self.set_tuning_actions(self.lblAudioSvcs1, "svc1", True, True)
self.set_tuning_actions(self.lblAudioSvcs2, "svc2", True, True)
self.set_tuning_actions(self.lblAudioSvcs3, "svc3", True, True)
self.set_tuning_actions(self.lblAudioSvcs4, "svc4", True, True)
self.set_tuning_actions(self.lblAudioSvcs5, "svc5", True, True)
self.set_tuning_actions(self.lblAudioSvcs6, "svc6", True, True)
self.set_tuning_actions(self.lblAudioSvcs7, "svc7", True, True)
# setup bookmarks listview
nameRenderer = Gtk.CellRendererText()
nameRenderer.set_property("editable", True)
nameRenderer.connect("edited", self.on_bookmarkNameEdited)
colStation = Gtk.TreeViewColumn("Station", Gtk.CellRendererText(), text=0)
colName = Gtk.TreeViewColumn("Name", nameRenderer, text=1)
colStation.set_resizable(True)
colStation.set_sort_column_id(2)
colName.set_resizable(True)
colName.set_sort_column_id(1)
self.lvBookmarks.append_column(colStation)
self.lvBookmarks.append_column(colName)
# regex for getting nrsc5 output
self.regex = [
re.compile("^[0-9:]{8,8} Station name: (.*)$"), # 0 match station name
re.compile("^[0-9:]{8,8} Station location: (-?[0-9.]+) (-?[0-9.]+), ([0-9]+)m$"), # 1 match station location
re.compile("^[0-9:]{8,8} Slogan: (.*)$"), # 2 match station slogan
re.compile("^[0-9:]{8,8} Audio bit rate: (.*) kbps$"), # 3 match audio bit rate
re.compile("^[0-9:]{8,8} Title: (.*)$"), # 4 match title
re.compile("^[0-9:]{8,8} Artist: (.*)$"), # 5 match artist
re.compile("^[0-9:]{8,8} Album: (.*)$"), # 6 match album
re.compile("^[0-9:]{8,8} LOT file: port=([0-9]+) lot=([0-9]+) name=(.*[.](?:jpg|jpeg|png|txt)) size=([0-9]+) mime=([a-zA-Z0-9_]+) .*$"), # 7 match file (album art, maps, weather info)
re.compile("^[0-9:]{8,8} MER: (-?[0-9]+[.][0-9]+) dB [(]lower[)], (-?[0-9]+[.][0-9]+) dB [(]upper[)]$"), # 8 match MER
re.compile("^[0-9:]{8,8} BER: (0[.][0-9]+), avg: (0[.][0-9]+), min: (0[.][0-9]+), max: (0[.][0-9]+)$"), # 9 match BER
re.compile("^Best gain: (.*) dB,.*$"), # 10 match gain
re.compile("^[0-9:]{8,8} SIG Service: type=(.*) number=(.*) name=(.*)$"), # 11 match stream
re.compile("^[0-9:]{8,8} .*Data component:.* id=([0-9]+).* port=([0-9]+).* service_data_type=([0-9]+) .*$"), # 12 match port (and data_service_type)
re.compile("^[0-9:]{8,8} XHDR: (.*) ([0-9A-Fa-f]{8}) (.*)$"), # 13 match xhdr tag
re.compile("^[0-9:]{8,8} Unique file identifier: PPC;07; ([a-zA-Z0-9_.]+).*$"), # 14 match unique file id
re.compile("^[0-9:]{8,8} Genre: (.*)$"), # 15 match genre
re.compile("^[0-9:]{8,8} Message: (.*)$"), # 16 match message
re.compile("^[0-9:]{8,8} Alert: (.*)$"), # 17 match alert
re.compile("^[0-9:]{8,8} .*Audio component:.* id=([0-9]+).* port=([0-9]+).* type=([0-9]+) .*$"), # 18 match port (and type)
re.compile("^[0-9:]{8,8} Synchronized$"), # 19 synchronized
re.compile("^[0-9:]{8,8} Lost synchronization$"), # 20 lost synch
re.compile("^[0-9:]{8,8} Lost device$"), # 21 lost device
re.compile("^[0-9:]{8,8} Open device failed.$"), # 22 No device
re.compile("^[0-9:]{8,8} Stream data: port=([0-9]+).* mime=([a-zA-Z0-9_]+) size=([0-9]+)$"), # 23 Navteq/HERE stream info
re.compile("^[0-9:]{8,8} Packet data: port=([0-9]+).* mime=([a-zA-Z0-9_]+) size=([0-9]+)$") # 24 Navteq/HERE packet info
]
self.loadSettings()
self.proccessWeatherMaps()
# set up pty
self.nrsc5master,self.nrsc5slave = pty.openpty()
def set_tuning_actions(self, widget, name, has_win, set_curs):
widget.set_property("name",name)
widget.set_sensitive(False)
if has_win:
widget.set_has_window(True)
widget.set_events(Gdk.EventMask.BUTTON_PRESS_MASK)
widget.connect("button-press-event", self.on_program_select)
if set_curs:
widget.add_events(Gdk.EventMask.ENTER_NOTIFY_MASK)
widget.connect("enter-notify-event", self.on_enter_set_cursor)
def on_enter_set_cursor(self, widget, event):
if (widget.get_label() != ""):
widget.get_window().set_cursor(self.hand_cursor)
def on_cbCovers_clicked(self, btn):
dlCoversSet = self.cbCovers.get_active()
self.lblCoverIncl.set_sensitive(dlCoversSet)
self.cbCoverIncl.set_sensitive(dlCoversSet)
self.lblExtend.set_sensitive(dlCoversSet)
self.cbExtend.set_sensitive(dlCoversSet)
def restart_program(self):
python = sys.executable
os.execl(python, python, *sys.argv)
def confirm_dialog(self, title, message):
dialog = Gtk.MessageDialog(parent=self.mainWindow, flags=0, message_type=Gtk.MessageType.WARNING, buttons=Gtk.ButtonsType.YES_NO, text=title)
dialog.format_secondary_text(message)
dialog.set_default_response(Gtk.ResponseType.YES)
response = dialog.run()
dialog.destroy()
return (response == Gtk.ResponseType.YES)
def on_cbxAspect_changed(self, btn):
screenAspect = self.cbxAspect.get_active_text()
if (screenAspect == "narrow") or (screenAspect == "wide"):
mainFile = os.path.join(resDir, "mainForm.glade")
gladeFile = os.path.join(resDir, "mainForm-"+screenAspect+".glade")
if (os.path.isfile(gladeFile)):
shutil.copy(gladeFile,mainFile)
title = "Aspect Changed"
message = "You have change the display layout to "+screenAspect+". This change will not happen until the application is restarted. Would you like to restart it now?"
if (self.confirm_dialog(title,message)):
self.restart_program()
def on_cbxSDRRadio_changed(self, btn):
useSDRPlay = (self.cbxSDRRadio.get_active_text() == "SDRPlay")
self.lblSdrPlaySer.set_visible(useSDRPlay)
self.txtSDRPlaySer.set_visible(useSDRPlay)
self.txtSDRPlaySer.set_can_focus(useSDRPlay)
self.label14d.set_visible(useSDRPlay)
self.lblSDRPlayAnt.set_visible(useSDRPlay)
self.cbxSDRPlayAnt.set_visible(useSDRPlay)
self.cbxSDRPlayAnt.set_can_focus(useSDRPlay)
self.label14a.set_visible(useSDRPlay)
self.lblRTL.set_visible(not(useSDRPlay))
self.spinRTL.set_visible(not(useSDRPlay))
self.spinRTL.set_can_focus(not(useSDRPlay))
self.label14b.set_visible(useSDRPlay)
self.lblDevIP.set_visible(not(useSDRPlay))
self.txtDevIP.set_visible(not(useSDRPlay))
self.txtDevIP.set_can_focus(not(useSDRPlay))
self.cbDevIP.set_visible(not(useSDRPlay))
self.cbDevIP.set_can_focus(not(useSDRPlay))
def img_to_pixbuf(self,img):
"""convert PIL.Image to GdkPixbuf.Pixbuf"""
data = GLib.Bytes.new(img.tobytes())
return GdkPixbuf.Pixbuf.new_from_bytes(data, GdkPixbuf.Colorspace.RGB, 'A' in img.getbands(),8, img.width, img.height, len(img.getbands())*img.width)
def did_resize(self):
result = False
width, height = self.mainWindow.get_size()
if (self.width != width) or (self.height != height):
self.width = width
self.height = height
result = True
return result
def on_cover_resize(self, container):
global mapDir, imgLANCZOS
if (self.did_resize()):
self.showArtwork(self.coverImage)
img_size = min(self.alignmentMap.get_allocated_height(), self.alignmentMap.get_allocated_width()) - 12
if (self.mapData["mapMode"] == 0):
map_file = os.path.join(mapDir, "TrafficMap.png")
if os.path.isfile(map_file):
map_img = Image.open(map_file).resize((img_size, img_size), imgLANCZOS)
self.imgMap.set_from_pixbuf(self.img_to_pixbuf(map_img))
else:
self.imgMap.set_from_icon_name("MISSING_IMAGE", Gtk.IconSize.DIALOG)
elif (self.mapData["mapMode"] == 1):
if os.path.isfile(self.mapData["weatherNow"]):
map_img = Image.open(self.mapData["weatherNow"]).resize((img_size, img_size), imgLANCZOS)
self.imgMap.set_from_pixbuf(self.img_to_pixbuf(map_img))
else:
self.imgMap.set_from_icon_name("MISSING_IMAGE", Gtk.IconSize.DIALOG)
def id3_did_change(self):
oldTitle = self.txtTitle.get_label().strip()
oldArtist = self.txtArtist.get_label().strip()
newTitle = self.streamInfo["Title"].strip()
newArtist = self.streamInfo["Artist"].strip()
return ((newArtist != oldArtist) and (newTitle != oldTitle))
def fix_artist(self):
newArtist = self.streamInfo["Artist"]
if ("/" in newArtist):
m = re.search(r"/",newArtist)
if (m.start() > -1):
newArtist = newArtist[:m.start()].strip()
return newArtist
def check_value(self,arg,group,default):
result = default
if(arg in group):
result = group[arg]
return result
def check_terms(self,inStr,terms):
result = False
for term in terms:
result=(term in inStr)
if result:
break
return result
def check_musicbrainz_cover(self,inID):
result = False
imageList = None
try:
imageList = musicbrainzngs.get_image_list(inID)
except:
print("MusicBrainz image list retrieval error for id "+inID)
if (imageList is not None) and ('images' in imageList):
for (idx, image) in enumerate(imageList['images']):
imgTypes = self.check_value('types', image, None)
imgApproved = self.check_value('approved', image, "False")
result = ('Front' in imgTypes) and imgApproved
if (result):
break
return result
def save_musicbrainz_cover(self,inID,saveStr):
imgData = None
result = False
try:
imgData = musicbrainzngs.get_image_front(inID, size="500")
except:
print("MusicBrainz image retrieval error for id "+inID)
if (imgData is not None) and (len(imgData) > 0):
dataBytes = io.BytesIO(imgData)
imgCvr = Image.open(dataBytes)
imgCvr.save(saveStr)
result = True
return result
def get_cover_image_online(self):
global aasDir
got_cover = False
albumExclude = ['hitzone','now that’s what i call music']
# only care about the first artist listed if separated by slashes
newArtist = self.fix_artist().replace("'","’")
setExtend = (self.cbExtend.get_sensitive() and self.cbExtend.get_active())
searchArtist = newArtist
newTitle = self.streamInfo["Title"].replace("'","’")
baseStr = str(newArtist+" - "+self.streamInfo["Title"]).replace(" ","_").replace("/","_").replace(":","_")+".jpg"
saveStr = os.path.join(aasDir, baseStr)
if ((newArtist=="") and (newTitle=="")):
self.displayLogo()
self.streamInfo['Album']=""
self.streamInfo['Genre']=""
return
# does it already exist?
if (os.path.isfile(saveStr)):
self.coverImage = saveStr
if (baseStr in self.coverMetas):
self.streamInfo['Album'] = self.coverMetas[baseStr][2]
self.streamInfo['Genre'] = self.coverMetas[baseStr][3]
# if not, get it from MusicBrainz
else:
try:
imgSaved = False
i = 1
while (not imgSaved):
setStrict = (i in [1,3,5,7])
setType = ''
if (i in [1,2,3,4]):
setType = 'Album'
setStatus = ''
if (i in [1,2,5,6]):
setStatus = 'Official'
result = None
try:
result = musicbrainzngs.search_recordings(strict=setStrict, artist=searchArtist, recording=newTitle, type=setType, status=setStatus)
except:
print("MusicBrainz recording search error")
print("iteration =",i,".")
print("imgSaved =",imgSaved,".")
print("strict =",setStrict,".")
print("artist =",searchArtist,".")
print("recording =",newTitle,".")
print("type =",setType,".")
print("status =",setStatus,".")
if (result is not None) and ('recording-list' in result) and (len(result['recording-list']) != 0):
# loop through the list until you get a match
for (idx, release) in enumerate(result['recording-list']):
resultID = self.check_value('id',release,"")
resultScore = self.check_value('ext:score',release,"0")
resultArtist = self.check_value('artist-credit-phrase',release,"")
resultTitle = self.check_value('title',release,"")
resultGenre = self.check_value('name',self.check_value('tag-list',release,""),"")
scoreMatch = (int(resultScore) > 90)
artistMatch = (newArtist.lower() in resultArtist.lower())
titleMatch = (newTitle.lower() in resultTitle.lower())
recordingMatch = (artistMatch and titleMatch and scoreMatch)
# don't bother dealing with releases if artist, title and score don't match
resultStatus = ""
resultType = ""
resultAlbum = ""
resultArtist2 = ""
releaseMatch = False
imageMatch = False
if recordingMatch and ('release-list' in release):
for (idx2, release2) in enumerate(release['release-list']):
imageMatch = False
resultID = self.check_value('id',release2,"")
resultStatus = self.check_value('status',release2,"Official")
resultType = self.check_value('type',self.check_value('release-group',release2,""),"")
resultAlbum = self.check_value('title',release2,"")
resultArtist2 = self.check_value('artist-credit-phrase',release2,"")
typeMatch = (resultType in ['Single','Album','EP'])
statusMatch = (resultStatus == 'Official')
albumMatch = (not self.check_terms(resultAlbum, albumExclude))
artistMatch2 = (not ('Various' in resultArtist2))
releaseMatch = (artistMatch2 and albumMatch and typeMatch and statusMatch)
# don't bother checking for covers unless album, type, and status match
if releaseMatch:
imageMatch = self.check_musicbrainz_cover(resultID)
if (releaseMatch and imageMatch and ((idx2+1) < len(release['release-list']))):
break
if (recordingMatch and releaseMatch and imageMatch):
# got a full match, now get the cover art
if self.save_musicbrainz_cover(resultID,saveStr):
self.coverImage = saveStr
imgSaved = True
self.streamInfo['Album']=resultAlbum
self.streamInfo['Genre']=resultGenre
self.coverMetas[baseStr] = [self.streamInfo["Title"],self.streamInfo["Artist"],self.streamInfo["Album"],self.streamInfo["Genre"]]
if (imgSaved) and ((idx+1) < len(result['recording-list'])) or (not scoreMatch):
break
i = i + 1
# if we got an image or Strict was false the first time through, there's no need to run through it again
if (imgSaved) or (i == 9) or ((not setExtend) and (i == 2)):
break
# If no match use the station logo if there is one
if (not imgSaved):
self.coverImage = os.path.join(aasDir, self.stationLogos[self.stationStr][self.streamNum])
self.streamInfo['Album']=""
self.streamInfo['Genre']=""
except:
print("general error in the musicbrainz routine")
# now display it by simulating a window resize
self.showArtwork(self.coverImage)
def showArtwork(self, art):
if (art != "") and (art[-5:] != "/aas/"):
img_size = min(self.alignmentCover.get_allocated_height(), self.alignmentCover.get_allocated_width()) - 12
self.pixbuf = GdkPixbuf.Pixbuf.new_from_file(art)
self.pixbuf = self.pixbuf.scale_simple(img_size, img_size, GdkPixbuf.InterpType.BILINEAR)
self.imgCover.set_from_pixbuf(self.pixbuf)
def displayLogo(self):
global aasDir
if (self.stationStr in self.stationLogos):
# show station logo if it's cached
logo = os.path.join(aasDir, self.stationLogos[self.stationStr][self.streamNum])
if (os.path.isfile(logo)):
self.streamInfo["Logo"] = self.stationLogos[self.stationStr][self.streamNum]
self.coverImage = logo
self.showArtwork(logo)
else:
# add entry in database for the station if it doesn't exist
self.stationLogos[self.stationStr] = ["", "", "", "", "", "", "", ""]
def service_data_type_name(self, type):
for key, value in self.ServiceDataType.items():
if (key == type):
return value
def program_type_name(self, type):
for key, value in self.ProgramType.items():
if (key == type):
return value
def handle_window_resize(self):
if (self.pixbuf != None):
desired_size = min(self.alignmentCover.get_allocated_height(), self.alignmentCover.get_allocated_width()) - 12
self.pixbuf = self.pixbuf.scale_simple(desired_size, desired_size, GdkPixbuf.InterpType.BILINEAR)
self.imgCover.set_from_pixbuf(self.pixbuf)
def on_window_resized(self,window):
self.handle_window_resize()
def on_btnPlay_clicked(self, btn):
global aasDir
# start playback
if (not self.playing):
self.nrsc5Args = [self.nrsc5Path]
# update all of the spin buttons to prevent the text from sticking
self.spinFreq.update()
self.spinGain.update()
self.spinPPM.update()
self.spinRTL.update()
useSDRPlay = (self.cbxSDRRadio.get_active_text() == "SDRPlay")
# enable aas output if temp dir was created
if (aasDir is not None):
self.nrsc5Args.append("--dump-aas-files")
self.nrsc5Args.append(aasDir)
# set IP address if rtl_tcp is used
if (not(useSDRPlay)) and (self.cbDevIP.get_active()):
self.nrsc5Args.append("-H")
self.nrsc5Args.append(self.txtDevIP.get_text())
# set gain if auto gain is not selected
if (not self.cbAutoGain.get_active()):
self.streamInfo["Gain"] = round(self.spinGain.get_value(),2)
self.nrsc5Args.append("-g")
self.nrsc5Args.append(str(self.streamInfo["Gain"]))
# set ppm error if not zero
if (self.spinPPM.get_value() != 0):
self.nrsc5Args.append("-p")
self.nrsc5Args.append(str(int(self.spinPPM.get_value())))
# set rtl device number if not zero
if (not(useSDRPlay)) and (self.spinRTL.get_value() != 0):
self.nrsc5Args.append("-d")
self.nrsc5Args.append(str(int(self.spinRTL.get_value())))
# set log level to 2 if SDRPLay enabled
#if (self.cbSDRPlay.get_active()):
if (useSDRPlay):
self.nrsc5Args.append("-l2")
# set SDRPlay serial number if not blank
#if (self.cbSDRPlay.get_active()) and (self.txtSDRPlaySer.get_text() != ""):
if (useSDRPlay) and (self.txtSDRPlaySer.get_text() != ""):
self.nrsc5Args.append("-d")
self.nrsc5Args.append(self.txtSDRPlaySer.get_text())
# set SDRPlay antenna if not blank
#if (self.cbSDRPlay.get_active()) and (self.cbxSDRPlayAnt.get_active_text() != ""):
if (useSDRPlay) and (self.cbxSDRPlayAnt.get_active_text() != ""):
if self.cbxSDRPlayAnt.get_active_text() != "Auto":
self.nrsc5Args.append("-A")
self.nrsc5Args.append("Antenna "+self.cbxSDRPlayAnt.get_active_text())
# set frequency and stream
self.nrsc5Args.append(str(self.spinFreq.get_value()))
self.nrsc5Args.append(str(int(self.streamNum)))
print(self.nrsc5Args)
# start the timer
self.statusTimer = Timer(1, self.checkStatus)
self.statusTimer.start()
# disable the controls
self.spinFreq.set_sensitive(False)
self.cbxAspect.set_sensitive(False)
self.cbxSDRRadio.set_sensitive(False)
self.spinGain.set_sensitive(False)
self.spinPPM.set_sensitive(False)
self.spinRTL.set_sensitive(False)
self.txtDevIP.set_sensitive(False)
self.cbDevIP.set_sensitive(False)
self.txtSDRPlaySer.set_sensitive(False)
self.cbxSDRPlayAnt.set_sensitive(False)
self.btnPlay.set_sensitive(False)
self.btnStop.set_sensitive(True)
self.cbAutoGain.set_sensitive(False)
self.playing = True
self.lastXHDR = ""
self.lastLOT = ""
# start the player thread
self.playerThread = Thread(target=self.play)
self.playerThread.start()
self.stationStr = str(self.spinFreq.get_value())
self.displayLogo()
# check if station is bookmarked
self.bookmarked = False
freq = int((self.spinFreq.get_value()+0.005)*100) + int(self.streamNum + 1)
for b in self.bookmarks:
if (b[2] == freq):
self.bookmarked = True
break
self.get_bookmark_names()
self.btnBookmark.set_sensitive(not self.bookmarked)
if (self.notebookMain.get_current_page() != 3):
self.btnDelete.set_sensitive(self.bookmarked)
def get_bookmark_names(self):
self.booknames = ["","","","","","","",""]
freq = str(int((self.spinFreq.get_value()+0.005)*10))
for b in self.bookmarks:
test = str(b[2])
if (test[:-1] == freq):
self.booknames[int(test[-1])-1] = b[1]
def on_btnStop_clicked(self, btn):
# stop playback
if (self.playing):
self.playing = False
# shutdown nrsc5
if (self.nrsc5 is not None and not self.nrsc5.poll()):
self.nrsc5.terminate()
if (self.playerThread is not None) and (btn is not None):
self.playerThread.join(1)
# stop timer
self.statusTimer.cancel()
self.statusTimer = None
# enable controls
if (not self.cbAutoGain.get_active()):
self.spinGain.set_sensitive(True)
self.spinFreq.set_sensitive(True)
self.cbxAspect.set_sensitive(True)
self.cbxSDRRadio.set_sensitive(True)
self.spinPPM.set_sensitive(True)
self.spinRTL.set_sensitive(True)
self.txtDevIP.set_sensitive(True)
self.cbDevIP.set_sensitive(True)
self.txtSDRPlaySer.set_sensitive(True)
self.cbxSDRPlayAnt.set_sensitive(True)
self.btnPlay.set_sensitive(True)
self.btnStop.set_sensitive(False)
self.btnBookmark.set_sensitive(False)
self.cbAutoGain.set_sensitive(True)
# clear stream info
self.initStreamInfo()
self.btnBookmark.set_sensitive(False)
if (self.notebookMain.get_current_page() != 3):
self.btnDelete.set_sensitive(False)
def on_btnBookmark_clicked(self, btn):
# pack frequency and channel number into one int
freq = int((self.spinFreq.get_value()+0.005)*100) + int(self.streamNum + 1)
# create bookmark
bookmark = [
"{:4.1f}-{:1.0f}".format(self.spinFreq.get_value(), self.streamNum + 1),
self.streamInfo["Callsign"],
freq
]
self.bookmarked = True # mark as bookmarked
self.bookmarks.append(bookmark) # store bookmark in array
self.lsBookmarks.append(bookmark) # add bookmark to listview
self.btnBookmark.set_sensitive(False) # disable bookmark button
if (self.notebookMain.get_current_page() != 3):
self.btnDelete.set_sensitive(True) # enable delete button
self.get_bookmark_names()
def on_btnDelete_clicked(self, btn):
# select current station if not on bookmarks page
if (self.notebookMain.get_current_page() != 3):
station = int((self.spinFreq.get_value()+0.005)*100) + int(self.streamNum + 1)
for i in range(0, len(self.lsBookmarks)):
if (self.lsBookmarks[i][2] == station):
self.lvBookmarks.set_cursor(i)
break
# get station of selected row
(model, iter) = self.lvBookmarks.get_selection().get_selected()
station = model.get_value(iter, 2)
# remove row
model.remove(iter)
# remove bookmark
for i in range(0, len(self.bookmarks)):
if (self.bookmarks[i][2] == station):
self.bookmarks.pop(i)
break
if (self.notebookMain.get_current_page() != 3 and self.playing):
self.btnBookmark.set_sensitive(True)
self.bookmarked = False
self.get_bookmark_names()
def on_btnAbout_activate(self, btn):
global resDir
# sets up and displays about dialog
if self.about_dialog:
self.about_dialog.present()
return
authors = [
"Cody Nybo <[email protected]>",
"Clayton Smith <[email protected]>",
"zefie <[email protected]>",
"Mark J. Fine <[email protected]>"
]
license = """
NRSC5 DUI - A second-generation graphical interface for nrsc5
Copyright (C) 2017-2019 Cody Nybo & Clayton Smith, 2019 zefie, 2021-24 Mark J. Fine
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>."""
about_dialog = Gtk.AboutDialog()
about_dialog.set_transient_for(self.mainWindow)
about_dialog.set_destroy_with_parent(True)
about_dialog.set_name(self.app_name)
about_dialog.set_program_name(self.app_name)
about_dialog.set_version(self.version)
about_dialog.set_copyright(self.copyright)
about_dialog.set_website(self.web_addr)
about_dialog.set_comments("A second-generation graphical interface for nrsc5.")
about_dialog.set_authors(authors)
about_dialog.set_license(license)
about_dialog.set_logo(GdkPixbuf.Pixbuf.new_from_file(os.path.join(resDir,"logo.png")))
# callbacks for destroying the dialog
def close(dialog, response, editor):
editor.about_dialog = None
dialog.destroy()
def delete_event(dialog, event, editor):
editor.about_dialog = None
return True
about_dialog.connect("response", close, self)
about_dialog.connect("delete-event", delete_event, self)
self.about_dialog = about_dialog
about_dialog.show()
def on_stream_changed(self):
self.lastXHDR = ""
self.lastLOT = ""
self.streamInfo["Title"] = ""
self.streamInfo["Album"] = ""
self.streamInfo["Artist"] = ""
self.streamInfo["Genre"] = ""
self.streamInfo["Cover"] = ""
self.streamInfo["Logo"] = ""
self.streamInfo["Bitrate"] = 0
self.set_program_btns()
if self.playing:
self.nrsc5msg = str(self.streamNum)
self.displayLogo()
def set_program_btns(self):
self.btnAudioPrgs0.set_active(self.update_btns and self.streamNum == 0)
self.btnAudioPrgs1.set_active(self.update_btns and self.streamNum == 1)
self.btnAudioPrgs2.set_active(self.update_btns and self.streamNum == 2)
self.btnAudioPrgs3.set_active(self.update_btns and self.streamNum == 3)
self.btnAudioPrgs4.set_active(self.update_btns and self.streamNum == 4)
self.btnAudioPrgs5.set_active(self.update_btns and self.streamNum == 5)
self.btnAudioPrgs6.set_active(self.update_btns and self.streamNum == 6)
self.btnAudioPrgs7.set_active(self.update_btns and self.streamNum == 7)
self.update_btns = True
def on_program_select(self, _label, evt):
stream_num = int(_label.get_property("name")[-1])
is_lbl = _label.get_property("name")[0] != "b"
self.update_btns = is_lbl
self.streamNum = stream_num
self.on_stream_changed()
def on_cbAutoGain_toggled(self, btn):
self.spinGain.set_sensitive(not btn.get_active())
self.lblGain.set_visible(btn.get_active())
def on_listviewBookmarks_row_activated(self, treeview, path, view_column):
if (len(path) != 0):
# get station from bookmark row
tree_iter = treeview.get_model().get_iter(path[0])
station = treeview.get_model().get_value(tree_iter, 2)
# set frequency and stream
self.spinFreq.set_value(float(int(station/10)/10.0))
self.streamNum = (station%10)-1
self.on_stream_changed()
# stop playback if playing
if (self.playing):
self.on_btnStop_clicked(None)
time.sleep(1)
# play bookmarked station
self.on_btnPlay_clicked(None)
def on_lvBookmarks_selection_changed(self, tree_selection):
# enable delete button if bookmark is selected
(model, pathlist) = self.lvBookmarks.get_selection().get_selected_rows()
self.btnDelete.set_sensitive(len(pathlist) != 0)
def on_bookmarkNameEdited(self, cell, path, text, data=None):
# update name in listview
iter = self.lsBookmarks.get_iter(path)
self.lsBookmarks.set(iter, 1, text)
# update name in bookmarks array
for b in self.bookmarks:
if (b[2] == self.lsBookmarks[path][2]):
b[1] = text
break
def on_notebookMain_switch_page(self, notebook, page, page_num):
# disable delete button if not on bookmarks page and station is not bookmarked
if (page_num != 3 and (not self.bookmarked or not self.playing)):
self.btnDelete.set_sensitive(False)
# enable delete button if not on bookmarks page and station is bookmarked
elif (page_num != 3 and self.bookmarked):
self.btnDelete.set_sensitive(True)
# enable delete button if on bookmarks page and a bookmark is selected
else:
(model, iter) = self.lvBookmarks.get_selection().get_selected()
self.btnDelete.set_sensitive(iter is not None)
def on_radMap_toggled(self, btn):
global mapDir, imgLANCZOS
if (btn.get_active()):
img_size = min(self.alignmentMap.get_allocated_height(), self.alignmentMap.get_allocated_width()) - 12
if (img_size < 200):
img_size = 200
if (btn == self.radMapTraffic):
self.mapData["mapMode"] = 0
mapFile = os.path.join(mapDir, "TrafficMap.png")
if (os.path.isfile(mapFile)): # check if map exists
mapImg = Image.open(mapFile).resize((img_size, img_size), imgLANCZOS) # scale map to fit window
self.imgMap.set_from_pixbuf(imgToPixbuf(mapImg)) # convert image to pixbuf and display
else: