Debian Codegraph @

bento4-embedded/Source/C++/Apps/Mp4Fragment/Mp4Fragment.cpp

raw
1 /*****************************************************************
2 |
3 | AP4 - MP4 Fragmenter
4 |
5 | Copyright 2002-2019 Axiomatic Systems, LLC
6 |
7 |
8 | This file is part of Bento4/AP4 (MP4 Atom Processing Library).
9 |
10 | Unless you have obtained Bento4 under a difference license,
11 | this version of Bento4 is Bento4|GPL.
12 | Bento4|GPL is free software; you can redistribute it and/or modify
13 | it under the terms of the GNU General Public License as published by
14 | the Free Software Foundation; either version 2, or (at your option)
15 | any later version.
16 |
17 | Bento4|GPL is distributed in the hope that it will be useful,
18 | but WITHOUT ANY WARRANTY; without even the implied warranty of
19 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 | GNU General Public License for more details.
21 |
22 | You should have received a copy of the GNU General Public License
23 | along with Bento4|GPL; see the file COPYING. If not, write to the
24 | Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
25 | 02111-1307, USA.
26 |
27 ****************************************************************/
28
29 /*----------------------------------------------------------------------
30 | includes
31 +---------------------------------------------------------------------*/
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <time.h>
35
36 #include "Ap4.h"
37
38 /*----------------------------------------------------------------------
39 | constants
40 +---------------------------------------------------------------------*/
41 #define BANNER "MP4 Fragmenter - Version 1.7.0\n"\
42 "(Bento4 Version " AP4_VERSION_STRING ")\n"\
43 "(c) 2002-2020 Axiomatic Systems, LLC"
44
45 /*----------------------------------------------------------------------
46 | constants
47 +---------------------------------------------------------------------*/
48 const unsigned int AP4_FRAGMENTER_DEFAULT_FRAGMENT_DURATION = 2000; // ms
49 const unsigned int AP4_FRAGMENTER_MAX_AUTO_FRAGMENT_DURATION = 40000;
50 const unsigned int AP4_FRAGMENTER_OUTPUT_MOVIE_TIMESCALE = 1000;
51
52 typedef enum {
53 AP4_FRAGMENTER_FORCE_SYNC_MODE_NONE,
54 AP4_FRAGMENTER_FORCE_SYNC_MODE_AUTO,
55 AP4_FRAGMENTER_FORCE_SYNC_MODE_ALL
56 } ForceSyncMode;
57
58 /*----------------------------------------------------------------------
59 | options
60 +---------------------------------------------------------------------*/
61 struct _Options {
62 unsigned int verbosity;
63 bool trim;
64 bool debug;
65 bool no_tfdt;
66 double tfdt_start;
67 unsigned int sequence_number_start;
68 ForceSyncMode force_i_frame_sync;
69 bool no_zero_elst;
70 } Options;
71
72 /*----------------------------------------------------------------------
73 | PrintUsageAndExit
74 +---------------------------------------------------------------------*/
75 static void
76 PrintUsageAndExit()
77 {
78 fprintf(stderr,
79 BANNER
80 "\n\nusage: mp4fragment [options] <input> <output>\n"
81 "options are:\n"
82 " --verbosity <n> sets the verbosity (details) level to <n> (between 0 and 3)\n"
83 " --debug enable debugging information output\n"
84 " --quiet don't print out notice messages\n"
85 " --fragment-duration <milliseconds> (default = automatic)\n"
86 " --timescale <n> (use 10000000 for Smooth Streaming compatibility)\n"
87 " --track <track-id or type> only include media from one track (pass a track ID, 'audio', 'video' or 'subtitles')\n"
88 " --index (re)create the segment index\n"
89 " --trim trim excess media in longer tracks\n"
90 " --no-tfdt don't add 'tfdt' boxes in the fragments (may be needed for legacy Smooth Streaming clients)\n"
91 " --tfdt-start <start> value of the first tfdt timestamp, expressed as a floating point number in seconds\n"
92 " --sequence-number-start <start> value of the first segment sequence number (default: 1)\n"
93 " --force-i-frame-sync <auto|all> treat all I-frames as sync samples (for open-gop sequences)\n"
94 " 'auto' only forces the flag if an open-gop source is detected, 'all' forces the flag in all cases\n"
95 " --copy-udta copy the moov/udta atom from input to output\n"
96 " --no-zero-elst don't set the last edit list entry to 0 duration\n"
97 " --trun-version-zero set the 'trun' box version to zero (default version: 1)\n"
98 );
99 exit(1);
100 }
101
102 /*----------------------------------------------------------------------
103 | platform adaptation
104 +---------------------------------------------------------------------*/
105 #if defined(_MSC_VER)
106 static double
107 strtof(char* s, char** /* end */)
108 {
109 _CRT_DOUBLE value = {0.0};
110 int result = _atodbl(&value, s);
111 return result == 0 ? (double)value.x : 0.0;
112 }
113 #endif
114
115
116
117 /*----------------------------------------------------------------------
118 | SampleArray
119 +---------------------------------------------------------------------*/
120 class SampleArray {
121 public:
122 SampleArray(AP4_Track* track) :
123 m_Track(track) {
124 m_SampleCount = m_Track->GetSampleCount();
125 if (m_SampleCount) {
126 m_ForcedSync = new bool[m_SampleCount];
127 for (unsigned int i=0; i<m_SampleCount; i++) {
128 m_ForcedSync[i] = false;
129 }
130 } else {
131 m_ForcedSync = NULL;
132 }
133 }
134 virtual ~SampleArray() {
135 delete[] m_ForcedSync;
136 }
137
138 virtual AP4_Cardinal GetSampleCount() {
139 return m_SampleCount;
140 }
141 virtual AP4_Result GetSample(AP4_Ordinal index, AP4_Sample& sample) {
142 AP4_Result result = m_Track->GetSample(index, sample);
143 if (AP4_SUCCEEDED(result)) {
144 if (m_ForcedSync[index]) {
145 sample.SetSync(true);
146 }
147 }
148 return result;
149 }
150 virtual AP4_Result AddSample(AP4_Sample& /*sample*/) {
151 return AP4_ERROR_NOT_SUPPORTED;
152 }
153 virtual void ForceSync(AP4_Ordinal index) {
154 if (index < m_SampleCount) {
155 m_ForcedSync[index] = true;
156 }
157 }
158
159 protected:
160 AP4_Track* m_Track;
161 AP4_Cardinal m_SampleCount;
162 bool* m_ForcedSync;
163 };
164
165 /*----------------------------------------------------------------------
166 | CachedSampleArray
167 +---------------------------------------------------------------------*/
168 class CachedSampleArray : public SampleArray {
169 public:
170 CachedSampleArray(AP4_Track* track) :
171 SampleArray(track) {}
172
173 virtual AP4_Cardinal GetSampleCount() {
174 return m_Samples.ItemCount();
175 }
176 virtual AP4_Result GetSample(AP4_Ordinal index, AP4_Sample& sample) {
177 if (index >= m_Samples.ItemCount()) {
178 return AP4_ERROR_OUT_OF_RANGE;
179 } else {
180 sample = m_Samples[index];
181 return AP4_SUCCESS;
182 }
183 }
184 virtual AP4_Result AddSample(AP4_Sample& sample) {
185 return m_Samples.Append(sample);
186 }
187
188 protected:
189 AP4_Array<AP4_Sample> m_Samples;
190 };
191
192 /*----------------------------------------------------------------------
193 | TrackCursor
194 +---------------------------------------------------------------------*/
195 class TrackCursor
196 {
197 public:
198 TrackCursor(AP4_Track* track, SampleArray* samples);
199 ~TrackCursor();
200
201 AP4_Result Init();
202 AP4_Result SetSampleIndex(AP4_Ordinal sample_index);
203
204 AP4_Track* m_Track;
205 SampleArray* m_Samples;
206 AP4_Ordinal m_SampleIndex;
207 AP4_Ordinal m_FragmentIndex;
208 AP4_Sample m_Sample;
209 AP4_UI64 m_Timestamp;
210 AP4_UI64 m_UnscaledTimestamp;
211 bool m_Eos;
212 AP4_TfraAtom* m_Tfra;
213 };
214
215 /*----------------------------------------------------------------------
216 | TrackCursor::TrackCursor
217 +---------------------------------------------------------------------*/
218 TrackCursor::TrackCursor(AP4_Track* track, SampleArray* samples) :
219 m_Track(track),
220 m_Samples(samples),
221 m_SampleIndex(0),
222 m_FragmentIndex(0),
223 m_Timestamp(0),
224 m_UnscaledTimestamp(0),
225 m_Eos(false),
226 m_Tfra(new AP4_TfraAtom(0))
227 {
228 }
229
230 /*----------------------------------------------------------------------
231 | TrackCursor::~TrackCursor
232 +---------------------------------------------------------------------*/
233 TrackCursor::~TrackCursor()
234 {
235 delete m_Tfra;
236 delete m_Samples;
237 }
238
239 /*----------------------------------------------------------------------
240 | TrackCursor::Init
241 +---------------------------------------------------------------------*/
242 AP4_Result
243 TrackCursor::Init()
244 {
245 return m_Samples->GetSample(0, m_Sample);
246 }
247
248 /*----------------------------------------------------------------------
249 | TrackCursor::SetSampleIndex
250 +---------------------------------------------------------------------*/
251 AP4_Result
252 TrackCursor::SetSampleIndex(AP4_Ordinal sample_index)
253 {
254 m_SampleIndex = sample_index;
255
256 // check if we're at the end
257 if (sample_index >= m_Samples->GetSampleCount()) {
258 AP4_UI64 end_dts = m_Sample.GetDts()+m_Sample.GetDuration();
259 m_Sample.Reset();
260 m_Sample.SetDts(end_dts);
261 m_Eos = true;
262 } else {
263 return m_Samples->GetSample(m_SampleIndex, m_Sample);
264 }
265
266 return AP4_SUCCESS;
267 }
268
269 /*----------------------------------------------------------------------
270 | FragmentInfo
271 +---------------------------------------------------------------------*/
272 class FragmentInfo {
273 public:
274 FragmentInfo(SampleArray* samples, AP4_TfraAtom* tfra, AP4_UI64 timestamp, AP4_ContainerAtom* moof) :
275 m_Samples(samples),
276 m_Tfra(tfra),
277 m_Timestamp(timestamp),
278 m_Duration(0),
279 m_Moof(moof),
280 m_MoofPosition(0),
281 m_MdatSize(0) {}
282
283 SampleArray* m_Samples;
284 AP4_TfraAtom* m_Tfra;
285 AP4_UI64 m_Timestamp;
286 AP4_UI32 m_Duration;
287 AP4_Array<AP4_UI32> m_SampleIndexes;
288 AP4_ContainerAtom* m_Moof;
289 AP4_Position m_MoofPosition;
290 AP4_UI32 m_MdatSize;
291 };
292
293 /*----------------------------------------------------------------------
294 | IndexSegmentInfo
295 +---------------------------------------------------------------------*/
296 class IndexedSegmentInfo {
297 public:
298 IndexedSegmentInfo() : m_Size(0), m_Duration(0) {}
299 AP4_UI32 m_Size;
300 AP4_UI32 m_Duration;
301 };
302
303 /*----------------------------------------------------------------------
304 | Fragment
305 +---------------------------------------------------------------------*/
306 static void
307 Fragment(AP4_File& input_file,
308 AP4_ByteStream& output_stream,
309 AP4_Array<TrackCursor*>& cursors,
310 AP4_UI32 fragment_duration,
311 AP4_UI32 timescale,
312 bool create_segment_index,
313 bool copy_udta,
314 bool trun_version_one)
315 {
316 AP4_List<FragmentInfo> fragments;
317 AP4_List<IndexedSegmentInfo> indexed_segments;
318 IndexedSegmentInfo* current_indexed_segment = NULL;
319 AP4_Result result;
320
321 // get the movie
322 AP4_Movie* input_movie = input_file.GetMovie();
323 if (input_movie == NULL) {
324 fprintf(stderr, "ERROR: no moov found in the input file\n");
325 return;
326 }
327
328 // create the output file object
329 AP4_UI64 creation_time = 0;
330 time_t now = time(NULL);
331 if (now != (time_t)-1) {
332 // adjust the time based on the MPEG time origin
333 creation_time = (AP4_UI64)now + 0x7C25B080;
334 }
335 AP4_Movie* output_movie = new AP4_Movie(AP4_FRAGMENTER_OUTPUT_MOVIE_TIMESCALE, 0, creation_time, creation_time);
336
337 // create an mvex container
338 AP4_ContainerAtom* mvex = new AP4_ContainerAtom(AP4_ATOM_TYPE_MVEX);
339 AP4_MehdAtom* mehd = new AP4_MehdAtom(0);
340 mvex->AddChild(mehd);
341
342 // add an output track for each track in the input file
343 for (unsigned int i=0; i<cursors.ItemCount(); i++) {
344 AP4_Track* track = cursors[i]->m_Track;
345
346 result = cursors[i]->Init();
347 if (AP4_FAILED(result)) {
348 fprintf(stderr, "ERROR: failed to init sample cursor (%d), skipping track %d\n", result, track->GetId());
349 return;
350 }
351
352 // create a sample table (with no samples) to hold the sample description
353 AP4_SyntheticSampleTable* sample_table = new AP4_SyntheticSampleTable();
354 for (unsigned int j=0; j<track->GetSampleDescriptionCount(); j++) {
355 AP4_SampleDescription* sample_description = track->GetSampleDescription(j);
356 sample_table->AddSampleDescription(sample_description, false);
357 }
358
359 // create the track
360 AP4_Track* output_track = new AP4_Track(sample_table,
361 track->GetId(),
362 timescale?timescale:AP4_FRAGMENTER_OUTPUT_MOVIE_TIMESCALE,
363 AP4_ConvertTime(track->GetDuration(),
364 input_movie->GetTimeScale(),
365 timescale?timescale:AP4_FRAGMENTER_OUTPUT_MOVIE_TIMESCALE),
366 timescale?timescale:track->GetMediaTimeScale(),
367 0,//track->GetMediaDuration(),
368 track);
369
370 // add an edit list if needed
371 if (!trun_version_one) {
372 if (const AP4_TrakAtom* trak = track->GetTrakAtom()) {
373 AP4_ContainerAtom* edts = AP4_DYNAMIC_CAST(AP4_ContainerAtom, trak->GetChild(AP4_ATOM_TYPE_EDTS));
374 if (edts) {
375 // create an 'edts' container
376 AP4_ContainerAtom* new_edts = new AP4_ContainerAtom(AP4_ATOM_TYPE_EDTS);
377
378 // create a new 'edts' for each original 'edts'
379 for (AP4_List<AP4_Atom>::Item* edts_entry = edts->GetChildren().FirstItem();
380 edts_entry;
381 edts_entry = edts_entry->GetNext()) {
382 AP4_ElstAtom* elst = AP4_DYNAMIC_CAST(AP4_ElstAtom, edts_entry->GetData());
383 AP4_ElstAtom* new_elst = new AP4_ElstAtom();
384
385 // adjust the fields to match the correct timescale
386 for (unsigned int j=0; j<elst->GetEntries().ItemCount(); j++) {
387 AP4_ElstEntry new_elst_entry = elst->GetEntries()[j];
388 if (j == elst->GetEntries().ItemCount() - 1 &&
389 new_elst_entry.m_SegmentDuration == track->GetDuration() &&
390 !Options.no_zero_elst) {
391 // if this is the last entry, make the segment duration 0 (i.e last until the end)
392 // in order to be compliant with the CMAF specification
393 new_elst_entry.m_SegmentDuration = 0;
394 } else {
395 new_elst_entry.m_SegmentDuration = AP4_ConvertTime(new_elst_entry.m_SegmentDuration,
396 input_movie->GetTimeScale(),
397 AP4_FRAGMENTER_OUTPUT_MOVIE_TIMESCALE);
398 }
399 if (new_elst_entry.m_MediaTime > 0 && timescale) {
400 new_elst_entry.m_MediaTime = (AP4_SI64)AP4_ConvertTime(new_elst_entry.m_MediaTime,
401 track->GetMediaTimeScale(),
402 timescale?timescale:track->GetMediaTimeScale());
403
404 }
405 new_elst->AddEntry(new_elst_entry);
406 }
407
408 // add the 'elst' to the 'edts' container
409 new_edts->AddChild(new_elst);
410 }
411
412 // add the edit list to the output track (just after the 'tkhd' atom)
413 output_track->UseTrakAtom()->AddChild(new_edts, 1);
414 }
415 }
416 }
417
418 // add the track to the output
419 output_movie->AddTrack(output_track);
420
421 // add a trex entry to the mvex container
422 AP4_TrexAtom* trex = new AP4_TrexAtom(track->GetId(),
423 1,
424 0,
425 0,
426 0);
427 mvex->AddChild(trex);
428 }
429
430 // select the anchor cursor
431 TrackCursor* anchor_cursor = NULL;
432 if (cursors.ItemCount() == 1) {
433 // only one track, that's our anchor
434 anchor_cursor = cursors[0];
435 }
436 if (anchor_cursor == NULL) {
437 for (unsigned int i=0; i<cursors.ItemCount(); i++) {
438 // use this as the anchor track if it is the first video track
439 if (cursors[i]->m_Track->GetType() == AP4_Track::TYPE_VIDEO) {
440 anchor_cursor = cursors[i];
441 break;
442 }
443 }
444 }
445 if (anchor_cursor == NULL) {
446 // no video track to anchor with, pick the first audio track
447 for (unsigned int i=0; i<cursors.ItemCount(); i++) {
448 if (cursors[i]->m_Track->GetType() == AP4_Track::TYPE_AUDIO) {
449 anchor_cursor = cursors[i];
450 break;
451 }
452 }
453 // no audio track to anchor with, pick the first subtitles track
454 for (unsigned int i=0; i<cursors.ItemCount(); i++) {
455 if (cursors[i]->m_Track->GetType() == AP4_Track::TYPE_SUBTITLES) {
456 anchor_cursor = cursors[i];
457 break;
458 }
459 }
460 }
461 if (anchor_cursor == NULL) {
462 // this should never happen
463 fprintf(stderr, "ERROR: no anchor track\n");
464 return;
465 }
466 if (Options.debug) {
467 printf("Using track ID %d as anchor\n", anchor_cursor->m_Track->GetId());
468 }
469
470 // decide which tracks to index and in which order
471 TrackCursor* indexed_cursor = anchor_cursor;
472
473 // update the mehd duration
474 mehd->SetDuration(output_movie->GetDuration());
475
476 // add the mvex container to the moov container
477 output_movie->GetMoovAtom()->AddChild(mvex);
478
479 // copy the moov/udta atom to the moov container
480 if (copy_udta) {
481 AP4_Atom* udta = input_movie->GetMoovAtom()->GetChild(AP4_ATOM_TYPE_UDTA);
482 if (udta != NULL) {
483 output_movie->GetMoovAtom()->AddChild(udta->Clone());
484 }
485 }
486
487 // compute all the fragments
488 unsigned int sequence_number = Options.sequence_number_start;
489 for(;;) {
490 TrackCursor* cursor = NULL;
491
492 // pick the first track with a fragment index lower than the anchor's
493 for (unsigned int i=0; i<cursors.ItemCount(); i++) {
494 if (cursors[i]->m_Eos) continue;
495 if (cursors[i]->m_FragmentIndex < anchor_cursor->m_FragmentIndex) {
496 cursor = cursors[i];
497 break;
498 }
499 }
500
501 // check if we found a non-anchor cursor to use
502 if (cursor == NULL) {
503 // the anchor should be used in this round, check if we can use it
504 if (anchor_cursor->m_Eos) {
505 // the anchor is done, pick a new anchor unless we need to trim
506 anchor_cursor = NULL;
507 if (!Options.trim) {
508 for (unsigned int i=0; i<cursors.ItemCount(); i++) {
509 if (cursors[i]->m_Eos) continue;
510 if (anchor_cursor == NULL ||
511 cursors[i]->m_Track->GetType() == AP4_Track::TYPE_VIDEO ||
512 cursors[i]->m_Track->GetType() == AP4_Track::TYPE_AUDIO) {
513 anchor_cursor = cursors[i];
514 if (Options.debug) {
515 printf("+++ New anchor: Track ID %d\n", anchor_cursor->m_Track->GetId());
516 }
517 }
518 }
519 }
520 }
521 cursor = anchor_cursor;
522 }
523 if (cursor == NULL) break; // all done
524
525 // decide how many samples go into this fragment
526 AP4_UI64 target_dts;
527 if (cursor == anchor_cursor) {
528 // compute the current dts in milliseconds
529 AP4_UI64 anchor_dts_ms = AP4_ConvertTime(cursor->m_Sample.GetDts(),
530 cursor->m_Track->GetMediaTimeScale(),
531 1000);
532 // round to the nearest multiple of fragment_duration
533 AP4_UI64 anchor_position = (anchor_dts_ms + (fragment_duration/2))/fragment_duration;
534
535 // pick the next fragment_duration multiple at our target
536 target_dts = AP4_ConvertTime(fragment_duration*(anchor_position+1),
537 1000,
538 cursor->m_Track->GetMediaTimeScale());
539 } else {
540 target_dts = AP4_ConvertTime(anchor_cursor->m_Sample.GetDts(),
541 anchor_cursor->m_Track->GetMediaTimeScale(),
542 cursor->m_Track->GetMediaTimeScale());
543 if (target_dts <= cursor->m_Sample.GetDts()) {
544 // we must be at the end, past the last anchor sample, just use the target duration
545 target_dts = AP4_ConvertTime((AP4_UI64)fragment_duration*(cursor->m_FragmentIndex+1),
546 1000,
547 cursor->m_Track->GetMediaTimeScale());
548
549 if (target_dts <= cursor->m_Sample.GetDts()) {
550 // we're still behind, there may have been an alignment/rounding error, just advance by one segment duration
551 target_dts = cursor->m_Sample.GetDts()+AP4_ConvertTime(fragment_duration,
552 1000,
553 cursor->m_Track->GetMediaTimeScale());
554 }
555 }
556 }
557
558 unsigned int end_sample_index = cursor->m_Samples->GetSampleCount();
559 AP4_UI64 smallest_diff = (AP4_UI64)(0xFFFFFFFFFFFFFFFFULL);
560 AP4_Sample sample;
561 for (unsigned int i=cursor->m_SampleIndex+1; i<=cursor->m_Samples->GetSampleCount(); i++) {
562 AP4_UI64 dts;
563 if (i < cursor->m_Samples->GetSampleCount()) {
564 result = cursor->m_Samples->GetSample(i, sample);
565 if (AP4_FAILED(result)) {
566 fprintf(stderr, "ERROR: failed to get sample %d (%d)\n", i, result);
567 return;
568 }
569 if (!sample.IsSync()) continue; // only look for sync samples
570 dts = sample.GetDts();
571 } else {
572 result = cursor->m_Samples->GetSample(i-1, sample);
573 if (AP4_FAILED(result)) {
574 fprintf(stderr, "ERROR: failed to get sample %d (%d)\n", i-1, result);
575 return;
576 }
577 dts = sample.GetDts()+sample.GetDuration();
578 }
579 AP4_SI64 diff = dts-target_dts;
580 AP4_UI64 abs_diff = diff<0?-diff:diff;
581 if (abs_diff < smallest_diff) {
582 // this sample is the closest to the target so far
583 end_sample_index = i;
584 smallest_diff = abs_diff;
585 }
586 if (diff >= 0) {
587 // this sample is past the target, it is not going to get any better, stop looking
588 break;
589 }
590 }
591 if (cursor->m_Eos) continue;
592
593 if (Options.debug) {
594 if (cursor == anchor_cursor) {
595 printf("====");
596 } else {
597 printf("----");
598 }
599 printf(" Track ID %d - dts=%lld, target=%lld, start=%d, end=%d/%d\n",
600 cursor->m_Track->GetId(),
601 cursor->m_Sample.GetDts(),
602 target_dts,
603 cursor->m_SampleIndex,
604 end_sample_index,
605 cursor->m_Track->GetSampleCount());
606 }
607
608 // emit a fragment for the selected track
609 if (Options.verbosity > 1) {
610 printf("fragment: track ID %d\n", cursor->m_Track->GetId());
611 }
612
613 // decide which sample description index to use
614 // (this is not very sophisticated, we only look at the sample description
615 // index of the first sample in the group, which may not be correct. This
616 // should be fixed later)
617 unsigned int sample_desc_index = cursor->m_Sample.GetDescriptionIndex();
618
619 // set initial flag values
620 AP4_UI32 tfhd_flags = AP4_TFHD_FLAG_DEFAULT_BASE_IS_MOOF | AP4_TFHD_FLAG_SAMPLE_DESCRIPTION_INDEX_PRESENT;
621 AP4_UI32 trun_flags = AP4_TRUN_FLAG_DATA_OFFSET_PRESENT |
622 AP4_TRUN_FLAG_SAMPLE_SIZE_PRESENT;
623 AP4_UI32 sync_sample_flags = 0;
624 AP4_UI32 non_sync_sample_flags = 0x10000; // 0x10000 -> sample_is_non_sync
625 if (cursor->m_Track->GetType() == AP4_Track::TYPE_VIDEO ||
626 (cursor->m_Track->GetSampleDescriptionCount() > 0 &&
627 cursor->m_Track->GetSampleDescription(0)->GetFormat() == AP4_SAMPLE_FORMAT_AC_4)) {
628 non_sync_sample_flags |= 0x1000000; // sample_depends_on=1 (not I frame)
629 sync_sample_flags |= 0x2000000; // sample_depends_on=2 (I frame)
630 }
631
632 // setup the moof structure
633 AP4_ContainerAtom* moof = new AP4_ContainerAtom(AP4_ATOM_TYPE_MOOF);
634 AP4_MfhdAtom* mfhd = new AP4_MfhdAtom(sequence_number++);
635 moof->AddChild(mfhd);
636 AP4_ContainerAtom* traf = new AP4_ContainerAtom(AP4_ATOM_TYPE_TRAF);
637 AP4_TfhdAtom* tfhd = new AP4_TfhdAtom(tfhd_flags,
638 cursor->m_Track->GetId(),
639 0,
640 sample_desc_index+1,
641 0,
642 0,
643 0);
644 traf->AddChild(tfhd);
645 if (!Options.no_tfdt) {
646 AP4_TfdtAtom* tfdt = new AP4_TfdtAtom(1, cursor->m_Timestamp + (AP4_UI64)(Options.tfdt_start * (double)cursor->m_Track->GetMediaTimeScale()));
647 traf->AddChild(tfdt);
648 }
649
650 // create the `trun` and `traf` atoms
651 AP4_TrunAtom* trun = new AP4_TrunAtom(trun_flags, 0, 0);
652 unsigned int initial_offset = 0;
653 if (trun_version_one) {
654 trun->SetVersion(1);
655 initial_offset = cursor->m_Sample.GetCtsDelta();
656 }
657 traf->AddChild(trun);
658 moof->AddChild(traf);
659
660 // create a new FragmentInfo object to store the fragment details
661 FragmentInfo* fragment = new FragmentInfo(cursor->m_Samples, cursor->m_Tfra, cursor->m_Timestamp, moof);
662 fragments.Add(fragment);
663
664 // add samples to the fragment
665 unsigned int sample_count = 0;
666 AP4_Array<AP4_TrunAtom::Entry> trun_entries;
667 fragment->m_MdatSize = AP4_ATOM_HEADER_SIZE;
668 AP4_UI32 constant_sample_duration = 0;
669 bool all_sample_durations_equal = true;
670 bool all_samples_are_sync = true;
671 bool only_first_sample_is_sync = true;
672 for (;;) {
673 // if we have one non-zero CTS delta, we'll need to express it
674 if (cursor->m_Sample.GetCtsDelta()) {
675 trun_flags |= AP4_TRUN_FLAG_SAMPLE_COMPOSITION_TIME_OFFSET_PRESENT;
676 }
677
678 // add one sample
679 trun_entries.SetItemCount(sample_count+1);
680 AP4_TrunAtom::Entry& trun_entry = trun_entries[sample_count];
681 AP4_UI64 next_unscaled_timestamp = cursor->m_UnscaledTimestamp+cursor->m_Sample.GetDuration();
682 AP4_UI64 next_scaled_timestamp = timescale?
683 AP4_ConvertTime(next_unscaled_timestamp,
684 cursor->m_Track->GetMediaTimeScale(),
685 timescale):
686 next_unscaled_timestamp;
687 trun_entry.sample_duration = (AP4_UI32)(next_scaled_timestamp-cursor->m_Timestamp);
688 trun_entry.sample_size = cursor->m_Sample.GetSize();
689 trun_entry.sample_flags = cursor->m_Sample.IsSync() ? sync_sample_flags : non_sync_sample_flags;
690 trun_entry.sample_composition_time_offset = timescale?
691 (AP4_UI32)AP4_ConvertTime(cursor->m_Sample.GetCtsDelta(),
692 cursor->m_Track->GetMediaTimeScale(),
693 timescale):
694 cursor->m_Sample.GetCtsDelta();
695
696 if (trun->GetVersion() == 1) {
697 trun_entry.sample_composition_time_offset -= initial_offset;
698 }
699 fragment->m_SampleIndexes.SetItemCount(sample_count+1);
700 fragment->m_SampleIndexes[sample_count] = cursor->m_SampleIndex;
701 fragment->m_MdatSize += trun_entry.sample_size;
702 fragment->m_Duration += trun_entry.sample_duration;
703
704 // check if the durations are all the same
705 if (all_sample_durations_equal) {
706 if (constant_sample_duration == 0) {
707 constant_sample_duration = trun_entry.sample_duration;
708 } else {
709 if (constant_sample_duration != trun_entry.sample_duration) {
710 all_sample_durations_equal = false;
711 }
712 }
713 }
714
715 // update flag metadata
716 if (cursor->m_Sample.IsSync()) {
717 if (sample_count) {
718 only_first_sample_is_sync = false;
719 }
720 } else {
721 all_samples_are_sync = false;
722 }
723
724 // next sample
725 cursor->m_UnscaledTimestamp = next_unscaled_timestamp;
726 cursor->m_Timestamp = next_scaled_timestamp;
727 result = cursor->SetSampleIndex(cursor->m_SampleIndex+1);
728 if (AP4_FAILED(result)) {
729 fprintf(stderr, "ERROR: failed to get sample %d (%d)\n", cursor->m_SampleIndex+1, result);
730 return;
731 }
732 sample_count++;
733 if (cursor->m_Eos) {
734 if (Options.debug) {
735 printf("[Track ID %d has reached the end]\n", cursor->m_Track->GetId());
736 }
737 break;
738 }
739 if (cursor->m_SampleIndex >= end_sample_index) {
740 break; // done with this fragment
741 }
742 }
743 if (Options.verbosity > 2) {
744 printf(" %d samples\n", sample_count);
745 printf(" constant sample duration: %s\n", all_sample_durations_equal?"yes":"no");
746 }
747
748 // update the flags
749 if (only_first_sample_is_sync) {
750 trun_flags |= AP4_TRUN_FLAG_FIRST_SAMPLE_FLAGS_PRESENT;
751 trun->SetFirstSampleFlags(sync_sample_flags);
752 tfhd_flags |= AP4_TFHD_FLAG_DEFAULT_SAMPLE_FLAGS_PRESENT;
753 tfhd->SetDefaultSampleFlags(non_sync_sample_flags);
754 } else {
755 if (all_samples_are_sync) {
756 tfhd_flags |= AP4_TFHD_FLAG_DEFAULT_SAMPLE_FLAGS_PRESENT;
757 tfhd->SetDefaultSampleFlags(0);
758 } else {
759 trun_flags |= AP4_TRUN_FLAG_SAMPLE_FLAGS_PRESENT;
760 }
761 }
762
763 if (all_sample_durations_equal) {
764 tfhd_flags |= AP4_TFHD_FLAG_DEFAULT_SAMPLE_DURATION_PRESENT;
765 tfhd->SetDefaultSampleDuration(constant_sample_duration);
766 } else {
767 trun_flags |= AP4_TRUN_FLAG_SAMPLE_DURATION_PRESENT;
768 }
769
770 tfhd->UpdateFlags(tfhd_flags);
771 trun->UpdateFlags(trun_flags);
772
773 // update moof and children
774 trun->SetEntries(trun_entries);
775 trun->SetDataOffset((AP4_UI32)moof->GetSize()+AP4_ATOM_HEADER_SIZE);
776
777 // keep track of fragments that will be part of the index
778 if (cursor == anchor_cursor) {
779 // start a new segment
780 current_indexed_segment = new IndexedSegmentInfo();
781 indexed_segments.Add(current_indexed_segment);
782 current_indexed_segment->m_Duration = fragment->m_Duration;
783 }
784 if (current_indexed_segment) {
785 current_indexed_segment->m_Size += (AP4_UI32)(fragment->m_Moof->GetSize()+fragment->m_MdatSize);
786 }
787
788 // advance the cursor's fragment index
789 ++cursor->m_FragmentIndex;
790 }
791
792 // write the ftyp atom
793 AP4_FtypAtom* ftyp = input_file.GetFileType();
794 if (ftyp) {
795 // keep the existing brand and compatible brands
796 AP4_Array<AP4_UI32> compatible_brands;
797 compatible_brands.EnsureCapacity(ftyp->GetCompatibleBrands().ItemCount()+1);
798 for (unsigned int i=0; i<ftyp->GetCompatibleBrands().ItemCount(); i++) {
799 compatible_brands.Append(ftyp->GetCompatibleBrands()[i]);
800 }
801
802 // add the compatible brand if it is not already there
803 if (!ftyp->HasCompatibleBrand(AP4_FILE_BRAND_ISO5)) {
804 compatible_brands.Append(AP4_FILE_BRAND_ISO5);
805 }
806
807 // create a replacement
808 AP4_FtypAtom* new_ftyp = new AP4_FtypAtom(ftyp->GetMajorBrand(),
809 ftyp->GetMinorVersion(),
810 &compatible_brands[0],
811 compatible_brands.ItemCount());
812 ftyp = new_ftyp;
813 } else {
814 AP4_UI32 compat[2] = {
815 AP4_FILE_BRAND_ISOM,
816 AP4_FILE_BRAND_ISO5
817 };
818 ftyp = new AP4_FtypAtom(AP4_FTYP_BRAND_MP42, 0, &compat[0], 2);
819 }
820 ftyp->Write(output_stream);
821 delete ftyp;
822
823 // write the moov atom
824 output_movie->GetMoovAtom()->Write(output_stream);
825
826 // write the (not-yet fully computed) indexes if needed
827 AP4_SidxAtom* sidx = NULL;
828 AP4_Position sidx_position = 0;
829 output_stream.Tell(sidx_position);
830 if (create_segment_index) {
831 AP4_UI32 sidx_timescale = timescale ? timescale : indexed_cursor->m_Track->GetMediaTimeScale();
832 AP4_UI64 earliest_presentation_time = (AP4_UI64)(Options.tfdt_start * (double)sidx_timescale);
833 sidx = new AP4_SidxAtom(indexed_cursor->m_Track->GetId(),
834 sidx_timescale,
835 earliest_presentation_time,
836 0);
837 // reserve space for the entries now, but they will be computed and updated later
838 sidx->SetReferenceCount(indexed_segments.ItemCount());
839 sidx->Write(output_stream);
840 }
841
842 // write all fragments
843 for (AP4_List<FragmentInfo>::Item* item = fragments.FirstItem();
844 item;
845 item = item->GetNext()) {
846 FragmentInfo* fragment = item->GetData();
847
848 // remember the time and position of this fragment
849 output_stream.Tell(fragment->m_MoofPosition);
850 fragment->m_Tfra->AddEntry(fragment->m_Timestamp, fragment->m_MoofPosition);
851
852 // write the moof
853 fragment->m_Moof->Write(output_stream);
854
855 // write mdat
856 output_stream.WriteUI32(fragment->m_MdatSize);
857 output_stream.WriteUI32(AP4_ATOM_TYPE_MDAT);
858 AP4_DataBuffer sample_data;
859 AP4_Sample sample;
860 for (unsigned int i=0; i<fragment->m_SampleIndexes.ItemCount(); i++) {
861 // get the sample
862 result = fragment->m_Samples->GetSample(fragment->m_SampleIndexes[i], sample);
863 if (AP4_FAILED(result)) {
864 fprintf(stderr, "ERROR: failed to get sample %d (%d)\n", fragment->m_SampleIndexes[i], result);
865 return;
866 }
867
868 // read the sample data
869 result = sample.ReadData(sample_data);
870 if (AP4_FAILED(result)) {
871 fprintf(stderr, "ERROR: failed to read sample data for sample %d (%d)\n", fragment->m_SampleIndexes[i], result);
872 return;
873 }
874
875 // write the sample data
876 result = output_stream.Write(sample_data.GetData(), sample_data.GetDataSize());
877 if (AP4_FAILED(result)) {
878 fprintf(stderr, "ERROR: failed to write sample data (%d)\n", result);
879 return;
880 }
881 }
882 }
883
884 // update the index and re-write it if needed
885 if (create_segment_index) {
886 unsigned int segment_index = 0;
887 AP4_SidxAtom::Reference reference;
888 for (AP4_List<IndexedSegmentInfo>::Item* item = indexed_segments.FirstItem();
889 item;
890 item = item->GetNext()) {
891 IndexedSegmentInfo* segment = item->GetData();
892
893 // update the sidx entry
894 reference.m_ReferencedSize = segment->m_Size;
895 reference.m_SubsegmentDuration = segment->m_Duration;
896 reference.m_StartsWithSap = true;
897 reference.m_SapType = 1;
898 sidx->SetReference(segment_index++, reference);
899 }
900 AP4_Position here = 0;
901 output_stream.Tell(here);
902 output_stream.Seek(sidx_position);
903 sidx->Write(output_stream);
904 output_stream.Seek(here);
905 delete sidx;
906 }
907
908 // create an mfra container and write out the index
909 AP4_ContainerAtom mfra(AP4_ATOM_TYPE_MFRA);
910 for (unsigned int i=0; i<cursors.ItemCount(); i++) {
911 mfra.AddChild(cursors[i]->m_Tfra);
912 cursors[i]->m_Tfra = NULL;
913 }
914 AP4_MfroAtom* mfro = new AP4_MfroAtom((AP4_UI32)mfra.GetSize()+16);
915 mfra.AddChild(mfro);
916 result = mfra.Write(output_stream);
917 if (AP4_FAILED(result)) {
918 fprintf(stderr, "ERROR: failed to write 'mfra' (%d)\n", result);
919 return;
920 }
921
922 // cleanup
923 for (unsigned int i=0; i<cursors.ItemCount(); i++) {
924 delete cursors[i];
925 }
926 for (AP4_List<FragmentInfo>::Item* item = fragments.FirstItem();
927 item;
928 item = item->GetNext()) {
929 FragmentInfo* fragment = item->GetData();
930 delete fragment->m_Moof;
931 }
932 fragments.DeleteReferences();
933 indexed_segments.DeleteReferences();
934 delete output_movie;
935 }
936
937 /*----------------------------------------------------------------------
938 | AutoDetectFragmentDuration
939 +---------------------------------------------------------------------*/
940 static unsigned int
941 AutoDetectFragmentDuration(TrackCursor* cursor)
942 {
943 AP4_Sample sample;
944 unsigned int sample_count = cursor->m_Samples->GetSampleCount();
945
946 // get the first sample as the starting point
947 AP4_Result result = cursor->m_Samples->GetSample(0, sample);
948 if (AP4_FAILED(result)) {
949 fprintf(stderr, "ERROR: failed to read first sample\n");
950 return 0;
951 }
952 if (!sample.IsSync()) {
953 fprintf(stderr, "ERROR: first sample is not an I frame\n");
954 return 0;
955 }
956
957 for (unsigned int interval = 1; interval < sample_count; interval++) {
958 bool irregular = false;
959 unsigned int sync_count = 0;
960 unsigned int i;
961 for (i = 0; i < sample_count; i += interval) {
962 result = cursor->m_Samples->GetSample(i, sample);
963 if (AP4_FAILED(result)) {
964 fprintf(stderr, "ERROR: failed to read sample %d\n", i);
965 return 0;
966 }
967 if (!sample.IsSync()) {
968 irregular = true;
969 break;
970 }
971 ++sync_count;
972 }
973 if (sync_count < 1) continue;
974 if (!irregular) {
975 // found a pattern
976 AP4_UI64 duration = sample.GetDts();
977 double fps = (double)(interval*(sync_count-1))/((double)duration/(double)cursor->m_Track->GetMediaTimeScale());
978 if (Options.verbosity > 0) {
979 printf("found regular I-frame interval: %d frames (at %.3f frames per second)\n",
980 interval, (float)fps);
981 }
982 return (unsigned int)(1000.0*(double)interval/fps);
983 }
984 }
985
986 return 0;
987 }
988
989 /*----------------------------------------------------------------------
990 | AutoDetectAudioFragmentDuration
991 +---------------------------------------------------------------------*/
992 static unsigned int
993 AutoDetectAudioFragmentDuration(AP4_ByteStream& stream, TrackCursor* cursor)
994 {
995 // remember where we are in the stream
996 AP4_Position where = 0;
997 stream.Tell(where);
998 AP4_LargeSize stream_size = 0;
999 stream.GetSize(stream_size);
1000 AP4_LargeSize bytes_available = stream_size-where;
1001
1002 AP4_UI64 fragment_count = 0;
1003 AP4_UI32 last_fragment_size = 0;
1004 AP4_Atom* atom = NULL;
1005 AP4_DefaultAtomFactory atom_factory;
1006 while (AP4_SUCCEEDED(atom_factory.CreateAtomFromStream(stream, bytes_available, atom))) {
1007 if (atom && atom->GetType() == AP4_ATOM_TYPE_MOOF) {
1008 AP4_ContainerAtom* moof = AP4_DYNAMIC_CAST(AP4_ContainerAtom, atom);
1009 AP4_TfhdAtom* tfhd = AP4_DYNAMIC_CAST(AP4_TfhdAtom, moof->FindChild("traf/tfhd"));
1010 if (tfhd && tfhd->GetTrackId() == cursor->m_Track->GetId()) {
1011 ++fragment_count;
1012 AP4_TrunAtom* trun = AP4_DYNAMIC_CAST(AP4_TrunAtom, moof->FindChild("traf/trun"));
1013 if (trun) {
1014 last_fragment_size = trun->GetEntries().ItemCount();
1015 }
1016 }
1017 }
1018 delete atom;
1019 atom = NULL;
1020 }
1021
1022 // restore the stream to its original position
1023 stream.Seek(where);
1024
1025 // decide if we can infer an fragment size
1026 if (fragment_count == 0 || cursor->m_Samples->GetSampleCount() == 0) {
1027 return 0;
1028 }
1029 // don't count the last fragment if we have more than one
1030 if (fragment_count > 1 && last_fragment_size) {
1031 --fragment_count;
1032 }
1033 if (fragment_count <= 1 || cursor->m_Samples->GetSampleCount() < last_fragment_size) {
1034 last_fragment_size = 0;
1035 }
1036 AP4_Sample sample;
1037 AP4_UI64 total_duration = 0;
1038 for (unsigned int i=0; i<cursor->m_Samples->GetSampleCount()-last_fragment_size; i++) {
1039 cursor->m_Samples->GetSample(i, sample);
1040 total_duration += sample.GetDuration();
1041 }
1042 return (unsigned int)AP4_ConvertTime(total_duration/fragment_count, cursor->m_Track->GetMediaTimeScale(), 1000);
1043 }
1044
1045 /*----------------------------------------------------------------------
1046 | ReadGolomb
1047 +---------------------------------------------------------------------*/
1048 static unsigned int
1049 ReadGolomb(AP4_BitStream& bits)
1050 {
1051 unsigned int leading_zeros = 0;
1052 while (bits.ReadBit() == 0) {
1053 leading_zeros++;
1054 }
1055 if (leading_zeros) {
1056 return (1<<leading_zeros)-1+bits.ReadBits(leading_zeros);
1057 } else {
1058 return 0;
1059 }
1060 }
1061
1062 /*----------------------------------------------------------------------
1063 | IsIFrame
1064 +---------------------------------------------------------------------*/
1065 static bool
1066 IsIFrame(AP4_Sample& sample, AP4_AvcSampleDescription* avc_desc) {
1067 AP4_DataBuffer sample_data;
1068 if (AP4_FAILED(sample.ReadData(sample_data))) {
1069 return false;
1070 }
1071
1072 const unsigned char* data = sample_data.GetData();
1073 AP4_Size size = sample_data.GetDataSize();
1074
1075 while (size >= avc_desc->GetNaluLengthSize()) {
1076 unsigned int nalu_length = 0;
1077 if (avc_desc->GetNaluLengthSize() == 1) {
1078 nalu_length = *data++;
1079 --size;
1080 } else if (avc_desc->GetNaluLengthSize() == 2) {
1081 nalu_length = AP4_BytesToUInt16BE(data);
1082 data += 2;
1083 size -= 2;
1084 } else if (avc_desc->GetNaluLengthSize() == 4) {
1085 nalu_length = AP4_BytesToUInt32BE(data);
1086 data += 4;
1087 size -= 4;
1088 } else {
1089 return false;
1090 }
1091 if (nalu_length <= size) {
1092 size -= nalu_length;
1093 } else {
1094 size = 0;
1095 }
1096
1097 switch (*data & 0x1F) {
1098 case 1: {
1099 AP4_BitStream bits;
1100 bits.WriteBytes(data+1, 8);
1101 ReadGolomb(bits);
1102 unsigned int slice_type = ReadGolomb(bits);
1103 if (slice_type == 2 || slice_type == 7) {
1104 return true;
1105 } else {
1106 return false; // only show first slice type
1107 }
1108 }
1109
1110 case 5:
1111 return true;
1112 }
1113
1114 data += nalu_length;
1115 }
1116
1117 return false;
1118 }
1119
1120 /*----------------------------------------------------------------------
1121 | main
1122 +---------------------------------------------------------------------*/
1123 int
1124 main(int argc, char** argv)
1125 {
1126 if (argc < 2) {
1127 PrintUsageAndExit();
1128 }
1129
1130 // init the variables
1131 const char* input_filename = NULL;
1132 const char* output_filename = NULL;
1133 const char* track_selector = NULL;
1134 unsigned int fragment_duration = 0;
1135 bool auto_detect_fragment_duration = true;
1136 bool create_segment_index = false;
1137 bool quiet = false;
1138 bool copy_udta = false;
1139 bool trun_version_one = true;
1140 AP4_UI32 timescale = 0;
1141 AP4_Result result;
1142
1143 Options.verbosity = 1;
1144 Options.debug = false;
1145 Options.trim = false;
1146 Options.no_tfdt = false;
1147 Options.tfdt_start = 0.0;
1148 Options.sequence_number_start = 1;
1149 Options.force_i_frame_sync = AP4_FRAGMENTER_FORCE_SYNC_MODE_NONE;
1150
1151 // parse the command line
1152 argv++;
1153 char* arg;
1154 while ((arg = *argv++)) {
1155 if (!strcmp(arg, "--verbosity")) {
1156 arg = *argv++;
1157 if (arg == NULL) {
1158 fprintf(stderr, "ERROR: missing argument after --verbosity option\n");
1159 return 1;
1160 }
1161 Options.verbosity = (unsigned int)strtoul(arg, NULL, 10);
1162 } else if (!strcmp(arg, "--debug")) {
1163 Options.debug = true;
1164 } else if (!strcmp(arg, "--index")) {
1165 create_segment_index = true;
1166 } else if (!strcmp(arg, "--quiet")) {
1167 quiet = true;
1168 } else if (!strcmp(arg, "--trim")) {
1169 Options.trim = true;
1170 } else if (!strcmp(arg, "--no-tfdt")) {
1171 Options.no_tfdt = true;
1172 } else if (!strcmp(arg, "--tfdt-start")) {
1173 arg = *argv++;
1174 if (arg == NULL) {
1175 fprintf(stderr, "ERROR: missing argument after --tfdt-start option\n");
1176 return 1;
1177 }
1178 Options.tfdt_start = strtod(arg, NULL);
1179 } else if (!strcmp(arg, "--sequence-number-start")) {
1180 arg = *argv++;
1181 if (arg == NULL) {
1182 fprintf(stderr, "ERROR: missing argument after --sequence-number-start option\n");
1183 return 1;
1184 }
1185 Options.sequence_number_start = (unsigned int)strtoul(arg, NULL, 10);
1186 } else if (!strcmp(arg, "--force-i-frame-sync")) {
1187 arg = *argv++;
1188 if (arg == NULL) {
1189 fprintf(stderr, "ERROR: missing argument after --fragment-duration option\n");
1190 return 1;
1191 }
1192 if (!strcmp(arg, "all")) {
1193 Options.force_i_frame_sync = AP4_FRAGMENTER_FORCE_SYNC_MODE_ALL;
1194 } else if (!strcmp(arg, "auto")) {
1195 Options.force_i_frame_sync = AP4_FRAGMENTER_FORCE_SYNC_MODE_AUTO;
1196 } else {
1197 fprintf(stderr, "ERROR: unknown mode for --force-i-frame-sync\n");
1198 return 1;
1199 }
1200 } else if (!strcmp(arg, "--fragment-duration")) {
1201 arg = *argv++;
1202 if (arg == NULL) {
1203 fprintf(stderr, "ERROR: missing argument after --fragment-duration option\n");
1204 return 1;
1205 }
1206 fragment_duration = (unsigned int)strtoul(arg, NULL, 10);
1207 auto_detect_fragment_duration = false;
1208 } else if (!strcmp(arg, "--timescale")) {
1209 arg = *argv++;
1210 if (arg == NULL) {
1211 fprintf(stderr, "ERROR: missing argument after --timescale option\n");
1212 return 1;
1213 }
1214 timescale = (unsigned int)strtoul(arg, NULL, 10);
1215 } else if (!strcmp(arg, "--track")) {
1216 track_selector = *argv++;
1217 if (track_selector == NULL) {
1218 fprintf(stderr, "ERROR: missing argument after --track option\n");
1219 return 1;
1220 }
1221 } else if (!strcmp(arg, "--trun-version-zero")) {
1222 trun_version_one = false;
1223 } else if (!strcmp(arg, "--copy-udta")) {
1224 copy_udta = true;
1225 } else if (!strcmp(arg, "--no-zero-elst")) {
1226 Options.no_zero_elst = true;
1227 } else {
1228 if (input_filename == NULL) {
1229 input_filename = arg;
1230 } else if (output_filename == NULL) {
1231 output_filename = arg;
1232 } else {
1233 fprintf(stderr, "ERROR: unexpected argument '%s'\n", arg);
1234 return 1;
1235 }
1236 }
1237 }
1238 if (Options.debug && Options.verbosity == 0) {
1239 Options.verbosity = 1;
1240 }
1241
1242 if (input_filename == NULL) {
1243 fprintf(stderr, "ERROR: no input specified\n");
1244 return 1;
1245 }
1246 AP4_ByteStream* input_stream = NULL;
1247 result = AP4_FileByteStream::Create(input_filename,
1248 AP4_FileByteStream::STREAM_MODE_READ,
1249 input_stream);
1250 if (AP4_FAILED(result)) {
1251 fprintf(stderr, "ERROR: cannot open input (%d)\n", result);
1252 return 1;
1253 }
1254 if (output_filename == NULL) {
1255 fprintf(stderr, "ERROR: no output specified\n");
1256 return 1;
1257 }
1258 AP4_ByteStream* output_stream = NULL;
1259 result = AP4_FileByteStream::Create(output_filename,
1260 AP4_FileByteStream::STREAM_MODE_WRITE,
1261 output_stream);
1262 if (AP4_FAILED(result)) {
1263 fprintf(stderr, "ERROR: cannot create/open output (%d)\n", result);
1264 return 1;
1265 }
1266
1267 // parse the input MP4 file (moov only)
1268 AP4_File input_file(*input_stream, true);
1269
1270 // check the file for basic properties
1271 if (input_file.GetMovie() == NULL) {
1272 fprintf(stderr, "ERROR: no movie found in the file\n");
1273 return 1;
1274 }
1275 if (!quiet && input_file.GetMovie()->HasFragments()) {
1276 fprintf(stderr, "NOTICE: file is already fragmented, it will be re-fragmented\n");
1277 }
1278
1279 // create a cusor list to keep track of the tracks we will read from
1280 AP4_Array<TrackCursor*> cursors;
1281
1282 // iterate over all tracks
1283 TrackCursor* video_track = NULL;
1284 TrackCursor* audio_track = NULL;
1285 TrackCursor* subtitles_track = NULL;
1286 TrackCursor* selected_track = NULL;
1287 unsigned int video_track_count = 0;
1288 unsigned int audio_track_count = 0;
1289 unsigned int subtitles_track_count = 0;
1290 for (AP4_List<AP4_Track>::Item* track_item = input_file.GetMovie()->GetTracks().FirstItem();
1291 track_item;
1292 track_item = track_item->GetNext()) {
1293 AP4_Track* track = track_item->GetData();
1294
1295 // sanity check
1296 if (track->GetSampleCount() == 0 && !input_file.GetMovie()->HasFragments()) {
1297 fprintf(stderr, "WARNING: track %d has no samples, it will be skipped\n", track->GetId());
1298 continue;
1299 }
1300
1301 // create a sample array for this track
1302 SampleArray* sample_array;
1303 if (input_file.GetMovie()->HasFragments()) {
1304 sample_array = new CachedSampleArray(track);
1305 } else {
1306 sample_array = new SampleArray(track);
1307 }
1308
1309 // create a cursor for the track
1310 TrackCursor* cursor = new TrackCursor(track, sample_array);
1311 cursor->m_Tfra->SetTrackId(track->GetId());
1312 cursors.Append(cursor);
1313
1314 if (track->GetType() == AP4_Track::TYPE_VIDEO) {
1315 if (video_track) {
1316 fprintf(stderr, "WARNING: more than one video track found\n");
1317 } else {
1318 video_track = cursor;
1319 }
1320 video_track_count++;
1321 } else if (track->GetType() == AP4_Track::TYPE_AUDIO) {
1322 if (audio_track == NULL) {
1323 audio_track = cursor;
1324 }
1325 audio_track_count++;
1326 } else if (track->GetType() == AP4_Track::TYPE_SUBTITLES) {
1327 if (subtitles_track == NULL) {
1328 subtitles_track = cursor;
1329 }
1330 subtitles_track_count++;
1331 }
1332 }
1333
1334 if (cursors.ItemCount() == 0) {
1335 fprintf(stderr, "ERROR: no valid track found\n");
1336 return 1;
1337 }
1338
1339 if (track_selector) {
1340 if (!strncmp("audio", track_selector, 5)) {
1341 if (audio_track) {
1342 selected_track = audio_track;
1343 } else {
1344 fprintf(stderr, "ERROR: no audio track found\n");
1345 return 1;
1346 }
1347 } else if (!strncmp("video", track_selector, 5)) {
1348 if (video_track) {
1349 selected_track = video_track;
1350 } else {
1351 fprintf(stderr, "ERROR: no video track found\n");
1352 return 1;
1353 }
1354 } else if (!strncmp("subtitles", track_selector, 9)) {
1355 if (subtitles_track) {
1356 selected_track = subtitles_track;
1357 } else {
1358 fprintf(stderr, "ERROR: no subtitles track found\n");
1359 return 1;
1360 }
1361 } else {
1362 AP4_UI32 selected_track_id = (AP4_UI32)strtol(track_selector, NULL, 10);
1363 for (unsigned int i=0; i<cursors.ItemCount(); i++) {
1364 if (cursors[i]->m_Track->GetId() == selected_track_id) {
1365 selected_track = cursors[i];
1366 break;
1367 }
1368 }
1369 if (!selected_track) {
1370 fprintf(stderr, "ERROR: track not found\n");
1371 return 1;
1372 }
1373 }
1374 }
1375
1376 if (video_track_count == 0 && audio_track_count == 0 && subtitles_track_count == 0) {
1377 fprintf(stderr, "ERROR: no audio, video, or subtitles track in the file\n");
1378 return 1;
1379 }
1380 AP4_AvcSampleDescription* avc_desc = NULL;
1381 if (video_track && (Options.force_i_frame_sync != AP4_FRAGMENTER_FORCE_SYNC_MODE_NONE)) {
1382 // that feature is only supported for AVC
1383 AP4_SampleDescription* sdesc = video_track->m_Track->GetSampleDescription(0);
1384 if (sdesc) {
1385 avc_desc = AP4_DYNAMIC_CAST(AP4_AvcSampleDescription, sdesc);
1386 }
1387 if (avc_desc == NULL) {
1388 fprintf(stderr, "--force-i-frame-sync can only be used with AVC/H.264 video\n");
1389 return 1;
1390 }
1391 }
1392
1393 // remember where the stream was
1394 AP4_Position position;
1395 input_stream->Tell(position);
1396
1397 // for fragmented input files, we need to populate the sample arrays
1398 if (input_file.GetMovie()->HasFragments()) {
1399 AP4_LinearReader reader(*input_file.GetMovie(), input_stream);
1400 for (unsigned int i=0; i<cursors.ItemCount(); i++) {
1401 reader.EnableTrack(cursors[i]->m_Track->GetId());
1402 }
1403 AP4_UI32 track_id;
1404 AP4_Sample sample;
1405 do {
1406 result = reader.GetNextSample(sample, track_id);
1407 if (AP4_SUCCEEDED(result)) {
1408 for (unsigned int i=0; i<cursors.ItemCount(); i++) {
1409 if (cursors[i]->m_Track->GetId() == track_id) {
1410 cursors[i]->m_Samples->AddSample(sample);
1411 break;
1412 }
1413 }
1414 }
1415 } while (AP4_SUCCEEDED(result));
1416
1417 } else if (video_track && (Options.force_i_frame_sync != AP4_FRAGMENTER_FORCE_SYNC_MODE_NONE)) {
1418 AP4_Sample sample;
1419 if (Options.force_i_frame_sync == AP4_FRAGMENTER_FORCE_SYNC_MODE_AUTO) {
1420 // detect if this looks like an open-gop source
1421 for (unsigned int i=1; i<video_track->m_Samples->GetSampleCount(); i++) {
1422 if (AP4_SUCCEEDED(video_track->m_Samples->GetSample(i, sample))) {
1423 if (sample.IsSync()) {
1424 // we found a sync i-frame, assume this is *not* an open-gop source
1425 Options.force_i_frame_sync = AP4_FRAGMENTER_FORCE_SYNC_MODE_NONE;
1426 if (Options.debug) {
1427 printf("this does not look like an open-gop source, not forcing i-frame sync flags\n");
1428 }
1429 break;
1430 }
1431 }
1432 }
1433 }
1434 if (Options.force_i_frame_sync != AP4_FRAGMENTER_FORCE_SYNC_MODE_NONE) {
1435 for (unsigned int i=0; i<video_track->m_Samples->GetSampleCount(); i++) {
1436 if (AP4_SUCCEEDED(video_track->m_Samples->GetSample(i, sample))) {
1437 if (IsIFrame(sample, avc_desc)) {
1438 video_track->m_Samples->ForceSync(i);
1439 }
1440 }
1441 }
1442 }
1443 }
1444
1445 // return the stream to its original position
1446 input_stream->Seek(position);
1447
1448 // auto-detect the fragment duration if needed
1449 if (auto_detect_fragment_duration) {
1450 if (video_track) {
1451 fragment_duration = AutoDetectFragmentDuration(video_track);
1452 } else if (audio_track && input_file.GetMovie()->HasFragments()) {
1453 fragment_duration = AutoDetectAudioFragmentDuration(*input_stream, audio_track);
1454 }
1455 if (fragment_duration == 0) {
1456 if (Options.verbosity > 0) {
1457 fprintf(stderr, "unable to autodetect fragment duration, using default\n");
1458 }
1459 fragment_duration = AP4_FRAGMENTER_DEFAULT_FRAGMENT_DURATION;
1460 } else if (fragment_duration > AP4_FRAGMENTER_MAX_AUTO_FRAGMENT_DURATION) {
1461 if (Options.verbosity > 0) {
1462 fprintf(stderr, "auto-detected fragment duration too large, using default\n");
1463 }
1464 fragment_duration = AP4_FRAGMENTER_DEFAULT_FRAGMENT_DURATION;
1465 }
1466 }
1467
1468 // fragment the file
1469 AP4_Array<TrackCursor*> tracks_to_fragment;
1470 if (selected_track) {
1471 tracks_to_fragment.Append(selected_track);
1472 } else {
1473 tracks_to_fragment = cursors;
1474 }
1475 Fragment(input_file, *output_stream, tracks_to_fragment, fragment_duration, timescale, create_segment_index, copy_udta, trun_version_one);
1476
1477 // cleanup and exit
1478 if (input_stream) input_stream->Release();
1479 if (output_stream) output_stream->Release();
1480
1481 return 0;
1482 }