-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathrtmd2srt.py
1033 lines (881 loc) · 33.7 KB
/
rtmd2srt.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
import os
#multi-platform keyboard intercept load
if os.name == 'nt':
import msvcrt
else:
import select
import sys
import re
import io
import struct
import mmap
import math
import subprocess
import bitstring
from bitstring import ConstBitStream, BitArray #, BitStream, pack, Bits,
from datetime import datetime, timedelta
import argparse
import gpxpy
import gpxpy.gpx
#import gpxpy.gpx as mod_gpx
try:
import lxml.etree as mod_etree # Load LXML or fallback to cET or ET
except:
try:
import xml.etree.cElementTree as mod_etree
except:
import xml.etree.ElementTree as mod_etree
#Variables
parser = argparse.ArgumentParser(description='Extracts realtime meta-data from XAVC files and put to SRT (subtitle) file',)
parser.add_argument('infile',help='Put SOURCE XAVC S file path (ends with .MP4')
parser.add_argument('-muxmkv', action='store_true', help='Key to mux meta-data srt stream into new MKV file with ffmpeg')
parser.add_argument('-sidecar', action='store_true', help='Key to generate XML sidecar file from XAVC S file (if you lost original XML sidecar written by camera)')
parser.add_argument('-gpx', action='store_true', help='Write GPX Track file if GPS data available')
parser.add_argument('-check',action='store_true', help='Just output some basic file data')
parser.add_argument('-sens',action='store_true', help='Try to extract embedded gyroscope, accelerometer and OSS-sensor data if found (RX0M2 and RX100M7 only yet)')
args = parser.parse_args()
#print (args)
'''
GENERAL RTMD tags FORMAT
TAG ID (2 bytes)
ver? (1 byte)
tag length (1 byte)
TAG value (length = tag length)
RDD 18 tags from Mediainfo MXF parser (https://github.com/MediaArea/MediaInfoLib/blob/master/Source/MediaInfo/Multiple/File_Mxf.cpp):
0x3210: return "CaptureGammaEquation";
060E2B34040101010401010101020000 = rec.709
060E2B34040101010401010101030000 = SMPTE ST 240
06.0E.2B.34.04.01.01.vv.0E.xx.xx.xx.xx.xx.xx.xx = custom
0x3219 = CaptureColorPrimaries (rec709, S-Logx, Rec2100-HLG, e.t.c.)
0x321A = Coding Equations = (rec.709, rec2020nc, e.t.c.)
0x8000: return "IrisFNumber";
0x8001: return "FocusPositionFromImagePlane";
0x8002: return "FocusPositionFromFrontLensVertex";
0x8003: return "MacroSetting";
0x8004: return "LensZoom35mmStillCameraEquivalent";
0x8005: return "LensZoomActualFocalLength";
0x8006: return "OpticalExtenderMagnification";
0x8007: return "LensAttributes";
0x8008: return "IrisTNumber";
0x8009: return "IrisRingPosition";
0x800A: return "FocusRingPosition";
0x800B: return "ZoomRingPosition";
0x8100: return "AutoExposureMode";
0x8101: return "AutoFocusSensingAreaSetting";
0x8102: return "ColorCorrectionFilterWheelSetting";
0x8103: return "NeutralDensityFilterWheelSetting";
0x8104: return "ImageSensorDimensionEffectiveWidth";
0x8105: return "ImageSensorDimensionEffectiveHeight";
0x8106: return "CaptureFrameRate";
0x8107: return "ImageSensorReadoutMode";
0x8108: return "ShutterSpeed_Angle";
0x8109: return "ShutterSpeed_Time";
0x810A: return "CameraMasterGainAdjustment";
0x810B: return "ISOSensitivity";
0x810C: return "ElectricalExtenderMagnification";
0x810D: return "AutoWhiteBalanceMode";
0x810E: return "WhiteBalance";
0x810F: return "CameraMasterBlackLevel";
0x8110: return "CameraKneePoint";
0x8111: return "CameraKneeSlope";
0x8112: return "CameraLuminanceDynamicRange";
0x8113: return "CameraSettingFileURI";
0x8114: return "CameraAttributes";
0x8115: return "ExposureIndexofPhotoMeter";
0x8116: return "GammaForCDL";
0x8117: return "ASC_CDL_V12";
0x8118: return "ColorMatrix";
0xE000: UDAM ID (10 bytes) ???
unkn tags
E300 - 1 byte - in XAVC S always = 00
E301 - 4 bytes - ISO?
E302 - 1 byte - in XAVC S always = 01
E303 - 1 byte - in XAVC S always = FF (255)
E304 - 8 bytes - Current record date and time in YY-YY-MM-DD-HH-MM-SS format
'''
def getfn():
k=sub.find('0x8000',bytealigned = True)
if len(k) == 0 :
fn = 'N/A'
return fn
sub.pos+=32
fn = sub.read(16).uint
fn= 2**((1-float(fn)/65536)*8)
fn=round(fn,1)
return str(fn)
def getdist():
#DIST TAG = 0x8001
k=sub.find('0x8001',bytealigned = True)
if len(k) == 0 :
dist = 'N/A'
return dist
try:
sub.pos+=32
diste = sub.read('int:4')
distm = sub.read('uint:12')
dist = float(distm*(10**diste))
dist = round(dist,4)
if dist >= 65500 :
dist = 'Inf.'
else: dist = str(dist)+'m'
except (bitstring.ReadError, ValueError) : return 'N/A'
return dist
#Get Accel/Gyro TEST
gyro_temp = ['frame,ts,pitch,roll,yaw']
acc_temp = ['frame,ts,x,y,z']
oss_temp = ['frame,ts,scan,x,y,unkn']
gyro_ts = 0
acc_ts = 0
oss_ts = 0
#0xe43b
def get_gyro():
global gyro_ts
k=sub.find('0xe43b',bytealigned = True)
if len(k) == 0 :
return None
try:
sub.pos+=32
rows = sub.read('int:32')
sets = sub.read('int:32')
#os.system('cls')
#sys.stdout.write ('\rFrame: '+str(c))
for i in range(rows):
pitch = sub.read('intbe:16')
roll = sub.read('intbe:16')
yaw = sub.read('intbe:16')
gyro_ts += sdur/rows
gyro_temp.append(str(c)+','+str(gyro_ts)+','+str(pitch)+","+str(roll)+","+str(yaw))
except (bitstring.ReadError, ValueError) : return 'N/A'
return None
#0xe437 - 4 bytes
def get_0xe437():
k=sub.find('0xe437',bytealigned = True)
if len(k) == 0 :
dist = 'N/A'
return dist
try:
sub.pos+=32
rows = sub.read('int:32')
sys.stdout.write ('\n0x0437 =' + str(rows))
except (bitstring.ReadError, ValueError) : return 'N/A'
return None
#0xe447 - 4 bytes
def get_0xe447():
k=sub.find('0xe447',bytealigned = True)
if len(k) == 0 :
dist = 'N/A'
return dist
try:
sub.pos+=32
rows = sub.read('int:32')
sys.stdout.write (' 0x0447 =' + str(rows))
except (bitstring.ReadError, ValueError) : return 'N/A'
return None
#0xe447 - 8 bytes - Changing!!!
def get_0xe409():
k=sub.find('0xe409',bytealigned = True)
if len(k) == 0 :
dist = 'N/A'
return dist
try:
sub.pos+=32
#print ('0x0409 = ' + str(sub.read('int:32')) + ' '+ str(sub.read('int:32')))
except (bitstring.ReadError, ValueError) : return 'N/A'
return None
#0xe416
def get_oss_table():
global oss_ts
k=sub.find('0xe416',bytealigned = True)
if len(k) == 0 :
return None
try:
sub.pos+=32
rows = sub.read('int:32')
sets = sub.read('int:32')
if sets != 16: return None
for i in range (rows):
set=[]
for k in range (int(sets/4)):
#fn= 2**((1-float(sub.read('uint:16'))/65536)*8)
#fn=round(fn,1)
set.append(sub.read('int:32'))
oss_ts+=sdur/rows
#oss_temp.append(str(c)+'|'+str(set[0])+'|'+str(set[1])+'|'+str(set[2])+'|'+str(set[3])+'|'+str(set[4])+'|'+str(set[5])+'|'+str(set[6])+'|'+str(set[7]))
oss_temp.append(str(c)+','+str(oss_ts)+','+str(set[0])+','+str(set[1])+','+str(set[2])+','+str(set[3]))
#print(oss_temp)
#print(set)
#print()
"""
for i in range(rows):
oss_temp.append(str(c)+'|'+str(sub.read('int:32'))+'|'+str(sub.read('int:32'))+'|'+str(sub.read('int:32'))+'|'+str(sub.read('int:32')))
"""
except (bitstring.ReadError, ValueError) : return 'N/A'
return None
def get_0xe423():
global oss_ts
k=sub.find('0xe423',bytealigned = True)
if len(k) == 0 :
return None
try:
sub.pos+=8*12
rows = sub.read('int:32')
sets = sub.read('int:32')
#print(rows)
#print(sets)
if sets != 4: return None
sset=[]
for i in range (rows):
set=[]
for k in range (sets):
#fn= 2**((1-float(sub.read('uint:16'))/65536)*8)
#fn=round(fn,1)
set.append(sub.read('int:32'))
oss_ts+=sdur/rows
sset.append(set)
#oss_temp.append(str(c)+'|'+str(set[0])+'|'+str(set[1])+'|'+str(set[2])+'|'+str(set[3])+'|'+str(set[4])+'|'+str(set[5])+'|'+str(set[6])+'|'+str(set[7]))
#print(sset)
#print((str(c)+','+str(oss_ts)+','+str(set[0])+','+str(set[1])+','+str(set[2])+','+str(set[3])))
#oss_temp.append(str(c)+','+str(oss_ts)+','+str(set[0])+','+str(set[1])+','+str(set[2])+','+str(set[3]))
#print(oss_temp)
#print(set)
#print()
"""
for i in range(rows):
oss_temp.append(str(c)+'|'+str(sub.read('int:32'))+'|'+str(sub.read('int:32'))+'|'+str(sub.read('int:32'))+'|'+str(sub.read('int:32')))
"""
except (bitstring.ReadError, ValueError) : return 'N/A'
return None
#0xe44b
def get_accel():
global acc_ts
k=sub.find('0xe44b',bytealigned = True)
if len(k) == 0 :
return None
try:
sub.pos+=32
rows = sub.read('int:32')
sets = sub.read('int:32')
#os.system('cls')
#sys.stdout.write ('\rFrame: '+str(c))
for i in range(rows):
#a1e = sub.read('int:4')
x = sub.read('intbe:16')
#a2e = sub.read('int:4')
y = sub.read('intbe:16')
#a3e = sub.read('int:4')
z = sub.read('intbe:16')
acc_ts+=sdur/rows
#print("a1 =",round(float(a1*(10**a1e)),3), "a2 =",round(float(a2*(10**a2e)),3), "a3 =",round(float(a3*(10**a3e)),3))
#print("a2 =",float(a2*(10**a2e)))
#print("a3 =",float(a3*(10**a3e)))
#gyro_temp.append(str(c)+'|'+str(float(a1*(10**a1e)))+"|"+str(float(a2*(10**a2e)))+"|"+str(float(a3*(10**a3e))))
acc_temp.append(str(c)+','+str(acc_ts)+','+str(x)+","+str(y)+","+str(z))
#print (b1,b2,b3)
except (bitstring.ReadError, ValueError) : return 'N/A'
return None
#
def getss():
#SHUTTER SPEED TAG = 0x8109, 2 parts by 4 bytes
k = sub.find('0x810900',bytealigned = True)
if len(k) == 0 :
ss = 'N/A'
return ss
try:
sub.pos+=32
ss1 = sub.read(32).uint
ss2 = sub.read(32).uint
except (bitstring.ReadError, ValueError) : return 'N/A'
ss = str(ss1) + '/' +str(ss2)
return str(ss)
def getiso():
#ISO TAG = 0x810b,
k = sub.find('0x8115',bytealigned = True)
if len(k) == 0:
k = sub.find('0x810b00',bytealigned = True)
if len(k) == 0:
iso = 'N/A'
return iso
try:
sub.pos+=32
iso = sub.read(16).uint
except (bitstring.ReadError, ValueError, UnicodeDecodeError) : return 'N/A'
return str(iso)
def getdb():
k = sub.find('0x810a00',bytealigned = True)
if len(k) == 0:
db = 'N/A'
return db
sub.pos+=32
db = sub.read(16).uint/100
return str(db)
def getdz():
k = sub.find('0x810c00',bytealigned = True)
if len(k) == 0:
dz = 'N/A'
return dz
sub.pos+=32
dz = float(sub.read(16).uint)/100
return str(dz)
def getwbmode():
k = sub.find('0x810d',bytealigned = True)
if len(k) == 0:
wb = 'N/A'
return wb
try:
sub.pos+=32
wb = sub.read(8).int
if wb == 0:
wb = 'Man'
elif wb == 1:
wb = 'Auto'
elif wb == 2:
wb = 'Hold'
elif wb == 3:
wb = 'One Push'
except (bitstring.ReadError, ValueError, UnicodeDecodeError) : return 'N/A'
return str(wb)
def getaf():
k = sub.find('0x810100',bytealigned = True)
if len(k) == 0:
af = 'N/A'
return af
sub.pos+=32
af = sub.read(8).int
if af == 0:
af = 'MF'
elif af == 1:
af = 'AF Center'
elif af == 2:
af = 'AF Whole'
elif af == 3:
af = 'AF Multi'
elif af == 4:
af = 'AF Spot'
return str(af)
def gettime():
k = sub.find('0xe304',bytealigned = True)
if len(k) == 0:
time = 'N/A'
return time
try:
sub.pos+=40
time = str(sub.read(16).hex)+'/'+str(sub.read(8).hex)+'/'+str(sub.read(8).hex)+' '+str(sub.read(8).hex)+':'+str(sub.read(8).hex)+':'+str(sub.read(8).hex)
except (bitstring.ReadError, UnicodeDecodeError) : return 'N/A'
return str(time)
def getpasm():
k = sub.find('0x810000',bytealigned = True)
if len(k) == 0:
ae = 'N/A'
return ae
sub.pos+=32
ae = sub.read(16*8).hex
if ae == '060e2b340401010b0510010101010000' : ae = 'Exp.mode: M '
elif ae == '060e2b340401010b0510010101020000' : ae = 'Exp.mode: AUTO'
elif ae == '060e2b340401010b0510010101030000' : ae = 'Exp.mode: GAIN'
elif ae == '060e2b340401010b0510010101040000' : ae = 'Exp.mode: A'
elif ae == '060e2b340401010b0510010101050000' : ae = 'Exp.mode: S'
else : ae = 'N/A'
return ae
def getge():
k = sub.find('0x321000',bytealigned = True)
if len(k) == 0:
ge = 'N/A'
return ge
try:
sub.pos+=32
ge = sub.read(16*8).hex
if ge == '060e2b34040101010401010101020000' : ge = 'Gamma: rec709'
elif ge == '060e2b34040101010401010101030000' : ge = 'Gamma: SMPTE ST 240M'
elif ge == '060e2b340401010d0401010101080000' : ge = 'rec709-xvycc'
elif ge == '060e2b34040101060e06040101010602' : ge = 'Still'
elif ge == '060e2b34040101060e06040101010301' : ge = 'Cine1'
elif ge == '060e2b34040101060e06040101010302' : ge = 'Cine2'
elif ge == '060e2b34040101060e06040101010303' : ge = 'Cine3'
elif ge == '060e2b34040101060e06040101010304' : ge = 'Cine4'
elif ge == '060e2b34040101060e06040101010508' : ge = 'S-Log2'
elif ge == '060e2b34040101060e06040101010605' : ge = 'S-Log3-Cine'
elif ge == '060e2b34040101060e06040101010604' : ge = 'S-Log3'
elif ge == '060e2b340401010d04010101010b0000' : ge = 'Rec2100-HLG'
else :
ge = 'Gamma: Unkn/Custom'
sub.pos+=32
cp = sub.read(16*8).hex
if cp == '060e2b34040101060401010103030000' : ge = ge + '/rec709'
elif cp == '060e2b34040101060e06040101030103' : ge = ge + '/S-Gamut'
elif cp == '060e2b34040101060e06040101030104' : ge = ge + '/S-Gamut3'
elif cp == '060e2b34040101060e06040101030105' : ge = ge + '/S-Gamut3.Cine'
elif cp == '060e2b340401010d0401010103040000' : ge = ge + '/rec2020'
else :
cp == 'ColorSpace Unkn/Custom'
except (bitstring.ReadError, ValueError) : return 'N/A'
return ge
'''
GPS tags
0x8500 - 4 bytes - gps version - 2.2.0.0 (02020000)
0x8501 - 1 byte - LatitudeRef - N (4e)
0x8502 - 18h bytes - Latitude - [4]/[4]:[4]/[4]:[4]/[4] = 09:09:09.123
0x8503 - 1 byte - LongtitudeRef - E (45)
0x8504 - 18h bytes - Longtitude - [4]/[4]:[4]/[4]:[4]/[4] = 09:09:09.123
0x8505 - 1 byte - AltitudeRef (equal to 1)
0x8506 - 8 bytes - Altitude (meters) ([4]/[4]???). Second [4] almost always = 1000 dec
0x8507 - 18h bytes - Timestamp - [4]/[4]:[4]/[4]:[4]/[4] = 09:09:09.123
0x8509 - 1 byte - STATUS - 'A' (if GPS not acquired, = 'V')
0x850a - 1 byte - MeasureMode - (2 = 2D, 3 = 3D)
0x850b - 8 bytes - DOP ([4]/[4]???). Second [4] almost always = 1000 dec
read 0x850c - 1 byte - SpeedRef (K = km/h, M = mph, N = knots)
read 0x850d - 8 bytes ([4]/[4]???) - SPEED
read 0x850e - 1 byte - TrackRef (Direction Reference, T = True direction, M = Magnetic direction)
read 0x850f - Direction 8 bytes ([4]/[4]???) (degrees from 0.0 to 359.99)
0x8512 - 6 bytes - MapDatum - 57 47 53 2D 38 34 (WGS-84)
0x851d - 0a bytes - string (2018:10:30)
used in GPX:
lat (calculated from latref and lat)
lon (calculated from lonref and lon)
time (timestamp = date+timestamp in UTZ format)
MeasureMode
speed (in GPX 1.0 only!)
altitude (calculated from altref and alitude)
DOP (?HDOP, VDOP, PDOP?)
'''
def getgps(old_dt):
# k = sub.find('0x851200',bytealigned = True)
# if len(k) == 0:
# gps = 'N/A'
# return gps
try:
sub.find('0x85000004',bytealigned = True)
sub.pos+=32
#read 0x850000 - GPS Ver
gpsver = sub.read(4*8)
sub.pos+=32
#read 0x8501 - Latitude Ref (N or S)
latref = BitArray(sub.read(8))
latref = latref.tobytes().decode('utf-8')
sub.pos+=32
# read 0x8502 - latiture (6 chunks)
l1 = sub.read(4*8).uint
l2 = sub.read(4*8).uint
l3 = sub.read(4*8).uint
l4 = sub.read(4*8).uint
l5 = sub.read(4*8).uint
l6 = sub.read(4*8).uint
if ( l2 == 0 or l4 == 0 or l6 == 0):
gps = 'N/A'
return gps
#write latitute string for text output
lat = str(l1/l2) + '°' + str(l3/l4) + "'" + str(float(l5)/float(l6)) + '"'
latdd = round((float(l1)/float(l2) + (float(l3)/float(l4))/60 + (float(l5)/float(l6)/(60*60)) * (-1 if latref in ['W', 'S'] else 1)), 7)
sub.pos+=32
#read 0x8503 - longtitude ref (E or W)
lonref = BitArray(sub.read(8))
lonref = lonref.tobytes().decode('utf-8')
# read 0x8504 - lontgiture (6 chunks)
sub.pos+=32
l1 = sub.read(4*8).uint
l2 = sub.read(4*8).uint
l3 = sub.read(4*8).uint
l4 = sub.read(4*8).uint
l5 = sub.read(4*8).uint
l6 = sub.read(4*8).uint
if ( l2 == 0 or l4 == 0 or l6 == 0):
gps = 'N/A'
return gps
#write latitute string for text output
lon = str(float(l1)/float(l2)) + '°' + str(float(l3)/float(l4)) + "'" + str(float(l5)/float(l6)) + '"'
londd = round((float(l1)/float(l2) + float(l3)/float(l4)/60 + (float(l5)/float(l6)/(60*60)) * (-1 if lonref in ['W', 'S'] else 1)), 7)
k = sub.find('0x85050001',bytealigned = True)
if len(k) != 0 :
sub.pos+=32
#read 0x8505 - 1 bytes = AltitudeRef (0 = above sea level, 1 = below sea level)
x8505 = sub.read (8).uint
sub.pos+=32
#read 0x8506 - 8 bytes ([4]/[4]) - Altitude
x8506_1 = sub.read(4*8).uint
x8506_2 = sub.read(4*8).uint
x8506 = str(float(x8506_1)/float(x8506_2))
else : x8505 = None
sub.pos+=32
# read 0x8507 - timestamp (6 chunks)
l1 = sub.read(4*8).uint
l2 = sub.read(4*8).uint
l3 = sub.read(4*8).uint
l4 = sub.read(4*8).uint
l5 = sub.read(4*8).uint
l6 = sub.read(4*8).uint
if ( l2 == 0 or l4 == 0 or l6 == 0):
gps = 'N/A'
return gps
#write timestamp for text output (hh:mm:ss.xxx)
gpsts = str(int(float(l1)/float(l2))).zfill(2) + ':' + str(int(float(l3)/float(l4))).zfill(2) + ":" + str(int(float(l5)/float(l6))).zfill(2)
#print (gpsts)
sub.pos+=32
#read 0x8509 - GPS fix STATUS (not used yet)
gpsfix = BitArray(sub.read(8))
gpsfix = gpsfix.tobytes().decode('utf-8')
sub.pos+=32
# read 0x850a - GPS Measure mode (2 = 2D, 3 = 3D) - not used yet
gpsmeasure = BitArray(sub.read(8))
gpsmeasure = gpsmeasure.tobytes().decode('utf-8')
sub.pos+=32
#read 0x850b - 8 bytes ([4]/[4]) -- DOP -not used yet
x850b_1 = sub.read(4*8).uint
x850b_2 = sub.read(4*8).uint
x850b = str(float(x850b_1)/float(x850b_2))
if sub.read(4*8) == '0x850c0001' :
#read 0x850c - 1 byte - SpeedRef (K = km/h, M = mph, N = knots)
x850c = BitArray(sub.read(8))
x850c = x850c.tobytes().decode('utf-8')
sub.pos+=32
#read 0x850d - 8 bytes ([4]/[4]???) - SPEED
x850d_1 = sub.read(4*8).uint
x850d_2 = sub.read(4*8).uint
x850d = round(float(x850d_1)/float(x850d_2),2)
else : x850d = 'N/A'
if sub.read(4*8) == '0x850e0001' :
#read 0x850e - 1 byte - TrackRef (Direction Reference, T = True direction, M = Magnetic direction)
x850e = BitArray(sub.read(8))
x850e = x850e.tobytes().decode('utf-8')
sub.pos+=32
#read 0x850f - Course 8 bytes ([4]/[4]) (degrees from 0.0 to 359.99)
x850f_1 = sub.read(4*8).uint
x850f_2 = sub.read(4*8).uint
x850f = round(float(x850f_1)/float(x850f_2),2)
else : x850f = 'N/A'
#write full lat + lon + timestamp for text output
if latref == None or lonref == None : gps = 'N/A'
else :
gps = lat + str(latref) + ' ' + lon + str(lonref) + ' ' + gpsts
# debug
#gps = gps + '\n' +str(x8505) + ' ' + str(x8506) + ' ' + str(gpsfix) + ' ' + str(gpsmeasure) + ' ' + str(x850b) + ' ' + str(x850c) + ' ' + str(x850d) + ' ' + str(x850e) + ' ' + str(x850f)
if x850d != 'N/A' or x850f != 'N/A' :
gps = gps + '\n' 'Speed: ' + str(x850d) + 'km/h Course: ' + str(x850f)
k = sub.find('0x851d000a',bytealigned = True)
sub.pos+=32
gpxdate = BitArray(sub.read(8*10))
gpxdate = gpxdate.tobytes().decode('utf-8')
gpxdate = gpxdate.replace(':','-')
gpxdate = gpxdate + 'T' + gpsts + 'Z'
dt = datetime.strptime(gpxdate, '%Y-%m-%dT%H:%M:%SZ')
#print (lat,lon, x850d, x850f)
#write GPX.
if (args.gpx and 'ExifGPS'.encode() in exifchk) and old_dt < dt.timestamp() :
if x8505 != None:
gpx_point = gpxpy.gpx.GPXTrackPoint(latdd, londd, position_dilution = x850b, type_of_gpx_fix = (gpsmeasure+'d'), elevation=(float(x8506) * (-1 if x8505 == 1 else 1)),
time=datetime(dt.year,dt.month,dt.day,dt.hour,dt.minute,dt.second))
else :
gpx_point = gpxpy.gpx.GPXTrackPoint(latdd, londd, position_dilution = x850b, type_of_gpx_fix = (gpsmeasure+'d'),
time=datetime(dt.year,dt.month,dt.day,dt.hour,dt.minute,dt.second))
gpx_segment.points.append(gpx_point)
#GPX EXT TEST AREA
namespace = '{gpxtx}'
nsmap = {'gpxtpx' : namespace[1:-1]} #
root = mod_etree.Element(namespace + 'TrackPointExtension')
subnode1 = mod_etree.SubElement(root, namespace + 'speed')
subnode2 = mod_etree.SubElement(root, namespace + 'course')
if x850d != 'N/A' and x850c == 'K':
subnode1.text = str(round(x850d_1/x850d_2/3.6,2))
elif x850d != 'N/A' and x850c == 'M':
subnode1.text = str(round(x850d_1/x850d_2/2.23694,2))
elif x850d != 'N/A' and x850c == 'N':
subnode1.text = str(round(x850d_1/x850d_2/1.94384,2))
if x850f != 'N/A' :
subnode2.text = str(x850f)
gpx.nsmap = nsmap
if x850d != 'N/A' or x850f != 'N/A' :
gpx_point.extensions.append(root)
old_dt = dt.timestamp()
except (bitstring.ReadError, UnicodeDecodeError) : return 'N/A'
return gps, old_dt
def sampletime (ssec,sdur):
sec = timedelta(seconds=float(ssec))
delta = timedelta(seconds=float(sdur))
d = datetime(1,1,1) + sec
de = d+delta
d=str(d).split(' ',1)[1]
d=d.replace('.',',')
de=str(de).split(' ',1)[1]
de=de.replace('.',',')
if len(d) == 8: d = d + ',000000'
if len(de) == 8: de = de + ',000000'
result = d[:-3] + ' --> ' + de[:-3]
return result
def opt_sidecar():
print ('Extracting sidecar...')
pos = s.find('0x3C3F786D6C',bytealigned=True)
if pos == ():
print ('Error: No embedded Non-Realtime Metadata XML part found in file!')
return
endpos = s.find('0x3C2F4E6F6E5265616C54696D654D6574613E',bytealigned=True)
sidecar = s[pos[0]:(endpos[0]+18*8)]
with open(F[:-3]+'XML', 'wb') as f:
sidecar.tofile(f)
print ('Sidecar XML created: ' + (F[:-3]+'XML'))
def opt_muxmkv():
if os.path.isfile('ffmpeg.exe') == False :
print ('')
print ('Error: No ffmpeg.exe found. MuxMKV operation skipped.')
exit()
print ('Muxing new file with built-in subtitle')
f = (F[:-3]+'srt')
fout = (F[:-4]+'_sub.mkv')
subprocess.call(['ffmpeg','-i',F,'-i',f,'-c','copy','-c:s','srt','-hide_banner','-y',fout]) #ccopy,cs,
#Main Program###
if not os.path.exists(args.infile) :
print ('Error! Given input file name not found! Please check path given in CMD or set in script code!')
sys.exit()
F = args.infile
print ('Opened file ' + F)
print ('Analyzing...')
s = ConstBitStream(filename=F)
print(s[32:96])
if s[32:96] != '0x6674797058415643' :
print ('No XAVC type tag detected. Please user original XAVC MP4 file. Exiting.')
sys.exit()
### Get filesize ###
filesize = os.path.getsize(F)
#check for mdat atom tag
sampl_check = s.find('0x6D646174000000', bytealigned=True)
if len(sampl_check) != 0:
#s.bytepos+=13
#sampl_string = s.read(4*8)
sampl_string = '0x001C0100'
else:
print ('No mdat tags detected. Probably you have corrupted XAVC file. Exiting.')
sys.exit()
all_the_data = open(F,'rb')
offset = (int(filesize/mmap.ALLOCATIONGRANULARITY)-10)* mmap.ALLOCATIONGRANULARITY
m = mmap.mmap(all_the_data.fileno(),0,access=mmap.ACCESS_READ, offset = int(offset))
pattern = b'Duration value="(.*?)"'# .*?formatFps="(.*?)".*?Device manufacturer="(.*?)".*?modelName="(.*?)"'
rx = re.compile(pattern, re.IGNORECASE|re.MULTILINE|re.DOTALL)
duration = rx.findall(m)[0]
pattern = b'Device manufacturer="(.*?)"'# .*?formatFps="(.*?)".*?Device manufacturer="(.*?)".*?modelName="(.*?)"'
rx = re.compile(pattern, re.IGNORECASE|re.MULTILINE|re.DOTALL)
vendor = rx.findall(m)[0]
pattern = b'modelName="(.*?)"'# .*?formatFps="(.*?)".*?Device manufacturer="(.*?)".*?modelName="(.*?)"'
rx = re.compile(pattern, re.IGNORECASE|re.MULTILINE|re.DOTALL)
modelname = rx.findall(m)[0]
pattern = b'Group name="(.*?)"'# .*?formatFps="(.*?)".*?Device manufacturer="(.*?)".*?modelName="(.*?)"'
rx = re.compile(pattern, re.IGNORECASE|re.MULTILINE|re.DOTALL)
exifchk = rx.findall(m)
s = ConstBitStream(filename=F, offset = offset*8) #,length=(mmap.ALLOCATIONGRANULARITY),offset = offset
# Get mdhd
pos = s.rfind('0x6D646864',bytealigned=True)
s.read(32).hex
v = s.read(8).uint
s.read(24).hex
if v == 0:
s.read(32).uint
else: s.read(64).uint
if v == 0:
s.read(32).uint
else: s.read(64).uint
ts = s.read(32).uint #i.e. 30000
if v == 0:
tdur = s.read(32).uint
else: tdur = s.read(64).uint
#Get stts - 0x73747473
pos = s.rfind('0x73747473',bytealigned=True)
s.read(32).hex
v = s.read(8).uint
s.read(24).uint
s.read(32).uint
s.read(32).uint
sd = s.read(32).uint
sdur = float(sd)/float(ts) #each frame duration
print ('Model Name:', vendor.decode(), modelname.decode())
print ('Video duration (frames):', duration.decode())
print ('Framerate:', float(ts)/float(sd))
print ('Video duration (sec):', float(duration.decode())/(float(ts)/float(sd)))
if not args.gpx:
if 'ExifGPS'.encode() in exifchk : print ('ExifGPS group detected in non-realtime meta-data section. GPX Track search and extraction possible with "-gpx" argument.')
if args.gpx and 'ExifGPS'.encode() in exifchk : print ('"-gpx" argument specified. Will try to find & extract GPX track.')
if args.sens: print ('"-sens" argument specified. Will try to decode and write embedded gyro/accel/OSS sensors tables if they are in file.')
if args.sidecar == True:
opt_sidecar()
all_the_data.close()
if args.check :
print ('XAVC S file check completed')
sys.exit()
### NRT_Acquire END ###
print ('Processing...')
if args.gpx and 'ExifGPS'.encode() in exifchk :
gpx = gpxpy.gpx.GPX()
# Create first track in our GPX:
gpx_track = gpxpy.gpx.GPXTrack(name='Trackname')
gpx.tracks.append(gpx_track)
# Create first segment in our GPX track:
gpx_segment = gpxpy.gpx.GPXTrackSegment()
gpx_track.segments.append(gpx_segment)
gpx.nsmap = {
'gpxtpx' : 'https://www.8garmin.com/xmlschemas/TrackPointExtension/v2',
'version' : '1.1',
'xsi' : 'http://www.w3.org/2001/XMLSchema-instance',
'targetNamespace' : 'http://www.topografix.com/GPX/1/1',
'elementFormDefault' : 'qualified'
}
gpx.schema_locations = [
#'http://www.garmin.com/xmlschemas/GpxExtensions/v3',
#'http://www.garmin.com/xmlschemas/GpxExtensionsv3.xsd',
'http://www.topografix.com/GPX/1/1',
'http://www.topografix.com/GPX/1/1/gpx.xsd',
'https://www.8garmin.com/xmlschemas/TrackPointExtension/v2',
'https://www.8garmin.com/xmlschemas/TrackPointExtensionv2.xsd'
]
#GPX EXT TEST AREA - to delete
"""
namespace = '{gpx.py}'
nsmap = {'gpxtpx' : namespace[1:-1]}
root = mod_etree.Element(namespace + 'TrackPointExtension')
#root.text = ''
#root.tail = ''
subnode1 = mod_etree.SubElement(root, namespace + 'speed')
subnode1.text=''
subnode1.tail=''
subnode3 = mod_etree.SubElement(root, namespace + 'course')
subnode3.text=''
subnode3.tail=''
gpx.nsmap = nsmap
"""
#GPX EXT TEST AREA
ssec = 0
k=0
offset = 0
old_dt = 0
if modelname.decode() in ('DSC-RX0M2','ILCE-7RM4','DSC-RX100M7','ILCE-6600','MODEL-NAME', 'ILCE-9M2','ILCE-7SM3','ILCE-7C','ILCE-1','ZV-1','ILME-FX3'):
block_length = 1024*8*3
if not args.sens:
print ('You have camera model with 3072 bytes RTMD blocks. They may contain also gyro/accel/oss_sensor data from built-in sensors. Try use "-sens" parameter to find&extract them.')
else:
block_length = 1024*8
f = io.StringIO()
for c in range(int(duration)):
s = ConstBitStream(filename=F)
#Debug# print s
samples = (s.find(sampl_string, start = offset, bytealigned=True))
offset = samples[0] + block_length
i = samples[0]
sub = s[i:(i+block_length)]
#skip if no XAVC S timestamp tag in block :
if '0xe3040008' not in sub :
"""
c+=1
f.write (str(c) +'\n')
f.write (str(sampletime(ssec,sdur)) + '\n')
f.write ('Frame: ' + str(c) + '/' + duration.decode() + '\n') #removed ('Model: ' + vendor + ' ' + modelname + ' |)
f.write (ae +' ' + iso + ' Gain: ' + str(db) +'db' + ' F' + str(fn) + ' Shutter: ' + str(ss) + '\n')
f.write ('WB mode: '+ str(wb) + ' | AF mode: ' + str(af) + '\n')
if dist != 'N/A' :
f.write ('Focus Distance: ' + dist + '\n') #'D.zoom: '+dz+'x '+ + ' ' + ge
if gps != 'N/A' :
#print (gps)
f.write ('GPS: ' + gps[0] + '\n')
if ge != 'N/A' :
f.write (ge + '\n')
#f.write (time + '\n')
f.write ('\n')
if gps != 'N/A' :
old_dt = gps[1]
ssec=ssec+sdur
"""
continue
fn = getfn()
dist=getdist()
if args.sens:
#get_0xe409()
get_0xe423()
get_gyro()
get_accel()
get_oss_table()
#get_0xe437()
#get_0xe447()
ss= getss()
iso= getiso()
if iso == 'N/A':
iso = ''
else:
iso = 'ISO: ' + str(iso)
db = getdb()
#dz = getdz() --- digital zoom (turned off now)
ae= getpasm()
if ae == 'N/A':
ae = ''
wb= getwbmode()
af= getaf()
time = gettime()
ge = getge()
if (args.gpx and 'ExifGPS'.encode() in exifchk) :
gps = getgps(old_dt)
else : gps = 'N/A'
c+=1
f.write (str(c) +'\n')
f.write (str(sampletime(ssec,sdur)) + '\n')
f.write ('Frame: ' + str(c) + '/' + duration.decode() + '\n') #removed ('Model: ' + vendor + ' ' + modelname + ' |)
f.write (ae +' ' + iso + ' Gain: ' + str(db) +'db' + ' F' + str(fn) + ' Shutter: ' + str(ss) + '\n')
f.write ('WB mode: '+ str(wb) + ' | AF mode: ' + str(af) + '\n')
if dist != 'N/A' :
f.write ('Focus Distance: ' + dist + '\n') #'D.zoom: '+dz+'x '+ + ' ' + ge
if gps != 'N/A' :
f.write ('GPS: ' + gps[0] + '\n')
if ge != 'N/A' :
f.write (ge + '\n')
#f.write (time + '\n') - timestamp (swiched off)
f.write ('\n')
if gps != 'N/A' :
#print (gps)
old_dt = float(gps[1])
ssec=ssec+sdur
sys.stdout.write ('\rProcessed ' + str(c) + ' frames of ' + str(duration.decode()) + ' (' + str(round(samples[0]/8/(1000**2))) + 'MB of ' + str(round(filesize/(1000**2))) + 'MB)')
sys.stdout.flush()
if os.name == 'nt':
if msvcrt.kbhit() and (msvcrt.getch() == b'\x1b'):
print ('\n \n Aborted! Saving processed data...')
break
""" This code to be used for non-windows OS, not FINISHED!!!
else:
dr,dw,de = select([sys.stdin], [], [], 0)
kbinter = sys.stdin.read(1)
if ord(kbinter) == 27:
print ('\n \n Aborted! Saving processed data...')
break
"""
with open(F[:-3]+'srt', 'w') as outfile:
outfile.write(f.getvalue())
f.close()
print ('\nLast frame processed:', c)
print ('Success! SRT file created: ' + F[:-3]+'srt')
#print (gps)
if gps == "N/A":
print("No GPS data found.")
else:
if args.gpx and 'ExifGPS'.encode() in exifchk:
print ('Writting GPX file')