Debian Codegraph @

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

raw symbols SCIP
1 /*****************************************************************
2 |
3 | AP4 - Elementary Stream Muliplexer
4 |
5 | Copyright 2002-2020 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 <string.h>
35 #include <ctype.h>
36 #include <time.h>
37
38 #include "Ap4.h"
39
40 /*----------------------------------------------------------------------
41 | constants
42 +---------------------------------------------------------------------*/
43 #define BANNER "MP4 Elementary Stream Multiplexer - Version 3.0\n"\
44 "(Bento4 Version " AP4_VERSION_STRING ")\n"\
45 "(c) 2002-20020 Axiomatic Systems, LLC"
46
47 const unsigned int AP4_MUX_DEFAULT_VIDEO_FRAME_RATE = 24;
48 const unsigned int AP4_MUX_READ_BUFFER_SIZE = 65536;
49
50 /*----------------------------------------------------------------------
51 | globals
52 +---------------------------------------------------------------------*/
53 static struct {
54 bool verbose;
55 } Options;
56
57 /*----------------------------------------------------------------------
58 | SampleOrder
59 +---------------------------------------------------------------------*/
60 struct SampleOrder {
61 SampleOrder(AP4_UI32 decode_order, AP4_UI32 display_order) :
62 m_DecodeOrder(decode_order),
63 m_DisplayOrder(display_order) {}
64 AP4_UI32 m_DecodeOrder;
65 AP4_UI32 m_DisplayOrder;
66 };
67
68 /*----------------------------------------------------------------------
69 | Parameter
70 +---------------------------------------------------------------------*/
71 struct Parameter {
72 Parameter(const char* name, const char* value) :
73 m_Name(name),
74 m_Value(value) {}
75 AP4_String m_Name;
76 AP4_String m_Value;
77 };
78
79 /*----------------------------------------------------------------------
80 | PrintUsageAndExit
81 +---------------------------------------------------------------------*/
82 static void
83 PrintUsageAndExit()
84 {
85 fprintf(stderr,
86 BANNER
87 "\n\nusage: mp4mux [options] --track [<type>:]<input>[#<params>] [--track [<type>:]<input>[#<params>] ...] <output>\n"
88 "\n"
89 " <params>, when specified, are expressd as a comma-separated list of\n"
90 " one or more <name>=<value> parameters\n"
91 "\n"
92 "Supported types:\n"
93 " h264: H264/AVC NAL units\n"
94 " optional params:\n"
95 " dv_profile: integer number for Dolby vision profile ID (valid value: 9)\n"
96 " dv_bc: integer number for Dolby vision BL signal cross-compatibility ID (must be 2 if dv_profile is set to 9)\n"
97 " frame_rate: floating point number in frames per second (default=24.0)\n"
98 " format: avc1 (default) or avc3 for AVC tracks and Dolby Vision back-compatible tracks\n"
99 " h265: H265/HEVC NAL units\n"
100 " optional params:\n"
101 " dv_profile: integer number for Dolby vision profile ID (valid value: 5,8)\n"
102 " dv_bc: integer number for Dolby vision BL signal cross-compatibility ID (mandatory if dv_profile is set to 8)\n"
103 " frame_rate: floating point number in frames per second (default=24.0)\n"
104 " format: hev1 or hvc1 (default) for HEVC tracks and Dolby Vision backward-compatible tracks\n"
105 " dvhe or dvh1 (default) for Dolby vision tracks\n"
106 " aac: AAC in ADTS format\n"
107 " ac3: Dolby Digital\n"
108 " ec3: Dolby Digital Plus\n"
109 " ac4: Dolby AC-4\n"
110
111 " mp4: MP4 track(s) from an MP4 file\n"
112 " optional params:\n"
113 " track: audio, video, or integer track ID (default=all tracks)\n"
114 "\n"
115 "Common optional parameters for all types:\n"
116 " language: language code (3-character ISO 639-2 Alpha-3 code)\n"
117 "\n"
118 "If no type is specified for an input, the type will be inferred from the file extension\n"
119 "\n"
120 "Options:\n"
121 " --verbose: show more details\n");
122 exit(1);
123 }
124
125 /*----------------------------------------------------------------------
126 | ParseParameters
127 +---------------------------------------------------------------------*/
128 static AP4_Result
129 ParseParameters(const char* params_str, AP4_Array<Parameter>& parameters)
130 {
131 AP4_Array<AP4_String> params;
132 const char* cursor = params_str;
133 const char* start = params_str;
134 do {
135 if (*cursor == ',' || *cursor == '\0') {
136 AP4_String param;
137 param.Assign(start, (unsigned int)(cursor-start));
138 params.Append(param);
139 if (*cursor == ',') {
140 start = cursor+1;
141 }
142 }
143 } while (*cursor++);
144
145 for (unsigned int i=0; i<params.ItemCount(); i++) {
146 AP4_String& param = params[i];
147 AP4_String name;
148 AP4_String value;
149 int equal = param.Find('=');
150 if (equal >= 0) {
151 name.Assign(param.GetChars(), equal);
152 value = param.GetChars()+equal+1;
153 } else {
154 name = param;
155 }
156 parameters.Append(Parameter(name.GetChars(), value.GetChars()));
157 }
158
159 return AP4_SUCCESS;
160 }
161
162 /*----------------------------------------------------------------------
163 | ComputeDoviLevel
164 +---------------------------------------------------------------------*/
165 static AP4_Result
166 ComputeDoviLevel(AP4_UI32 video_width, AP4_UI32 video_height, double frame_rate, AP4_UI32& dv_level)
167 {
168 double level = video_width * video_height * frame_rate;
169
170 if (level <= 1280*720*24) {
171 dv_level = 1;
172 } else if (level<= 1280*720*30) {
173 dv_level = 2;
174 } else if (level <= 1920*1080*24) {
175 dv_level = 3;
176 } else if (level <= 1920*1080*30) {
177 dv_level = 4;
178 } else if (level <= 1920*1080*60) {
179 dv_level = 5;
180 } else if (level <= 3840*2160*24) {
181 dv_level = 6;
182 } else if (level <= 3840*2160*30) {
183 dv_level = 7;
184 } else if (level <= 3840*2160*48) {
185 dv_level = 8;
186 } else if (level <= 3840*2160*60) {
187 dv_level = 9;
188 } else if (level <= 3840*2160*120) {
189 if (video_width == 7680) {
190 dv_level = 11;
191 } else {
192 dv_level = 10;
193 }
194 } else if (level <= 7680*4320*60) {
195 dv_level = 12;
196 } else if (level <= (double)7680*4320*120) {
197 dv_level = 13;
198 }
199
200 return AP4_SUCCESS;
201 }
202
203 /*----------------------------------------------------------------------
204 | CheckDoviInputParameters
205 +---------------------------------------------------------------------*/
206 static AP4_Result
207 CheckDoviInputParameters(AP4_Array<Parameter>& parameters)
208 {
209 AP4_UI32 profile = 0;
210 AP4_UI32 bc = -1;
211 AP4_UI32 format = 0;
212
213 //check: profile set correctly
214 for (unsigned int i=0; i<parameters.ItemCount(); i++) {
215 if (parameters[i].m_Name == "dv_profile") {
216 profile = atoi(parameters[i].m_Value.GetChars());
217 if ((profile != 5) && (profile != 8) && (profile != 9)) {
218 fprintf(stderr, "ERROR: invalid dolby vision profile id\n");
219 return AP4_ERROR_INVALID_PARAMETERS;
220 }
221 }
222 }
223
224 //check: bl signal compatibility id value range
225 for (unsigned int i=0; i<parameters.ItemCount(); i++) {
226 if (parameters[i].m_Name == "dv_bc") {
227 bc = atoi(parameters[i].m_Value.GetChars());
228 if (bc > 7) {
229 fprintf(stderr, "ERROR: invalid dolby vision bl signal compatibility id\n");
230 return AP4_ERROR_INVALID_PARAMETERS;
231 }
232 }
233 }
234
235 for (unsigned int i=0; i<parameters.ItemCount(); i++) {
236 if (parameters[i].m_Name == "format") {
237 if (parameters[i].m_Value == "hvc1") {
238 format = AP4_SAMPLE_FORMAT_HVC1;
239 } else if (parameters[i].m_Value == "hev1") {
240 format = AP4_SAMPLE_FORMAT_HEV1;
241 } else if (parameters[i].m_Value == "dvh1") {
242 format = AP4_SAMPLE_FORMAT_DVH1;
243 } else if (parameters[i].m_Value == "dvhe") {
244 format = AP4_SAMPLE_FORMAT_DVHE;
245 } else if (parameters[i].m_Value == "avc1") {
246 format = AP4_SAMPLE_FORMAT_AVC1;
247 } else if (parameters[i].m_Value == "avc3") {
248 format = AP4_SAMPLE_FORMAT_AVC3;
249 } else if (parameters[i].m_Value == "dvav") {
250 format = AP4_SAMPLE_FORMAT_DVAV;
251 } else if (parameters[i].m_Value == "dva1") {
252 format = AP4_SAMPLE_FORMAT_DVA1;
253 } else {
254 fprintf(stderr, "ERROR: format name is invalid\n");
255 return AP4_ERROR_INVALID_PARAMETERS;
256 }
257 }
258 }
259
260 //check: sample entry box name is set correctly
261
262 if (format) {
263 if (profile == 5) {
264 // profile 5 does not compatible with other profile, only use dvhe or dvh1
265 if ((format != AP4_SAMPLE_FORMAT_DVHE) && (format != AP4_SAMPLE_FORMAT_DVH1)) {
266 fprintf(stderr, "ERROR: sample entry name is not correct for profile 5\n");
267 return AP4_ERROR_INVALID_PARAMETERS;
268 }
269 } else if (profile == 8) {
270 // profile 8 has CCID with 1, 2, 4, may be compatible with HDR10, SDR or HLG, should
271 // not use dvhe or dvh1
272 if ((format != AP4_SAMPLE_FORMAT_HVC1) && (format != AP4_SAMPLE_FORMAT_HEV1)) {
273 fprintf(stderr, "ERROR: sample entry name is not correct for profile 8\n");
274 return AP4_ERROR_INVALID_PARAMETERS;
275 }
276 } else if (profile == 9) {
277 // profile 9 only has CCID with 2, which is SDR compliant, should not use dvav or dva1
278 if ((format != AP4_SAMPLE_FORMAT_AVC1) && (format != AP4_SAMPLE_FORMAT_AVC3)) {
279 fprintf(stderr, "ERROR: sample entry name is not correct for profile 9\n");
280 return AP4_ERROR_INVALID_PARAMETERS;
281 }
282 }
283 }
284
285 //check: for profile 8/9, bl signal compatibility id must be set
286 if ((bc == (AP4_UI32)-1) && ((profile == 8) || (profile == 9))) {
287 fprintf(stderr, "ERROR: dolby vision bl signal compatibility id must be set when profile is 8 or 9\n");
288 return AP4_ERROR_INVALID_PARAMETERS;
289 }
290
291 //check: for profile 8, bl signal compatibility id must be: 1,2,4
292 if ((profile == 8) && (bc != 1) && (bc != 2) && (bc != 4)) {
293 fprintf(stderr, "ERROR: for dolby vision profile 8, bl signal compatibility id must be: 1, 2 or 4\n");
294 return AP4_ERROR_INVALID_PARAMETERS;
295 }
296
297 //check: for profile 9, bl signal compatibility id must be: 2
298 if ((profile == 9) && (bc != 2) ) {
299 fprintf(stderr, "ERROR: for dolby vision profile 9, bl signal compatibility id must be 2\n");
300 return AP4_ERROR_INVALID_PARAMETERS;
301 }
302
303 //check: for profile 5, bl signal compatibility id must be 0
304 if ((profile == 5) && (bc != 0) && (bc != (AP4_UI32)-1)) {
305 fprintf(stderr, "ERROR: for dolby vision profile 5, bl signal compatibility id must be 0\n");
306 return AP4_ERROR_INVALID_PARAMETERS;
307 }
308
309 return AP4_SUCCESS;
310 }
311
312 /*----------------------------------------------------------------------
313 | SampleFileStorage
314 +---------------------------------------------------------------------*/
315 class SampleFileStorage
316 {
317 public:
318 static AP4_Result Create(const char* basename, SampleFileStorage*& sample_file_storage);
319 ~SampleFileStorage() {
320 m_Stream->Release();
321 remove(m_Filename.GetChars());
322 }
323
324 AP4_ByteStream* GetStream() { return m_Stream; }
325
326 private:
327 SampleFileStorage(const char* basename) : m_Stream(NULL) {
328 AP4_Size name_length = (AP4_Size)AP4_StringLength(basename);
329 char* filename = new char[name_length+2];
330 AP4_CopyMemory(filename, basename, name_length);
331 filename[name_length] = '_';
332 filename[name_length+1] = '\0';
333 m_Filename = filename;
334 delete[] filename;
335 }
336
337 AP4_ByteStream* m_Stream;
338 AP4_String m_Filename;
339 };
340
341 /*----------------------------------------------------------------------
342 | SampleFileStorage::Create
343 +---------------------------------------------------------------------*/
344 AP4_Result
345 SampleFileStorage::Create(const char* basename, SampleFileStorage*& sample_file_storage)
346 {
347 sample_file_storage = NULL;
348 SampleFileStorage* object = new SampleFileStorage(basename);
349 AP4_Result result = AP4_FileByteStream::Create(object->m_Filename.GetChars(),
350 AP4_FileByteStream::STREAM_MODE_WRITE,
351 object->m_Stream);
352 if (AP4_FAILED(result)) {
353 return result;
354 }
355 sample_file_storage = object;
356 return AP4_SUCCESS;
357 }
358
359 /*----------------------------------------------------------------------
360 | SortSamples
361 +---------------------------------------------------------------------*/
362 static void
363 SortSamples(SampleOrder* array, unsigned int n)
364 {
365 if (n < 2) {
366 return;
367 }
368 SampleOrder pivot = array[n / 2];
369 SampleOrder* left = array;
370 SampleOrder* right = array + n - 1;
371 while (left <= right) {
372 if (left->m_DisplayOrder < pivot.m_DisplayOrder) {
373 ++left;
374 continue;
375 }
376 if (right->m_DisplayOrder > pivot.m_DisplayOrder) {
377 --right;
378 continue;
379 }
380 SampleOrder temp = *left;
381 *left++ = *right;
382 *right-- = temp;
383 }
384 SortSamples(array, (unsigned int)(right - array + 1));
385 SortSamples(left, (unsigned int)(array + n - left));
386 }
387
388 /*----------------------------------------------------------------------
389 | GetLanguageFromParameters
390 +---------------------------------------------------------------------*/
391 static const char*
392 GetLanguageFromParameters(AP4_Array<Parameter>& parameters, const char* defaut_value)
393 {
394 // check if we have a language parameter
395 for (unsigned int i=0; i<parameters.ItemCount(); i++) {
396 if (parameters[i].m_Name == "language") {
397 const char* language = parameters[i].m_Value.GetChars();
398
399 // the language must be a 3-character ISO 639-2 Alpha-3 code
400 if (strlen(language) != 3) {
401 fprintf(stderr, "ERROR: language codes must be 3-character ISO 639-2 Alpha-3 codes\n");
402 return NULL;
403 }
404
405 return language;
406 }
407 }
408
409 return defaut_value;
410 }
411
412 /*----------------------------------------------------------------------
413 | AddAacTrack
414 +---------------------------------------------------------------------*/
415 static void
416 AddAacTrack(AP4_Movie& movie,
417 const char* input_name,
418 AP4_Array<Parameter>& parameters,
419 SampleFileStorage& sample_storage)
420 {
421 AP4_ByteStream* input;
422 AP4_Result result = AP4_FileByteStream::Create(input_name, AP4_FileByteStream::STREAM_MODE_READ, input);
423 if (AP4_FAILED(result)) {
424 fprintf(stderr, "ERROR: cannot open input file '%s' (%d))\n", input_name, result);
425 return;
426 }
427
428 // check if we have a language parameter
429 const char* language = GetLanguageFromParameters(parameters, "und");
430 if (!language) return;
431
432 // create a sample table
433 AP4_SyntheticSampleTable* sample_table = new AP4_SyntheticSampleTable();
434
435 // create an ADTS parser
436 AP4_AdtsParser parser;
437 bool initialized = false;
438 unsigned int sample_description_index = 0;
439
440 // read from the input, feed, and get AAC frames
441 AP4_UI32 sample_rate = 0;
442 AP4_Cardinal sample_count = 0;
443 bool eos = false;
444 for(;;) {
445 // try to get a frame
446 AP4_AacFrame frame;
447 result = parser.FindFrame(frame);
448 if (AP4_SUCCEEDED(result)) {
449 if (Options.verbose) {
450 printf("AAC frame [%06d]: size = %d, %d kHz, %d ch\n",
451 sample_count,
452 frame.m_Info.m_FrameLength,
453 (int)frame.m_Info.m_SamplingFrequency,
454 frame.m_Info.m_ChannelConfiguration);
455 }
456 if (!initialized) {
457 initialized = true;
458
459 // create a sample description for our samples
460 AP4_DataBuffer dsi;
461 unsigned char aac_dsi[2];
462
463 unsigned int object_type = 2; // AAC LC by default
464 aac_dsi[0] = (object_type<<3) | (frame.m_Info.m_SamplingFrequencyIndex>>1);
465 aac_dsi[1] = ((frame.m_Info.m_SamplingFrequencyIndex&1)<<7) | (frame.m_Info.m_ChannelConfiguration<<3);
466
467 dsi.SetData(aac_dsi, 2);
468 AP4_MpegAudioSampleDescription* sample_description =
469 new AP4_MpegAudioSampleDescription(
470 AP4_OTI_MPEG4_AUDIO, // object type
471 (AP4_UI32)frame.m_Info.m_SamplingFrequency,
472 16, // sample size
473 frame.m_Info.m_ChannelConfiguration,
474 &dsi, // decoder info
475 6144, // buffer size
476 128000, // max bitrate
477 128000); // average bitrate
478 sample_description_index = sample_table->GetSampleDescriptionCount();
479 sample_table->AddSampleDescription(sample_description);
480 sample_rate = (AP4_UI32)frame.m_Info.m_SamplingFrequency;
481 }
482
483 // read and store the sample data
484 AP4_Position position = 0;
485 sample_storage.GetStream()->Tell(position);
486 AP4_DataBuffer sample_data(frame.m_Info.m_FrameLength);
487 sample_data.SetDataSize(frame.m_Info.m_FrameLength);
488 frame.m_Source->ReadBytes(sample_data.UseData(), frame.m_Info.m_FrameLength);
489 sample_storage.GetStream()->Write(sample_data.GetData(), frame.m_Info.m_FrameLength);
490
491 // add the sample to the table
492 sample_table->AddSample(*sample_storage.GetStream(), position, frame.m_Info.m_FrameLength, 1024, sample_description_index, 0, 0, true);
493 sample_count++;
494 } else {
495 if (result == AP4_ERROR_CORRUPTED_BITSTREAM) {
496 fprintf(stderr, "WARN: The stream in corrupted, muxing stopped. The muxed MP4 only contains the first %d samples.\n", sample_count);
497 break;
498 } else if ((result == AP4_ERROR_NOT_ENOUGH_DATA) && (parser.GetBytesAvailable() == (AP4_BITSTREAM_BUFFER_SIZE -1))){
499 fprintf(stderr, "WARN: The frame %d size is larger than the max buffer size, muxing stopped. The muxed MP4 only contains the first %d samples.\n", sample_count + 1, sample_count);
500 break;
501 }
502 if (eos) break;
503 }
504
505 // read some data and feed the parser
506 AP4_UI08 input_buffer[AP4_MUX_READ_BUFFER_SIZE];
507 AP4_Size to_read = parser.GetBytesFree();
508 if (to_read) {
509 AP4_Size bytes_read = 0;
510 if (to_read > sizeof(input_buffer)) to_read = sizeof(input_buffer);
511 result = input->ReadPartial(input_buffer, to_read, bytes_read);
512 if (AP4_SUCCEEDED(result)) {
513 AP4_Size to_feed = bytes_read;
514 result = parser.Feed(input_buffer, &to_feed);
515 if (AP4_FAILED(result)) {
516 AP4_Debug("ERROR: parser.Feed() failed (%d)\n", result);
517 return;
518 }
519 } else {
520 if (result == AP4_ERROR_EOS) {
521 eos = true;
522 parser.Feed(NULL, NULL, AP4_BITSTREAM_FLAG_EOS);
523 }
524 }
525 }
526 }
527
528 // create an audio track
529 AP4_Track* track = new AP4_Track(AP4_Track::TYPE_AUDIO,
530 sample_table,
531 0, // track id
532 sample_rate, // movie time scale
533 sample_count*1024, // track duration
534 sample_rate, // media time scale
535 sample_count*1024, // media duration
536 language, // language
537 0, 0); // width, height
538
539 // cleanup
540 input->Release();
541
542 movie.AddTrack(track);
543 }
544
545 /*----------------------------------------------------------------------
546 | AddAc3Track
547 +---------------------------------------------------------------------*/
548 static void
549 AddAc3Track(AP4_Movie& movie,
550 const char* input_name,
551 AP4_Array<Parameter>& parameters,
552 SampleFileStorage& sample_storage)
553 {
554 AP4_ByteStream* input;
555 AP4_Result result = AP4_FileByteStream::Create(input_name, AP4_FileByteStream::STREAM_MODE_READ, input);
556 if (AP4_FAILED(result)) {
557 fprintf(stderr, "ERROR: cannot open input file '%s' (%d))\n", input_name, result);
558 return;
559 }
560
561 // check if we have a language parameter
562 const char* language = GetLanguageFromParameters(parameters, "und");
563 if (!language) return;
564
565 // create a sample table
566 AP4_SyntheticSampleTable* sample_table = new AP4_SyntheticSampleTable(); // chunk_size is used to control chunk size in 'stsc' box
567
568 // create an AC-3 Sync Frame parser
569 AP4_Ac3Parser parser;
570 bool initialized = false;
571 unsigned int sample_description_index = 0;
572
573 // read from the input, feed, and get AC-3 frames
574 AP4_UI32 sample_rate = 0;
575 AP4_Cardinal sample_count = 0;
576
577 bool eos = false;
578 for(;;) {
579 // try to get a frame
580 AP4_Ac3Frame frame;
581 result = parser.FindFrame(frame);
582 if (AP4_SUCCEEDED(result)) {
583 if (Options.verbose) {
584 printf("AC-3 frame [%06d]: size = %d, %d kHz, %d ch\n",
585 sample_count,
586 frame.m_Info.m_FrameSize,
587 frame.m_Info.m_SampleRate,
588 frame.m_Info.m_ChannelCount);
589 }
590 if (!initialized) {
591 initialized = true;
592
593 // create a sample description for our samples
594 AP4_Dac3Atom::StreamInfo *ac3_stream_info = &frame.m_Info.m_Ac3StreamInfo;
595
596 AP4_Ac3SampleDescription* sample_description =
597 new AP4_Ac3SampleDescription(
598 frame.m_Info.m_SampleRate, // sample rate
599 16, // sample size
600 2, // channel count
601 frame.m_Info.m_FrameSize, // Access Unit size
602 ac3_stream_info); // AC-3 SubStream
603
604 sample_description_index = sample_table->GetSampleDescriptionCount();
605 sample_table->AddSampleDescription(sample_description);
606 sample_rate = frame.m_Info.m_SampleRate;
607 }
608
609 // read and store the sample data
610 AP4_Position position = 0;
611 sample_storage.GetStream()->Tell(position);
612 AP4_DataBuffer sample_data(frame.m_Info.m_FrameSize);
613 sample_data.SetDataSize(frame.m_Info.m_FrameSize);
614 frame.m_Source->ReadBytes(sample_data.UseData(), frame.m_Info.m_FrameSize);
615 if (frame.m_LittleEndian) {
616 AP4_ByteSwap16(sample_data.UseData(), (unsigned int)frame.m_Info.m_FrameSize);
617 }
618 sample_storage.GetStream()->Write(sample_data.GetData(), frame.m_Info.m_FrameSize);
619
620 // add the sample to the table
621 sample_table->AddSample(*sample_storage.GetStream(), position, frame.m_Info.m_FrameSize, 1536, sample_description_index, 0, 0, true);
622 sample_count++;
623 } else {
624 if (eos) break;
625 }
626
627 // read some data and feed the parser
628 AP4_UI08 input_buffer[AP4_MUX_READ_BUFFER_SIZE];
629 AP4_Size to_read = parser.GetBytesFree();
630 if (to_read) {
631 AP4_Size bytes_read = 0;
632 if (to_read > sizeof(input_buffer)) to_read = sizeof(input_buffer);
633 result = input->ReadPartial(input_buffer, to_read, bytes_read);
634 if (AP4_SUCCEEDED(result)) {
635 AP4_Size to_feed = bytes_read;
636 result = parser.Feed(input_buffer, &to_feed);
637 if (AP4_FAILED(result)) {
638 AP4_Debug("ERROR: parser.Feed() failed (%d)\n", result);
639 return;
640 }
641 } else {
642 if (result == AP4_ERROR_EOS) {
643 eos = true;
644 parser.Feed(NULL, NULL, AP4_BITSTREAM_FLAG_EOS);
645 }
646 }
647 }
648 }
649
650 // create an audio track
651 AP4_Track* track = new AP4_Track(AP4_Track::TYPE_AUDIO,
652 sample_table,
653 0, // track id
654 sample_rate, // movie time scale
655 sample_count * 1536, // track duration
656 sample_rate, // media time scale
657 sample_count * 1536, // media duration
658 language, // language
659 0, 0);
660
661 // add an edit list with MediaTime==0 to ac3 track defautly.
662 if (1) {
663 // create an 'edts' container
664 AP4_ContainerAtom* new_edts = new AP4_ContainerAtom(AP4_ATOM_TYPE_EDTS);
665 AP4_ElstAtom* new_elst = new AP4_ElstAtom();
666 AP4_UI64 duration = 0;
667 if (!movie.GetTimeScale()) {
668 duration = sample_count * 1536;
669 } else {
670 duration = AP4_ConvertTime(1000*sample_table->GetSampleCount(), sample_rate, movie.GetTimeScale());
671 }
672 AP4_ElstEntry new_elst_entry = AP4_ElstEntry(duration, 0, 1);
673 new_elst->AddEntry(new_elst_entry);
674 new_edts->AddChild(new_elst);
675 track->UseTrakAtom()->AddChild(new_edts, 1);
676 }
677
678 // cleanup
679 input->Release();
680
681 movie.AddTrack(track);
682 }
683
684 /*----------------------------------------------------------------------
685 | AddEac3Track
686 +---------------------------------------------------------------------*/
687 static void
688 AddEac3Track(AP4_Movie& movie,
689 const char* input_name,
690 AP4_Array<Parameter>& parameters,
691 SampleFileStorage& sample_storage)
692 {
693 AP4_ByteStream* input;
694 AP4_Result result = AP4_FileByteStream::Create(input_name, AP4_FileByteStream::STREAM_MODE_READ, input);
695 if (AP4_FAILED(result)) {
696 fprintf(stderr, "ERROR: cannot open input file '%s' (%d))\n", input_name, result);
697 return;
698 }
699
700 // check if we have a language parameter
701 const char* language = GetLanguageFromParameters(parameters, "und");
702 if (!language) return;
703
704 // create a sample table
705 AP4_SyntheticSampleTable* sample_table = new AP4_SyntheticSampleTable(); // The parameter chunk_size is used to control chunk size in 'stsc' box
706
707 // create an E-AC-3 Sync Frame parser
708 AP4_Eac3Parser parser;
709 bool initialized = false;
710 unsigned int sample_description_index = 0;
711
712 // read from the input, feed, and get E-AC-3 frames
713 AP4_UI32 sample_rate = 0;
714 AP4_Cardinal sample_count = 0;
715
716 bool eos = false;
717 for(;;) {
718 // try to get a frame
719 AP4_Eac3Frame frame;
720 result = parser.FindFrame(frame);
721 if (AP4_SUCCEEDED(result)) {
722 if (Options.verbose) {
723 printf("E-AC-3 frame [%06d]: size = %d, %d kHz, %d ch\n",
724 sample_count,
725 frame.m_Info.m_FrameSize,
726 frame.m_Info.m_SampleRate,
727 frame.m_Info.m_ChannelCount);
728 }
729 if (!initialized) {
730 initialized = true;
731
732 // create a sample description for our samples
733 AP4_Dec3Atom::SubStream *eac3_substream = &frame.m_Info.m_Eac3SubStream;
734 const unsigned int obj_num = frame.m_Info.complexity_index_type_a;
735
736 AP4_Eac3SampleDescription* sample_description =
737 new AP4_Eac3SampleDescription(
738 frame.m_Info.m_SampleRate, // sample rate
739 16, // sample size
740 2, // channel count
741 frame.m_Info.m_FrameSize, // Access Unit size
742 eac3_substream, // E-AC-3 SubStream
743 obj_num); // DD+JOC object numbers
744 sample_description_index = sample_table->GetSampleDescriptionCount();
745 sample_table->AddSampleDescription(sample_description);
746 sample_rate = frame.m_Info.m_SampleRate;
747 }
748
749 // read and store the sample data
750 AP4_Position position = 0;
751 sample_storage.GetStream()->Tell(position);
752 AP4_DataBuffer sample_data(frame.m_Info.m_FrameSize);
753 sample_data.SetDataSize(frame.m_Info.m_FrameSize);
754 frame.m_Source->ReadBytes(sample_data.UseData(), frame.m_Info.m_FrameSize);
755 if (frame.m_LittleEndian) {
756 AP4_ByteSwap16(sample_data.UseData(), (unsigned int)frame.m_Info.m_FrameSize);
757 }
758 sample_storage.GetStream()->Write(sample_data.GetData(), frame.m_Info.m_FrameSize);
759
760 // add the sample to the table
761 sample_table->AddSample(*sample_storage.GetStream(), position, frame.m_Info.m_FrameSize, 1536, sample_description_index, 0, 0, true);
762 sample_count++;
763 } else {
764 if (result == AP4_ERROR_CORRUPTED_BITSTREAM) {
765 fprintf(stderr, "WARN: The stream in corrupted, so stop muxing. The muxed MP4 only contains the first %d samples.\n", sample_count);
766 break;
767 } else if ((result == AP4_ERROR_NOT_ENOUGH_DATA) && (parser.GetBytesAvailable() == (AP4_BITSTREAM_BUFFER_SIZE -1))){
768 fprintf(stderr, "WARN: The frame %d size is larger than pre-defined buffer size (8191 bytes), so stop muxing. The muxed MP4 only contains the first %d samples.\n", sample_count + 1, sample_count);
769 break;
770 }
771 if (eos) break;
772 }
773
774 // read some data and feed the parser
775 AP4_UI08 input_buffer[AP4_MUX_READ_BUFFER_SIZE];
776 AP4_Size to_read = parser.GetBytesFree();
777 if (to_read) {
778 AP4_Size bytes_read = 0;
779 if (to_read > sizeof(input_buffer)) to_read = sizeof(input_buffer);
780 result = input->ReadPartial(input_buffer, to_read, bytes_read);
781 if (AP4_SUCCEEDED(result)) {
782 AP4_Size to_feed = bytes_read;
783 result = parser.Feed(input_buffer, &to_feed);
784 if (AP4_FAILED(result)) {
785 AP4_Debug("ERROR: parser.Feed() failed (%d)\n", result);
786 return;
787 }
788 } else {
789 if (result == AP4_ERROR_EOS) {
790 eos = true;
791 parser.Feed(NULL, NULL, AP4_BITSTREAM_FLAG_EOS);
792 }
793 }
794 }
795 }
796
797 // create an audio track
798 AP4_Track* track = new AP4_Track(AP4_Track::TYPE_AUDIO,
799 sample_table,
800 0, // track id
801 sample_rate, // movie time scale
802 sample_count * 1536, // track duration
803 sample_rate, // media time scale
804 sample_count * 1536, // media duration
805 language, // language
806 0, 0); // width, height
807
808 // add an edit list with MediaTime==0 to ec3 track defautly.
809 if (1) {
810 // create an 'edts' container
811 AP4_ContainerAtom* new_edts = new AP4_ContainerAtom(AP4_ATOM_TYPE_EDTS);
812 AP4_ElstAtom* new_elst = new AP4_ElstAtom();
813 AP4_UI64 duration = 0;
814 if (!movie.GetTimeScale()) {
815 duration = sample_count * 1536;
816 } else {
817 duration = AP4_ConvertTime(1000*sample_table->GetSampleCount(), sample_rate, movie.GetTimeScale());
818 }
819 AP4_ElstEntry new_elst_entry = AP4_ElstEntry(duration, 0, 1);
820 new_elst->AddEntry(new_elst_entry);
821 new_edts->AddChild(new_elst);
822 track->UseTrakAtom()->AddChild(new_edts, 1);
823 }
824
825 // cleanup
826 input->Release();
827
828 movie.AddTrack(track);
829 }
830
831 /*----------------------------------------------------------------------
832 | AddAc4Track
833 +---------------------------------------------------------------------*/
834 static void
835 AddAc4Track(AP4_Movie& movie,
836 const char* input_name,
837 AP4_Array<Parameter>& parameters,
838 SampleFileStorage& sample_storage)
839 {
840 AP4_ByteStream* input;
841 AP4_Result result = AP4_FileByteStream::Create(input_name, AP4_FileByteStream::STREAM_MODE_READ, input);
842 if (AP4_FAILED(result)) {
843 fprintf(stderr, "ERROR: cannot open input file '%s' (%d))\n", input_name, result);
844 return;
845 }
846
847 // check if we have a language parameter
848 const char* language = GetLanguageFromParameters(parameters, "und");
849 if (!language) return;
850
851 // create a sample table
852 AP4_SyntheticSampleTable* sample_table = new AP4_SyntheticSampleTable(); // The parameter chunk_size is used to control chunk size in 'stsc' box
853
854 // create an AC-4 Sync Frame parser
855 AP4_Ac4Parser parser;
856 bool initialized = false;
857 unsigned int sample_description_index = 0;
858
859 // read from the input, feed, and get AC-4 frames
860 // AP4_UI32 sample_rate = 0;
861 AP4_Cardinal sample_count = 0;
862 AP4_Cardinal sample_duration = 0;
863 AP4_Cardinal media_time_scale = 0;
864 bool eos = false;
865 for(;;) {
866 // try to get a frame
867 AP4_Ac4Frame frame;
868 result = parser.FindFrame(frame);
869 if (AP4_SUCCEEDED(result)) {
870 if (Options.verbose) {
871 printf("AC-4 frame [%06d]: size = %d, %d kHz, %d ch\n",
872 sample_count,
873 frame.m_Info.m_FrameSize,
874 (int)frame.m_Info.m_Ac4Dsi.d.v1.fs,
875 frame.m_Info.m_ChannelCount);
876 }
877 if (!initialized) {
878 initialized = true;
879
880 // create a sample description for our samples
881 AP4_Dac4Atom::Ac4Dsi *ac4Dsi = &frame.m_Info.m_Ac4Dsi;
882
883 AP4_Ac4SampleDescription* sample_description =
884 new AP4_Ac4SampleDescription(
885 frame.m_Info.m_Ac4Dsi.d.v1.fs, // sample rate
886 16, // sample size
887 frame.m_Info.m_ChannelCount, // channel count
888 frame.m_Info.m_FrameSize, // DIS size, can't calcuate the DSI size in advance, so assume the maximum value is frame size.
889 ac4Dsi); // AC-4 DSI
890 sample_description_index = sample_table->GetSampleDescriptionCount();
891 sample_table->AddSampleDescription(sample_description);
892 /* sample_rate = frame.m_Info.m_Ac4Dsi.d.v1.fs */;
893 sample_duration = frame.m_Info.m_SampleDuration;
894 media_time_scale = frame.m_Info.m_MediaTimeScale;
895
896 }
897
898 // read and store the sample data
899 AP4_Position position = 0;
900 sample_storage.GetStream()->Tell(position);
901 AP4_DataBuffer sample_data(frame.m_Info.m_FrameSize);
902 sample_data.SetDataSize(frame.m_Info.m_FrameSize);
903 frame.m_Source->ReadBytes(sample_data.UseData(), frame.m_Info.m_FrameSize);
904 sample_storage.GetStream()->Write(sample_data.GetData(), frame.m_Info.m_FrameSize);
905
906 // add the sample to the table
907 sample_table->AddSample(*sample_storage.GetStream(), position, frame.m_Info.m_FrameSize, sample_duration, sample_description_index, 0, 0, (frame.m_Info.m_Iframe == 1));
908 sample_count++;
909 // Skip the CRC word for 0xAC41 stream
910 frame.m_Source->SkipBytes(frame.m_Info.m_CRCSize);
911 } else {
912 if (result == AP4_ERROR_CORRUPTED_BITSTREAM) {
913 fprintf(stderr, "WARN: The stream in corrupted, so stop muxing. The muxed MP4 only contains the first %d samples.\n", sample_count);
914 break;
915 } else if ((result == AP4_ERROR_NOT_ENOUGH_DATA) && (parser.GetBytesAvailable() == (AP4_BITSTREAM_BUFFER_SIZE -1))){
916 fprintf(stderr, "WARN: The frame %d size is larger than pre-defined buffer size (8191 bytes), so stop muxing. The muxed MP4 only contains the first %d samples.\n", sample_count + 1, sample_count);
917 break;
918 }
919 if (eos) break;
920 }
921
922 // read some data and feed the parser
923 AP4_UI08 input_buffer[AP4_MUX_READ_BUFFER_SIZE];
924 AP4_Size to_read = parser.GetBytesFree();
925 if (to_read) {
926 AP4_Size bytes_read = 0;
927 if (to_read > sizeof(input_buffer)) to_read = sizeof(input_buffer);
928 result = input->ReadPartial(input_buffer, to_read, bytes_read);
929 if (AP4_SUCCEEDED(result)) {
930 AP4_Size to_feed = bytes_read;
931 result = parser.Feed(input_buffer, &to_feed);
932 if (AP4_FAILED(result)) {
933 AP4_Debug("ERROR: parser.Feed() failed (%d)\n", result);
934 return;
935 }
936 } else {
937 if (result == AP4_ERROR_EOS) {
938 eos = true;
939 parser.Feed(NULL, NULL, AP4_BITSTREAM_FLAG_EOS);
940 }
941 }
942 }
943 }
944
945 // create an audio track
946 AP4_Track* track = new AP4_Track(AP4_Track::TYPE_AUDIO,
947 sample_table,
948 0, // track id
949 media_time_scale, // movie time scale
950 AP4_UI64(sample_count) * sample_duration, // track duration
951 media_time_scale, // media time scale
952 AP4_UI64(sample_count) * sample_duration, // media duration
953 language, // language
954 0, 0); // width, height
955
956 // add an edit list with MediaTime==0 to ac4 track defautly.
957 if (1) {
958 // create an 'edts' container
959 AP4_ContainerAtom* new_edts = new AP4_ContainerAtom(AP4_ATOM_TYPE_EDTS);
960 AP4_ElstAtom* new_elst = new AP4_ElstAtom();
961 AP4_UI64 duration = 0;
962 if (!movie.GetTimeScale()) {
963 duration = AP4_UI64(sample_count) * sample_duration;
964 } else {
965 duration = AP4_ConvertTime(1000*sample_table->GetSampleCount(), media_time_scale, movie.GetTimeScale());
966 }
967 AP4_ElstEntry new_elst_entry = AP4_ElstEntry(duration, 0, 1);
968 new_elst->AddEntry(new_elst_entry);
969 new_edts->AddChild(new_elst);
970 track->UseTrakAtom()->AddChild(new_edts, 1);
971 }
972
973 // cleanup
974 input->Release();
975
976 movie.AddTrack(track);
977 }
978
979 /*----------------------------------------------------------------------
980 | AddH264Track
981 +---------------------------------------------------------------------*/
982 static void
983 AddH264Track(AP4_Movie& movie,
984 const char* input_name,
985 AP4_Array<Parameter>& parameters,
986 AP4_Array<AP4_UI32>& brands,
987 SampleFileStorage& sample_storage)
988 {
989 AP4_ByteStream* input;
990 AP4_Result result = AP4_FileByteStream::Create(input_name, AP4_FileByteStream::STREAM_MODE_READ, input);
991 if (AP4_FAILED(result)) {
992 fprintf(stderr, "ERROR: cannot open input file '%s' (%d))\n", input_name, result);
993 return;
994 }
995
996 // check if we have a language parameter
997 const char* language = GetLanguageFromParameters(parameters, "und");
998 if (!language) return;
999
1000 // see if the frame rate is specified
1001 unsigned int video_frame_rate = AP4_MUX_DEFAULT_VIDEO_FRAME_RATE*1000;
1002 for (unsigned int i=0; i<parameters.ItemCount(); i++) {
1003 if (parameters[i].m_Name == "frame_rate") {
1004 double frame_rate = atof(parameters[i].m_Value.GetChars());
1005 if (frame_rate == 0.0) {
1006 fprintf(stderr, "ERROR: invalid video frame rate %s\n", parameters[i].m_Value.GetChars());
1007 input->Release();
1008 return;
1009 }
1010 video_frame_rate = (unsigned int)(1000.0*frame_rate);
1011 }
1012 }
1013
1014 // create a sample table
1015 AP4_SyntheticSampleTable* sample_table = new AP4_SyntheticSampleTable();
1016
1017 // allocate an array to keep track of sample order
1018 AP4_Array<SampleOrder> sample_orders;
1019
1020 // parse the input
1021 AP4_AvcFrameParser parser;
1022 for (;;) {
1023 bool eos;
1024 unsigned char input_buffer[AP4_MUX_READ_BUFFER_SIZE];
1025 AP4_Size bytes_in_buffer = 0;
1026 result = input->ReadPartial(input_buffer, sizeof(input_buffer), bytes_in_buffer);
1027 if (AP4_SUCCEEDED(result)) {
1028 eos = false;
1029 } else if (result == AP4_ERROR_EOS) {
1030 eos = true;
1031 } else {
1032 fprintf(stderr, "ERROR: failed to read from input file\n");
1033 break;
1034 }
1035 AP4_Size offset = 0;
1036 bool found_access_unit = false;
1037 do {
1038 AP4_AvcFrameParser::AccessUnitInfo access_unit_info;
1039
1040 found_access_unit = false;
1041 AP4_Size bytes_consumed = 0;
1042 result = parser.Feed(&input_buffer[offset],
1043 bytes_in_buffer,
1044 bytes_consumed,
1045 access_unit_info,
1046 eos);
1047 if (AP4_FAILED(result)) {
1048 fprintf(stderr, "ERROR: Feed() failed (%d)\n", result);
1049 break;
1050 }
1051 if (access_unit_info.nal_units.ItemCount()) {
1052 // we got one access unit
1053 found_access_unit = true;
1054 if (Options.verbose) {
1055 printf("H264 Access Unit, %d NAL units, decode_order=%d, display_order=%d\n",
1056 access_unit_info.nal_units.ItemCount(),
1057 access_unit_info.decode_order,
1058 access_unit_info.display_order);
1059 }
1060
1061 // compute the total size of the sample data
1062 unsigned int sample_data_size = 0;
1063 for (unsigned int i=0; i<access_unit_info.nal_units.ItemCount(); i++) {
1064 sample_data_size += 4+access_unit_info.nal_units[i]->GetDataSize();
1065 }
1066
1067 // store the sample data
1068 AP4_Position position = 0;
1069 sample_storage.GetStream()->Tell(position);
1070 for (unsigned int i=0; i<access_unit_info.nal_units.ItemCount(); i++) {
1071 sample_storage.GetStream()->WriteUI32(access_unit_info.nal_units[i]->GetDataSize());
1072 sample_storage.GetStream()->Write(access_unit_info.nal_units[i]->GetData(), access_unit_info.nal_units[i]->GetDataSize());
1073 }
1074
1075 // add the sample to the track
1076 sample_table->AddSample(*sample_storage.GetStream(), position, sample_data_size, 1000, 0, 0, 0, access_unit_info.is_idr);
1077
1078 // remember the sample order
1079 sample_orders.Append(SampleOrder(access_unit_info.decode_order, access_unit_info.display_order));
1080
1081 // free the memory buffers
1082 access_unit_info.Reset();
1083 }
1084
1085 offset += bytes_consumed;
1086 bytes_in_buffer -= bytes_consumed;
1087 } while (bytes_in_buffer || found_access_unit);
1088 if (eos) break;
1089 }
1090
1091 // adjust the sample CTS/DTS offsets based on the sample orders
1092 if (sample_orders.ItemCount() > 1) {
1093 unsigned int start = 0;
1094 for (unsigned int i=1; i<=sample_orders.ItemCount(); i++) {
1095 if (i == sample_orders.ItemCount() || sample_orders[i].m_DisplayOrder == 0) {
1096 // we got to the end of the GOP, sort it by display order
1097 SortSamples(&sample_orders[start], i-start);
1098 start = i;
1099 }
1100 }
1101 }
1102 unsigned int max_delta = 0;
1103 for (unsigned int i=0; i<sample_orders.ItemCount(); i++) {
1104 if (sample_orders[i].m_DecodeOrder > i) {
1105 unsigned int delta =sample_orders[i].m_DecodeOrder-i;
1106 if (delta > max_delta) {
1107 max_delta = delta;
1108 }
1109 }
1110 }
1111 for (unsigned int i=0; i<sample_orders.ItemCount(); i++) {
1112 sample_table->UseSample(sample_orders[i].m_DecodeOrder).SetCts(1000ULL*(AP4_UI64)(i+max_delta));
1113 }
1114
1115 // check the video parameters
1116 AP4_AvcSequenceParameterSet* sps = NULL;
1117 for (unsigned int i=0; i<=AP4_AVC_SPS_MAX_ID; i++) {
1118 if (parser.GetSequenceParameterSets()[i]) {
1119 sps = parser.GetSequenceParameterSets()[i];
1120 break;
1121 }
1122 }
1123 if (sps == NULL) {
1124 fprintf(stderr, "ERROR: no sequence parameter set found in video\n");
1125 input->Release();
1126 return;
1127 }
1128 unsigned int video_width = 0;
1129 unsigned int video_height = 0;
1130 sps->GetInfo(video_width, video_height);
1131 if (Options.verbose) {
1132 printf("VIDEO: %dx%d\n", video_width, video_height);
1133 }
1134
1135 // collect the SPS and PPS into arrays
1136 AP4_Array<AP4_DataBuffer> sps_array;
1137 for (unsigned int i=0; i<=AP4_AVC_SPS_MAX_ID; i++) {
1138 if (parser.GetSequenceParameterSets()[i]) {
1139 sps_array.Append(parser.GetSequenceParameterSets()[i]->raw_bytes);
1140 }
1141 }
1142 AP4_Array<AP4_DataBuffer> pps_array;
1143 for (unsigned int i=0; i<=AP4_AVC_PPS_MAX_ID; i++) {
1144 if (parser.GetPictureParameterSets()[i]) {
1145 pps_array.Append(parser.GetPictureParameterSets()[i]->raw_bytes);
1146 }
1147 }
1148
1149 // setup the video the sample descripton
1150 AP4_AvcSampleDescription* sample_description =
1151 new AP4_AvcSampleDescription(AP4_SAMPLE_FORMAT_AVC1,
1152 video_width,
1153 video_height,
1154 24,
1155 "AVC Coding",
1156 sps->profile_idc,
1157 sps->level_idc,
1158 sps->constraint_set0_flag<<7 |
1159 sps->constraint_set1_flag<<6 |
1160 sps->constraint_set2_flag<<5 |
1161 sps->constraint_set3_flag<<4,
1162 4,
1163 sps->chroma_format_idc,
1164 sps->bit_depth_luma_minus8,
1165 sps->bit_depth_chroma_minus8,
1166 sps_array,
1167 pps_array);
1168 sample_table->AddSampleDescription(sample_description);
1169
1170 AP4_UI32 movie_timescale = 1000;
1171 AP4_UI32 media_timescale = video_frame_rate;
1172 AP4_UI64 video_track_duration = AP4_ConvertTime(1000*sample_table->GetSampleCount(), media_timescale, movie_timescale);
1173 AP4_UI64 video_media_duration = 1000*sample_table->GetSampleCount();
1174
1175 // create a video track
1176 AP4_Track* track = new AP4_Track(AP4_Track::TYPE_VIDEO,
1177 sample_table,
1178 0, // auto-select track id
1179 movie_timescale, // movie time scale
1180 video_track_duration, // track duration
1181 media_timescale, // media time scale
1182 video_media_duration, // media duration
1183 language, // language
1184 video_width<<16, // width
1185 video_height<<16 // height
1186 );
1187 // Use an edit list to compensate for the inital cts offset
1188 if (max_delta) {
1189 // create an 'edts' container
1190 AP4_ContainerAtom* new_edts = new AP4_ContainerAtom(AP4_ATOM_TYPE_EDTS);
1191 AP4_ElstAtom* new_elst = new AP4_ElstAtom();
1192 AP4_UI64 duration = 0;
1193 if (!movie.GetTimeScale()) {
1194 duration = video_media_duration;
1195 } else {
1196 duration = AP4_ConvertTime(1000*sample_table->GetSampleCount(), media_timescale, movie.GetTimeScale());
1197 }
1198 AP4_ElstEntry new_elst_entry = AP4_ElstEntry(duration, max_delta*1000ULL, 1);
1199 new_elst->AddEntry(new_elst_entry);
1200 new_edts->AddChild(new_elst);
1201 track->UseTrakAtom()->AddChild(new_edts, 1);
1202 }
1203 // update the brands list
1204 brands.Append(AP4_FILE_BRAND_AVC1);
1205
1206 // cleanup
1207 input->Release();
1208
1209 movie.AddTrack(track);
1210 }
1211
1212 /*----------------------------------------------------------------------
1213 | AddH264DoviTrack
1214 +---------------------------------------------------------------------*/
1215 static void
1216 AddH264DoviTrack(AP4_Movie& movie,
1217 const char* input_name,
1218 AP4_Array<Parameter>& parameters,
1219 AP4_Array<AP4_UI32>& brands,
1220 SampleFileStorage& sample_storage)
1221 {
1222 double frame_rate = 0.0;
1223 //based on the Dovi iso spec, set the following values to const
1224 const AP4_UI32 dv_major_version = 1;
1225 const AP4_UI32 dv_minor_version = 0;
1226 const bool dv_rpu_flag = 1;
1227 const bool dv_el_flag = 0;
1228 const bool dv_bl_flag = 1;
1229
1230 AP4_UI32 dv_profile = 0;
1231 AP4_UI32 dv_bl_signal_comp_id = 0;
1232 AP4_UI32 dv_level = 0;
1233
1234 AP4_UI32 format = 0;
1235
1236 AP4_ByteStream* input;
1237 AP4_Result result = AP4_FileByteStream::Create(input_name, AP4_FileByteStream::STREAM_MODE_READ, input);
1238 if (AP4_FAILED(result)) {
1239 fprintf(stderr, "ERROR: cannot open input file '%s' (%d))\n", input_name, result);
1240 return;
1241 }
1242
1243 // check if we have a language parameter
1244 const char* language = GetLanguageFromParameters(parameters, "und");
1245 if (!language) return;
1246
1247 // see if the frame rate is specified
1248 AP4_UI32 video_frame_rate = AP4_MUX_DEFAULT_VIDEO_FRAME_RATE*1000;
1249 for (unsigned int i=0; i<parameters.ItemCount(); i++) {
1250 if (parameters[i].m_Name == "frame_rate") {
1251 frame_rate = atof(parameters[i].m_Value.GetChars());
1252 if (frame_rate == 0.0) {
1253 fprintf(stderr, "ERROR: invalid video frame rate %s\n", parameters[i].m_Value.GetChars());
1254 input->Release();
1255 return;
1256 }
1257 video_frame_rate = (unsigned int)(1000.0*frame_rate);
1258 } else if (parameters[i].m_Name == "format") {
1259 if (parameters[i].m_Value == "avc1") {
1260 format = AP4_SAMPLE_FORMAT_AVC1;
1261 } else if (parameters[i].m_Value == "avc3") {
1262 format = AP4_SAMPLE_FORMAT_AVC3;
1263 } else if (parameters[i].m_Value == "dva1") {
1264 format = AP4_SAMPLE_FORMAT_DVA1;
1265 } else if (parameters[i].m_Value == "dvav") {
1266 format = AP4_SAMPLE_FORMAT_DVAV;
1267 }
1268 } else if (parameters[i].m_Name == "dv_profile") {
1269 dv_profile = atoi(parameters[i].m_Value.GetChars());
1270 } else if (parameters[i].m_Name == "dv_bc") {
1271 dv_bl_signal_comp_id = atoi(parameters[i].m_Value.GetChars());
1272 }
1273 }
1274
1275 //set default frame rate value
1276 if (frame_rate == 0.0) {
1277 frame_rate = 24.0;
1278 }
1279
1280 // create a sample table
1281 AP4_SyntheticSampleTable* sample_table = new AP4_SyntheticSampleTable();
1282
1283 // allocate an array to keep track of sample order
1284 AP4_Array<SampleOrder> sample_orders;
1285
1286 // parse the input
1287 AP4_AvcFrameParser parser;
1288
1289 if (format == AP4_SAMPLE_FORMAT_AVC3 || format == AP4_SAMPLE_FORMAT_DVAV) {
1290 parser.SetParameterControl(true);
1291 } else if (format == AP4_SAMPLE_FORMAT_AVC1 || format == AP4_SAMPLE_FORMAT_DVA1) {
1292 parser.SetParameterControl(false);
1293 }
1294
1295 for (;;) {
1296 bool eos;
1297 unsigned char input_buffer[AP4_MUX_READ_BUFFER_SIZE];
1298 AP4_Size bytes_in_buffer = 0;
1299 result = input->ReadPartial(input_buffer, sizeof(input_buffer), bytes_in_buffer);
1300 if (AP4_SUCCEEDED(result)) {
1301 eos = false;
1302 } else if (result == AP4_ERROR_EOS) {
1303 eos = true;
1304 } else {
1305 fprintf(stderr, "ERROR: failed to read from input file\n");
1306 break;
1307 }
1308 AP4_Size offset = 0;
1309 bool found_access_unit = false;
1310 do {
1311 AP4_AvcFrameParser::AccessUnitInfo access_unit_info;
1312
1313 found_access_unit = false;
1314 AP4_Size bytes_consumed = 0;
1315 result = parser.Feed(&input_buffer[offset],
1316 bytes_in_buffer,
1317 bytes_consumed,
1318 access_unit_info,
1319 eos);
1320 if (AP4_FAILED(result)) {
1321 fprintf(stderr, "ERROR: Feed() failed (%d)\n", result);
1322 break;
1323 }
1324 if (access_unit_info.nal_units.ItemCount()) {
1325 // we got one access unit
1326 found_access_unit = true;
1327 if (Options.verbose) {
1328 printf("H264 Access Unit, %d NAL units, decode_order=%d, display_order=%d\n",
1329 access_unit_info.nal_units.ItemCount(),
1330 access_unit_info.decode_order,
1331 access_unit_info.display_order);
1332 }
1333
1334 // compute the total size of the sample data
1335 unsigned int sample_data_size = 0;
1336 for (unsigned int i=0; i<access_unit_info.nal_units.ItemCount(); i++) {
1337 sample_data_size += 4+access_unit_info.nal_units[i]->GetDataSize();
1338 }
1339
1340 // store the sample data
1341 AP4_Position position = 0;
1342 sample_storage.GetStream()->Tell(position);
1343 for (unsigned int i=0; i<access_unit_info.nal_units.ItemCount(); i++) {
1344 sample_storage.GetStream()->WriteUI32(access_unit_info.nal_units[i]->GetDataSize());
1345 sample_storage.GetStream()->Write(access_unit_info.nal_units[i]->GetData(), access_unit_info.nal_units[i]->GetDataSize());
1346 }
1347
1348 // add the sample to the track
1349 sample_table->AddSample(*sample_storage.GetStream(), position, sample_data_size, 1000, 0, 0, 0, access_unit_info.is_idr);
1350
1351 // remember the sample order
1352 sample_orders.Append(SampleOrder(access_unit_info.decode_order, access_unit_info.display_order));
1353
1354 // free the memory buffers
1355 access_unit_info.Reset();
1356 }
1357
1358 offset += bytes_consumed;
1359 bytes_in_buffer -= bytes_consumed;
1360 } while (bytes_in_buffer || found_access_unit);
1361 if (eos) break;
1362 }
1363
1364 // adjust the sample CTS/DTS offsets based on the sample orders
1365 if (sample_orders.ItemCount() > 1) {
1366 unsigned int start = 0;
1367 for (unsigned int i=1; i<=sample_orders.ItemCount(); i++) {
1368 if (i == sample_orders.ItemCount() || sample_orders[i].m_DisplayOrder == 0) {
1369 // we got to the end of the GOP, sort it by display order
1370 SortSamples(&sample_orders[start], i-start);
1371 start = i;
1372 }
1373 }
1374 }
1375 unsigned int max_delta = 0;
1376 for (unsigned int i=0; i<sample_orders.ItemCount(); i++) {
1377 if (sample_orders[i].m_DecodeOrder > i) {
1378 unsigned int delta =sample_orders[i].m_DecodeOrder-i;
1379 if (delta > max_delta) {
1380 max_delta = delta;
1381 }
1382 }
1383 }
1384 for (unsigned int i=0; i<sample_orders.ItemCount(); i++) {
1385 sample_table->UseSample(sample_orders[i].m_DecodeOrder).SetCts(1000ULL*(AP4_UI64)(i+max_delta));
1386 }
1387
1388 // check the video parameters
1389 AP4_AvcSequenceParameterSet* sps = NULL;
1390 for (unsigned int i=0; i<=AP4_AVC_SPS_MAX_ID; i++) {
1391 if (parser.GetSequenceParameterSets()[i]) {
1392 sps = parser.GetSequenceParameterSets()[i];
1393 break;
1394 }
1395 }
1396 if (sps == NULL) {
1397 fprintf(stderr, "ERROR: no sequence parameter set found in video\n");
1398 input->Release();
1399 return;
1400 }
1401 unsigned int video_width = 0;
1402 unsigned int video_height = 0;
1403 sps->GetInfo(video_width, video_height);
1404 if (Options.verbose) {
1405 printf("VIDEO: %dx%d\n", video_width, video_height);
1406 }
1407
1408 // collect the SPS and PPS into arrays
1409 AP4_Array<AP4_DataBuffer> sps_array;
1410 for (unsigned int i=0; i<=AP4_AVC_SPS_MAX_ID; i++) {
1411 if (parser.GetSequenceParameterSets()[i]) {
1412 sps_array.Append(parser.GetSequenceParameterSets()[i]->raw_bytes);
1413 }
1414 }
1415 AP4_Array<AP4_DataBuffer> pps_array;
1416 for (unsigned int i=0; i<=AP4_AVC_PPS_MAX_ID; i++) {
1417 if (parser.GetPictureParameterSets()[i]) {
1418 pps_array.Append(parser.GetPictureParameterSets()[i]->raw_bytes);
1419 }
1420 }
1421
1422 // compute the dolby vision level
1423 ComputeDoviLevel(video_width, video_height, frame_rate, dv_level);
1424
1425 // setup the video the sample descripton
1426 AP4_AvcDoviSampleDescription* sample_description =
1427 new AP4_AvcDoviSampleDescription(format,
1428 video_width,
1429 video_height,
1430 24,
1431 "DOVI Coding",
1432 sps->profile_idc,
1433 sps->level_idc,
1434 sps->constraint_set0_flag<<7 |
1435 sps->constraint_set1_flag<<6 |
1436 sps->constraint_set2_flag<<5 |
1437 sps->constraint_set3_flag<<4,
1438 4,
1439 sps_array,
1440 pps_array,
1441 sps->chroma_format_idc,
1442 sps->bit_depth_luma_minus8,
1443 sps->bit_depth_chroma_minus8,
1444 dv_major_version,
1445 dv_minor_version,
1446 dv_profile,
1447 dv_level,
1448 dv_rpu_flag,
1449 dv_el_flag,
1450 dv_bl_flag,
1451 dv_bl_signal_comp_id);
1452 sample_table->AddSampleDescription(sample_description);
1453
1454 AP4_UI32 movie_timescale = 1000;
1455 AP4_UI32 media_timescale = video_frame_rate;
1456 AP4_UI64 video_track_duration = AP4_ConvertTime(1000*sample_table->GetSampleCount(), media_timescale, movie_timescale);
1457 AP4_UI64 video_media_duration = 1000*sample_table->GetSampleCount();
1458
1459 // create a video track
1460 AP4_Track* track = new AP4_Track(AP4_Track::TYPE_VIDEO,
1461 sample_table,
1462 0, // auto-select track id
1463 movie_timescale, // movie time scale
1464 video_track_duration, // track duration
1465 media_timescale, // media time scale
1466 video_media_duration, // media duration
1467 language, // language
1468 video_width<<16, // width
1469 video_height<<16 // height
1470 );
1471 // Using edit list to compensate the inital cts offset
1472 if (max_delta) {
1473 // create an 'edts' container
1474 AP4_ContainerAtom* new_edts = new AP4_ContainerAtom(AP4_ATOM_TYPE_EDTS);
1475 AP4_ElstAtom* new_elst = new AP4_ElstAtom();
1476 AP4_UI64 duration = 0;
1477 if (!movie.GetTimeScale()) {
1478 duration = video_media_duration;
1479 } else {
1480 duration = AP4_ConvertTime(1000*sample_table->GetSampleCount(), media_timescale, movie.GetTimeScale());
1481 }
1482 AP4_ElstEntry new_elst_entry = AP4_ElstEntry(duration, max_delta*1000ULL, 1);
1483 new_elst->AddEntry(new_elst_entry);
1484 new_edts->AddChild(new_elst);
1485 track->UseTrakAtom()->AddChild(new_edts, 1);
1486 }
1487 // update the brands list
1488 brands.Append(format);
1489
1490 // cleanup
1491 input->Release();
1492
1493 movie.AddTrack(track);
1494 }
1495
1496 /*----------------------------------------------------------------------
1497 | AddH265Track
1498 +---------------------------------------------------------------------*/
1499 static void
1500 AddH265Track(AP4_Movie& movie,
1501 const char* input_name,
1502 AP4_Array<Parameter>& parameters,
1503 AP4_Array<AP4_UI32>& brands,
1504 SampleFileStorage& sample_storage)
1505 {
1506 unsigned int video_width = 0;
1507 unsigned int video_height = 0;
1508 AP4_UI32 format = AP4_SAMPLE_FORMAT_HVC1;
1509
1510 AP4_ByteStream* input;
1511 AP4_Result result = AP4_FileByteStream::Create(input_name, AP4_FileByteStream::STREAM_MODE_READ, input);
1512 if (AP4_FAILED(result)) {
1513 fprintf(stderr, "ERROR: cannot open input file '%s' (%d))\n", input_name, result);
1514 return;
1515 }
1516
1517 // check if we have a language parameter
1518 const char* language = GetLanguageFromParameters(parameters, "und");
1519 if (!language) return;
1520
1521 // see if the frame rate is specified
1522 unsigned int video_frame_rate = AP4_MUX_DEFAULT_VIDEO_FRAME_RATE*1000;
1523 for (unsigned int i=0; i<parameters.ItemCount(); i++) {
1524 if (parameters[i].m_Name == "frame_rate") {
1525 double frame_rate = atof(parameters[i].m_Value.GetChars());
1526 if (frame_rate == 0.0) {
1527 fprintf(stderr, "ERROR: invalid video frame rate %s\n", parameters[i].m_Value.GetChars());
1528 input->Release();
1529 return;
1530 }
1531 video_frame_rate = (unsigned int)(1000.0*frame_rate);
1532 } else if (parameters[i].m_Name == "format") {
1533 if (parameters[i].m_Value == "hev1") {
1534 format = AP4_SAMPLE_FORMAT_HEV1;
1535 } else if (parameters[i].m_Value == "hvc1") {
1536 format = AP4_SAMPLE_FORMAT_HVC1;
1537 }
1538 }
1539 }
1540
1541 // create a sample table
1542 AP4_SyntheticSampleTable* sample_table = new AP4_SyntheticSampleTable();
1543
1544 // allocate an array to keep track of sample order
1545 AP4_Array<SampleOrder> sample_orders;
1546
1547 // parse the input
1548 AP4_HevcFrameParser parser;
1549 for (;;) {
1550 bool eos;
1551 unsigned char input_buffer[AP4_MUX_READ_BUFFER_SIZE];
1552 AP4_Size bytes_in_buffer = 0;
1553 result = input->ReadPartial(input_buffer, sizeof(input_buffer), bytes_in_buffer);
1554 if (AP4_SUCCEEDED(result)) {
1555 eos = false;
1556 } else if (result == AP4_ERROR_EOS) {
1557 eos = true;
1558 } else {
1559 fprintf(stderr, "ERROR: failed to read from input file\n");
1560 break;
1561 }
1562 AP4_Size offset = 0;
1563 bool found_access_unit = false;
1564 do {
1565 AP4_HevcFrameParser::AccessUnitInfo access_unit_info;
1566
1567 found_access_unit = false;
1568 AP4_Size bytes_consumed = 0;
1569 result = parser.Feed(&input_buffer[offset],
1570 bytes_in_buffer,
1571 bytes_consumed,
1572 access_unit_info,
1573 eos);
1574 if (AP4_FAILED(result)) {
1575 fprintf(stderr, "ERROR: Feed() failed (%d)\n", result);
1576 break;
1577 }
1578 if (access_unit_info.nal_units.ItemCount()) {
1579 // we got one access unit
1580 found_access_unit = true;
1581 if (Options.verbose) {
1582 printf("H265 Access Unit, %d NAL units, decode_order=%d, display_order=%d\n",
1583 access_unit_info.nal_units.ItemCount(),
1584 access_unit_info.decode_order,
1585 access_unit_info.display_order);
1586 }
1587
1588 // compute the total size of the sample data
1589 unsigned int sample_data_size = 0;
1590 for (unsigned int i=0; i<access_unit_info.nal_units.ItemCount(); i++) {
1591 sample_data_size += 4+access_unit_info.nal_units[i]->GetDataSize();
1592 }
1593
1594 // store the sample data
1595 AP4_Position position = 0;
1596 sample_storage.GetStream()->Tell(position);
1597 for (unsigned int i=0; i<access_unit_info.nal_units.ItemCount(); i++) {
1598 sample_storage.GetStream()->WriteUI32(access_unit_info.nal_units[i]->GetDataSize());
1599 sample_storage.GetStream()->Write(access_unit_info.nal_units[i]->GetData(), access_unit_info.nal_units[i]->GetDataSize());
1600 }
1601
1602 // add the sample to the track
1603 sample_table->AddSample(*sample_storage.GetStream(), position, sample_data_size, 1000, 0, 0, 0, access_unit_info.is_random_access);
1604
1605 // remember the sample order
1606 sample_orders.Append(SampleOrder(access_unit_info.decode_order, access_unit_info.display_order));
1607
1608 // free the memory buffers
1609 access_unit_info.Reset();
1610 }
1611
1612 offset += bytes_consumed;
1613 bytes_in_buffer -= bytes_consumed;
1614 } while (bytes_in_buffer || found_access_unit);
1615 if (eos) break;
1616 }
1617
1618 // adjust the sample CTS/DTS offsets based on the sample orders
1619 if (sample_orders.ItemCount() > 1) {
1620 unsigned int start = 0;
1621 for (unsigned int i=1; i<=sample_orders.ItemCount(); i++) {
1622 if (i == sample_orders.ItemCount() || sample_orders[i].m_DisplayOrder == 0) {
1623 // we got to the end of the GOP, sort it by display order
1624 SortSamples(&sample_orders[start], i-start);
1625 start = i;
1626 }
1627 }
1628 }
1629 unsigned int max_delta = 0;
1630 for (unsigned int i=0; i<sample_orders.ItemCount(); i++) {
1631 if (sample_orders[i].m_DecodeOrder > i) {
1632 unsigned int delta =sample_orders[i].m_DecodeOrder-i;
1633 if (delta > max_delta) {
1634 max_delta = delta;
1635 }
1636 }
1637 }
1638 for (unsigned int i=0; i<sample_orders.ItemCount(); i++) {
1639 sample_table->UseSample(sample_orders[i].m_DecodeOrder).SetCts(1000ULL*(AP4_UI64)(i+max_delta));
1640 }
1641
1642 // check that we have at least one SPS
1643 AP4_HevcSequenceParameterSet* sps = NULL;
1644 for (unsigned int i=0; i<=AP4_HEVC_SPS_MAX_ID; i++) {
1645 sps = parser.GetSequenceParameterSets()[i];
1646 if (sps) break;
1647 }
1648 if (sps == NULL) {
1649 fprintf(stderr, "ERROR: no sequence parameter set found in video\n");
1650 input->Release();
1651 return;
1652 }
1653
1654 // collect parameters from the first SPS entry
1655 // TODO: synthesize from multiple SPS entries if we have more than one
1656 AP4_UI08 general_profile_space = sps->profile_tier_level.general_profile_space;
1657 AP4_UI08 general_tier_flag = sps->profile_tier_level.general_tier_flag;
1658 AP4_UI08 general_profile = sps->profile_tier_level.general_profile_idc;
1659 AP4_UI32 general_profile_compatibility_flags = sps->profile_tier_level.general_profile_compatibility_flags;
1660 AP4_UI64 general_constraint_indicator_flags = sps->profile_tier_level.general_constraint_indicator_flags;
1661 AP4_UI08 general_level = sps->profile_tier_level.general_level_idc;
1662 AP4_UI32 min_spatial_segmentation = 0; // TBD (should read from VUI if present)
1663 AP4_UI08 parallelism_type = 0; // unknown
1664 AP4_UI08 chroma_format = sps->chroma_format_idc;
1665 AP4_UI08 luma_bit_depth = 8; // hardcoded temporarily, should be read from the bitstream
1666 AP4_UI08 chroma_bit_depth = 8; // hardcoded temporarily, should be read from the bitstream
1667 AP4_UI16 average_frame_rate = 0; // unknown
1668 AP4_UI08 constant_frame_rate = 0; // unknown
1669 AP4_UI08 num_temporal_layers = 0; // unknown
1670 AP4_UI08 temporal_id_nested = 0; // unknown
1671 AP4_UI08 nalu_length_size = 4;
1672
1673 sps->GetInfo(video_width, video_height);
1674 if (Options.verbose) {
1675 printf("VIDEO: %dx%d\n", video_width, video_height);
1676 }
1677
1678 // collect the VPS, SPS and PPS into arrays
1679 AP4_Array<AP4_DataBuffer> vps_array;
1680 for (unsigned int i=0; i<=AP4_HEVC_VPS_MAX_ID; i++) {
1681 if (parser.GetVideoParameterSets()[i]) {
1682 vps_array.Append(parser.GetVideoParameterSets()[i]->raw_bytes);
1683 }
1684 }
1685 AP4_Array<AP4_DataBuffer> sps_array;
1686 for (unsigned int i=0; i<=AP4_HEVC_SPS_MAX_ID; i++) {
1687 if (parser.GetSequenceParameterSets()[i]) {
1688 sps_array.Append(parser.GetSequenceParameterSets()[i]->raw_bytes);
1689 }
1690 }
1691 AP4_Array<AP4_DataBuffer> pps_array;
1692 for (unsigned int i=0; i<=AP4_HEVC_PPS_MAX_ID; i++) {
1693 if (parser.GetPictureParameterSets()[i]) {
1694 pps_array.Append(parser.GetPictureParameterSets()[i]->raw_bytes);
1695 }
1696 }
1697
1698 // setup the video the sample descripton
1699 AP4_UI08 parameters_completeness = (format == AP4_SAMPLE_FORMAT_HVC1 ? 1 : 0);
1700 AP4_HevcSampleDescription* sample_description =
1701 new AP4_HevcSampleDescription(format,
1702 video_width,
1703 video_height,
1704 24,
1705 "HEVC Coding",
1706 general_profile_space,
1707 general_tier_flag,
1708 general_profile,
1709 general_profile_compatibility_flags,
1710 general_constraint_indicator_flags,
1711 general_level,
1712 min_spatial_segmentation,
1713 parallelism_type,
1714 chroma_format,
1715 luma_bit_depth,
1716 chroma_bit_depth,
1717 average_frame_rate,
1718 constant_frame_rate,
1719 num_temporal_layers,
1720 temporal_id_nested,
1721 nalu_length_size,
1722 vps_array,
1723 parameters_completeness,
1724 sps_array,
1725 parameters_completeness,
1726 pps_array,
1727 parameters_completeness);
1728
1729 sample_table->AddSampleDescription(sample_description);
1730
1731 AP4_UI32 movie_timescale = 1000;
1732 AP4_UI32 media_timescale = video_frame_rate;
1733 AP4_UI64 video_track_duration = AP4_ConvertTime(1000*sample_table->GetSampleCount(), media_timescale, movie_timescale);
1734 AP4_UI64 video_media_duration = 1000*sample_table->GetSampleCount();
1735
1736 // create a video track
1737 AP4_Track* track = new AP4_Track(AP4_Track::TYPE_VIDEO,
1738 sample_table,
1739 0, // auto-select track id
1740 movie_timescale, // movie time scale
1741 video_track_duration, // track duration
1742 media_timescale, // media time scale
1743 video_media_duration, // media duration
1744 language, // language
1745 video_width<<16, // width
1746 video_height<<16 // height
1747 );
1748
1749 // Use an edit list to compensate for the inital cts offset
1750 if (max_delta) {
1751 // create an 'edts' container
1752 AP4_ContainerAtom* new_edts = new AP4_ContainerAtom(AP4_ATOM_TYPE_EDTS);
1753 AP4_ElstAtom* new_elst = new AP4_ElstAtom();
1754 AP4_UI64 duration = 0;
1755 if (!movie.GetTimeScale()) {
1756 duration = video_media_duration;
1757 } else {
1758 duration = AP4_ConvertTime(1000*sample_table->GetSampleCount(), media_timescale, movie.GetTimeScale());
1759 }
1760 AP4_ElstEntry new_elst_entry = AP4_ElstEntry(duration, max_delta*1000ULL, 1);
1761 new_elst->AddEntry(new_elst_entry);
1762 new_edts->AddChild(new_elst);
1763 track->UseTrakAtom()->AddChild(new_edts, 1);
1764 }
1765 // update the brands list
1766 brands.Append(AP4_FILE_BRAND_HVC1);
1767
1768 // cleanup
1769 input->Release();
1770
1771 movie.AddTrack(track);
1772 }
1773
1774 /*----------------------------------------------------------------------
1775 | AddH265DoviTrack
1776 +---------------------------------------------------------------------*/
1777 static void
1778 AddH265DoviTrack(AP4_Movie& movie,
1779 const char* input_name,
1780 AP4_Array<Parameter>& parameters,
1781 AP4_Array<AP4_UI32>& brands,
1782 SampleFileStorage& sample_storage)
1783 {
1784 AP4_UI32 video_width = 0;
1785 AP4_UI32 video_height = 0;
1786 double frame_rate = 0.0;
1787
1788 //based on the Dovi iso spec, set the following values to const
1789 const AP4_UI32 dv_major_version = 1;
1790 const AP4_UI32 dv_minor_version = 0;
1791 const bool dv_rpu_flag = 1;
1792 const bool dv_el_flag = 0;
1793 const bool dv_bl_flag = 1;
1794
1795 AP4_UI32 dv_profile = 0;
1796 AP4_UI32 dv_bl_signal_comp_id = 0;
1797 AP4_UI32 dv_level = 0;
1798
1799 AP4_UI32 format = 0;
1800
1801 AP4_ByteStream* input;
1802 AP4_Result result = AP4_FileByteStream::Create(input_name, AP4_FileByteStream::STREAM_MODE_READ, input);
1803 if (AP4_FAILED(result)) {
1804 fprintf(stderr, "ERROR: cannot open input file '%s' (%d))\n", input_name, result);
1805 return;
1806 }
1807
1808 // check if we have a language parameter
1809 const char* language = GetLanguageFromParameters(parameters, "und");
1810 if (!language) return;
1811
1812 // see if the frame rate/format/dv_profile/dv_bc is specified
1813 unsigned int video_frame_rate = AP4_MUX_DEFAULT_VIDEO_FRAME_RATE*1000;
1814 for (unsigned int i=0; i<parameters.ItemCount(); i++) {
1815 if (parameters[i].m_Name == "frame_rate") {
1816 frame_rate = atof(parameters[i].m_Value.GetChars());
1817 if (frame_rate == 0.0) {
1818 fprintf(stderr, "ERROR: invalid video frame rate %s\n", parameters[i].m_Value.GetChars());
1819 input->Release();
1820 return;
1821 }
1822 video_frame_rate = (unsigned int)(1000.0*frame_rate);
1823 } else if (parameters[i].m_Name == "format") {
1824 if (parameters[i].m_Value == "hvc1") {
1825 format = AP4_SAMPLE_FORMAT_HVC1;
1826 } else if (parameters[i].m_Value == "hev1") {
1827 format = AP4_SAMPLE_FORMAT_HEV1;
1828 } else if (parameters[i].m_Value == "dvh1") {
1829 format = AP4_SAMPLE_FORMAT_DVH1;
1830 } else if (parameters[i].m_Value == "dvhe") {
1831 format = AP4_SAMPLE_FORMAT_DVHE;
1832 }
1833 } else if (parameters[i].m_Name == "dv_profile") {
1834 dv_profile = atoi(parameters[i].m_Value.GetChars());
1835 } else if (parameters[i].m_Name == "dv_bc") {
1836 dv_bl_signal_comp_id = atoi(parameters[i].m_Value.GetChars());
1837 }
1838 }
1839
1840 //if not set format, set the default one based on profile
1841 if (!format) {
1842 if (dv_profile == 5) {
1843 format = AP4_SAMPLE_FORMAT_DVH1;
1844 } else if (dv_profile == 8) {
1845 if (dv_bl_signal_comp_id) {
1846 format = AP4_SAMPLE_FORMAT_HVC1;
1847 } else {
1848 format = AP4_SAMPLE_FORMAT_DVH1;
1849 }
1850 }
1851 }
1852
1853 // create a sample table
1854 AP4_SyntheticSampleTable* sample_table = new AP4_SyntheticSampleTable();
1855
1856 // allocate an array to keep track of sample order
1857 AP4_Array<SampleOrder> sample_orders;
1858
1859 // parse the input
1860 AP4_HevcFrameParser parser;
1861 if (format == AP4_SAMPLE_FORMAT_HEV1 || format == AP4_SAMPLE_FORMAT_DVHE) {
1862 parser.SetParameterControl(true);
1863 } else if (format == AP4_SAMPLE_FORMAT_HVC1 || format == AP4_SAMPLE_FORMAT_DVH1) {
1864 parser.SetParameterControl(false);
1865 }
1866 for (;;) {
1867 bool eos;
1868 unsigned char input_buffer[AP4_MUX_READ_BUFFER_SIZE];
1869 AP4_Size bytes_in_buffer = 0;
1870 result = input->ReadPartial(input_buffer, sizeof(input_buffer), bytes_in_buffer);
1871 if (AP4_SUCCEEDED(result)) {
1872 eos = false;
1873 } else if (result == AP4_ERROR_EOS) {
1874 eos = true;
1875 } else {
1876 fprintf(stderr, "ERROR: failed to read from input file\n");
1877 break;
1878 }
1879 AP4_Size offset = 0;
1880 bool found_access_unit = false;
1881 do {
1882 AP4_HevcFrameParser::AccessUnitInfo access_unit_info;
1883
1884 found_access_unit = false;
1885 AP4_Size bytes_consumed = 0;
1886 result = parser.Feed(&input_buffer[offset],
1887 bytes_in_buffer,
1888 bytes_consumed,
1889 access_unit_info,
1890 eos);
1891 if (AP4_FAILED(result)) {
1892 fprintf(stderr, "ERROR: Feed() failed (%d)\n", result);
1893 break;
1894 }
1895 if (access_unit_info.nal_units.ItemCount()) {
1896 // we got one access unit
1897 found_access_unit = true;
1898 if (Options.verbose) {
1899 printf("H265 Access Unit, %d NAL units, decode_order=%d, display_order=%d\n",
1900 access_unit_info.nal_units.ItemCount(),
1901 access_unit_info.decode_order,
1902 access_unit_info.display_order);
1903 }
1904
1905 // compute the total size of the sample data
1906 unsigned int sample_data_size = 0;
1907 for (unsigned int i=0; i<access_unit_info.nal_units.ItemCount(); i++) {
1908 sample_data_size += 4+access_unit_info.nal_units[i]->GetDataSize();
1909 }
1910
1911 // store the sample data
1912 AP4_Position position = 0;
1913 sample_storage.GetStream()->Tell(position);
1914 for (unsigned int i=0; i<access_unit_info.nal_units.ItemCount(); i++) {
1915 sample_storage.GetStream()->WriteUI32(access_unit_info.nal_units[i]->GetDataSize());
1916 sample_storage.GetStream()->Write(access_unit_info.nal_units[i]->GetData(), access_unit_info.nal_units[i]->GetDataSize());
1917 }
1918
1919 // add the sample to the track
1920 sample_table->AddSample(*sample_storage.GetStream(), position, sample_data_size, 1000, 0, 0, 0, access_unit_info.is_random_access);
1921
1922 // remember the sample order
1923 sample_orders.Append(SampleOrder(access_unit_info.decode_order, access_unit_info.display_order));
1924
1925 // free the memory buffers
1926 access_unit_info.Reset();
1927 }
1928
1929 offset += bytes_consumed;
1930 bytes_in_buffer -= bytes_consumed;
1931 } while (bytes_in_buffer || found_access_unit);
1932 if (eos) break;
1933 }
1934
1935 // adjust the sample CTS/DTS offsets based on the sample orders
1936 if (sample_orders.ItemCount() > 1) {
1937 unsigned int start = 0;
1938 for (unsigned int i=1; i<=sample_orders.ItemCount(); i++) {
1939 if (i == sample_orders.ItemCount() || sample_orders[i].m_DisplayOrder == 0) {
1940 // we got to the end of the GOP, sort it by display order
1941 SortSamples(&sample_orders[start], i-start);
1942 start = i;
1943 }
1944 }
1945 }
1946 unsigned int max_delta = 0;
1947 for (unsigned int i=0; i<sample_orders.ItemCount(); i++) {
1948 if (sample_orders[i].m_DecodeOrder > i) {
1949 unsigned int delta =sample_orders[i].m_DecodeOrder-i;
1950 if (delta > max_delta) {
1951 max_delta = delta;
1952 }
1953 }
1954 }
1955 for (unsigned int i=0; i<sample_orders.ItemCount(); i++) {
1956 sample_table->UseSample(sample_orders[i].m_DecodeOrder).SetCts(1000ULL*(AP4_UI64)(i+max_delta));
1957 }
1958
1959 // check that we have at least one SPS
1960 AP4_HevcSequenceParameterSet* sps = NULL;
1961 for (unsigned int i=0; i<=AP4_HEVC_SPS_MAX_ID; i++) {
1962 sps = parser.GetSequenceParameterSets()[i];
1963 if (sps) break;
1964 }
1965 if (sps == NULL) {
1966 fprintf(stderr, "ERROR: no sequence parameter set found in video\n");
1967 input->Release();
1968 return;
1969 }
1970
1971 // collect parameters from the first SPS entry
1972 // TODO: synthesize from multiple SPS entries if we have more than one
1973 AP4_UI08 general_profile_space = sps->profile_tier_level.general_profile_space;
1974 AP4_UI08 general_tier_flag = sps->profile_tier_level.general_tier_flag;
1975 AP4_UI08 general_profile = sps->profile_tier_level.general_profile_idc;
1976 AP4_UI32 general_profile_compatibility_flags = sps->profile_tier_level.general_profile_compatibility_flags;
1977 AP4_UI64 general_constraint_indicator_flags = sps->profile_tier_level.general_constraint_indicator_flags;
1978 AP4_UI08 general_level = sps->profile_tier_level.general_level_idc;
1979 AP4_UI32 min_spatial_segmentation = 0; // TBD (should read from VUI if present)
1980 AP4_UI08 parallelism_type = 0; // unknown
1981 AP4_UI08 chroma_format = sps->chroma_format_idc;
1982 AP4_UI08 luma_bit_depth = 8; // hardcoded temporarily, should be read from the bitstream
1983 AP4_UI08 chroma_bit_depth = 8; // hardcoded temporarily, should be read from the bitstream
1984 AP4_UI16 average_frame_rate = 0; // unknown
1985 AP4_UI08 constant_frame_rate = 0; // unknown
1986 AP4_UI08 num_temporal_layers = 0; // unknown
1987 AP4_UI08 temporal_id_nested = 0; // unknown
1988 AP4_UI08 nalu_length_size = 4;
1989 AP4_UI08 transfer_characteristics = sps->vui_parameters.transfer_characteristics;
1990
1991 sps->GetInfo(video_width, video_height);
1992 if (Options.verbose) {
1993 printf("VIDEO: %dx%d\n", video_width, video_height);
1994 }
1995
1996 // collect the VPS, SPS and PPS into arrays
1997 AP4_Array<AP4_DataBuffer> vps_array;
1998 for (unsigned int i=0; i<=AP4_HEVC_VPS_MAX_ID; i++) {
1999 if (parser.GetVideoParameterSets()[i]) {
2000 vps_array.Append(parser.GetVideoParameterSets()[i]->raw_bytes);
2001 }
2002 }
2003 AP4_Array<AP4_DataBuffer> sps_array;
2004 for (unsigned int i=0; i<=AP4_HEVC_SPS_MAX_ID; i++) {
2005 if (parser.GetSequenceParameterSets()[i]) {
2006 sps_array.Append(parser.GetSequenceParameterSets()[i]->raw_bytes);
2007 }
2008 }
2009 AP4_Array<AP4_DataBuffer> pps_array;
2010 for (unsigned int i=0; i<=AP4_HEVC_PPS_MAX_ID; i++) {
2011 if (parser.GetPictureParameterSets()[i]) {
2012 pps_array.Append(parser.GetPictureParameterSets()[i]->raw_bytes);
2013 }
2014 }
2015
2016 // get the frame rate from the VPS
2017 AP4_HevcVideoParameterSet* vps = parser.GetVideoParameterSets()[0];
2018 unsigned int vps_time_scale = 0;
2019 unsigned int vps_num_units = 0;
2020 vps->GetInfo(vps_time_scale, vps_num_units);
2021 if (vps_num_units) {
2022 frame_rate = vps_time_scale/vps_num_units;
2023 }
2024
2025 // set dolby vision level
2026 ComputeDoviLevel(video_width, video_height, frame_rate, dv_level);
2027
2028 // setup the video the sample descripton
2029 AP4_UI08 parameters_completeness = ((format == AP4_SAMPLE_FORMAT_HVC1 || format == AP4_SAMPLE_FORMAT_DVH1) ? 1 : 0);
2030 AP4_HevcDoviSampleDescription* sample_description =
2031 new AP4_HevcDoviSampleDescription(format,
2032 video_width,
2033 video_height,
2034 24,
2035 "DOVI Coding",
2036 general_profile_space,
2037 general_tier_flag,
2038 general_profile,
2039 general_profile_compatibility_flags,
2040 general_constraint_indicator_flags,
2041 general_level,
2042 min_spatial_segmentation,
2043 parallelism_type,
2044 chroma_format,
2045 luma_bit_depth,
2046 chroma_bit_depth,
2047 average_frame_rate,
2048 constant_frame_rate,
2049 num_temporal_layers,
2050 temporal_id_nested,
2051 nalu_length_size,
2052 vps_array,
2053 parameters_completeness,
2054 sps_array,
2055 parameters_completeness,
2056 pps_array,
2057 parameters_completeness,
2058 dv_major_version,
2059 dv_minor_version,
2060 dv_profile,
2061 dv_level,
2062 dv_rpu_flag,
2063 dv_el_flag,
2064 dv_bl_flag,
2065 dv_bl_signal_comp_id);
2066
2067 sample_table->AddSampleDescription(sample_description);
2068
2069 AP4_UI32 movie_timescale = 1000;
2070 AP4_UI32 media_timescale = video_frame_rate;
2071 AP4_UI64 video_track_duration = AP4_ConvertTime(1000*sample_table->GetSampleCount(), media_timescale, movie_timescale);
2072 AP4_UI64 video_media_duration = 1000*sample_table->GetSampleCount();
2073
2074 // create a video track
2075 AP4_Track* track = new AP4_Track(AP4_Track::TYPE_VIDEO,
2076 sample_table,
2077 0, // auto-select track id
2078 movie_timescale, // movie time scale
2079 video_track_duration, // track duration
2080 media_timescale, // media time scale
2081 video_media_duration, // media duration
2082 language, // language
2083 video_width<<16, // width
2084 video_height<<16 // height
2085 );
2086 // Using edit list to compensate the inital cts offset
2087 if (max_delta) {
2088 // create an 'edts' container
2089 AP4_ContainerAtom* new_edts = new AP4_ContainerAtom(AP4_ATOM_TYPE_EDTS);
2090 AP4_ElstAtom* new_elst = new AP4_ElstAtom();
2091 AP4_UI64 duration = 0;
2092 if (!movie.GetTimeScale()) {
2093 duration = video_media_duration;
2094 } else {
2095 duration = AP4_ConvertTime(1000*sample_table->GetSampleCount(), media_timescale, movie.GetTimeScale());
2096 }
2097 AP4_ElstEntry new_elst_entry = AP4_ElstEntry(duration, max_delta*1000ULL, 1);
2098 new_elst->AddEntry(new_elst_entry);
2099 new_edts->AddChild(new_elst);
2100 track->UseTrakAtom()->AddChild(new_edts, 1);
2101 }
2102 // update the brands list
2103 brands.Append(format);
2104 if (dv_profile == 8 && dv_bl_signal_comp_id == 4) {
2105 if (transfer_characteristics == 18) {
2106 brands.Append(AP4_FILE_BRAND_DB4H);
2107 } else if (transfer_characteristics == 14) {
2108 brands.Append(AP4_FILE_BRAND_DB4G);
2109 }
2110 }
2111
2112 // cleanup
2113 input->Release();
2114
2115 movie.AddTrack(track);
2116 }
2117
2118 /*----------------------------------------------------------------------
2119 | AddMp4Tracks
2120 +---------------------------------------------------------------------*/
2121 static void
2122 AddMp4Tracks(AP4_Movie& movie,
2123 const char* input_name,
2124 AP4_Array<Parameter>& parameters,
2125 AP4_Array<AP4_UI32>& /*brands*/)
2126 {
2127 // open the input
2128 AP4_ByteStream* input_stream = NULL;
2129 AP4_Result result = AP4_FileByteStream::Create(input_name,
2130 AP4_FileByteStream::STREAM_MODE_READ,
2131 input_stream);
2132 if (AP4_FAILED(result)) {
2133 fprintf(stderr, "ERROR: cannot open input file %s (%d)\n", input_name, result);
2134 return;
2135 }
2136
2137 AP4_File file(*input_stream, true);
2138 input_stream->Release();
2139 AP4_Movie* input_movie = file.GetMovie();
2140 if (input_movie == NULL) {
2141 return;
2142 }
2143
2144 // check if we have a language parameter
2145 const char* language = GetLanguageFromParameters(parameters, NULL);
2146
2147 // check the parameters to decide which track(s) to import
2148 unsigned int track_id = 0;
2149 for (unsigned int i=0; i<parameters.ItemCount(); i++) {
2150 if (parameters[i].m_Name == "track") {
2151 if (parameters[i].m_Value == "audio") {
2152 AP4_Track* track = input_movie->GetTrack(AP4_Track::TYPE_AUDIO);
2153 if (track == NULL) {
2154 fprintf(stderr, "ERROR: no audio track found in %s\n", input_name);
2155 return;
2156 } else {
2157 track_id = track->GetId();
2158 }
2159 } else if (parameters[i].m_Value == "video") {
2160 AP4_Track* track = input_movie->GetTrack(AP4_Track::TYPE_VIDEO);
2161 if (track == NULL) {
2162 fprintf(stderr, "ERROR: no video track found in %s\n", input_name);
2163 return;
2164 } else {
2165 track_id = track->GetId();
2166 }
2167 } else {
2168 track_id = (unsigned int)strtoul(parameters[i].m_Value.GetChars(), NULL, 10);
2169 if (track_id == 0) {
2170 fprintf(stderr, "ERROR: invalid track ID specified");
2171 return;
2172 }
2173 }
2174 }
2175 }
2176
2177 if (Options.verbose) {
2178 if (track_id == 0) {
2179 printf("MP4 Import: importing all tracks from %s\n", input_name);
2180 } else {
2181 printf("MP4 Import: importing track %d from %s\n", track_id, input_name);
2182 }
2183 }
2184
2185 AP4_List<AP4_Track>::Item* track_item = input_movie->GetTracks().FirstItem();
2186 while (track_item) {
2187 AP4_Track* track = track_item->GetData();
2188 if (track_id == 0 || track->GetId() == track_id) {
2189 track = track->Clone();
2190
2191 // reset the track ID so that it can be re-assigned
2192 track->SetId(0);
2193
2194 // override the language if specified in the parameters
2195 if (language) {
2196 track->SetTrackLanguage(language);
2197 }
2198
2199 movie.AddTrack(track);
2200 }
2201 track_item = track_item->GetNext();
2202 }
2203 }
2204
2205 /*----------------------------------------------------------------------
2206 | main
2207 +---------------------------------------------------------------------*/
2208 int
2209 main(int argc, char** argv)
2210 {
2211 if (argc < 2) {
2212 PrintUsageAndExit();
2213 }
2214 Options.verbose = false;
2215
2216 const char* output_filename = NULL;
2217 AP4_Array<char*> input_names;
2218
2219 while (char* arg = *++argv) {
2220 if (!strcmp(arg, "--verbose")) {
2221 Options.verbose = true;
2222 } else if (!strcmp(arg, "--track")) {
2223 input_names.Append(*++argv);
2224 } else if (output_filename == NULL) {
2225 output_filename = arg;
2226 } else {
2227 fprintf(stderr, "ERROR: unexpected argument '%s'\n", arg);
2228 return 1;
2229 }
2230 }
2231
2232 if (input_names.ItemCount() == 0) {
2233 fprintf(stderr, "ERROR: no input\n");
2234 return 1;
2235 }
2236 if (output_filename == NULL) {
2237 fprintf(stderr, "ERROR: output filename missing\n");
2238 return 1;
2239 }
2240
2241 // create the movie object to hold the tracks
2242 AP4_UI64 creation_time = 0;
2243 time_t now = time(NULL);
2244 if (now != (time_t)-1) {
2245 // adjust the time based on the MPEG time origin
2246 creation_time = (AP4_UI64)now + 0x7C25B080;
2247 }
2248 AP4_Movie* movie = new AP4_Movie(0, 0, creation_time, creation_time);
2249
2250 // setup the brands
2251 AP4_Array<AP4_UI32> brands;
2252 brands.Append(AP4_FILE_BRAND_ISOM);
2253 brands.Append(AP4_FILE_BRAND_MP42);
2254
2255 // create a temp file to store the sample data
2256 SampleFileStorage* sample_storage = NULL;
2257 AP4_Result result = SampleFileStorage::Create(output_filename, sample_storage);
2258 if (AP4_FAILED(result)) {
2259 fprintf(stderr, "ERROR: failed to create temporary sample data storage (%d)\n", result);
2260 return 1;
2261 }
2262
2263 // add all the tracks
2264 bool hasDovi = false;
2265 AP4_UI08 dolby_vision_ccid = 0;
2266 for (unsigned int i=0; i<input_names.ItemCount(); i++) {
2267 char* input_name = input_names[i];
2268 const char* input_type = NULL;
2269 char* input_params = NULL;
2270
2271 char* separator = strchr(input_name, ':');
2272 if (separator) {
2273 input_type = input_name;
2274 input_name = separator+1;
2275 *separator = '\0';
2276 }
2277 separator = strchr(input_name, '#');
2278 if (separator) {
2279 input_params = separator+1;
2280 *separator = '\0';
2281 }
2282
2283 if (input_type == NULL) {
2284 // no type, try to guess
2285 separator = strrchr(input_name, '.');
2286 if (separator) {
2287 input_type = separator+1;
2288 for (unsigned int j=1; separator[j]; j++) {
2289 separator[j] = (char)tolower(separator[j]);
2290 }
2291 if (!strcmp("264", input_type)) {
2292 input_type = "h264";
2293 } else if (!strcmp("avc", input_type)) {
2294 input_type = "h264";
2295 } else if (!strcmp("265", input_type)) {
2296 input_type = "h265";
2297 } else if (!strcmp("hevc", input_type)) {
2298 input_type = "h265";
2299 } else if (!strcmp("adts", input_type)) {
2300 input_type = "aac";
2301 } else if (!strcmp("m4a", input_type) ||
2302 !strcmp("m4v", input_type) ||
2303 !strcmp("mov", input_type)) {
2304 input_type = "aac";
2305 }
2306 } else {
2307 fprintf(stderr, "ERROR: unable to determine type for input '%s'\n", input_name);
2308 delete sample_storage;
2309 return 1;
2310 }
2311 }
2312
2313 // parse parameters
2314 AP4_Array<Parameter> parameters;
2315 if (input_params) {
2316 ParseParameters(input_params, parameters);
2317 }
2318
2319 bool isDovi = false;
2320 for (unsigned int i=0; i<parameters.ItemCount(); i++) {
2321 if (parameters[i].m_Name == "dv_profile") {
2322 isDovi = true;
2323 }
2324 if (parameters[i].m_Name == "dv_bc") {
2325 if (parameters[i].m_Value == "1") {
2326 dolby_vision_ccid |= 0x1;
2327 } else if (parameters[i].m_Value == "2") {
2328 dolby_vision_ccid |= 0x2;
2329 } else if (parameters[i].m_Value == "4") {
2330 dolby_vision_ccid |= 0x4;
2331 }
2332 }
2333 }
2334
2335 if (!strcmp(input_type, "h264")) {
2336 if (isDovi) {
2337 if (CheckDoviInputParameters(parameters) != AP4_SUCCESS) {
2338 fprintf(stderr, "ERROR: dolby vision input parameter error\n");
2339 delete sample_storage;
2340 return 1;
2341 } else {
2342 AddH264DoviTrack(*movie, input_name, parameters, brands, *sample_storage);
2343 hasDovi = true;
2344 }
2345 } else {
2346 AddH264Track(*movie, input_name, parameters, brands, *sample_storage);
2347 }
2348 } else if (!strcmp(input_type, "h265")) {
2349 if (isDovi) {
2350 if (CheckDoviInputParameters(parameters) != AP4_SUCCESS) {
2351 fprintf(stderr, "ERROR: dolby vision input parameter error\n");
2352 delete sample_storage;
2353 return 1;
2354 } else {
2355 AddH265DoviTrack(*movie, input_name, parameters, brands, *sample_storage);
2356 hasDovi = true;
2357 }
2358 } else {
2359 AddH265Track(*movie, input_name, parameters, brands, *sample_storage);
2360 }
2361 } else if (!strcmp(input_type, "aac")) {
2362 AddAacTrack(*movie, input_name, parameters, *sample_storage);
2363 } else if (!strcmp(input_type, "ac3")) {
2364 AddAc3Track(*movie, input_name, parameters, *sample_storage);
2365 } else if (!strcmp(input_type, "ec3")) {
2366 AddEac3Track(*movie, input_name, parameters, *sample_storage);
2367 } else if (!strcmp(input_type, "ac4")) {
2368 AddAc4Track(*movie, input_name, parameters, *sample_storage);
2369 } else if (!strcmp(input_type, "mp4")) {
2370 AddMp4Tracks(*movie, input_name, parameters, brands);
2371 } else {
2372 fprintf(stderr, "ERROR: unsupported input type '%s'\n", input_type);
2373 delete sample_storage;
2374 return 1;
2375 }
2376 }
2377
2378 // for Dolby Vision, add the 'dby1' brand
2379 if (hasDovi) {
2380 brands.Append(AP4_FILE_BRAND_DBY1);
2381 }
2382 // brand of Dolby Vision with CCID == 4 needs transfer characteristic to be decided later
2383 if (dolby_vision_ccid & 0x1) {
2384 brands.Append(AP4_FILE_BRAND_DB1P);
2385 }
2386 if (dolby_vision_ccid & 0x2) {
2387 brands.Append(AP4_FILE_BRAND_DB2G);
2388 }
2389
2390 movie->GetMvhdAtom()->SetNextTrackId(movie->GetTracks().ItemCount() + 1);
2391
2392 // open the output
2393 AP4_ByteStream* output = NULL;
2394 result = AP4_FileByteStream::Create(output_filename, AP4_FileByteStream::STREAM_MODE_WRITE, output);
2395 if (AP4_FAILED(result)) {
2396 AP4_Debug("ERROR: cannot open output '%s' (%d)\n", output_filename, result);
2397 delete sample_storage;
2398 return 1;
2399 }
2400
2401 {
2402 // create a multimedia file
2403 AP4_File file(movie);
2404
2405 // set the file type
2406 file.SetFileType(AP4_FILE_BRAND_MP42, 1, &brands[0], brands.ItemCount());
2407
2408 // write the file to the output
2409 AP4_FileWriter::Write(file, *output);
2410 }
2411
2412 // cleanup
2413 delete sample_storage;
2414 output->Release();
2415
2416 return 0;
2417 }