Repository navigation
Expand file tree
/
Copy pathMetaDataDumper.py
More file actions
3339 lines (3160 loc) · 146 KB
/
Copy pathMetaDataDumper.py
File metadata and controls
3339 lines (3160 loc) · 146 KB
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
# CopyLeft 2026 github.com/i-execute
# Author: I_execute.t.me
# Licensed under AGPLv3.
__version__ = (1, 3, 0)
# meta developer: Execute_forge.t.me
import asyncio
import html
import io
import json
import logging
import math
import mimetypes
import os
import stat
import plistlib
import re
import shutil
import struct
import tarfile
import tempfile
import time
import contextlib
import hashlib
import urllib.parse
import urllib.request
import uuid
import zipfile
import zlib
from collections import OrderedDict
from datetime import datetime, timedelta, timezone
from telethon.tl.types import (
DocumentAttributeAnimated,
DocumentAttributeAudio,
DocumentAttributeFilename,
DocumentAttributeSticker,
DocumentAttributeVideo,
MessageMediaDocument,
MessageMediaPhoto,
)
from .. import loader, utils
from ..inline.types import InlineCall
logger = logging.getLogger(__name__)
CHUNK = 512 * 1024
PAGE_LIMIT = 3300
ET_GROUP_CAP = 120
MOOV_CAP = 96 * 1024 * 1024
EXIFTOOL_URLS = (
"https://sourceforge.net/projects/exiftool/files/Image-ExifTool-{v}.tar.gz/download",
"https://github.com/exiftool/exiftool/archive/refs/tags/{v}.tar.gz",
)
EXIFTOOL_VER_URL = "https://exiftool.org/ver.txt"
EXIFTOOL_FALLBACK_VER = "13.59"
EXIFTOOL_HOSTS = ("sourceforge.net", "github.com", "codeload.github.com", "exiftool.org")
EXIFTOOL_SHA256 = ""
MP4_EPOCH = datetime(1904, 1, 1, tzinfo=timezone.utc)
WAVE_BARS = "\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588"
NATURAL_ORDER = (
0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5,
12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28,
35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51,
58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63,
)
ANNEX_K_LUMA = (
16, 11, 10, 16, 24, 40, 51, 61,
12, 12, 14, 19, 26, 58, 60, 55,
14, 13, 16, 24, 40, 57, 69, 56,
14, 17, 22, 29, 51, 87, 80, 62,
18, 22, 37, 56, 68, 109, 103, 77,
24, 35, 55, 64, 81, 104, 113, 92,
49, 64, 78, 87, 103, 121, 120, 101,
72, 92, 95, 98, 112, 100, 103, 99,
)
ANNEX_K_CHROMA = (
17, 18, 24, 47, 99, 99, 99, 99,
18, 21, 26, 66, 99, 99, 99, 99,
24, 26, 56, 99, 99, 99, 99, 99,
47, 66, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
)
EXIF_TAGS = {
0x0100: "ImageWidth", 0x0101: "ImageHeight", 0x010E: "ImageDescription",
0x010F: "Make", 0x0110: "Model", 0x0112: "Orientation",
0x011A: "XResolution", 0x011B: "YResolution", 0x0128: "ResolutionUnit",
0x0131: "Software", 0x0132: "ModifyDate", 0x013B: "Artist",
0x013C: "HostComputer", 0x0213: "YCbCrPositioning", 0x8298: "Copyright",
0x829A: "ExposureTime", 0x829D: "FNumber", 0x8822: "ExposureProgram",
0x8827: "ISO", 0x8830: "SensitivityType", 0x9000: "ExifVersion",
0x9003: "DateTimeOriginal", 0x9004: "CreateDate", 0x9010: "OffsetTime",
0x9011: "OffsetTimeOriginal", 0x9012: "OffsetTimeDigitized",
0x9201: "ShutterSpeedValue", 0x9202: "ApertureValue", 0x9203: "BrightnessValue",
0x9204: "ExposureCompensation", 0x9205: "MaxApertureValue", 0x9207: "MeteringMode",
0x9209: "Flash", 0x920A: "FocalLength", 0x9214: "SubjectArea",
0x927C: "MakerNote", 0x9286: "UserComment", 0x9290: "SubSecTime",
0x9291: "SubSecTimeOriginal", 0x9292: "SubSecTimeDigitized",
0xA000: "FlashpixVersion", 0xA001: "ColorSpace", 0xA002: "ExifImageWidth",
0xA003: "ExifImageHeight", 0xA217: "SensingMethod", 0xA301: "SceneType",
0xA401: "CustomRendered", 0xA402: "ExposureMode", 0xA403: "WhiteBalance",
0xA404: "DigitalZoomRatio", 0xA405: "FocalLengthIn35mmFormat",
0xA406: "SceneCaptureType", 0xA420: "ImageUniqueID", 0xA430: "OwnerName",
0xA431: "SerialNumber", 0xA432: "LensInfo", 0xA433: "LensMake",
0xA434: "LensModel", 0xA435: "LensSerialNumber", 0xA460: "CompositeImage",
0x8769: "ExifOffset", 0x8825: "GPSInfo", 0xA005: "InteropOffset",
0x0103: "Compression", 0x0201: "ThumbnailOffset", 0x0202: "ThumbnailLength",
0x9C9B: "XPTitle", 0x9C9C: "XPComment", 0x9C9D: "XPAuthor",
0x9C9E: "XPKeywords", 0x9C9F: "XPSubject", 0x4746: "Rating",
}
GPS_TAGS = {
0x00: "GPSVersionID", 0x01: "GPSLatitudeRef", 0x02: "GPSLatitude",
0x03: "GPSLongitudeRef", 0x04: "GPSLongitude", 0x05: "GPSAltitudeRef",
0x06: "GPSAltitude", 0x07: "GPSTimeStamp", 0x08: "GPSSatellites",
0x09: "GPSStatus", 0x0A: "GPSMeasureMode", 0x0B: "GPSDOP",
0x0C: "GPSSpeedRef", 0x0D: "GPSSpeed", 0x0E: "GPSTrackRef", 0x0F: "GPSTrack",
0x10: "GPSImgDirectionRef", 0x11: "GPSImgDirection", 0x12: "GPSMapDatum",
0x17: "GPSDestBearingRef", 0x18: "GPSDestBearing", 0x1B: "GPSProcessingMethod",
0x1D: "GPSDateStamp", 0x1F: "GPSHPositioningError",
}
QT_KEYS = {
"\xa9too": "Encoder", "\xa9swr": "Software", "\xa9mak": "Make",
"\xa9mod": "Model", "\xa9xyz": "GPSCoordinates", "\xa9day": "Date",
"\xa9nam": "Title", "\xa9ART": "Artist", "\xa9cmt": "Comment",
"\xa9des": "Description", "\xa9enc": "EncodedBy", "\xa9fmt": "Format",
"\xa9inf": "Information", "\xa9src": "Source", "\xa9swf": "Creator",
"\xa9wrt": "Composer", "\xa9alb": "Album", "\xa9gen": "Genre",
"\xa9cpy": "Copyright", "cprt": "Copyright", "auth": "Author",
"desc": "Description", "ldes": "LongDescription", "\xa9lyr": "Lyrics",
}
ISO_CONTAINERS = {
b"moov", b"trak", b"mdia", b"minf", b"stbl", b"udta", b"edts",
b"dinf", b"mvex", b"tref", b"gmhd", b"sinf", b"schi",
}
UUID_NAMES = {
"be7acfcb97a942e89c71999491e3afac": "XMP",
"50524f4621d24fcebb88695cfac9c740": "Sony PROF",
"55534d5421d24fcebb88695cfac9c740": "Sony USMT",
"85c0b687820f11e08111f4ce462b6a48": "Canon CNTH",
"ffcc8263f8554a938814587a02521fdd": "Spherical Video",
"05370497f4d94f8d8e1f3e8cf8f0e5fa": "GoPro GPMF",
}
HDLR_HINTS = (
("VideoHandle", "Android MP4 writer (VideoHandle)"),
("SoundHandle", "Android MP4 writer (SoundHandle)"),
("Core Media", "Apple AVFoundation / CoreMedia"),
("VideoHandler", "FFmpeg / libavformat default handler"),
("SoundHandler", "FFmpeg / libavformat default handler"),
("ISO Media file produced by Google", "Google / YouTube pipeline"),
("L-SMASH", "L-SMASH muxer"),
("GPAC", "GPAC / MP4Box"),
("Mainconcept", "MainConcept (Adobe Premiere / Media Encoder)"),
("Apple Video Media Handler", "Apple QuickTime"),
("Apple Sound Media Handler", "Apple QuickTime"),
("Bento4", "Bento4"),
("DJI", "DJI camera"),
("GoPro", "GoPro camera"),
("Ambarella", "Ambarella camera SoC (action cam / dashcam)"),
("Video Media Handler", "Generic QuickTime writer"),
)
SOFTWARE_RULES = (
(r"adobe photoshop lightroom|lightroom", "Adobe Lightroom", 3),
(r"adobe photoshop", "Adobe Photoshop", 3),
(r"photoshop express", "Photoshop Express", 3),
(r"adobe illustrator", "Adobe Illustrator", 3),
(r"adobe indesign", "Adobe InDesign", 3),
(r"adobe premiere", "Adobe Premiere", 3),
(r"after effects", "Adobe After Effects", 3),
(r"adobe firefly", "Adobe Firefly (AI)", 3),
(r"\bgimp\b", "GIMP", 3),
(r"snapseed", "Snapseed", 3),
(r"picsart", "PicsArt", 3),
(r"\bvsco\b", "VSCO", 3),
(r"meitu", "Meitu", 3),
(r"facetune", "Facetune", 3),
(r"capcut", "CapCut", 3),
(r"inshot", "InShot", 3),
(r"\bcanva\b", "Canva", 3),
(r"pixelmator", "Pixelmator", 3),
(r"affinity", "Affinity", 3),
(r"paint\.net", "Paint.NET", 3),
(r"darktable", "darktable", 3),
(r"rawtherapee", "RawTherapee", 3),
(r"capture one", "Capture One", 3),
(r"luminar", "Luminar", 3),
(r"instagram", "Instagram", 3),
(r"hdr\+", "Google Pixel camera (HDR+)", 3),
(r"^picasa", "Picasa", 2),
(r"windows photo editor|microsoft windows photo", "Windows Photos", 2),
(r"^microsoft windows", "Microsoft Windows", 2),
(r"^macos|^mac os x", "macOS", 2),
(r"handbrake", "HandBrake", 3),
(r"davinci resolve", "DaVinci Resolve", 3),
(r"final cut", "Final Cut Pro", 3),
(r"imovie", "iMovie", 3),
(r"kinemaster", "KineMaster", 3),
(r"obs studio|\bobs\b", "OBS Studio", 2),
(r"^lavf|^lavc|ffmpeg", "FFmpeg", 2),
(r"stable diffusion|automatic1111|comfyui|invokeai|novelai|midjourney|dall-?e", "AI image generator", 3),
(r"chatgpt|openai", "OpenAI (AI)", 3),
)
PDF_RULES = (
(r"skia/pdf", "Chromium print-to-PDF (Chrome / Edge / Electron)", 3),
(r"ios version .*quartz pdfcontext", "Apple iOS (Quartz PDFContext)", 3),
(r"mac os x .*quartz pdfcontext|macos .*quartz pdfcontext", "Apple macOS (Quartz PDFContext)", 3),
(r"quartz pdfcontext", "Apple Quartz (iOS / macOS)", 2),
(r"microsoft. word", "Microsoft Word", 3),
(r"microsoft. excel", "Microsoft Excel", 3),
(r"microsoft. powerpoint", "Microsoft PowerPoint", 3),
(r"microsoft: print to pdf", "Windows Print to PDF", 3),
(r"libreoffice", "LibreOffice", 3),
(r"openoffice", "OpenOffice", 3),
(r"google docs renderer|google docs", "Google Docs", 3),
(r"wps office|kingsoft", "WPS Office", 3),
(r"adobe acrobat|acrobat distiller|acrobat pdfmaker", "Adobe Acrobat", 3),
(r"adobe pdf library", "Adobe PDF Library", 2),
(r"adobe indesign", "Adobe InDesign", 3),
(r"pdftex|luatex|xetex|latex|dvipdfm", "LaTeX", 3),
(r"wkhtmltopdf", "wkhtmltopdf", 3),
(r"ghostscript", "Ghostscript", 3),
(r"itext", "iText (Java / .NET library)", 3),
(r"pdfsharp", "PDFsharp (.NET)", 3),
(r"reportlab", "ReportLab (Python)", 3),
(r"fpdf|tcpdf|mpdf|dompdf", "PHP PDF library", 3),
(r"weasyprint", "WeasyPrint", 3),
(r"princexml|prince", "Prince", 2),
(r"pdf-lib", "pdf-lib (JavaScript)", 3),
(r"pypdf|pdfminer|pikepdf|qpdf", "Python / qpdf toolchain", 2),
(r"camscanner", "CamScanner (scanner app)", 3),
(r"adobe scan", "Adobe Scan (scanner app)", 3),
(r"microsoft lens|office lens", "Microsoft Lens (scanner app)", 3),
(r"genius scan", "Genius Scan (scanner app)", 3),
(r"scanbot", "Scanbot (scanner app)", 3),
(r"tiny ?scanner", "Tiny Scanner (scanner app)", 3),
(r"samsung notes", "Samsung Notes", 3),
(r"pdfium", "PDFium", 2),
(r"\bqt\b", "Qt framework", 2),
(r"foxit", "Foxit", 3),
(r"nitro", "Nitro PDF", 3),
(r"pages", "Apple Pages", 2),
(r"keynote", "Apple Keynote", 2),
(r"canva", "Canva", 3),
)
OPUS_RULES = (
(r"^libopus unknown-fixed$", "Telegram Android", 3),
(r"^libopus unknown$", "Telegram X (Android)", 3),
(r"^libopus \d+\.\d+(\.\d+)?-fixed$", "Telegram macOS (native)", 3),
(r"^libopus \d+\.\d+(\.\d+)?$", "Telegram iOS", 3),
(r"^lavf", "Telegram Desktop / FFmpeg", 2),
(r"^tweb", "Telegram Web K", 3),
(r"^telegram-web-a", "Telegram Web A", 3),
(r"whatsapp", "WhatsApp", 3),
(r"^libopus", "libopus (unknown build)", 1),
(r"^xiph\.org libvorbis", "Xiph libvorbis (Vorbis)", 2),
)
FILENAME_RULES = (
(r"^ptt-\d{8}-wa\d{4}", "WhatsApp voice note", 3),
(r"^(img|vid|aud|doc|stk)-\d{8}-wa\d{4}", "WhatsApp media", 3),
(r"^pxl_\d{8}_\d+", "Google Pixel camera", 3),
(r"^telegram-cloud-(photo|document)", "Telegram iOS (shared from app)", 3),
(r"^photo_\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}", "Telegram Desktop (saved photo)", 3),
(r"^(video|audio|file|sticker|animation|voice|round)_\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}", "Telegram Desktop (saved media)", 3),
(r"^img_\d{8}_\d{6}_\d{3}\.", "Telegram Android (saved photo)", 2),
(r"^vid_\d{8}_\d{6}_\d{3}\.", "Telegram Android (saved video)", 2),
(r"^screenshot_\d{8}[-_]\d{6}(?:_(.+))?\.", "Android screenshot", 3),
(r"^screenshot_\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2}(?:-\d+)?(?:_(.+))?\.", "Android screenshot", 3),
(r"^screen ?shot \d{4}-\d{2}-\d{2} at ", "macOS screenshot", 3),
(r"^снимок экрана \d{4}-\d{2}-\d{2} в ", "macOS screenshot (RU)", 3),
(r"^снимок экрана \d{4}-\d{2}-\d{2} \d{6}", "Windows 11 Snipping Tool (RU)", 3),
(r"^screenshot \d{4}-\d{2}-\d{2} \d{6}", "Windows 11 Snipping Tool", 3),
(r"^снимок экрана( \(\d+\))?\.png", "Windows screenshot (RU)", 2),
(r"^img_e?\d{4}\.(heic|jpe?g|png|mov|mp4|dng)$", "iPhone / iPad camera roll", 3),
(r"^img_\d{8}_\d{6}", "Android camera", 2),
(r"^vid_\d{8}_\d{6}", "Android camera", 2),
(r"^(img|vid)_\d{8}_\d{6}_hdr", "Android camera (HDR)", 2),
(r"^signal-\d{4}-\d{2}-\d{2}-\d{6}", "Signal", 3),
(r"^received_\d+", "Facebook Messenger", 2),
(r"^\d+_\d+_\d+_n\.(jpe?g|mp4)", "Facebook / Instagram CDN", 3),
(r"^snapchat-\d+", "Snapchat", 3),
(r"^dsc_\d{4}", "Nikon camera", 2),
(r"^dsc\d{5}", "Sony camera", 2),
(r"^_?mg_\d{4}", "Canon camera", 2),
(r"^gopr\d{4}|^g[hx]\d{6}", "GoPro", 3),
(r"^dji_\d{4}", "DJI drone / camera", 3),
(r"^new recording( \d+)?\.m4a", "iOS Voice Memos", 3),
(r"^recording_\d+", "Android voice recorder", 2),
(r"^(rpreplay|screenrecording)_", "iOS screen recording", 3),
(r"^screen_recording_\d{8}_\d{6}", "Android screen recording", 3),
(r"^voice\.ogg$|^audio\.ogg$", "Generic voice file", 1),
)
ANDROID_MAKERS = (
"samsung", "xiaomi", "redmi", "poco", "huawei", "honor", "oppo", "vivo",
"oneplus", "realme", "motorola", "nokia", "sony", "lg", "google", "asus",
"zte", "nothing", "tecno", "infinix", "meizu", "lenovo", "fairphone", "htc",
)
def _esc(text):
return html.escape(str(text), quote=False)
def _clip(text, n=300):
text = str(text)
return text if len(text) <= n else text[: n - 3] + "..."
def _fmt_bytes(b):
if b is None:
return "?"
b = float(b)
for unit in ("B", "KB", "MB", "GB"):
if b < 1024 or unit == "GB":
return f"{int(b)} B" if unit == "B" else f"{b:.2f} {unit}"
b /= 1024
return f"{b:.2f} GB"
def _fmt_dur(sec):
if sec is None:
return "?"
sec = float(sec)
m, s = divmod(sec, 60)
h, m = divmod(int(m), 60)
if h:
return f"{h}:{m:02d}:{s:06.3f}"
return f"{m}:{s:06.3f}"
def _fmt_dt(dt):
if not dt:
return None
if isinstance(dt, (int, float)):
dt = datetime.fromtimestamp(dt, tz=timezone.utc)
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
return dt.astimezone(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
def _fmt_delta(sec):
sign = "-" if sec < 0 else "+"
sec = abs(int(sec))
d, rem = divmod(sec, 86400)
h, rem = divmod(rem, 3600)
m, s = divmod(rem, 60)
parts = []
if d:
parts.append(f"{d}d")
if h:
parts.append(f"{h}h")
if m:
parts.append(f"{m}m")
parts.append(f"{s}s")
return sign + " ".join(parts)
def _mp4_time(value):
if not value or value < 86400 * 365:
return None
try:
return MP4_EPOCH + timedelta(seconds=value)
except Exception:
return None
def _dec(data):
if isinstance(data, str):
return data
for enc in ("utf-8", "utf-16"):
try:
return data.decode(enc)
except Exception:
pass
return data.decode("latin-1", errors="replace")
def _printable(data, limit=200):
text = data.decode("latin-1", errors="replace")
text = "".join(ch if 32 <= ord(ch) < 127 else "." for ch in text)
return _clip(text, limit)
def _fourcc(b):
return b.decode("latin-1", errors="replace")
def _sniff(head):
if head[:3] == b"\xff\xd8\xff":
return "jpeg"
if head[:8] == b"\x89PNG\r\n\x1a\n":
return "png"
if head[4:8] == b"ftyp" or head[4:8] in (b"moov", b"mdat", b"wide", b"free", b"skip"):
return "isobmff"
if head[:4] == b"OggS":
return "ogg"
if head[:5] == b"%PDF-":
return "pdf"
if head[:4] in (b"PK\x03\x04", b"PK\x05\x06"):
return "zip"
if head[:3] == b"ID3" or (len(head) > 1 and head[0] == 0xFF and head[1] & 0xE0 == 0xE0):
return "mp3"
if head[:4] == b"\x1a\x45\xdf\xa3":
return "ebml"
if head[:4] in (b"RIFF", b"RIFX"):
return "riff"
if head[:6] in (b"GIF87a", b"GIF89a"):
return "gif"
if head[:4] == b"fLaC":
return "flac"
if head[:2] in (b"II", b"MM") and head[2:4] in (b"*\x00", b"\x00*"):
return "tiff"
if head[:4] == b"Rar!":
return "rar"
if head[:6] == b"7z\xbc\xaf\x27\x1c":
return "7z"
if head[:2] == b"\x1f\x8b":
return "gzip"
return "unknown"
def _parse_tiff(buf):
out = OrderedDict()
if len(buf) < 8:
return out
if buf[:2] == b"II":
e = "<"
elif buf[:2] == b"MM":
e = ">"
else:
return out
sizes = {1: 1, 2: 1, 3: 2, 4: 4, 5: 8, 6: 1, 7: 1, 8: 2, 9: 4, 10: 8, 11: 4, 12: 8}
def value(typ, count, raw, tag):
try:
if typ == 2:
return raw.split(b"\x00", 1)[0].decode("utf-8", errors="replace").strip()
if typ in (1, 6):
if count <= 8:
return list(raw[:count]) if count > 1 else raw[0]
return f"<{count} bytes>"
if typ == 7:
if tag == 0x9286:
code, body = raw[:8], raw[8:]
if code.startswith(b"UNICODE"):
return body.decode("utf-16-be" if e == ">" else "utf-16-le", errors="replace").strip("\x00 ")
return body.decode("utf-8", errors="replace").strip("\x00 ")
if tag == 0x927C:
sig = raw[:16]
return f"<{count} bytes, header '{_printable(sig, 16)}'>"
if tag in (0x9000, 0xA000):
return raw[:4].decode("latin-1", errors="replace")
if count <= 16:
return raw.hex()
return f"<{count} bytes>"
if typ == 3:
vals = struct.unpack(e + "H" * count, raw[: 2 * count])
elif typ == 8:
vals = struct.unpack(e + "h" * count, raw[: 2 * count])
elif typ == 4:
vals = struct.unpack(e + "I" * count, raw[: 4 * count])
elif typ == 9:
vals = struct.unpack(e + "i" * count, raw[: 4 * count])
elif typ in (5, 10):
fmt = "I" if typ == 5 else "i"
nums = struct.unpack(e + fmt * (2 * count), raw[: 8 * count])
vals = tuple(
(nums[i] / nums[i + 1]) if nums[i + 1] else 0.0
for i in range(0, len(nums), 2)
)
elif typ == 11:
vals = struct.unpack(e + "f" * count, raw[: 4 * count])
elif typ == 12:
vals = struct.unpack(e + "d" * count, raw[: 8 * count])
else:
return f"<type {typ}>"
if tag in (0x9C9B, 0x9C9C, 0x9C9D, 0x9C9E, 0x9C9F):
return bytes(vals).decode("utf-16-le", errors="replace").strip("\x00")
if count > 16:
return f"<{count} values>"
return vals[0] if len(vals) == 1 else list(vals)
except Exception:
return None
def read_ifd(offset, names, prefix, depth=0):
if depth > 4 or offset <= 0 or offset + 2 > len(buf):
return 0
count = struct.unpack(e + "H", buf[offset: offset + 2])[0]
if count > 512:
return 0
for i in range(count):
p = offset + 2 + i * 12
if p + 12 > len(buf):
break
tag, typ, cnt = struct.unpack(e + "HHI", buf[p: p + 8])
size = sizes.get(typ, 1) * cnt
if size <= 4:
raw = buf[p + 8: p + 8 + size]
else:
off = struct.unpack(e + "I", buf[p + 8: p + 12])[0]
if off + size > len(buf) or size > 4 * 1024 * 1024:
continue
raw = buf[off: off + size]
if tag == 0x8769 and prefix != "GPS":
sub = struct.unpack(e + "I", raw[:4])[0] if len(raw) >= 4 else 0
read_ifd(sub, EXIF_TAGS, "ExifIFD", depth + 1)
continue
if tag == 0x8825 and prefix != "GPS":
sub = struct.unpack(e + "I", raw[:4])[0] if len(raw) >= 4 else 0
read_ifd(sub, GPS_TAGS, "GPS", depth + 1)
continue
if tag == 0xA005:
continue
name = names.get(tag, f"Tag0x{tag:04X}")
val = value(typ, cnt, raw, tag)
if val is None or val == "":
continue
out[f"{prefix}:{name}"] = val
nxt_pos = offset + 2 + count * 12
if nxt_pos + 4 <= len(buf):
return struct.unpack(e + "I", buf[nxt_pos: nxt_pos + 4])[0]
return 0
try:
if struct.unpack(e + "H", buf[2:4])[0] != 42:
return out
first = struct.unpack(e + "I", buf[4:8])[0]
nxt = read_ifd(first, EXIF_TAGS, "IFD0")
if nxt:
read_ifd(nxt, EXIF_TAGS, "IFD1")
except Exception as e2:
logger.debug("[MDD] tiff parse error: %s", e2)
return out
def _gps_from_exif(exif):
def conv(vals, ref):
if not isinstance(vals, list) or len(vals) < 3:
return None
deg = float(vals[0]) + float(vals[1]) / 60 + float(vals[2]) / 3600
if str(ref).upper() in ("S", "W"):
deg = -deg
return deg
lat = conv(exif.get("GPS:GPSLatitude"), exif.get("GPS:GPSLatitudeRef", "N"))
lon = conv(exif.get("GPS:GPSLongitude"), exif.get("GPS:GPSLongitudeRef", "E"))
if lat is None or lon is None or (lat == 0 and lon == 0):
return None
return lat, lon
def _parse_icc(data):
out = OrderedDict()
if len(data) < 132:
return out
try:
out["CMM"] = _fourcc(data[4:8]).strip("\x00 ")
out["Version"] = f"{data[8]}.{data[9] >> 4}.{data[9] & 15}"
out["DeviceClass"] = _fourcc(data[12:16])
out["ColorSpace"] = _fourcc(data[16:20]).strip()
y, mo, d, h, mi, s = struct.unpack(">6H", data[24:36])
if y:
out["Created"] = f"{y:04d}-{mo:02d}-{d:02d} {h:02d}:{mi:02d}:{s:02d}"
out["Platform"] = _fourcc(data[40:44]).strip("\x00 ")
out["Manufacturer"] = _fourcc(data[48:52]).strip("\x00 ")
out["Creator"] = _fourcc(data[80:84]).strip("\x00 ")
count = struct.unpack(">I", data[128:132])[0]
for i in range(min(count, 64)):
p = 132 + i * 12
sig, off, size = struct.unpack(">4sII", data[p: p + 12])
if sig not in (b"desc", b"cprt", b"dmnd", b"dmdd"):
continue
body = data[off: off + size]
text = None
if body[:4] == b"desc":
n = struct.unpack(">I", body[8:12])[0]
text = body[12: 12 + n].split(b"\x00", 1)[0].decode("latin-1", errors="replace")
elif body[:4] == b"mluc":
recs = struct.unpack(">I", body[8:12])[0]
if recs:
ln, lo = struct.unpack(">II", body[20:28])
text = body[lo: lo + ln].decode("utf-16-be", errors="replace")
elif body[:4] == b"text":
text = body[8:].split(b"\x00", 1)[0].decode("latin-1", errors="replace")
if text:
key = {b"desc": "Description", b"cprt": "Copyright", b"dmnd": "DeviceMfg", b"dmdd": "DeviceModel"}[sig]
out[key] = text.strip()
except Exception:
pass
return out
def _parse_xmp(text):
out = OrderedDict()
if isinstance(text, bytes):
text = text.decode("utf-8", errors="replace")
skip = {"x:xmptk", "xmlns", "rdf:about", "rdf:parseType"}
for m in re.finditer(r'([A-Za-z][\w\-]*:[A-Za-z][\w\-]*)="([^"]{0,400})"', text):
k = m.group(1)
if k.startswith("xmlns") or k in skip:
continue
out.setdefault(k, html.unescape(m.group(2)))
for m in re.finditer(r"<([A-Za-z][\w\-]*:[A-Za-z][\w\-]*)>([^<]{1,400})</\1>", text):
k = m.group(1)
if k.startswith("rdf:"):
continue
out.setdefault(k, html.unescape(m.group(2).strip()))
for m in re.finditer(r"<([A-Za-z][\w\-]*:[A-Za-z][\w\-]*)>\s*<rdf:(?:Alt|Seq|Bag)>\s*<rdf:li[^>]*>([^<]{1,400})</rdf:li>", text):
out.setdefault(m.group(1), html.unescape(m.group(2).strip()))
x = re.search(r'x:xmptk="([^"]+)"', text)
if x:
out["x:xmptk"] = x.group(1)
return out
def _jpeg_quality(tables):
luma = tables.get(0)
if not luma or len(luma) < 64:
return None
chroma = tables.get(1)
nat_l = [0] * 64
for k, v in enumerate(luma[:64]):
nat_l[NATURAL_ORDER[k]] = v
nat_c = None
if chroma and len(chroma) >= 64:
nat_c = [0] * 64
for k, v in enumerate(chroma[:64]):
nat_c[NATURAL_ORDER[k]] = v
best = None
for q in range(1, 101):
scale = 5000 // q if q < 50 else 200 - 2 * q
diff = 0
for i in range(64):
ref = min(max((ANNEX_K_LUMA[i] * scale + 50) // 100, 1), 255)
diff += abs(ref - nat_l[i])
if nat_c:
for i in range(64):
ref = min(max((ANNEX_K_CHROMA[i] * scale + 50) // 100, 1), 255)
diff += abs(ref - nat_c[i])
if best is None or diff < best[1]:
best = (q, diff)
n = 128 if nat_c else 64
return {"quality": best[0], "exact": best[1] == 0, "mean_error": round(best[1] / n, 2)}
def _parse_jpeg(data):
if data[:2] != b"\xff\xd8":
return None
info = OrderedDict()
info["markers"] = []
tables = {}
icc_parts = []
exif = OrderedDict()
xmp = OrderedDict()
flags = []
i = 2
n = len(data)
sof_names = {
0xC0: "Baseline DCT", 0xC1: "Extended sequential DCT", 0xC2: "Progressive DCT",
0xC3: "Lossless", 0xC5: "Differential sequential", 0xC6: "Differential progressive",
0xC7: "Differential lossless", 0xC9: "Arithmetic sequential", 0xCA: "Arithmetic progressive",
}
while i + 4 <= n:
if data[i] != 0xFF:
nxt = data.find(b"\xff", i)
if nxt < 0:
break
i = nxt
continue
marker = data[i + 1]
if marker == 0xFF:
i += 1
continue
if marker in (0xD8, 0x01) or 0xD0 <= marker <= 0xD7:
i += 2
continue
if marker == 0xD9:
break
seglen = struct.unpack(">H", data[i + 2: i + 4])[0]
seg = data[i + 4: i + 2 + seglen]
name = f"APP{marker - 0xE0}" if 0xE0 <= marker <= 0xEF else f"0x{marker:02X}"
if marker == 0xDA:
info["markers"].append("SOS")
break
if 0xE0 <= marker <= 0xEF:
ident = seg.split(b"\x00", 1)[0][:40]
info["markers"].append(f"{name}({_printable(ident, 30)})")
if marker == 0xE0 and seg[:5] == b"JFIF\x00":
units = {0: "aspect", 1: "dpi", 2: "dpcm"}.get(seg[7], "?")
info["JFIF"] = f"v{seg[5]}.{seg[6]:02d}, {struct.unpack('>H', seg[8:10])[0]}x{struct.unpack('>H', seg[10:12])[0]} {units}"
elif marker == 0xE1 and seg[:6] == b"Exif\x00\x00":
exif.update(_parse_tiff(seg[6:]))
info["EXIF bytes"] = len(seg)
elif marker == 0xE1 and seg.startswith(b"http://ns.adobe.com/xap/1.0/\x00"):
xmp.update(_parse_xmp(seg[29:]))
info["XMP bytes"] = len(seg)
elif marker == 0xE1 and seg.startswith(b"http://ns.adobe.com/xmp/extension/\x00"):
flags.append("Extended XMP")
elif marker == 0xE2 and seg[:12] == b"ICC_PROFILE\x00":
icc_parts.append((seg[12], seg[14:]))
elif marker == 0xE2 and seg[:4] == b"MPF\x00":
try:
mp = _parse_tiff(seg[4:])
info["MPF"] = "Multi-Picture Format"
flags.append("MPF (depth map / HDR gain map / multi-frame)")
for k, v in mp.items():
if k.endswith("Tag0xB001"):
info["MPF images"] = v
except Exception:
flags.append("MPF")
elif marker == 0xEB and (b"c2pa" in seg[:64] or seg[:2] == b"JP"):
flags.append("C2PA / JUMBF content credentials")
elif marker == 0xED and seg.startswith(b"Photoshop 3.0"):
flags.append("Photoshop IRB / IPTC")
elif marker == 0xEE and seg[:5] == b"Adobe":
flags.append(f"Adobe APP14 (transform {seg[11] if len(seg) > 11 else '?'})")
elif marker == 0xEC and seg[:5] == b"Ducky":
flags.append("Ducky (Photoshop Save for Web)")
elif marker == 0xDB:
info["markers"].append("DQT")
p = 0
while p < len(seg):
pq, tq = seg[p] >> 4, seg[p] & 15
size = 128 if pq else 64
vals = seg[p + 1: p + 1 + size]
if pq:
tables[tq] = [struct.unpack(">H", vals[j: j + 2])[0] for j in range(0, len(vals), 2)]
else:
tables[tq] = list(vals)
p += 1 + size
elif marker in sof_names:
info["markers"].append(f"SOF{marker - 0xC0}")
info["Encoding"] = sof_names[marker]
info["Bits"] = seg[0]
h, w = struct.unpack(">HH", seg[1:5])
info["Size"] = f"{w}x{h}"
comps = seg[5]
sampling = []
for c in range(comps):
b = seg[6 + c * 3 + 1]
sampling.append((b >> 4, b & 15))
info["Components"] = comps
if comps == 3:
(h0, v0), (h1, v1) = sampling[0], sampling[1]
sub = {(1, 1): "4:4:4", (2, 1): "4:2:2", (2, 2): "4:2:0", (4, 1): "4:1:1", (1, 2): "4:4:0"}.get(
(h0 // max(h1, 1), v0 // max(v1, 1)), f"{h0}x{v0}/{h1}x{v1}")
info["Subsampling"] = sub
elif marker == 0xFE:
info["markers"].append("COM")
info["Comment"] = _clip(_dec(seg).strip("\x00"), 300)
elif marker == 0xDD:
info["Restart interval"] = struct.unpack(">H", seg[:2])[0]
elif marker == 0xC4:
info.setdefault("DHT", 0)
info["DHT"] += 1
i += 2 + seglen
q = _jpeg_quality(tables)
if q:
info["Quality"] = q
info["QT count"] = len(tables)
if icc_parts:
icc = b"".join(p for _, p in sorted(icc_parts, key=lambda x: x[0]))
info["ICC"] = _parse_icc(icc)
tail = data[-64:]
if tail.endswith(b"SEFT"):
flags.append("Samsung SEF trailer")
if b"MotionPhoto" in data[:200000] or b"MicroVideo" in data[:200000]:
flags.append("Motion Photo (embedded video)")
eoi = data.rfind(b"\xff\xd9")
if 0 < eoi < n - 2 and n - eoi - 2 > 16:
extra = data[eoi + 2:]
if extra[4:8] == b"ftyp":
flags.append(f"Embedded MP4 after EOI ({_fmt_bytes(len(extra))})")
elif "MPF" not in info:
flags.append(f"Trailing data after EOI ({_fmt_bytes(len(extra))})")
info["flags"] = flags
info["tables"] = tables
return info, exif, xmp
def _parse_png(data):
if data[:8] != b"\x89PNG\r\n\x1a\n":
return None
info = OrderedDict()
text = OrderedDict()
exif = OrderedDict()
xmp = OrderedDict()
chunks = []
p = 8
color_types = {0: "Grayscale", 2: "RGB", 3: "Palette", 4: "Gray+Alpha", 6: "RGBA"}
while p + 8 <= len(data):
ln, typ = struct.unpack(">I4s", data[p: p + 8])
body = data[p + 8: p + 8 + ln]
t = _fourcc(typ)
if t not in ("IDAT", "fdAT"):
chunks.append(t)
elif not chunks or chunks[-1] != t:
chunks.append(t)
try:
if t == "IHDR":
w, h, bd, ct, cm, fm, il = struct.unpack(">IIBBBBB", body[:13])
info["Size"] = f"{w}x{h}"
info["Bit depth"] = bd
info["Color"] = color_types.get(ct, ct)
info["Interlace"] = "Adam7" if il else "None"
elif t == "tEXt":
k, v = body.split(b"\x00", 1)
text[k.decode("latin-1")] = v.decode("latin-1", errors="replace")
elif t == "zTXt":
k, rest = body.split(b"\x00", 1)
text[k.decode("latin-1")] = zlib.decompress(rest[1:]).decode("latin-1", errors="replace")
elif t == "iTXt":
k, rest = body.split(b"\x00", 1)
comp, _method = rest[0], rest[1]
rest = rest[2:]
_lang, rest = rest.split(b"\x00", 1)
_tk, rest = rest.split(b"\x00", 1)
val = zlib.decompress(rest) if comp else rest
key = k.decode("latin-1")
if key == "XML:com.adobe.xmp":
xmp.update(_parse_xmp(val))
else:
text[key] = val.decode("utf-8", errors="replace")
elif t == "eXIf":
exif.update(_parse_tiff(body))
elif t == "iCCP":
name, rest = body.split(b"\x00", 1)
info["ICC name"] = name.decode("latin-1")
try:
info["ICC"] = _parse_icc(zlib.decompress(rest[1:]))
except Exception:
pass
elif t == "pHYs":
x, y, unit = struct.unpack(">IIB", body[:9])
if unit == 1:
info["DPI"] = f"{round(x * 0.0254)}x{round(y * 0.0254)}"
else:
info["Pixel aspect"] = f"{x}:{y}"
elif t == "sRGB":
info["sRGB intent"] = body[0]
elif t == "gAMA":
info["Gamma"] = struct.unpack(">I", body[:4])[0] / 100000
elif t == "tIME":
y, mo, d, h, mi, s = struct.unpack(">HBBBBB", body[:7])
info["Modified (tIME)"] = f"{y:04d}-{mo:02d}-{d:02d} {h:02d}:{mi:02d}:{s:02d}"
elif t == "acTL":
frames, plays = struct.unpack(">II", body[:8])
info["APNG"] = f"{frames} frames, loops {plays or 'inf'}"
elif t == "caBX":
info["C2PA"] = "Content credentials (caBX)"
except Exception:
pass
if t == "IEND":
break
p += 12 + ln
info["Chunks"] = " ".join(chunks)
return info, text, exif, xmp
def _iter_boxes(data, start, end):
p = start
while p + 8 <= end:
size, typ = struct.unpack(">I4s", data[p: p + 8])
hdr = 8
if size == 1:
if p + 16 > end:
return
size = struct.unpack(">Q", data[p + 8: p + 16])[0]
hdr = 16
elif size == 0:
size = end - p
if size < hdr or p + size > end + 8:
return
yield typ, p + hdr, min(p + size, end)
p += size
def _qt_string(payload):
if len(payload) >= 4:
ln = struct.unpack(">H", payload[:2])[0]
if 0 < ln <= len(payload) - 4:
return payload[4: 4 + ln].decode("utf-8", errors="replace")
return payload.decode("utf-8", errors="replace").strip("\x00")
def _ilst_value(data, start, end):
for typ, s, e in _iter_boxes(data, start, end):
if typ == b"data":
kind = struct.unpack(">I", data[s: s + 4])[0] & 0xFFFFFF
raw = data[s + 8: e]
if kind in (1, 4, 5):
return raw.decode("utf-8", errors="replace")
if kind == 2:
return raw.decode("utf-16-be", errors="replace")
if kind in (21, 22) and len(raw) in (1, 2, 4, 8):
return int.from_bytes(raw, "big", signed=kind == 21)
if kind == 23 and len(raw) == 4:
return struct.unpack(">f", raw)[0]
if kind == 24 and len(raw) == 8:
return struct.unpack(">d", raw)[0]
if kind in (13, 14):
return f"<image {len(raw)} bytes>"
return _printable(raw, 120) if raw else ""
return None
def _desc_len(buf, p):
n = 0
for _ in range(4):
if p >= len(buf):
break
b = buf[p]
p += 1
n = (n << 7) | (b & 0x7F)
if not b & 0x80:
break
return n, p
def _parse_esds(buf):
out = {}
try:
p = 0
if buf[p] != 0x03:
return out
_, p = _desc_len(buf, p + 1)
flags = buf[p + 2]
p += 3
if flags & 0x80:
p += 2
if flags & 0x40:
p += 1 + buf[p]
if flags & 0x20:
p += 2
if buf[p] != 0x04:
return out
_, p = _desc_len(buf, p + 1)
_oti, _st = buf[p], buf[p + 1]
mx, avg = struct.unpack(">II", buf[p + 5: p + 13])
if avg:
out["bitrate"] = f"avg {avg // 1000} kb/s, max {mx // 1000} kb/s"
p += 13
if p < len(buf) and buf[p] == 0x05:
ln, p = _desc_len(buf, p + 1)
aot = buf[p] >> 3
if aot == 31 and p + 1 < len(buf):
aot = 32 + (((buf[p] & 7) << 3) | (buf[p + 1] >> 5))
out["aac"] = {1: "AAC Main", 2: "AAC LC", 5: "HE-AAC (SBR)", 29: "HE-AACv2 (PS)", 23: "AAC LD", 39: "AAC ELD", 42: "xHE-AAC (USAC)"}.get(aot, f"AOT {aot}")
except Exception:
pass
return out
def _parse_meta_box(data, start, end, tags):
if end - start >= 8 and data[start + 4: start + 8] != b"hdlr":
start += 4
keys = []
for typ, s, e in _iter_boxes(data, start, end):
if typ == b"hdlr":
tags.setdefault("_meta_handler", _fourcc(data[s + 8: s + 12]))
elif typ == b"keys":
cnt = struct.unpack(">I", data[s + 4: s + 8])[0]
p = s + 8
for _ in range(min(cnt, 256)):
if p + 8 > e:
break
ksize = struct.unpack(">I", data[p: p + 4])[0]
keys.append(data[p + 8: p + ksize].decode("utf-8", errors="replace"))
p += max(ksize, 8)
elif typ == b"ilst":
for ityp, isub, iend in _iter_boxes(data, s, e):
idx = int.from_bytes(ityp, "big")
if keys and 1 <= idx <= len(keys):
name = keys[idx - 1]
else:
name = ityp.decode("latin-1")
name = QT_KEYS.get(name, name.replace("\xa9", "(c)"))
val = _ilst_value(data, isub, iend)
if val is not None:
tags[name] = val
def _parse_moov(data):