/
default.py
2089 lines (1937 loc) · 80.9 KB
/
default.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 -*-
# * 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 2, 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; see the file LICENSE.txt. If not, write to
# * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
# * http://www.gnu.org/copyleft/gpl.html
# *
# Modules General
import os
import glob
import sys
import mmap
import time
import datetime
import re
import traceback
from _winreg import *
import subprocess
from operator import itemgetter
import ctypes
import threading
from collections import namedtuple, deque
from ctypes import wintypes
# Modules XBMC
simul = False #'kodi' not in sys.executable.lower()
if simul:
import xbmcsim as xbmc
else:
import xbmc
import xbmcgui
import xbmcaddon
import xbmcvfs
try:
from PIL import Image as PILImage
except:
from resources.lib.dummypil import DummyPILImage as PILImage
# Modules AmbiBox
from resources.lib.ambibox import AmbiBox
from resources.lib.abxtimer import Timer
from resources.lib.xbmcoutput import notification, debug, info
from resources.lib.mediainfofromlog import get_log_mediainfo
from resources.lib.ambiwincon import *
AR_16x9 = 16.0/9.0
AR_4x3 = 4.0/3.0
TERM = chr(240)
refresh_settings = True
killonoffmonitor = False
__language__ = None
if not simul:
__addon__ = xbmcaddon.Addon()
__cwd__ = xbmc.translatePath(__addon__.getAddonInfo('path')).decode('utf-8')
__scriptname__ = __addon__.getAddonInfo('name')
__version__ = str(__addon__.getAddonInfo('version'))
__settings__ = xbmcaddon.Addon("script.ambibox")
__language__ = __settings__.getLocalizedString
__settingsdir__ = xbmc.translatePath(os.path.join(__cwd__, 'resources'))
__resource__ = xbmc.translatePath(os.path.join(__cwd__, 'resources', 'lib'))
__addon_datadir__ = xbmc.translatePath('special://userdata//addon_data')
mediax = None
screenx = 0
screeny = 0
sar = 0.0
ambibox = None
scriptsettings = None
gplayer = None
xbmcd_results = None
kbs = None
Arprofile_info = namedtuple('Arprofile_info', 'profile_name, aspectratio, lower_lmt, upper_lmt')
xbmc_version = 0
led_height = 0
led_width = 0
if hasattr(xbmc.RenderCapture(), 'waitForCaptureStateChangeEvent'):
legacyRC = True
else:
legacyRC = False
else:
legacyRC = False
msg = '### kodi.script.ambibox - Kodi running in simulation mode. sys.executable = %s' % sys.executable
try:
xbmc.log(msg)
except:
print msg
#
# class RenderCaptureLegacy(xbmc.RenderCapture):
#
# def __init__(self):
# super(RenderCaptureLegacy, self).__init__()
class RenderCaptureKrypton(xbmc.RenderCapture):
def __init__(self):
super(RenderCaptureKrypton, self).__init__()
self.width = 0
self.height = 0
self.lastw = -1
self.lasth = -1
self.timeout = 0
self.blank = bytearray(b'')
self.image = None
self.capturestate = xbmcCAPTURE_STATE_WORKING
self.firstrequest = True
def create_image(self, w, h):
if self.lastw != w or self.lasth != h:
image = '\xFF\0\0\xFF' * (w * h)
self.image = bytearray(image)
self.lastw = w
self.lasth = h
def capture(self, rc_width, rc_height, _=None):
self.width = rc_width
self.height = rc_height
self.create_image(rc_width, rc_height)
self.firstrequest = True
def waitForCaptureStateChangeEvent(self, timeout):
super(RenderCaptureKrypton, self).capture(self.width, self.height)
image = super(RenderCaptureKrypton, self).getImage(2 * timeout)
if image == self.blank:
if self.firstrequest:
self.capturestate = xbmcCAPTURE_STATE_DONE
self.firstrequest = False
else:
self.capturestate = xbmcCAPTURE_STATE_WORKING
else:
self.image = image
self.capturestate = xbmcCAPTURE_STATE_DONE
def getCaptureState(self):
return self.capturestate
def getImage(self):
return self.image
if legacyRC:
RenderCapture = xbmc.RenderCapture
xbmcCAPTURE_FLAG_CONTINUOUS = xbmc.CAPTURE_FLAG_CONTINUOUS
xbmcCAPTURE_STATE_DONE = xbmc.CAPTURE_STATE_DONE
xbmcCAPTURE_STATE_WORKING = xbmc.CAPTURE_STATE_WORKING
xbmcCAPTURE_STATE_FAILED = xbmc.CAPTURE_STATE_FAILED
else:
RenderCapture = RenderCaptureKrypton
xbmcCAPTURE_FLAG_CONTINUOUS = 0
xbmcCAPTURE_STATE_DONE = 1
xbmcCAPTURE_STATE_WORKING = 0
xbmcCAPTURE_STATE_FAILED = 0
def start_debugger(remote=False):
if remote:
if xbmcvfs.exists(
r'C:\\Users\\Ken User\\AppData\\Roaming\\Kodi\\addons\\script.ambibox\\resources\\lib\\'
r'pycharm-debug.py3k\\'):
sys.path.append(
r'C:\\Users\\Ken User\\AppData\\Roaming\\Kodi\\addons\\script.ambibox\\resources\\lib\\'
r'pycharm-debug.py3k\\')
import pydevd
pydevd.settrace('192.168.1.103', port=51234, stdoutToServer=True, stderrToServer=True, suspend=False)
else:
if xbmcvfs.exists(r"C:\Program Files (x86)\JetBrains\PyCharm 2016.2\debug-eggs\pycharm-debug-py3k.egg"):
sys.path.append(r"C:\Program Files (x86)\JetBrains\PyCharm 2016.2\debug-eggs\pycharm-debug-py3k.egg")
import pydevd
pydevd.settrace('localhost', port=51234, stdoutToServer=True, stderrToServer=True, suspend=False)
# start_debugger()
def chk_mediainfo():
# Check if user has installed mediainfo.dll to resources/lib or has installed full Mediainfo package
global mediax
__usingMediaInfo__ = False
if mediax is None:
mi_url = xbmc.translatePath(os.path.join(__resource__ + '\\mediainfo.dll'))
if xbmcvfs.exists(mi_url):
__usingMediaInfo__ = True
else:
try:
aReg = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
key = OpenKey(aReg, r'Software\Microsoft\Windows\CurrentVersion\App Paths\MediaInfo.exe')
path = QueryValue(key, None)
CloseKey(key)
CloseKey(aReg)
if path != '':
__usingMediaInfo__ = True
except WindowsError:
pass
if __usingMediaInfo__ is True:
#from media import *
try:
# import media as mediax
from resources.lib.media import Media as mediax
except ImportError:
mediax = None
class Profiles(object):
def __init__(self):
self._profile_dict = dict()
def add(self, name, is_xbmc_direct):
self._profile_dict[name] = is_xbmc_direct
def profiles(self):
return self._profile_dict
def __len__(self):
return len(self._profile_dict)
def is_xbmc_direct(self, name):
if name in self._profile_dict:
return self._profile_dict[name]
else:
return None
class XbmcAmbibox(AmbiBox):
LIGHTS_ON = True
LIGHTS_OFF = False
def __init__(self, host, port):
self.ambiboxw_installed = False
self.is_installed = False
self.chkAmibiboxInstalled()
self.is_running = False
self.chk_ambiboxw_running()
self.xbmc_started_ambiboxw = False
self.leds_on = False
self.current_profile = ''
self.ambibox_process = None
self.profiles = []
super(XbmcAmbibox, self).__init__(host, port)
if __settings__.getSetting('start_ambibox') == 'true' and self.is_running is False:
self.start_ambiboxw()
self.retrieve_profiles()
self.manual_off = False
def get_profiles(self):
if len(self.profiles) == 0:
self.retrieve_profiles()
return list(self.profiles)
def retrieve_profiles(self):
if self.connect() == 0:
self.profiles = self.getProfiles()
else:
self.profiles = []
aReg = ConnectRegistry(None, HKEY_CURRENT_USER)
try:
key = OpenKey(aReg, r'Software\Server IR\Backlight\Profiles')
profileCount = QueryValueEx(key, 'ProfilesCount')
if isinstance(profileCount[0], int):
count = int(profileCount[0])
else:
count = 0
for i in xrange(0, count):
key = OpenKey(aReg, r'Software\Server IR\Backlight\Profiles')
pname = QueryValueEx(key, 'ProfileName_%s' % str(i))
self.profiles.append(str(pname[0]))
CloseKey(aReg)
except WindowsError or EnvironmentError, e:
info("Error reading profiles from registry")
if hasattr(e, 'message'):
info(str(e.message))
return
except Exception, e:
info("Other error reading profiles from registry")
if hasattr(e, 'message'):
info(str(e.message))
return
def chkAmibiboxInstalled(self):
# returns number of profiles if installed, 0 if installed with no profiles, -1 not installed
aReg = ConnectRegistry(None, HKEY_CURRENT_USER)
try:
key = OpenKey(aReg, r'Software\Server IR\Backlight\Profiles')
profileCount = QueryValueEx(key, 'ProfilesCount')
if int(profileCount[0]) == 0:
ret = 0
else:
ret = int(profileCount[0])
CloseKey(key)
except WindowsError or EnvironmentError:
ret = -1
CloseKey(aReg)
if ret > 0:
self.is_installed = True
if ret == 0:
notification(__language__(32006)) # @[No profiles configured in Ambibox]
info('No profiles found in Ambibox')
elif ret == -1:
notification(__language__(32007)) # @[AmbiBox installation not found: exiting script]
info('Ambibox installation not found: terminating script')
sys.exit()
return ret
def chk_ambiboxw_running(self):
proclist = []
cmd = 'WMIC PROCESS get Caption,Commandline,Processid'
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
for line in proc.stdout:
proclist.append(str(line))
proc.terminate()
del proc
proclist.sort()
self.is_running = False
for proc in proclist:
if proc[0:7] == "AmbiBox":
self.is_running = True
break
elif str(proc[0:1]).lower() == 'b':
break
return self.is_running
def start_ambiboxw(self):
if self.is_running is False:
self.chk_ambiboxw_running()
if self.is_installed and self.is_running is False:
aReg = ConnectRegistry(None, HKEY_CURRENT_USER)
try:
key = OpenKey(aReg, r'Software\Server IR')
p = QueryValueEx(key, 'InstallPath')
ambiboxpath = xbmc.translatePath(str(p[0]) + r'\Ambibox.exe')
CloseKey(key)
CloseKey(aReg)
except WindowsError:
CloseKey(aReg)
return False
try:
popobj = subprocess.Popen([ambiboxpath])
self.ambibox_process = popobj
pid = popobj.pid
except WindowsError as e:
notification(__language__(32008)) # @[Ambibox could not be started]
info('Could not start AmbiBox executable')
if hasattr(e, 'message'):
info(e.message)
sys.exit()
else:
if pid is not None:
self.is_running = True
self.lightSwitch(self.LIGHTS_OFF)
return True
else:
notification(__language__(32008)) # @[Ambibox could not be started]
info('Could not start AmbiBox executable')
sys.exit()
def __del__(self):
if self.ambibox_process is not None:
self.close()
def set_profile(self, profile, enable=True, force=False):
"""
If connected to AmbiBox, change the profile to profile.
If force = true, turn on lights regardless of state
@type enable: string (either 'true' or 'false')
@type profile: string
@type force: bool
@rtype: None
"""
self.current_profile = profile
if self.connect() == 0:
self.lock()
if profile != 'None':
notification(__language__(32033) % profile) # @[Set profile %s]
self.setProfile(profile)
else:
notification(__language__(32032)) # @[Ambibox turned off]
self.unlock()
if force or profile != 'None':
self.lightSwitch(self.LIGHTS_ON)
else:
self.lightSwitch(self.LIGHTS_OFF)
def lightSwitch(self, lightChangeState):
global scriptsettings
"""
lightchangestate is class constant either LIGHTS_ON or LIGHTS_OFF
@param lightChangeState: LIGHTS_ON or LIGHTS_OFF
@type lightChangeState: bool
@rtype: None
"""
if self.connect() == 0:
self.lock()
try:
if lightChangeState is self.LIGHTS_ON and self.manual_off is False:
self.turnOn()
elif lightChangeState is self.LIGHTS_OFF:
self.turnOff()
except Exception:
pass
self.unlock()
def switch_to_default_profile(self):
global scriptsettings
if scriptsettings.settings['default_enable'] is True:
self.set_profile(scriptsettings.settings['default_profile'])
else:
self.lightSwitch(self.LIGHTS_OFF)
def close(self):
try:
if self.ambibox_process is not None:
self.ambibox_process.terminate()
self.ambibox_process = None
except Exception as e:
info('Error deleting ambibox process')
if hasattr(e, 'message'):
info(str(e.message))
class ScriptSettings(object):
def __init__(self):
self.settings = dict()
self.aspect_ratio_codes = ['43', '32', '169', '185', '22', '24']
self.ar_dict = {'43': AR_4x3, '32': 1.5, '69': AR_16x9, '85': 1.85, '22': 2.2, '24': 2.4}
self.stereo_modes = ['2D', '3DS', '3DT']
self.aspect_ratio_settings = []
self.profiles = Profiles()
self.refresh_settings()
def refresh_settings(self):
global __settings__
__settings__ = xbmcaddon.Addon('script.ambibox')
self.settings = dict()
settingliststr = ['host', 'port', 'notification', 'default_profile', 'audio_profile',
'video_profile', 'key_on_str', 'key_off_str', 'key_incr_str', 'key_decr_str',
'key_cap_str', 'key_cap_dir', 'XBMCD_profile']
settinglistint = ['video_choice', 'directXBMC_quality']
settinglistbool = ['notification', 'start_ambibox', 'default_enable', 'audio_enable', 'disable_on_screensaver',
'show_menu', 'use_threading', 'instrumented', '3D_enable', 'key_use_onoff', 'key_on_shift',
'key_on_ctrl', 'key_on_alt', 'key_off_shift', 'key_off_ctrl', 'key_off_alt', 'key_use_delay',
'key_incr_shift', 'key_incr_ctrl', 'key_incr_alt', 'key_decr_shift', 'key_decr_ctrl',
'key_decr_alt', 'key_use_cap', 'key_cap_shift', 'key_cap_ctrl', 'key_cap_alt']
settinglistfloat = ['throttle', 'delay']
for s in settingliststr:
self.settings[s] = str(__settings__.getSetting(s)).decode('utf-8')
for s in settinglistint:
try:
self.settings[s] = int(__settings__.getSetting(s))
except ValueError:
info('Error reading integer settings')
for s in settinglistbool:
if __settings__.getSetting(s) == 'true':
self.settings[s] = True
else:
self.settings[s] = False
for s in settinglistfloat:
self.settings[s] = float(__settings__.getSetting(s))
if int(self.settings['delay']) % 25 != 0:
# make delay a mulitple of 25 msec
global refresh_settings
self.settings['delay'] = float(((self.settings['delay'] + 12.5) // 25) * 25)
refresh_settings = False
__settings__.setSetting('delay', str(self.settings['delay']))
refresh_settings = True
self.chkProfileSettings()
self.updateprofilesettings()
self.get_ar_profiles()
self.get_profile_types_from_reg()
info('Settings refreshed')
def check_manual_switch(self):
global __settings__
__settings__ = xbmcaddon.Addon('script.ambibox')
return __settings__.getSetting('manual_switch')
def get_ar_profiles(self):
global ambibox
global Arprofile_info
arprofiles = {}
ambiboxprofiles = ambibox.get_profiles()
for stereomode in self.stereo_modes:
tempprofiles = []
for ar_code in self.aspect_ratio_codes:
settingid = '%s_%s' % (stereomode, ar_code)
profl = __settings__.getSetting(settingid)
if profl != 'None':
spfl = settingid[len(settingid) - 2:]
ar = self.ar_dict[spfl]
ar_profileinfo = Arprofile_info(profile_name=profl, aspectratio=ar, lower_lmt=ar, upper_lmt=ar)
if profl in ambiboxprofiles:
tempprofiles.append(ar_profileinfo)
elif not ambiboxprofiles:
#Should never get to this statement
info("Profile existance not checked due to unavailability of Amibibox API")
tempprofiles.append(ar_profileinfo)
tempprofiles.sort(key=itemgetter(1))
arprofiles[stereomode] = tempprofiles
for stereomode in self.stereo_modes:
tempprofiles = arprofiles[stereomode]
i1 = len(tempprofiles)
new_profiles = []
for i, pfl in enumerate(tempprofiles):
if i == 0:
ll = 0.1
else:
ll = float((pfl.aspectratio + tempprofiles[i - 1].aspectratio) / 2)
if i == i1 - 1:
ul = 99
else:
ul = float((pfl.aspectratio + tempprofiles[i + 1].aspectratio) / 2)
new_profile_info = Arprofile_info(profile_name=pfl.profile_name, aspectratio=pfl.aspectratio,
lower_lmt=ll, upper_lmt=ul)
new_profiles.append(new_profile_info)
arprofiles[stereomode] = new_profiles
self.aspect_ratio_settings = arprofiles
def get_profile_types_from_reg(self):
global led_height, led_width
reg_pfl_names = []
aReg = ConnectRegistry(None, HKEY_CURRENT_USER)
try:
key = OpenKey(aReg, r'Software\Server IR')
led_count = QueryValueEx(key, 'DMX Channel Count')[0] + 1
except WindowsError:
led_count = 80
led_height = led_count / (2 * (sar + 1))
led_width = int((led_height * sar) + 0.5)
led_height = int(led_height + 0.5)
info('LEDS - count %s, width %s, height %s' % (led_count, led_width, led_height))
try:
key = OpenKey(aReg, r'Software\Server IR\Backlight\Profiles')
profileCount = QueryValueEx(key, 'ProfilesCount')
if isinstance(profileCount[0], int):
count = int(profileCount[0])
else:
count = 0
for i in xrange(0, count):
key = OpenKey(aReg, r'Software\Server IR\Backlight\Profiles')
pname = QueryValueEx(key, 'ProfileName_%s' % str(i))
reg_pfl_names.append(str(pname[0]))
try:
key = OpenKey(aReg, r'Software\Server IR\Backlight\Profiles\%s' % str(pname[0]))
except Exception, e:
info('Error opening registry key for profile: %s' % str(pname[0]))
continue
backlight_plugin_name = QueryValueEx(key, 'BacklightPluginName')
grabber = QueryValueEx(key, 'Grabber')
debug('Profile - Pname: %s Plugin: %s Grabber: %s' % (pname[0], backlight_plugin_name[0], grabber[0]))
if grabber[0] == 8:
self.profiles.add(pname[0], True)
else:
self.profiles.add(pname[0], False)
if pname[0] == self.settings['XBMCD_profile']:
if grabber[0] == 8:
info('Profile %s found and correctly configured for XBMCDirect' % pname[0])
else:
info('Profile %s found however, it is incorrectly configured for XBMCDirect' % pname[0])
CloseKey(aReg)
except WindowsError or EnvironmentError, e:
info("Error reading profile types from registry")
if hasattr(e, 'message'):
info(str(e.message))
return
except Exception, e:
info("Other error reading profile types from registry")
if hasattr(e, 'message'):
info(str(e.message))
return
def chkProfileSettings(self):
global scriptsettings
if ambibox.connect() == 0:
pfls = ambibox.get_profiles()
sets2chk = ['default_profile', 'audio_profile', 'video_profile']
vidfmts = ['2D', '3DS', '3DT']
ars = ['43', '32', '169', '185', '22', '24']
for vidfmt in vidfmts:
for ar in ars:
setn = vidfmt + '_' + ar
sets2chk.append(setn)
dirty = False
for setn in sets2chk:
pname = __settings__.getSetting(setn)
if pname != 'None':
if not (pname in pfls):
dirty = True
__settings__.setSetting(setn, 'None')
info('Missing profile %s set to None' % setn)
if dirty is True:
self.refresh_settings()
def createdummyprofile_files(self, pfls):
pfls.append('None')
pfldir = os.path.join(__addon_datadir__, 'script.ambibox', 'profiles')
if os.path.exists(pfldir) is False:
try:
os.makedirs(pfldir)
except Exception as e:
# e = sys.exc_info()[0]
msg='Error creating profile directory: '
if hasattr(e, 'message'):
msg = str(e.message)
msg = msg + '\n' + traceback.format_exc()
info(msg)
for fl in glob.glob(os.path.join(pfldir, '*')):
try:
os.remove(fl)
except Exception as e:
# e = sys.exc_info()[0]
msg='Error deleting old profiles: '
if hasattr(e, 'message'):
msg = str(e.message)
msg = msg + '\n' + traceback.format_exc()
info(msg)
for pfl in pfls:
try:
with open(os.path.join(pfldir, pfl), 'w') as f:
f.write('x')
except Exception as e:
# e = sys.exc_info()[0]
msg='Error creating profile files: '
if hasattr(e, 'message'):
msg = str(e.message)
msg = msg + '\n' + traceback.format_exc()
info(msg)
def updateprofilesettings(self):
# updates choices (values="..") in settings.xml with profiles present in Ambibox program
pstrl = []
if ambibox.connect() == 0:
pfls = ambibox.get_profiles()
numpfls = len(pfls)
info('%s profile(s) retrieved from program' % numpfls)
# defpfl = 'None'
# pstrl.append('None')
# pstrl.append('|')
# for pfl in pfls:
# pstrl.append(str(pfl))
# pstrl.append('|')
# if str(pfl).lower() == 'default':
# defpfl = str(pfl)
# del pstrl[-1]
self.createdummyprofile_files(pfls)
# pstr = "".join(pstrl)
# info('Trying to open: %s\\settings.xml for rw' % __settingsdir__)
# try:
# with open('%s\\settings.xml' % __settingsdir__, 'r+') as f:
# f.read()
# except:
# e = sys.exc_info()[0]
# msg='Error opening settings.xml file(%s\\settings.xml) for rw: ' % __settingsdir__
# if hasattr(e, 'message'):
# msg = str(e.message)
# msg = msg + '\n' + traceback.format_exc()
# info(msg)
# else:
# info('Settings.xml successfully opened for rw')
# try:
# doc = ET.parse(__settingsdir__ + "\\settings.xml")
# repl = ".//setting[@type='labelenum']"
# fixg = doc.iterfind(repl)
# for fixe in fixg:
# fixe.set('values', pstr)
# fixe.set('default', defpfl)
# doc.write(__settingsdir__ + "\\settings.xml")
# xbmc.executebuiltin('UpdateLocalAddons')
# except:
# e = sys.exc_info()[0]
# msg='Error opening settings.xml file for ET.parse: '
# if hasattr(e, 'message'):
# msg = str(e.message)
# msg = msg + '\n' + traceback.format_exc()
# info(msg)
def set_setting(self, name, value):
global __settings__
__settings__ = xbmcaddon.Addon('script.ambibox')
__settings__.setSetting(name, value)
self.settings[name] = value
class CapturePlayer(xbmc.Player):
def __init__(self, *args):
self.re3D = re.compile("[-. _]3d[-. _]", re.IGNORECASE)
self.reTAB = re.compile("[-. _]h?tab[-. _]", re.IGNORECASE)
self.reSBS = re.compile("[-. _]h?sbs[-. _]", re.IGNORECASE)
self.onPBSfired = False
self.mi_called = False
self.xd = None
self.playing_file = ''
super(CapturePlayer, self).__init__(*args)
def showmenu(self):
menu = ambibox.get_profiles()
menu.append(__language__(32021)) # @[Backlight off]
menu.append(__language__(32022)) # @[Backlight on]
off = len(menu) - 2
on = len(menu) - 1
mquit = False
xbmc.sleep(100)
selected = xbmcgui.Dialog().select(__language__(32020), menu) # @[Select profile]
while not mquit:
if selected != -1:
if (off == int(selected)):
ambibox.lightSwitch(ambibox.LIGHTS_OFF)
elif (on == int(selected)):
ambibox.lightSwitch(ambibox.LIGHTS_ON)
else:
ambibox.set_profile(menu[selected])
info('Using menu profile: %s' % str(menu[selected]))
mquit = True
def onPlayBackPaused(self):
info('Playback paused')
def onPlayBackResumed(self):
info('Playback resumed')
if self.getPlayingFile() != self.playing_file:
info('Firing onPlayBackStarted due to file change')
self.onPlayBackEnded()
self.onPlayBackStarted()
def get_aspect_ratio(self):
infos = [0, 0, 1, 1.78, 30.0]
if not legacyRC:
# New Kryton method
pps = ['videowidth', 'videoheight', '', 'videodar', 'videofps']
i = 0
fail = False
for pp in pps:
try:
inf = xbmc.getInfoLabel('Player.Process(%s)' % pp)
except RuntimeError:
i += 1
fail = True
else:
if pp in ['videowidth', 'videoheight']:
try:
inff = int(inf.replace(',', ''))
except ValueError:
fail = True
else:
infos[i] = inff
elif pp != '':
try:
inff = float(inf.replace(',',''))
except ValueError:
fail = True
else:
infos[i] = inff
i += 1
if not fail:
return infos
self.mi_called = False
# Get aspect ratio
# First try Log, then MediaInfo, then infoLabels, then Capture. Default to screen dimensions.
if legacyRC:
info("Reading log **************")
infox = get_log_mediainfo()
if infox is not None:
if infox['dwidth'] != 0:
infos[0] = infox['dwidth']
if infox['dheight'] != 0:
infos[1] = infox['dheight']
if infox['dar'] != 0:
infos[3] = infox['dar']
if infox['fps'] != 0:
infos[4] = infox['fps']
if infos[0] != 0 and infos[1] != 0:
info('Aspect ratio determined from log: %s' % infos[3])
debug('Log Mediainfo- %s' % str(infox))
return infos
# MediaInfo Method
try:
if self.playing_file == '':
self.playing_file = self.getPlayingFile()
except:
info('Error retrieving video file from xbmc.player')
if infos[0] != 0 and infos[1] != 0 and (mediax is not None):
if self.playing_file[0:3] != 'pvr': # Cannot use for LiveTV stream
if xbmcvfs.exists(self.playing_file):
try:
infos = mediax().getInfos(self.playing_file)
self.mi_called = True
except:
infos = [0, 0, 1, 0, 0]
else:
if infos[3] != 0:
info('Aspect ratio determined by mediainfo.dll = % s' % infos[3])
return infos
else:
info('mediainfo.dll returned AR = 0')
else:
infos = [0, 0, 1, 0, 0]
else:
xbmc.sleep(1000)
#Info Label Method
if infos[3] == 0:
while xbmc.getInfoLabel("VideoPlayer.VideoAspect") is None:
xbmc.sleep(500)
vp_ar = xbmc.getInfoLabel("VideoPlayer.VideoAspect")
try:
infos[3] = float(vp_ar)
except TypeError:
infos[3] = float(0)
else:
if infos[3] == 1.78:
infos[3] = AR_16x9
elif infos[3] == 1.33:
infos[3] = AR_4x3
info('Aspect ratio determined by InfoLabel = %s' % infos[3])
return infos
# Capture Method
if infos[3] == 0:
rc = RenderCapture()
infos[3] = rc.getAspectRatio()
if not (0.95 < infos[3] < 1.05) and infos[3] != 0:
info('Aspect ratio determined by XBMC.Capture = %s' % infos[3])
else:
# Fallback Method
infos[3] = sar
info('Aspect ratio not able to be determined - using screen AR = %s' % infos[3])
return infos
def get_stereo_format(self):
# Get Stereoscopic Information
# Use filename regex or fallback to infoLabels
#sm2 = getStereoscopicMode()
m = self.re3D.search(self.playing_file)
if m:
n = self.reTAB.search(self.playing_file)
if n:
vidfmt = "3DT"
else:
n = self.reSBS.search(self.playing_file)
if n:
vidfmt = "3DS"
else:
info("Error in 3D filename - using default settings")
vidfmt = "2D"
else:
stereomode = xbmc.getInfoLabel("VideoPlayer.StereoscopicMode")
if stereomode == 'top_bottom':
vidfmt = '3DT'
elif stereomode == 'left_right':
vidfmt = '3DS'
else:
vidfmt = "2D"
info('StereoMode: %s' % vidfmt)
return vidfmt
def get_dimensions_for_XBMCD(self, infos):
# If using XBMCDirect, get video dimensions, some guesswork needed for Infolabel method
# May need to use guessed ratio other than 1.778 as 4K video becomes more prevalent
if ((infos[0] == 0) or (infos[1] == 0)) and (mediax is not None) and not self.mi_called:
xxx = self.getPlayingFile()
if xxx[0:3] != 'pvr': # Cannot use for LiveTV stream
if xbmcvfs.exists(xxx):
try:
infos = mediax().getInfos(xxx)
except:
infos = [0, 0, 1, 0]
# InfoLabel Method
if (infos[0] == 0) or (infos[1] == 0):
vp_res = xbmc.getInfoLabel("VideoPlayer.VideoResolution")
if str(vp_res).lower() == '4k':
vp_res_int = 2160
else:
try:
vp_res_int = int(vp_res)
except ValueError or TypeError:
vp_res_int = 0
if vp_res_int != 0 and infos[3] != 0:
if infos[3] > AR_16x9:
infos[0] = int(vp_res_int * AR_16x9)
infos[1] = int(infos[0] / infos[3])
else:
infos[0] = int(infos[3] * vp_res_int)
infos[1] = vp_res_int
# Fallback
if (infos[0] == 0) or (infos[1] == 0):
infos[0] = screenx
infos[1] = screeny
# Set quality
quality = scriptsettings.settings['directXBMC_quality']
minq = led_height
if minq < 8:
minq = 8
if quality == 0:
infos[1] = 32
infos[0] = 32
# infos[1] = 3 * minq
# infos[0] = int(infos[1] * infos[3])
elif quality == 1:
infos[1] = 3 * minq
infos[0] = int(infos[1] * infos[3])
elif quality == 2:
infos[1] = 6 * minq
infos[0] = int(infos[1] * infos[3])
else:
if infos[3] > sar:
if infos[1] == 0:
infos[1] = screeny
infos[0] = int(infos[1] * infos[3])
else:
if infos[0] == 0:
infos[0] = screenx
infos[1] = int(infos[0] / infos[3])
return infos, quality
def onPlayBackStarted(self):
if self.xd is not None:
self.kill_XBMCDirect()
self.onPBSfired = True
if ambibox.connect() != 0:
return
counter = 0
while (not (self.isPlayingAudio() or self.isPlayingVideo())) and counter < 20:
xbmc.sleep(500)
counter += 1
if self.isPlayingAudio():
ambibox.set_profile(scriptsettings.settings["audio_profile"],
enable=scriptsettings.settings["audio_enable"])
if self.isPlayingVideo():
self.playing_file = self.getPlayingFile()
infos = self.get_aspect_ratio()
vidfmt = self.get_stereo_format()
XBMCD_profile = scriptsettings.settings['XBMCD_profile']
# Switch profile
if XBMCD_profile == 'None':
videomode = scriptsettings.settings["video_choice"]
if videomode == 0: # Use Default Video Profile
info('Using default video profile')
ambibox.set_profile(scriptsettings.settings["video_profile"])
elif videomode == 1: # Autoswitch
DAR = infos[3]
if DAR != 0:
self.setprofilebydar(DAR, vidfmt)
info('Autoswitched on AR')
else:
info("Error retrieving DAR from video file")
elif videomode == 2: # Show menu
self.showmenu()
info('Using menu for profile pick')
elif videomode == 3: # Turn off
info('User set lights off for video')
ambibox.lightSwitch(ambibox.LIGHTS_OFF)
else:
# XBMC Direct
info('Switching to profile %s for XBMCDirect' % XBMCD_profile)
profile_is_XBMCDirect = scriptsettings.profiles.is_xbmc_direct(XBMCD_profile)
if profile_is_XBMCDirect is True:
ambibox.set_profile(XBMCD_profile)
result = XBMCDresult()
result.fn = self.getPlayingFile()
result.height_orig = infos[0]
result.width_orig = infos[1]
result.fps_orig = infos[4]
infos, quality = self.get_dimensions_for_XBMCD(infos)
# Get other settings associated with XBMC Direct
use_threading = scriptsettings.settings['use_threading']
throttle = scriptsettings.settings['throttle']
instrumented = True # scriptsettings.settings['instrumented']
delay = scriptsettings.settings['delay']
result.width_capture = infos[0]
result.height_capture = infos[1]
result.threaded = use_threading
result.throttle = throttle
result.qual = quality
result.delay = delay
info('XBMCDirect throttle = %s, qual = %s, captureX = %s, captureY = %s, thread = %s, instr = %s'
% (throttle, quality, infos[0], infos[1], use_threading, instrumented))
info('Delay: %s ms' % str(delay))
#Start XBMC Direct
self.run_XBMCD(infos, vidfmt, result, use_threading, instrumented, throttle)
elif profile_is_XBMCDirect is False:
info('XBMCDirect not started because profile not using XBMCDirect')
elif profile_is_XBMCDirect is None:
info('XBMCDirect not started due to an error detecting whether or not profile uses XBMCDirect')
def onPlayBackEnded(self):
ambibox.switch_to_default_profile()