-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
3033 lines (2658 loc) · 113 KB
/
Copy pathapp.py
File metadata and controls
3033 lines (2658 loc) · 113 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
#!/usr/bin/env python3
"""
Frayme
Recursively scans directories for corrupt or damaged MP4/MOV video files.
Detects: missing moov atoms, leading-zero corruption, truncated files,
and files with no valid container structure.
Offers best-effort recovery via moov transplant and raw stream extraction.
"""
import os
import sys
import json
import time
import struct
import threading
import queue as queue_mod
import csv
import io
import subprocess
import webbrowser
import tempfile
import shutil
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor, as_completed
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlparse, parse_qs
APP_DIR = os.path.dirname(os.path.abspath(__file__))
# ─── Global state ─────────────────────────────────────────────────────────────
scan_state = {
'running': False,
'cancelled': False,
'results': [],
}
# Per-directory donor map: { dir_path: filepath } (manual override)
donor_map = {}
# Auto-collected healthy files: { dir_path: [filepath, ...] }
donor_pool = {}
# Recovery queue infrastructure
_recover_queue = queue_mod.Queue()
_recover_jobs = {}
_recover_lock = threading.Lock()
_recover_counter = 0
_recover_worker_started = False
VIDEO_EXTS = {'.mp4', '.mov', '.m4v', '.m4a', '.3gp', '.3g2', '.avi'}
VALID_BOX_TYPES = {
b'ftyp', b'moov', b'mdat', b'free', b'skip', b'wide', b'pnot',
b'uuid', b'moof', b'mfra', b'meta', b'styp', b'sidx', b'ssix',
b'pdin', b'bloc', b'meco',
}
WORKER_THREADS = 4
# ─── ffmpeg / ffprobe detection ───────────────────────────────────────────────
def _find_tool(name):
return shutil.which(name)
_ffmpeg_path = _find_tool('ffmpeg')
_ffprobe_path = _find_tool('ffprobe')
def has_ffmpeg():
return _ffmpeg_path is not None
def has_ffprobe():
return _ffprobe_path is not None
# ─── MP4/MOV box parser (pure Python) ────────────────────────────────────────
def parse_boxes(filepath, max_depth=0):
"""Parse top-level MP4/MOV boxes.
Returns [(type_str, offset, size), ...] for each box found.
Stops at first invalid box or EOF.
"""
file_size = os.path.getsize(filepath)
boxes = []
with open(filepath, 'rb') as f:
pos = 0
while pos < file_size:
f.seek(pos)
hdr = f.read(8)
if len(hdr) < 8:
break
box_size = struct.unpack('>I', hdr[:4])[0]
box_type = hdr[4:8]
if box_size == 1:
ext = f.read(8)
if len(ext) < 8:
break
box_size = struct.unpack('>Q', ext)[0]
if box_size < 16:
break
elif box_size == 0:
box_size = file_size - pos
elif box_size < 8:
break
try:
bt = box_type.decode('ascii')
except (UnicodeDecodeError, ValueError):
break
if not all(c.isalnum() or c in ' _-' for c in bt):
break
boxes.append((bt, pos, box_size))
pos += box_size
return boxes
def _get_mvhd_duration(filepath):
"""Extract video duration in seconds from the moov/mvhd box.
Parses the binary mvhd directly — no ffprobe needed.
Returns float seconds or None.
"""
boxes = parse_boxes(filepath)
moov_offset = None
moov_size = None
for bt, off, sz in boxes:
if bt == 'moov':
moov_offset = off
moov_size = sz
break
if moov_offset is None:
return None
try:
with open(filepath, 'rb') as f:
f.seek(moov_offset + 8)
moov_data = f.read(min(moov_size - 8, 1024))
# Find mvhd child box
pos = 0
while pos < len(moov_data) - 8:
sz = struct.unpack('>I', moov_data[pos:pos + 4])[0]
bt = moov_data[pos + 4:pos + 8]
if sz < 8 or pos + sz > len(moov_data):
break
if bt == b'mvhd':
version = moov_data[pos + 8]
if version == 0:
timescale = struct.unpack('>I',
moov_data[pos + 20:pos + 24])[0]
duration = struct.unpack('>I',
moov_data[pos + 24:pos + 28])[0]
else:
timescale = struct.unpack('>I',
moov_data[pos + 28:pos + 32])[0]
duration = struct.unpack('>Q',
moov_data[pos + 32:pos + 40])[0]
if timescale > 0:
return round(duration / timescale, 2)
return None
pos += sz
except Exception:
pass
return None
def parse_moov_children(data, offset=0):
"""Parse child boxes inside a moov atom. Returns dict of type -> bytes."""
children = {}
pos = offset
while pos < len(data) - 8:
box_size = struct.unpack('>I', data[pos:pos + 4])[0]
box_type = data[pos + 4:pos + 8]
if box_size < 8 or pos + box_size > len(data):
break
try:
bt = box_type.decode('ascii')
except (UnicodeDecodeError, ValueError):
break
children[bt] = data[pos:pos + box_size]
pos += box_size
return children
def find_box_in_data(data, box_type_str):
"""Find a box by type in binary data. Returns (offset, size) or None."""
target = box_type_str.encode('ascii')
pos = 0
while pos < len(data) - 8:
box_size = struct.unpack('>I', data[pos:pos + 4])[0]
box_type = data[pos + 4:pos + 8]
if box_size < 8 or pos + box_size > len(data):
break
if box_type == target:
return pos, box_size
pos += box_size
return None
def _extract_moov(filepath):
"""Extract raw moov atom bytes from a video file. Returns bytes or None."""
boxes = parse_boxes(filepath)
for bt, offset, size in boxes:
if bt == 'moov':
with open(filepath, 'rb') as f:
f.seek(offset)
return f.read(size)
return None
def _extract_ftyp(filepath):
"""Extract raw ftyp atom bytes from a video file. Returns bytes or None."""
boxes = parse_boxes(filepath)
for bt, offset, size in boxes:
if bt == 'ftyp':
with open(filepath, 'rb') as f:
f.seek(offset)
return f.read(size)
return None
def _walk_box_children(data):
"""Iterate over child boxes, yielding (type_bytes, offset, size)."""
pos = 0
while pos < len(data) - 8:
sz = struct.unpack('>I', data[pos:pos + 4])[0]
bt = data[pos + 4:pos + 8]
if sz < 8 or pos + sz > len(data):
break
yield bt, pos, sz
pos += sz
def _navigate_to_stsd(moov_data, sample_entry_types):
"""Navigate moov > trak > mdia > minf > stbl > stsd and find a sample entry.
sample_entry_types: set of 4-byte box types to look for (e.g. {b'avc1', b'avc3'}).
Returns (entry_data_after_header, entry_box_size) or (None, 0).
"""
moov_body = moov_data[8:]
for bt, tpos, tsz in _walk_box_children(moov_body):
if bt != b'trak':
continue
trak_body = moov_body[tpos + 8:tpos + tsz]
path = [b'mdia', b'minf', b'stbl', b'stsd']
cur = trak_body
found = True
for target in path:
hit = False
for cbt, cpos, csz in _walk_box_children(cur):
if cbt == target:
cur = cur[cpos + 8:cpos + csz]
hit = True
break
if not hit:
found = False
break
if not found:
continue
if len(cur) < 16:
continue
stsd_body = cur[8:]
for etype, epos, esz in _walk_box_children(stsd_body):
if etype in sample_entry_types:
entry_data = stsd_body[epos + 8:epos + esz]
if len(entry_data) >= 78:
return entry_data[78:], esz
return None, 0
def _extract_avcc_params(moov_data):
"""Extract SPS/PPS NAL units from the avcC box inside a moov atom.
Navigates: moov > trak(video) > mdia > minf > stbl > stsd > avc1 > avcC.
Returns dict with 'sps_list', 'pps_list', 'nal_length_size' or None.
"""
ext_data, _ = _navigate_to_stsd(moov_data, {b'avc1', b'avc3'})
if ext_data is None:
return None
for xbt, xpos, xsz in _walk_box_children(ext_data):
if xbt != b'avcC':
continue
avcc = ext_data[xpos + 8:xpos + xsz]
if len(avcc) < 7:
return None
profile = avcc[1]
level = avcc[3]
nal_length_size = (avcc[4] & 0x03) + 1
num_sps = avcc[5] & 0x1F
off = 6
sps_list = []
for _ in range(num_sps):
if off + 2 > len(avcc):
break
sps_len = struct.unpack('>H', avcc[off:off + 2])[0]
off += 2
if off + sps_len > len(avcc):
break
sps_list.append(bytes(avcc[off:off + sps_len]))
off += sps_len
if off >= len(avcc):
return None
num_pps = avcc[off]
off += 1
pps_list = []
for _ in range(num_pps):
if off + 2 > len(avcc):
break
pps_len = struct.unpack('>H', avcc[off:off + 2])[0]
off += 2
if off + pps_len > len(avcc):
break
pps_list.append(bytes(avcc[off:off + pps_len]))
off += pps_len
return {
'sps_list': sps_list,
'pps_list': pps_list,
'nal_length_size': nal_length_size,
'profile': profile,
'level': level,
}
return None
def _extract_hvcc_params(moov_data):
"""Extract VPS/SPS/PPS NAL units from the hvcC box inside a moov atom.
Navigates: moov > trak(video) > mdia > minf > stbl > stsd > hvc1/hev1 > hvcC.
Returns dict with 'vps_list', 'sps_list', 'pps_list', 'nal_length_size' or None.
"""
ext_data, _ = _navigate_to_stsd(moov_data, {b'hvc1', b'hev1'})
if ext_data is None:
return None
for xbt, xpos, xsz in _walk_box_children(ext_data):
if xbt != b'hvcC':
continue
hvcc = ext_data[xpos + 8:xpos + xsz]
if len(hvcc) < 23:
return None
nal_length_size = (hvcc[21] & 0x03) + 1
num_arrays = hvcc[22]
off = 23
vps_list = []
sps_list = []
pps_list = []
for _ in range(num_arrays):
if off + 3 > len(hvcc):
break
nal_type = hvcc[off] & 0x3F
num_nalus = struct.unpack('>H', hvcc[off + 1:off + 3])[0]
off += 3
for _ in range(num_nalus):
if off + 2 > len(hvcc):
break
nal_len = struct.unpack('>H', hvcc[off:off + 2])[0]
off += 2
if off + nal_len > len(hvcc):
break
nal_data = bytes(hvcc[off:off + nal_len])
off += nal_len
if nal_type == 32:
vps_list.append(nal_data)
elif nal_type == 33:
sps_list.append(nal_data)
elif nal_type == 34:
pps_list.append(nal_data)
if sps_list:
return {
'vps_list': vps_list,
'sps_list': sps_list,
'pps_list': pps_list,
'nal_length_size': nal_length_size,
}
return None
def _scan_for_moov(filepath, start_offset):
"""Scan a file for a valid moov atom starting from start_offset.
Searches for the 'moov' signature and validates the box has
recognizable children (mvhd, trak).
Returns (moov_offset, moov_size) or None.
"""
file_size = os.path.getsize(filepath)
search_size = file_size - start_offset
if search_size < 16:
return None
target = b'moov'
chunk_size = 256 * 1024
with open(filepath, 'rb') as f:
offset = start_offset
while offset < file_size - 8:
f.seek(offset)
chunk = f.read(min(chunk_size, file_size - offset))
if len(chunk) < 8:
break
# Search for 'moov' in this chunk
pos = 0
while pos < len(chunk) - 8:
idx = chunk.find(target, pos + 4)
if idx == -1 or idx < 4:
break
# The 4 bytes before 'moov' should be the box size
box_offset = offset + idx - 4
size_bytes = chunk[idx - 4:idx]
box_size = struct.unpack('>I', size_bytes)[0]
if box_size < 16 or box_offset + box_size > file_size:
pos = idx + 1
continue
# Read and validate moov children
f.seek(box_offset)
moov_data = f.read(min(box_size, 4096))
if len(moov_data) < 16:
pos = idx + 1
continue
# Check for mvhd or trak as first child
child_pos = 8
has_valid_child = False
while child_pos < len(moov_data) - 8:
csz = struct.unpack('>I', moov_data[child_pos:child_pos + 4])[0]
ctype = moov_data[child_pos + 4:child_pos + 8]
if csz < 8:
break
if ctype in (b'mvhd', b'trak', b'udta', b'meta'):
has_valid_child = True
break
child_pos += csz
if has_valid_child:
return (box_offset, box_size)
pos = idx + 1
offset += len(chunk) - 8 # overlap to avoid missing split signatures
return None
def _scan_mdat_for_nals(filepath, mdat_offset, mdat_size,
nal_length_size=4, raw_data=False, codec='h264'):
"""Scan mdat for length-prefixed NAL units, skipping audio chunks.
Supports both H.264 and HEVC codecs. Uses buffered file I/O.
Returns list of (file_offset, nal_length) tuples where file_offset
points to the NAL data (after the length prefix).
If raw_data=True, mdat_offset points directly at NAL data (no mdat box
header to skip). Used for leading-zero recovery where the box header
was destroyed.
"""
if codec == 'hevc':
VALID_TYPES = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
16, 17, 18, 19, 20, 21}
else:
VALID_TYPES = {1, 2, 3, 4, 5, 6} # slices + SEI
MAX_NAL = 20 * 1024 * 1024 # 20MB sanity limit
# Determine mdat data range
if raw_data:
data_start = mdat_offset
else:
# Skip box header
with open(filepath, 'rb') as f:
f.seek(mdat_offset)
hdr = f.read(8)
box_sz = struct.unpack('>I', hdr[:4])[0]
if box_sz == 1:
data_start = mdat_offset + 16
else:
data_start = mdat_offset + 8
data_end = mdat_offset + mdat_size
nal_entries = []
def _is_valid_nal(fh, pos):
"""Read length prefix + NAL header and check validity."""
header_size = 2 if codec == 'hevc' else 1
if pos + nal_length_size + header_size > data_end:
return None
fh.seek(pos)
lb = fh.read(nal_length_size + header_size)
if len(lb) < nal_length_size + header_size:
return None
if nal_length_size == 4:
nal_len = struct.unpack('>I', lb[:4])[0]
elif nal_length_size == 2:
nal_len = struct.unpack('>H', lb[:2])[0]
else:
nal_len = lb[0]
if nal_len < header_size or nal_len > MAX_NAL:
return None
if pos + nal_length_size + nal_len > data_end:
return None
nal_byte = lb[nal_length_size]
if (nal_byte >> 7) & 1: # forbidden_zero_bit
return None
if codec == 'hevc':
nal_type = (nal_byte >> 1) & 0x3F
# Validate HEVC 2-byte header: layer_id must be 0,
# nuh_temporal_id_plus1 must be >= 1
nal_byte2 = lb[nal_length_size + 1]
layer_id = ((nal_byte & 1) << 5) | ((nal_byte2 >> 3) & 0x1F)
tid = nal_byte2 & 0x07
if layer_id != 0 or tid < 1:
return None
else:
nal_type = nal_byte & 0x1F
if nal_type not in VALID_TYPES:
return None
return nal_len
def _find_next_chain(fh, start):
"""Search forward for a position with 2+ consecutive valid NALs."""
CHUNK = 65536
pos = start
while pos < data_end - 8:
fh.seek(pos)
buf = fh.read(min(CHUNK, data_end - pos))
if len(buf) < nal_length_size + 1:
break
for i in range(len(buf) - nal_length_size - 1):
cand = pos + i
nl = _is_valid_nal(fh, cand)
if nl is None:
continue
# Validate second NAL in chain
nl2 = _is_valid_nal(fh, cand + nal_length_size + nl)
if nl2 is not None:
return cand
pos += len(buf) - 8 # overlap
return None
with open(filepath, 'rb') as fh:
pos = data_start
while pos < data_end - nal_length_size:
nl = _is_valid_nal(fh, pos)
if nl is not None:
nal_entries.append((pos + nal_length_size, nl))
pos += nal_length_size + nl
else:
nxt = _find_next_chain(fh, pos + 1)
if nxt is None:
break
pos = nxt
return nal_entries
def _collect_sps_candidates(fdir, primary_params, codec='h264'):
"""Collect unique SPS/PPS (and VPS for HEVC) from healthy donor pool files.
Returns a list of (vps_list, sps_list, pps_list) tuples with the primary
donor's params first, followed by other unique variants from the same
directory. For H.264, vps_list is always [].
"""
extract_fn = _extract_hvcc_params if codec == 'hevc' else _extract_avcc_params
seen = set()
candidates = []
# Primary donor first
vps = primary_params.get('vps_list', [])
key = tuple(s.hex() for s in primary_params['sps_list'])
seen.add(key)
candidates.append((vps, primary_params['sps_list'],
primary_params['pps_list']))
# Check other healthy files in the pool
for pool_file in donor_pool.get(fdir, []):
try:
moov = _extract_moov(pool_file)
if not moov:
continue
params = extract_fn(moov)
if not params:
continue
key = tuple(s.hex() for s in params['sps_list'])
if key not in seen:
seen.add(key)
candidates.append((params.get('vps_list', []),
params['sps_list'], params['pps_list']))
except Exception:
continue
return candidates
def _probe_sps_candidates(filepath, nal_entries, candidates, codec='h264'):
"""Try each (vps_list, sps_list, pps_list) candidate against the NAL data.
Writes a short test stream (first IDR + a few frames) with each
candidate, decodes it with ffmpeg, and returns the candidate
with the fewest decode errors.
Returns (best_vps_list, best_sps_list, best_pps_list).
"""
if not candidates or not has_ffmpeg():
return candidates[0] if candidates else ([], [], [])
if len(candidates) == 1:
return candidates[0]
idr_types = {19, 20} if codec == 'hevc' else {5}
ffmpeg_fmt = 'hevc' if codec == 'hevc' else 'h264'
# Find first IDR and collect a short segment (IDR + up to 10 frames)
test_nals = []
found_idr = False
with open(filepath, 'rb') as f:
for offset, length in nal_entries:
f.seek(offset)
b = f.read(1)
if not b:
continue
if codec == 'hevc':
nal_type = (b[0] >> 1) & 0x3F
else:
nal_type = b[0] & 0x1F
if not found_idr:
if nal_type in idr_types:
found_idr = True
else:
continue
test_nals.append((offset, length))
if len(test_nals) >= 15:
break
if not test_nals:
return candidates[0]
import tempfile
START_CODE = b'\x00\x00\x00\x01'
best = candidates[0]
best_errors = float('inf')
for vps_list, sps_list, pps_list in candidates:
try:
with tempfile.NamedTemporaryFile(suffix='.' + ffmpeg_fmt,
delete=False) as tmp:
tmp_path = tmp.name
for vps in vps_list:
tmp.write(START_CODE + vps)
for sps in sps_list:
tmp.write(START_CODE + sps)
for pps in pps_list:
tmp.write(START_CODE + pps)
with open(filepath, 'rb') as src:
for nal_off, nal_len in test_nals:
tmp.write(START_CODE)
src.seek(nal_off)
remaining = nal_len
while remaining > 0:
chunk = src.read(min(65536, remaining))
if not chunk:
break
tmp.write(chunk)
remaining -= len(chunk)
result = subprocess.run(
[_ffmpeg_path, '-v', 'error', '-f', ffmpeg_fmt,
'-i', tmp_path, '-f', 'null', '-'],
capture_output=True, timeout=10)
err_count = result.stderr.decode(errors='replace').count(
'error while decoding')
if err_count < best_errors:
best_errors = err_count
best = (vps_list, sps_list, pps_list)
if err_count == 0:
break
except Exception:
continue
finally:
try:
os.unlink(tmp_path)
except OSError:
pass
return best
def _write_annex_b_stream(filepath, nal_entries, sps_list, pps_list,
output_path, vps_list=None, codec='h264'):
"""Write NAL units as an Annex-B stream (.h264 or .hevc).
Skips NALs before the first IDR keyframe (P/B-frames without a reference
produce decode errors that break playback). Prepends VPS/SPS/PPS, re-emits
them before each IDR for decoder robustness.
Returns the number of NALs written.
"""
START_CODE = b'\x00\x00\x00\x01'
count = 0
if vps_list is None:
vps_list = []
if codec == 'hevc':
idr_types = {19, 20}
slice_types = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
else:
idr_types = {5}
slice_types = {1, 2, 3, 4}
def _get_nal_type(b):
if codec == 'hevc':
return (b >> 1) & 0x3F
return b & 0x1F
def _write_params(out):
for vps in vps_list:
out.write(START_CODE)
out.write(vps)
for sps in sps_list:
out.write(START_CODE)
out.write(sps)
for pps in pps_list:
out.write(START_CODE)
out.write(pps)
# Find first IDR keyframe — skip orphaned P/B-frames before it
first_idr = 0
with open(filepath, 'rb') as f:
for i, (offset, length) in enumerate(nal_entries):
f.seek(offset)
b = f.read(1)
if b and _get_nal_type(b[0]) in idr_types:
first_idr = i
break
with open(output_path, 'wb') as out, open(filepath, 'rb') as src:
_write_params(out)
need_keyframe = False
for nal_offset, nal_len in nal_entries[first_idr:]:
# Peek at NAL type
src.seek(nal_offset)
nal_byte = src.read(1)
if not nal_byte:
continue
nal_type = _get_nal_type(nal_byte[0])
# Probe for zero corruption: sample a few positions in the NAL
corrupted = False
if nal_len > 64:
for probe_pos in (nal_len // 4, nal_len // 2,
nal_len * 3 // 4):
src.seek(nal_offset + probe_pos)
sample = src.read(16)
if len(sample) == 16 and all(b == 0 for b in sample):
corrupted = True
break
if corrupted:
need_keyframe = True
continue
# After a gap, skip slice frames until next IDR
if need_keyframe:
if nal_type not in idr_types:
if nal_type in slice_types:
continue
else:
need_keyframe = False
# Re-emit VPS/SPS/PPS before each IDR keyframe
if nal_type in idr_types:
_write_params(out)
out.write(START_CODE)
# Copy NAL data in chunks
src.seek(nal_offset)
remaining = nal_len
while remaining > 0:
chunk = src.read(min(1024 * 1024, remaining))
if not chunk:
break
out.write(chunk)
remaining -= len(chunk)
count += 1
return count
def analyze_mdat(filepath, mdat_offset, mdat_size):
"""Scan first portion of mdat for codec information.
Returns dict with:
codec: 'h264' | 'h265' | 'unknown'
nal_count: number of NAL start codes found
has_sps: bool
has_pps: bool
has_idr: bool
resolution: (w, h) or None (from SPS if found)
"""
result = {
'codec': 'unknown',
'nal_count': 0,
'has_sps': False,
'has_pps': False,
'has_idr': False,
'resolution': None,
}
scan_len = min(mdat_size, 2 * 1024 * 1024)
data_offset = mdat_offset + 8 # skip mdat header
with open(filepath, 'rb') as f:
f.seek(data_offset)
data = f.read(scan_len)
if len(data) < 8:
return result
# Check if mdat uses length-prefixed NALs (MP4 style) vs start-code (Annex B)
# MP4 style: 4-byte big-endian length + NAL data
# Annex B: 00 00 00 01 + NAL data
is_annex_b = False
nal_count = 0
has_sps = False
has_pps = False
has_idr = False
codec = 'unknown'
# Try Annex B start codes first
i = 0
while i < len(data) - 4:
if data[i:i + 4] == b'\x00\x00\x00\x01':
nal_byte = data[i + 4]
# H.264: nal_unit_type is lower 5 bits
h264_type = nal_byte & 0x1F
# H.265: nal_unit_type is bits 1-6 of first byte
h265_type = (nal_byte >> 1) & 0x3F
if h264_type in (1, 5, 6, 7, 8, 9):
codec = 'h264'
if h264_type == 7:
has_sps = True
elif h264_type == 8:
has_pps = True
elif h264_type == 5:
has_idr = True
elif h265_type in (0, 1, 19, 20, 32, 33, 34, 35):
codec = 'h265'
if h265_type == 33:
has_sps = True
elif h265_type == 34:
has_pps = True
elif h265_type in (19, 20):
has_idr = True
nal_count += 1
is_annex_b = True
i += 4
else:
i += 1
if not is_annex_b and len(data) >= 8:
# Try MP4-style length-prefixed NALs.
# iPhone mdat may start with audio data — if the first NAL chain
# fails immediately, skip forward up to 64KB to find video data.
def _try_nal_chain(start):
"""Try to parse a chain of NALs from 'start'. Returns
(codec, nal_count, has_sps, has_pps, has_idr) or None."""
c_codec = 'unknown'
c_count = 0
c_sps = c_pps = c_idr = False
pos = start
while pos < len(data) - 5:
nl = struct.unpack('>I', data[pos:pos + 4])[0]
if nl < 1 or nl > mdat_size:
break
nb = data[pos + 4]
if (nb >> 7) & 1: # forbidden_zero_bit must be 0
break
h264t = nb & 0x1F
# H264 types are more specific — check first
if h264t in (1, 5, 6, 7, 8, 9):
c_codec = 'h264'
if h264t == 7: c_sps = True
elif h264t == 8: c_pps = True
elif h264t == 5: c_idr = True
c_count += 1
else:
h265t = (nb >> 1) & 0x3F
if h265t in (0, 1, 19, 20, 32, 33, 34, 35):
if c_codec == 'unknown':
c_codec = 'h265'
if h265t == 33: c_sps = True
elif h265t == 34: c_pps = True
elif h265t in (19, 20): c_idr = True
c_count += 1
else:
break # unrecognized NAL type
nxt = pos + 4 + nl
if nxt > len(data):
break
pos = nxt
if c_count >= 2:
return c_codec, c_count, c_sps, c_pps, c_idr
return None
# Try from the start first, then skip forward if it fails
# (iPhone mdat starts with audio data at offset 0 — video begins later)
chain = _try_nal_chain(0)
if not chain:
for skip in range(1, min(65536, len(data) - 8)):
chain = _try_nal_chain(skip)
if chain:
break
if chain:
codec, nal_count, has_sps, has_pps, has_idr = chain
result['codec'] = codec
result['nal_count'] = nal_count
result['has_sps'] = has_sps
result['has_pps'] = has_pps
result['has_idr'] = has_idr
return result
# ─── Video file checker ──────────────────────────────────────────────────────
def _check_avi(filepath, file_size, head, details):
"""Integrity check for AVI (RIFF) files. Recovery not supported."""
details['unrecoverable'] = True
# Validate RIFF/AVI signature
if len(head) < 12 or head[:4] != b'RIFF' or head[8:12] != b'AVI ':
if len(head) >= 4 and head[:4] == b'RIFF':
return ('corrupt', 'RIFF file but not a valid AVI container', details)
return ('corrupt', 'Not a valid AVI file — missing RIFF/AVI header', details)
# Check for truncation via RIFF chunk size (little-endian at bytes 4-7)
riff_data_size = struct.unpack('<I', head[4:8])[0]
declared_size = riff_data_size + 8
if declared_size > file_size + 8:
details['declared_size'] = declared_size
return ('truncated',
f'AVI file is truncated — declares {declared_size:,} bytes but '
f'file is only {file_size:,} bytes',
details)
# Use ffprobe to detect decode errors if available
if has_ffprobe():
try:
r = subprocess.run(
[_ffprobe_path, '-v', 'error', '-show_entries', 'format=duration',
'-of', 'csv=p=0', filepath],
capture_output=True, timeout=15)
err = r.stderr.decode(errors='replace').strip()
if r.returncode != 0 or err:
return ('corrupt',
f'AVI file is unreadable or corrupt: {err[:120]}' if err
else 'AVI file could not be read by ffprobe',
details)
# Try to extract duration
try:
dur = float(r.stdout.decode().strip())
if dur > 0:
details['duration'] = round(dur, 2)
except (ValueError, AttributeError):
pass
except subprocess.TimeoutExpired:
pass
except Exception:
pass
return 'ok', None, details
def check_video(filepath):
"""Check a video file for integrity issues.
Returns (status, reason, details_dict).
Statuses: ok, no_moov, corrupt, truncated, empty, error
"""
details = {}
try:
file_size = os.path.getsize(filepath)
details['file_size'] = file_size
if file_size == 0:
return 'empty', 'File is empty (0 bytes)', details
if file_size < 8:
return 'corrupt', f'File too small ({file_size} bytes)', details
# Check for leading zeros
with open(filepath, 'rb') as f:
head = f.read(min(64, file_size))
all_zero = all(b == 0 for b in head[:8])
if all_zero:
# Find where zeros end
zero_end = 0
with open(filepath, 'rb') as f: