forked from ponchio/untrunc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mp4.cpp
1347 lines (1120 loc) · 37.6 KB
/
mp4.cpp
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
//==================================================================//
/*
Untrunc - mp4.cpp
Untrunc is GPL software; you can freely distribute,
redistribute, modify & use under the terms of the GNU General
Public License; either version 2 or its successor.
Untrunc is distributed under the GPL "AS IS", without
any warranty; without the implied warranty of merchantability
or fitness for either an expressed or implied particular purpose.
Please see the included GNU General Public License (GPL) for
your rights and further details; see the file COPYING. If you
cannot, write to the Free Software Foundation, 59 Temple Place
Suite 330, Boston, MA 02111-1307, USA. Or www.fsf.org
Copyright 2010 Federico Ponchio
*/
//==================================================================//
#include <cassert>
#include <vector>
#include <algorithm>
#include <functional>
#include <string>
#include <iostream>
#include <ios> // Pre-C++11: may not be included by <iostream>.
#include <iomanip>
#include <limits>
#ifndef __STDC_LIMIT_MACROS
# define __STDC_LIMIT_MACROS 1
#endif
#ifndef __STDC_CONSTANT_MACROS
# define __STDC_CONSTANT_MACROS 1
#endif
extern "C" {
#include <stdint.h>
#ifdef _WIN32
# include <io.h> // for: _isatty()
#else
# include <unistd.h> // for: isatty()
#endif
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libavutil/log.h"
} // extern "C"
#include "mp4.h"
#include "atom.h"
#include "file.h"
#include "log.h"
// Stdio file descriptors.
#ifndef STDIN_FILENO
# define STDIN_FILENO 0
# define STDOUT_FILENO 1
# define STDERR_FILENO 2
#endif
#include <algorithm>
using namespace std;
namespace {
const int MaxFrameLength = 20000000;
// Store start-up addresses of C++ stdio stream buffers as identifiers.
// These addresses differ per process and must be statically linked in.
// Assume that the stream buffers at these stored addresses
// are always connected to their underlaying stdio files.
static const streambuf* const StdioBufs[] = {
cin.rdbuf(), cout.rdbuf(), cerr.rdbuf(), clog.rdbuf()
};
// Store start-up terminal/TTY statuses of C++ stdio stream buffers.
// These statuses differ per process and must be statically linked in.
// Assume that the statuses don't change during the process life-time.
static const bool StdioTtys[sizeof(StdioBufs)/sizeof(StdioBufs[0])] = {
#ifdef _WIN32
_isatty(STDIN_FILENO), _isatty(STDOUT_FILENO), _isatty(STDERR_FILENO), _isatty(STDERR_FILENO)
#else
(bool)isatty(STDIN_FILENO), (bool)isatty(STDOUT_FILENO), (bool)isatty(STDERR_FILENO), (bool)isatty(STDERR_FILENO)
#endif
};
// Is a Terminal/Console/TTY connected to the C++ stream?
// Use on C++ stdio chararacter streams: cin, cout, cerr and clog.
bool isATerminal(const ios& strm) {
for(unsigned int i = 0; i < sizeof(StdioBufs)/sizeof(StdioBufs[0]); ++i) {
if(strm.rdbuf() == StdioBufs[i])
return StdioTtys[i];
}
return false;
}
// Configure FFmpeg/Libav logging for use in C++.
class AvLog {
int lvl;
#ifdef AV_LOG_PRINT_LEVEL
int flgs;
#endif
public:
#ifdef AV_LOG_PRINT_LEVEL
# define DEFAULT_AVLOG_FLAGS AV_LOG_PRINT_LEVEL
#else
# define DEFAULT_AVLOG_FLAGS 0
#endif
explicit AvLog()
: lvl(av_log_get_level())
#ifdef AV_LOG_PRINT_LEVEL
, flgs(av_log_get_flags())
#endif
{
av_log_set_flags(DEFAULT_AVLOG_FLAGS);
// cout.flush(); // Flush C++ standard streams.
//cerr.flush(); // Unbuffered -> nothing to flush.
// clog.flush();
}
explicit AvLog(int level, int flags = DEFAULT_AVLOG_FLAGS)
: lvl(av_log_get_level())
#ifdef AV_LOG_PRINT_LEVEL
, flgs(av_log_get_flags())
#endif
{
if(lvl < level)
av_log_set_level(level);
av_log_set_flags(flags);
cout.flush(); // Flush C++ standard streams.
//cerr.flush(); // Unbuffered -> nothing to flush.
clog.flush();
}
~AvLog() {
fflush(stdout); // Flush C stdio files.
fflush(stderr);
av_log_set_level(lvl);
#ifdef AV_LOG_PRINT_LEVEL
av_log_set_flags(flgs);
#endif
}
};
// Redirect C files.
// This does not effect C++ standard I/O streams (cin, cout, cerr, clog).
class FileRedirect {
FILE *&file_ref;
FILE * file_value;
public:
explicit FileRedirect(FILE *&file, FILE *to_file)
: file_ref(file)
, file_value(file)
{
file = to_file;
if(file_ref) fflush(file_ref);
}
~FileRedirect() {
if(file_ref) fflush(file_ref);
file_ref = file_value;
}
};
}; // namespace
// Mp4
Mp4::Mp4() : timescale(0), duration(0), root(NULL), context(NULL) { }
Mp4::~Mp4() {
close();
}
void Mp4::open(string filename) {
Log::debug << "Opening: " << filename << '\n';
close();
try { // Parse ok file.
File file;
if(!file.open(filename))
throw "Could not open file: " + filename;
root = new Atom;
do {
Atom *atom = new Atom;
atom->parse(file);
Log::debug << "Found atom: " << atom->name << '\n';
root->children.push_back(atom);
} while(!file.atEnd());
} catch(const string &error) {
Log::info << error << "\n";
Log::flush();
if(!root->atomByName("moov"))
throw string("Failed parsing working mp4. Maybe the broken and working files got inverted.");
}/* catch(...) {
throw string("Failed parsing working mp4. Maybe the broken and working files got inverted.");
}*/
// {
file_name = filename;
if(root->atomByName("ctts"))
Log::debug << "Found 'Composition Time To Sample' atom (ctts). Out of order samples possible.\n";
if(root->atomByName("sdtp"))
Log::debug << "Found 'Independent and Disposable Samples' atom (sdtp). I and P frames might need to recover that info.\n";
Atom *mvhd = root->atomByName("mvhd");
if(!mvhd)
throw string("Missing 'Movie Header' atom (mvhd)");
// ASSUME: mvhd atom version 0.
timescale = mvhd->readInt(12);
duration = mvhd->readInt(16);
{ // Setup AV library.
AvLog useAvLog();
// Register all formats and codecs.
av_register_all();
// Open video file.
#ifdef OLD_AVFORMAT_API
int error = av_open_input_file(&context, filename.c_str(), NULL, 0, NULL);
#else
int error = avformat_open_input(&context, filename.c_str(), NULL, NULL);
#endif
if(error != 0)
throw "Could not parse AV file: " + filename;
// Retrieve stream information.
#ifdef OLD_AVFORMAT_API
if(av_find_stream_info(context) < 0)
#else
if(avformat_find_stream_info(context, NULL) < 0)
#endif
throw string("Could not find stream info");
} // {
parseTracks();
}
void Mp4::close() {
Atom *rm_root = root;
root = NULL; // Invalidate Mp4 data.
timescale = 0;
duration = 0;
tracks.clear(); // Must clear tracks before closing context.
if(context) {
AvLog useAvLog(AV_LOG_ERROR);
#ifdef OLD_AVFORMAT_API
av_close_input_file(&context);
#else
avformat_close_input(&context);
#endif
context = NULL;
}
file_name.clear();
delete rm_root;
}
void Mp4::printMediaInfo() {
if(context) {
cout.flush();
clog.flush();
Log::info << "Media Info:\n"
<< " Default stream: " << av_find_default_stream_index(context) << '\n';
AvLog useAvLog(AV_LOG_INFO);
FileRedirect redirect(stderr, stdout);
av_dump_format(context, 0, file_name.c_str(), 0);
}
}
void Mp4::printAtoms() {
if(root) {
Log::info << "Atoms:\n";
root->print(0);
}
}
bool Mp4::makeStreamable(string filename, string output_filename) {
Log::info << "Make Streamable: " << filename << '\n';
Atom atom_root;
{ // Parse input file.
File file;
if(!file.open(filename))
throw "Could not open file: " + filename;
while(!file.atEnd()) {
Atom *atom = new Atom;
atom->parse(file);
Log::debug << "Found atom: " << atom->name << '\n';
atom_root.children.push_back(atom);
}
} // {
Atom *ftyp = atom_root.atomByName("ftyp");
Atom *moov = atom_root.atomByName("moov");
Atom *mdat = atom_root.atomByName("mdat");
if(!moov || !mdat) {
if(!moov)
Log::error << "Missing 'Container for all the Meta-data' atom (moov).\n";
if(!mdat)
Log::error << "Missing 'Media Data container' atom (mdat).\n";
return false;
}
if(mdat->start > moov->start) {
Log::info << "File is already streamable." << endl;
return true;
}
int64_t old_start = mdat->start + 8;
int64_t new_start = moov->length + 8;
if(ftyp)
new_start += ftyp->length;
int64_t diff = new_start - old_start;
Log::debug << "Old: " << old_start << " -> New: " << new_start << '\n';
#if 0 // MIGHT HAVE TO FIX THIS ONE TOO?
Atom *co64 = trak->atomByName("co64");
if(co64) {
trak->prune("co64");
Atom *stbl = trak->atomByName("stbl");
if(stbl) {
Atom *new_stco = new Atom;
memcpy(new_stco->name, "stco", min(sizeof("stco"), sizeof(new_stco->name)-1));
stbl->children.push_back(new_stco);
}
}
#endif
std::vector<Atom *> stcos = moov->atomsByName("stco");
for(unsigned int i = 0; i < stcos.size(); ++i) {
Atom *stco = stcos[i];
int32_t nchunks = stco->readInt(4); // 4 version, 4 number of entries, 4 entries.
for(int j = 0; j < nchunks; ++j) {
int64_t pos = int64_t(8) + 4*j;
int64_t offset = stco->readInt(pos) + diff;
Log::debug << "O: " << offset << '\n';
stco->writeInt(offset, pos);
}
}
{ // Save to output file.
Log::debug << "Saving to: " << output_filename << '\n';
File file;
if(!file.create(output_filename))
throw "Could not create file for writing: " + output_filename;
if(ftyp)
ftyp->write(file);
moov->write(file);
mdat->write(file);
} // {
Log::debug << endl;
return true;
}
bool Mp4::save(string output_filename) {
// We save all atoms except:
// ctts: composition offset (we use sample to time).
// cslg: because it is used only when ctts is present.
// stps: partial sync, same as sync.
//
// Movie is made by ftyp, moov, mdat (we need to know mdat begin, for absolute offsets).
// Assume offsets in stco are absolute and so to find the relative just subtrack mdat->start + 8.
Log::info << "Saving to: " << output_filename << '\n';
if(!root) {
Log::error << "No file opened.\n";
return false;
}
if(timescale == 0) {
timescale = 600; // Default movie time scale.
Log::info << "Using new movie time scale: " << timescale << ".\n";
}
duration = 0;
for(unsigned int i = 0; i < tracks.size(); ++i) {
Track &track = tracks[i];
Log::debug << "Track " << i << " (" << track.codec.name << "): duration: "
<< track.duration << " timescale: " << track.timescale << '\n';
if(track.timescale == 0 && track.duration != 0)
Log::info << "Track " << i << " (" << track.codec.name << ") has no time scale.\n";
track.writeToAtoms();
// Convert duration to movie timescale.
if(timescale == 0) continue; // Shouldn't happen.
// Use default movie time scale if no track time scale was found.
int track_timescale = (track.timescale != 0) ? track.timescale : 600;
//convert track duration (in track.timescale units) to movie timesscale units.
int track_duration = static_cast<int>((int64_t(track.duration) * timescale - 1 + track_timescale)
/ track_timescale);
if(duration < track_duration)
duration = track_duration;
Atom *tkhd = track.trak->atomByName("tkhd");
if(!tkhd) {
Log::debug << "Missing 'Track Header' atom (tkhd).\n";
continue;
}
if(tkhd->readInt(20) == track_duration) continue;
Log::debug << "Adjusting track duration to movie timescale: New duration: "
<< track_duration << " timescale: " << timescale << ".\n";
tkhd->writeInt(track_duration, 20); // In movie timescale, not track timescale.
}
Log::debug << "Movie duration: " << duration/(double)timescale << "s with timescale: " << timescale << '\n';
Atom *mvhd = root->atomByName("mvhd");
if(!mvhd)
throw string("Missing 'Movie Header' atom (mvhd)");
mvhd->writeInt(duration, 16);
Atom *ftyp = root->atomByName("ftyp");
Atom *moov = root->atomByName("moov");
Atom *mdat = root->atomByName("mdat");
if(!moov || !mdat) {
if(!moov)
Log::error << "Missing 'Container for all the Meta-data' atom (moov).\n";
if(!mdat)
Log::error << "Missing 'Media Data container' atom (mdat).\n";
return false;
}
moov->prune("ctts");
moov->prune("cslg");
moov->prune("stps");
root->updateLength();
//we need to add mdat header bytes
int64_t offset = moov->length + 8;
if(mdat->length64)
offset += 8;
if(ftyp)
offset += ftyp->length; // Not all .mov have an ftyp.
for(unsigned int t = 0; t < tracks.size(); ++t) {
Track &track = tracks[t];
for(unsigned int i = 0; i < track.offsets.size(); ++i)
track.offsets[i] += offset;
track.writeToAtoms(); // Need to save the offsets back to the atoms.
}
{ // Save to output file.
File file;
if(!file.create(output_filename))
throw "Could not create file for writing: " + output_filename;
if(ftyp)
ftyp->write(file);
moov->write(file);
mdat->write(file);
} // {
return true;
}
void Mp4::analyze(int analyze_track, bool interactive) {
Log::info << "Analyze:\n";
if(!root) {
Log::error << "No file opened.\n";
return;
}
Atom *_mdat = root->atomByName("mdat");
if(!_mdat) {
Log::error << "Missing 'Media Data container' atom (mdat).\n";
return;
}
BufferedAtom *mdat = bufferedMdat(_mdat);
if(interactive) {
// For interactive analyzis, std::cin & std::cout must be connected to a terminal/tty.
if(!isATerminal(cin)) {
Log::debug << "Cannot analyze interactively as input doesn't come directly from a terminal.\n";
interactive = false;
}
if(interactive && !isATerminal(cout)) {
Log::debug << "Cannot analyze interactively as output doesn't go directly to a terminal.\n";
interactive = false;
}
if(interactive)
cin.clear(); // Reset state - clear transient errors of previous input operations.
#ifdef VERBOSE1
clog.flush();
#endif
}
for(unsigned int i = 0; i < tracks.size(); ++i) {
if(analyze_track != -1 && i != analyze_track)
continue;
Log::info << "\n\nTrack " << i << endl;
Track &track = tracks[i];
if(track.hint_track) {
Log::info << "Hint track for track: " << track.hinted_id << "\n";
} else {
Log::info << "Track codec: " << track.codec.name << '\n';
}
Log::info << "Keyframes : " << track.keyframes.size() << "\n\n";
if(track.codec.pcm) {
Log::info << "PCM codec, skipping keyframes\n\n";
} else if(track.default_size) {
Log::info << "Default size packets, skipping keyframes\n\n";
} else {
for(unsigned int i = 0; i < track.keyframes.size(); ++i) {
int k = track.keyframes[i];
int64_t offset = track.offsets[k] - mdat->content_start;
uint32_t begin = mdat->readInt(offset);
uint32_t next = mdat->readInt(offset + 4);
Log::debug << setw(8) << k
<< " Size: " << setw(6) << track.getSize(k)
<< " offset " << setw(10) << track.offsets[k]
<< " begin: " << hex << setw(5) << begin << ' ' << setw(8) << next << dec
<< " time: " << (track.default_time ? track.default_time : track.times[i]) << '\n';
}
}
if(track.default_size) {
Log::info << "Constant size for samples: " << track.default_size << "\n";
} else {
Log::info << "Sizes for samples: " << "\n";
for(int i = 0; i < 10 && i < track.sample_sizes.size(); i++) {
Log::info << track.sample_sizes[i] << " ";
}
Log::info << "\n";
}
if(track.default_time) {
Log::info << "Constant time for packet: " << track.default_time << endl;
}
if(track.default_size) {
if(!track.codec.pcm) {
Log::info << "Not a PCM codec, default size though.. we have hope.\n";
}
for(Track::Chunk &chunk: track.chunks) {
int64_t offset = chunk.offset - mdat->content_start;
int64_t maxlength64 = mdat->contentSize() - offset;
if(maxlength64 > MaxFrameLength)
maxlength64 = MaxFrameLength;
int maxlength = static_cast<int>(maxlength64);
int32_t begin = mdat->readInt(offset);
int32_t next = mdat->readInt(offset + 4);
int32_t end = mdat->readInt(offset + track.getSize(i) - 4);
Log::info << " Size: " << setw(6) << chunk.size
<< " offset " << setw(10) << chunk.offset
<< " begin: " << hex << setw(8) << begin << ' ' << setw(8) << next
<< " end: " << setw(8) << end << dec
<< " time: " << (track.default_time ? track.default_time : track.times[i]) << '\n';
}
}
int sample = 0;
for(unsigned int i = 0; i < track.chunks.size(); ++i) {
Track::Chunk &chunk = track.chunks[i];
int64_t offset = chunk.offset - mdat->content_start;
for(int k = 0; k < chunk.nsamples; k++) {
int64_t size = track.getSize(chunk.first_sample + k);
if(track.codec.pcm)
size = chunk.size;
unsigned char *start = mdat->getFragment(offset, size+200); //&(mdat->content[offset]);
int32_t begin = mdat->readInt(offset);
int32_t next = mdat->readInt(offset + 4);
Log::info << " Size: " << setw(6) << size
<< " offset " << setw(10) << offset + mdat->content_start
<< " begin: " << hex << setw(8) << begin << ' ' << setw(8) << next << dec << '\n';
sample++;
offset += size;
Match match = track.codec.match(start, size+200);
if(match.length == size)
continue;
if(match.length == 0) {
Log::error << "- Match failed!\n";
} else if(match.length < 0 || match.length > MaxFrameLength) {
Log::error << "- Invalid length!\n";
} else {
Log::error << "- Length mismatch: got " << match.length << " expected: " << size << "\n";
}
if(interactive) {
Log::info << " <Press [Enter] for next match>\r";
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}
}
}
}
void Mp4::simulate(Mp4::MdatStrategy strategy, int64_t begin) {
//TODO remove duplicated code with analyze.
Log::info << "Simulate:\n";
Log::info << "Analyze:\n";
if(!root) {
Log::error << "No file opened.\n";
return;
}
Atom *original_mdat = root->atomByName("mdat");
if(!original_mdat) {
Log::error << "Missing 'Media Data container' atom (mdat).\n";
return;
}
BufferedAtom *mdat = findMdat(file_name, strategy);
if(!mdat) {
Log::error << "MDAT not found.\n";
return;
}
//sort packets by start, length, track id
std::vector<Match> packets;
std::string codecs[tracks.size()];
for(unsigned int t = 0; t < tracks.size(); ++t) {
Track &track = tracks[t];
codecs[t] = track.codec.name;
//if pcm -> offsets should be chunks!
if(track.default_size) {
Log::debug << "Track " << t << " packets: " << track.chunks.size() << endl;
for(unsigned int i = 0;i < track.chunks.size(); i++) {
Track::Chunk &chunk = track.chunks[i];
Match match;
match.id = t;
match.offset = chunk.offset;
match.length = chunk.size;
match.duration = track.default_time? track.default_time : track.times[i];
packets.push_back(match);
}
} else {
Log::debug << "Track " << t << " packets: " << track.offsets.size() << endl;
for(unsigned int i = 0; i < track.offsets.size(); ++i) {
Match match;
match.id = t;
match.offset = track.offsets[i];
match.length = track.chunk_sizes[i];
match.duration = track.default_time? track.default_time : track.times[i];
packets.push_back(match);
}
}
}
std::sort(packets.begin(), packets.end(), [](const Match &m1, const Match &m2) { return m1.offset < m2.offset; });
if(packets[0].offset != original_mdat->content_start) {
Log::error << "First packet does not start with mdat, finding the start of the packets might be problematic" << endl;
}
//ensure mdat is correctly found.
if(original_mdat->content_start != mdat->file_begin) {
Log::error << "Wrong start of mdat: " << mdat->file_begin << " should be " << original_mdat->content_start << "\n";
mdat->file_begin = mdat->content_start = packets[0].offset;
}
int64_t offset = 0; //mdat->file_begin;
for(Match &m: packets) {
if(m.offset != mdat->file_begin + offset) {
Log::error << "Some empty space to be skipped! Real start = " << m.offset << " mdat start guessed at: " << offset + mdat->file_begin << "\n";
break;
}
unsigned char *start = mdat->getFragment(offset, 8);
unsigned int begin = readBE<int>(start);
unsigned int next = readBE<int>(start + 4);
Log::debug << "\n" << codecs[m.id] << " offset: " << setw(10) << (m.offset) << " Length: " << m.length
<< " begin: " << hex << setw(8) << begin << ' ' << setw(8) << next << dec << "\n";
MatchGroup matches = match(offset, mdat);
Match &best = matches[0];
for(Match m: matches) {
Log::debug << "Match for: " << m.id << " (" << codecs[m.id] << ") chances: " << m.chances << " length: " << m.length << "\n";
}
if(best.chances == 0.0f) {
//we could not detect best, in reconstruction we need to backtrack
Log::error << "Could not match packet for track " << m.id << "\n";
Log::flush();
Log::info << " <Press [Enter] for next match>\r";
cin.ignore(numeric_limits<streamsize>::max(), '\n');
// break;
}
if(m.id != best.id) {
Log::error << "Mismatch! Packet track should be on track: " << m.id << " (" << codecs[m.id] << ") it is: " << best.id << " (" << codecs[best.id] << ")\n";
Log::flush();
Log::info << " <Press [Enter] for next match>\r";
cin.ignore(numeric_limits<streamsize>::max(), '\n');
// break;
}
if(m.length != best.length) {
Log::error << "Packet length is wrong." << endl;
Log::flush();
Log::info << " <Press [Enter] for next match>\r";
cin.ignore(numeric_limits<streamsize>::max(), '\n');
// break;
}
offset += m.length;
}
}
MatchGroup Mp4::match(int64_t offset, BufferedAtom *mdat) {
MatchGroup group;
group.offset = offset;
int64_t maxlength64 = mdat->contentSize() - offset;
if(maxlength64 > MaxFrameLength)
maxlength64 = MaxFrameLength;
unsigned char *start = mdat->getFragment(offset, maxlength64);
int maxlength = static_cast<int>(maxlength64);
for(unsigned int i = 0; i < tracks.size(); ++i) {
Track &track = tracks[i];
Match m = track.codec.match(start, maxlength);
m.id = i;
m.offset = group.offset;
group.push_back(m);
}
sort(group.begin(), group.end(), [](const Match &m1, const Match &m2) { return m1.chances > m2.chances; });
return group;
}
void Mp4::writeTracksToAtoms() {
for(unsigned int i = 0; i < tracks.size(); ++i)
tracks[i].writeToAtoms();
}
bool Mp4::parseTracks() {
assert(root != NULL);
Atom *_mdat = root->atomByName("mdat");
if(!_mdat) {
Log::error << "Missing 'Media Data container' atom (mdat).\n";
return false;
}
BufferedAtom *mdat = bufferedMdat(_mdat);
vector<Atom *> traks = root->atomsByName("trak");
for(unsigned int i = 0; i < traks.size(); ++i) {
Track track;
track.codec.context = context->streams[i]->codec;
track.parse(traks[i]);
track.codec.stats.init(track, mdat);
tracks.push_back(track);
}
return true;
}
BufferedAtom *Mp4::bufferedMdat(Atom *mdat) {
BufferedAtom *_mdat = new BufferedAtom(file_name);
_mdat->start = mdat->start;
memcpy(_mdat->name, "mdat", 5);
_mdat->content_start = mdat->start;
_mdat->file_begin = mdat->start;
_mdat->file_end = _mdat->file.length();
return _mdat;
}
BufferedAtom *Mp4::findMdat(std::string filename, Mp4::MdatStrategy strategy) {
BufferedAtom *mdat = new BufferedAtom(filename);
int64_t start = findMdat(mdat, strategy);
if(start < 0) {
delete mdat;
return nullptr;
}
mdat->start = 0; //will be overwritten in repair.
memcpy(mdat->name, "mdat", 5);
mdat->content_start = start;
mdat->file_begin = start;
mdat->file_end = mdat->file.length();
return mdat;
}
/* strategy:
*
* 1) Look for mdat. It's almost always a good start, but sometime, the actual packets can start from 8 to 200000k and more after.
* 1.a) if non start guessable packets with fixed lenght are present we are blindly looking for them
* 2.b) if we have guessable start make a map of possible starts and check with what we have found, in that case we need to lookup find mdat start with a different approach.
* 2) if method 1 fails, we need to look for start guessable packets.
*
* Note: avc1 has size then start and for keyframes they are pretty guessable.
*/
int64_t Mp4::contentStart() {
vector<int64_t> offsets;
for(Track &track: tracks) {
for(Track::Chunk &chunk: track.chunks) {
offsets.push_back(chunk.offset);
break;
}
}
sort(offsets.begin(), offsets.end());
return offsets[0];
}
int64_t Mp4::findMdat(BufferedAtom *mdat, Mp4::MdatStrategy strategy) {
if(strategy == SAME)
return contentStart();
//look for mdat
int64_t mdat_offset = -1;
char m[4];
m[3] = 0;
//look for mdat in the first 20 MB
int64_t length = std::min(int64_t(20000000), mdat->file_end - mdat->file_begin);
uint8_t *data = mdat->getFragment(0, length);
if(strategy == FIRST || strategy == LAST) {
for(uint64_t i = 4; i < length-4; i++) {
uint32_t c = readBE<uint32_t>(data + i);
if(c != 0x6D646174) //mdat
continue;
mdat_offset = i+4;
//check if its 64bit mdat
uint32_t size = readBE<uint32_t>(data + i -4);
if(size == 1)
mdat_offset += 8;
//sometimes the length is not specified and still the first packet starts at +8 (see in repair)
if(strategy == FIRST)
break;
}
} else if(strategy == SEARCH) {
//TODO if we have some unique beginnigs, try to spot the first one.
for(uint64_t i = 4; i < length-4; i++) {
uint32_t c = readBE<uint32_t>(data + i);
if(c == 0) continue;
for(Track &track: tracks) {
//might want to look for video keyframes and actually skip the size of the frame (which is useless).
if(track.codec.stats.beginnings32.count(c)) {
mdat_offset = i;
break;
}
}
if(mdat_offset != -1)
break;
}
}
mdat->flush();
if(mdat_offset != -1) {
mdat->start = mdat_offset - 8;
mdat->content_start = mdat_offset;
}
Log::info << "Mdat not found!" << endl;
return mdat_offset;
}
//skip vast tract of zeros (up to the last one.
//multiple of 1024. If it's all zeros skip.
//if it's less than 8 bytes dont (might be alac?)
//otherwise we need to search for the actual begin using matches.
int zeroskip(BufferedAtom *mdat, unsigned char *start, int64_t maxlength) {
return 0;
int64_t block_size = std::min(int64_t(1<<10), maxlength);
//skip 4 bytes at a time.
int k = 0;
for(;k < block_size - 4; k+= 4) {
int value = readBE<int>(start + k);
if(value != 0)
break;
}
//don't skip very short zero sequences
if(k < 16)
return 0;
//play conservative of non aligned zero blocks
if(k < block_size)
k -= 4;
//zero bytes block aligned.
Log::debug << "Skipping zero bytes: " << k << "\n";
return k;
}
int Mp4::searchNext(BufferedAtom *mdat, int64_t offset) {
int64_t maxlength64 = mdat->contentSize() - offset;
if(maxlength64 > MaxFrameLength)
maxlength64 = MaxFrameLength;
unsigned char *start = mdat->getFragment(offset, maxlength64);
int maxlength = static_cast<int>(maxlength64);
Match best;
best.chances = 0;
best.offset = 0;
for(Track &track: tracks) {
Match m = track.codec.search(start, maxlength);
if(m.chances != 0 && (best.chances == 0 || m.offset < best.offset))
best = m;
}
return best.offset;
}
/* Entropy could be used to detect wrong sowt packets. */
double entropy(uint8_t *data, int size) {
int count[256];
memset(count, 0, 256*sizeof(int));
for(int i = 0; i < size; i++)
count[data[i]]++;
double e = 0.0;
double log2 = log(2.0);
for(int i = 0; i < 256; i++) {
if(count[i] == 0)
continue;
double p = count[i]/(double)size;
e -= p*log(p)/log2;
}
return e;
}
bool Mp4::repair(string corrupt_filename, Mp4::MdatStrategy strategy, int64_t mdat_begin, bool skip_zeros, bool drifting) {
Log::info << "Repair: " << corrupt_filename << '\n';
BufferedAtom *mdat = NULL;
File file;
if(!file.open(corrupt_filename))
throw "Could not open file: " + corrupt_filename;
if(0) { // Parse corrupt file.
// Find mdat. This fails with krois and a few other.
// TODO: Check for multiple mdat, or just look for the first one.
while(true) {
Atom atom;
try {
atom.parseHeader(file);
} catch(string) {
throw string("Failed to parse atoms in truncated file");
}
if(atom.name != string("mdat")) {
off_t pos = file.pos();
file.seek(pos - 8 + atom.length);
continue;
}
mdat = new BufferedAtom(corrupt_filename);
mdat->start = atom.start;
memcpy(mdat->name, atom.name, sizeof(mdat->name)-1);
memcpy(mdat->head, atom.head, sizeof(mdat->head));
memcpy(mdat->version, atom.version, sizeof(mdat->version));
mdat->file_begin = file.pos();
mdat->file_end = file.length() - file.pos();
Log::debug << "MDAT SIZE: " << mdat->file_end - mdat->file_begin << endl; //mdat->content = file.read(file.length() - file.pos());
break;
}
} else {