Debian Codegraph @

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

raw symbols SCIP
1 /*****************************************************************
2 |
3 | AP4 - MP4 to HLS File Converter
4 |
5 | Copyright 2002-2018 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
35 #include "Ap4.h"
36 #include "Ap4StreamCipher.h"
37 #include "Ap4Mp4AudioInfo.h"
38
39 /*----------------------------------------------------------------------
40 | constants
41 +---------------------------------------------------------------------*/
42 #define BANNER "MP4 To HLS File Converter - Version 1.2\n"\
43 "(Bento4 Version " AP4_VERSION_STRING ")\n"\
44 "(c) 2002-2018 Axiomatic Systems, LLC"
45
46 /*----------------------------------------------------------------------
47 | options
48 +---------------------------------------------------------------------*/
49 typedef enum {
50 ENCRYPTION_MODE_NONE,
51 ENCRYPTION_MODE_AES_128,
52 ENCRYPTION_MODE_SAMPLE_AES
53 } EncryptionMode;
54
55 typedef enum {
56 ENCRYPTION_IV_MODE_NONE,
57 ENCRYPTION_IV_MODE_SEQUENCE,
58 ENCRYPTION_IV_MODE_RANDOM,
59 ENCRYPTION_IV_MODE_FPS
60 } EncryptionIvMode;
61
62 typedef enum {
63 AUDIO_FORMAT_TS,
64 AUDIO_FORMAT_PACKED
65 } AudioFormat;
66
67 static struct _Options {
68 const char* input;
69 bool verbose;
70 unsigned int hls_version;
71 unsigned int pmt_pid;
72 unsigned int audio_pid;
73 unsigned int video_pid;
74 int audio_track_id;
75 int video_track_id;
76 AudioFormat audio_format;
77 const char* index_filename;
78 const char* iframe_index_filename;
79 bool output_single_file;
80 bool show_info;
81 const char* segment_filename_template;
82 const char* segment_url_template;
83 unsigned int segment_duration;
84 unsigned int segment_duration_threshold;
85 const char* allow_cache;
86 const char* encryption_key_hex;
87 AP4_UI08 encryption_key[16];
88 AP4_UI08 encryption_iv[16];
89 EncryptionMode encryption_mode;
90 EncryptionIvMode encryption_iv_mode;
91 const char* encryption_key_uri;
92 const char* encryption_key_format;
93 const char* encryption_key_format_versions;
94 AP4_Array<AP4_String> encryption_key_lines;
95 AP4_UI64 pcr_offset;
96 } Options;
97
98 static struct _Stats {
99 AP4_UI64 segments_total_size;
100 double segments_total_duration;
101 AP4_UI32 segment_count;
102 double max_segment_bitrate;
103 AP4_UI64 iframes_total_size;
104 AP4_UI32 iframe_count;
105 double max_iframe_bitrate;
106 } Stats;
107
108 /*----------------------------------------------------------------------
109 | constants
110 +---------------------------------------------------------------------*/
111 static const unsigned int DefaultSegmentDurationThreshold = 15; // milliseconds
112
113 const AP4_UI08 AP4_MPEG2_STREAM_TYPE_SAMPLE_AES_AVC = 0xDB;
114 const AP4_UI08 AP4_MPEG2_STREAM_TYPE_SAMPLE_AES_ISO_IEC_13818_7 = 0xCF;
115 const AP4_UI08 AP4_MPEG2_STREAM_TYPE_SAMPLE_AES_ATSC_AC3 = 0xC1;
116 const AP4_UI08 AP4_MPEG2_STREAM_TYPE_SAMPLE_AES_ATSC_EAC3 = 0xC2;
117 const AP4_UI08 AP4_MPEG2_PRIVATE_DATA_INDICATOR_DESCRIPTOR_TAG = 15;
118 const AP4_UI08 AP4_MPEG2_REGISTRATION_DESCRIPTOR_TAG = 5;
119
120 /*----------------------------------------------------------------------
121 | PrintUsageAndExit
122 +---------------------------------------------------------------------*/
123 static void
124 PrintUsageAndExit()
125 {
126 fprintf(stderr,
127 BANNER
128 "\n\nusage: mp42hls [options] <input>\n"
129 "Options:\n"
130 " --verbose\n"
131 " --show-info\n"
132 " --hls-version <n> (default: 3)\n"
133 " --pmt-pid <pid>\n"
134 " PID to use for the PMT (default: 0x100)\n"
135 " --audio-pid <pid>\n"
136 " PID to use for audio packets (default: 0x101)\n"
137 " --video-pid <pid>\n"
138 " PID to use for video packets (default: 0x102)\n"
139 " --audio-track-id <n>\n"
140 " Read audio from track ID <n> (0 means no audio)\n"
141 " --video-track-id <n>\n"
142 " Read video from track ID <n> (0 means no video)\n"
143 " --audio-format <format>\n"
144 " Format to use for audio-only segments: 'ts' or 'packed' (default: 'ts')\n"
145 " --segment-duration <n>\n"
146 " Target segment duration in seconds (default: 6)\n"
147 " --segment-duration-threshold <t>\n"
148 " Segment duration threshold in milliseconds (default: 15)\n"
149 " --pcr-offset <offset> in units of 90kHz (default 10000)\n"
150 " --index-filename <filename>\n"
151 " Filename to use for the playlist/index (default: stream.m3u8)\n"
152 " --allow-cache <YES|NO>\n"
153 " set #EXT-X-ALLOW-CACHE to YES or NO\n"
154 " --segment-filename-template <pattern>\n"
155 " Filename pattern to use for the segments. Use a printf-style pattern with\n"
156 " one number field for the segment number, unless using single file mode\n"
157 " (default: segment-%%d.<ext> for separate segment files, or stream.<ext> for single file)\n"
158 " --segment-url-template <pattern>\n"
159 " URL pattern to use for the segments. Use a printf-style pattern with\n"
160 " one number field for the segment number unless unsing single file mode.\n"
161 " (may be a relative or absolute URI).\n"
162 " (default: segment-%%d.<ext> for separate segment files, or stream.<ext> for single file)\n"
163 " --iframe-index-filename <filename>\n"
164 " Filename to use for the I-Frame playlist (default: iframes.m3u8 when HLS version >= 4)\n"
165 " --output-single-file\n"
166 " Output all the media in a single file instead of separate segment files.\n"
167 " The segment filename template and segment URL template must be simple strings\n"
168 " without '%%d' or other printf-style patterns\n"
169 " --encryption-mode <mode>\n"
170 " Encryption mode (only used when --encryption-key is specified). AES-128 or SAMPLE-AES (default: AES-128)\n"
171 " --encryption-key <key>\n"
172 " Encryption key in hexadecimal (default: no encryption)\n"
173 " --encryption-iv-mode <mode>\n"
174 " Encryption IV mode: 'sequence', 'random' or 'fps' (FairPlay Streaming) (default: sequence)\n"
175 " (when the mode is 'fps', the encryption key must be 32 bytes: 16 bytes for the key\n"
176 " followed by 16 bytes for the IV).\n"
177 " --encryption-key-uri <uri>\n"
178 " Encryption key URI (may be a realtive or absolute URI). (default: key.bin)\n"
179 " --encryption-key-format <format>\n"
180 " Encryption key format. (default: 'identity')\n"
181 " --encryption-key-format-versions <versions>\n"
182 " Encryption key format versions.\n"
183 " --encryption-key-line <ext-x-key-line>\n"
184 " Preformatted encryption key line (only the portion after the #EXT-X-KEY: tag).\n"
185 " This option can be used multiple times, once for each preformatted key line to be included in the playlist.\n"
186 " (this option is mutually exclusive with the --encryption-key-uri, --encryption-key-format and --encryption-key-format-versions options)\n"
187 " (the IV and METHOD parameters will automatically be added, so they must not appear in the <ext-x-key-line> argument)\n"
188 );
189 exit(1);
190 }
191
192 /*----------------------------------------------------------------------
193 | SampleReader
194 +---------------------------------------------------------------------*/
195 class SampleReader
196 {
197 public:
198 virtual ~SampleReader() {}
199 virtual AP4_Result ReadSample(AP4_Sample& sample, AP4_DataBuffer& sample_data) = 0;
200 };
201
202 /*----------------------------------------------------------------------
203 | TrackSampleReader
204 +---------------------------------------------------------------------*/
205 class TrackSampleReader : public SampleReader
206 {
207 public:
208 TrackSampleReader(AP4_Track& track) : m_Track(track), m_SampleIndex(0) {}
209 AP4_Result ReadSample(AP4_Sample& sample, AP4_DataBuffer& sample_data);
210
211 private:
212 AP4_Track& m_Track;
213 AP4_Ordinal m_SampleIndex;
214 };
215
216 /*----------------------------------------------------------------------
217 | TrackSampleReader
218 +---------------------------------------------------------------------*/
219 AP4_Result
220 TrackSampleReader::ReadSample(AP4_Sample& sample, AP4_DataBuffer& sample_data)
221 {
222 if (m_SampleIndex >= m_Track.GetSampleCount()) return AP4_ERROR_EOS;
223 return m_Track.ReadSample(m_SampleIndex++, sample, sample_data);
224 }
225
226 /*----------------------------------------------------------------------
227 | FragmentedSampleReader
228 +---------------------------------------------------------------------*/
229 class FragmentedSampleReader : public SampleReader
230 {
231 public:
232 FragmentedSampleReader(AP4_LinearReader& fragment_reader, AP4_UI32 track_id) :
233 m_FragmentReader(fragment_reader), m_TrackId(track_id) {
234 fragment_reader.EnableTrack(track_id);
235 }
236 AP4_Result ReadSample(AP4_Sample& sample, AP4_DataBuffer& sample_data);
237
238 private:
239 AP4_LinearReader& m_FragmentReader;
240 AP4_UI32 m_TrackId;
241 };
242
243 /*----------------------------------------------------------------------
244 | FragmentedSampleReader
245 +---------------------------------------------------------------------*/
246 AP4_Result
247 FragmentedSampleReader::ReadSample(AP4_Sample& sample, AP4_DataBuffer& sample_data)
248 {
249 return m_FragmentReader.ReadNextSample(m_TrackId, sample, sample_data);
250 }
251
252 /*----------------------------------------------------------------------
253 | OpenOutput
254 +---------------------------------------------------------------------*/
255 static AP4_ByteStream*
256 OpenOutput(const char* filename_pattern, unsigned int segment_number)
257 {
258 AP4_ByteStream* output = NULL;
259 char filename[4096];
260 sprintf(filename, filename_pattern, segment_number);
261 AP4_Result result = AP4_FileByteStream::Create(filename, AP4_FileByteStream::STREAM_MODE_WRITE, output);
262 if (AP4_FAILED(result)) {
263 fprintf(stderr, "ERROR: cannot open output (%d)\n", result);
264 return NULL;
265 }
266
267 return output;
268 }
269
270 /*----------------------------------------------------------------------
271 | PreventStartCodeEmulation
272 +---------------------------------------------------------------------*/
273 static void
274 PreventStartCodeEmulation(const AP4_UI08* payload, AP4_Size payload_size, AP4_DataBuffer& output)
275 {
276 output.Reserve(payload_size*2); // more than enough
277 AP4_Size output_size = 0;
278 AP4_UI08* buffer = output.UseData();
279
280 unsigned int zero_counter = 0;
281 for (unsigned int i = 0; i < payload_size; i++) {
282 if (zero_counter == 2) {
283 if (payload[i] == 0 || payload[i] == 1 || payload[i] == 2 || payload[i] == 3) {
284 buffer[output_size++] = 3;
285 zero_counter = 0;
286 }
287 }
288
289 buffer[output_size++] = payload[i];
290
291 if (payload[i] == 0) {
292 ++zero_counter;
293 } else {
294 zero_counter = 0;
295 }
296 }
297
298 output.SetDataSize(output_size);
299 }
300
301 /*----------------------------------------------------------------------
302 | EncryptingStream
303 +---------------------------------------------------------------------*/
304 class EncryptingStream: public AP4_ByteStream {
305 public:
306 static AP4_Result Create(const AP4_UI08* key, const AP4_UI08* iv, AP4_ByteStream* output, EncryptingStream*& stream);
307 virtual AP4_Result ReadPartial(void* , AP4_Size, AP4_Size&) {
308 return AP4_ERROR_NOT_SUPPORTED;
309 }
310 virtual AP4_Result WritePartial(const void* buffer,
311 AP4_Size bytes_to_write,
312 AP4_Size& bytes_written) {
313 AP4_UI08* out = new AP4_UI08[bytes_to_write+16];
314 AP4_Size out_size = bytes_to_write+16;
315 AP4_Result result = m_StreamCipher->ProcessBuffer((const AP4_UI08*)buffer,
316 bytes_to_write,
317 out,
318 &out_size);
319 if (AP4_SUCCEEDED(result)) {
320 result = m_Output->Write(out, out_size);
321 bytes_written = bytes_to_write;
322 m_Size += bytes_to_write;
323 } else {
324 bytes_written = 0;
325 }
326 delete[] out;
327 return result;
328 }
329 virtual AP4_Result Flush() {
330 AP4_UI08 trailer[16];
331 AP4_Size trailer_size = sizeof(trailer);
332 AP4_Result result = m_StreamCipher->ProcessBuffer(NULL, 0, trailer, &trailer_size, true);
333 if (AP4_SUCCEEDED(result) && trailer_size) {
334 m_Output->Write(trailer, trailer_size);
335 m_Size += 16-(m_Size%16);
336 }
337
338 return AP4_SUCCESS;
339 }
340 virtual AP4_Result Seek(AP4_Position) { return AP4_ERROR_NOT_SUPPORTED; }
341 virtual AP4_Result Tell(AP4_Position& position) { position = m_Size; return AP4_SUCCESS; }
342 virtual AP4_Result GetSize(AP4_LargeSize& size) { size = m_Size; return AP4_SUCCESS; }
343
344 void AddReference() {
345 ++m_ReferenceCount;
346 }
347 void Release() {
348 if (--m_ReferenceCount == 0) {
349 delete this;
350 }
351 }
352
353 private:
354 EncryptingStream(AP4_CbcStreamCipher* stream_cipher, AP4_ByteStream* output):
355 m_ReferenceCount(1),
356 m_StreamCipher(stream_cipher),
357 m_Output(output),
358 m_Size(0) {
359 output->AddReference();
360 }
361 ~EncryptingStream() {
362 m_Output->Release();
363 delete m_StreamCipher;
364 }
365 unsigned int m_ReferenceCount;
366 AP4_CbcStreamCipher* m_StreamCipher;
367 AP4_ByteStream* m_Output;
368 AP4_LargeSize m_Size;
369 };
370
371 /*----------------------------------------------------------------------
372 | EncryptingStream::Create
373 +---------------------------------------------------------------------*/
374 AP4_Result
375 EncryptingStream::Create(const AP4_UI08* key, const AP4_UI08* iv, AP4_ByteStream* output, EncryptingStream*& stream) {
376 stream = NULL;
377 AP4_BlockCipher* block_cipher = NULL;
378 AP4_Result result = AP4_DefaultBlockCipherFactory::Instance.CreateCipher(AP4_BlockCipher::AES_128,
379 AP4_BlockCipher::ENCRYPT,
380 AP4_BlockCipher::CBC,
381 NULL,
382 key,
383 16,
384 block_cipher);
385 if (AP4_FAILED(result)) return result;
386 AP4_CbcStreamCipher* stream_cipher = new AP4_CbcStreamCipher(block_cipher);
387 stream_cipher->SetIV(iv);
388 stream = new EncryptingStream(stream_cipher, output);
389
390 return AP4_SUCCESS;
391 }
392
393 /*----------------------------------------------------------------------
394 | SampleEncrypter
395 +---------------------------------------------------------------------*/
396 class SampleEncrypter {
397 public:
398 static AP4_Result Create(const AP4_UI08* key, const AP4_UI08* iv, SampleEncrypter*& encrypter);
399 ~SampleEncrypter() {
400 delete m_StreamCipher;
401 }
402
403 AP4_Result EncryptAudioSample(AP4_DataBuffer& sample, AP4_SampleDescription* sample_description);
404 AP4_Result EncryptVideoSample(AP4_DataBuffer& sample, AP4_UI08 nalu_length_size);
405
406 private:
407 SampleEncrypter(AP4_CbcStreamCipher* stream_cipher, const AP4_UI08* iv):
408 m_StreamCipher(stream_cipher) {
409 AP4_CopyMemory(m_IV, iv, 16);
410 }
411
412 AP4_CbcStreamCipher* m_StreamCipher;
413 AP4_UI08 m_IV[16];
414 };
415
416 /*----------------------------------------------------------------------
417 | SampleEncrypter::Create
418 +---------------------------------------------------------------------*/
419 AP4_Result
420 SampleEncrypter::Create(const AP4_UI08* key, const AP4_UI08* iv, SampleEncrypter*& encrypter) {
421 encrypter = NULL;
422 AP4_BlockCipher* block_cipher = NULL;
423 AP4_Result result = AP4_DefaultBlockCipherFactory::Instance.CreateCipher(AP4_BlockCipher::AES_128,
424 AP4_BlockCipher::ENCRYPT,
425 AP4_BlockCipher::CBC,
426 NULL,
427 key,
428 16,
429 block_cipher);
430 if (AP4_FAILED(result)) return result;
431 AP4_CbcStreamCipher* stream_cipher = new AP4_CbcStreamCipher(block_cipher);
432 encrypter = new SampleEncrypter(stream_cipher, iv);
433
434 return AP4_SUCCESS;
435 }
436
437 /*----------------------------------------------------------------------
438 | SampleEncrypter::EncryptAudioSample
439 |
440 | AAC: entire frame
441 | ADTS_header // 7 or 9
442 | unencrypted_leader // 16 bytes
443 | while (bytes_remaining() >= 16) {
444 | protected_block // 16 bytes
445 | }
446 | unencrypted_trailer // 0-15 bytes
447 |
448 | AC3: entire frame
449 | unencrypted_leader // 16 bytes
450 | while (bytes_remaining() >= 16) {
451 | encrypted_block // 16 bytes
452 | }
453 | unencrypted_trailer // 0-15 bytes
454 |
455 | E-AC3: each syncframe
456 | unencrypted_leader // 16 bytes
457 | while (bytes_remaining() >= 16) {
458 | encrypted_block // 16 bytes
459 | }
460 | unencrypted_trailer // 0-15 bytes
461 |
462 +---------------------------------------------------------------------*/
463 AP4_Result
464 SampleEncrypter::EncryptAudioSample(AP4_DataBuffer& sample, AP4_SampleDescription* sample_description)
465 {
466 if (sample.GetDataSize() <= 16) {
467 return AP4_SUCCESS;
468 }
469
470 // deal with E-AC3 syncframes
471 if (sample_description->GetFormat() == AP4_SAMPLE_FORMAT_EC_3) {
472 // syncword : 16
473 // strmtyp : 2
474 // substreamid : 3
475 // frmsiz : 11
476 AP4_UI08* data = sample.UseData();
477 unsigned int data_size = sample.GetDataSize();
478 while (data_size > 4) {
479 unsigned int syncword = (data[0]<<8) | data[1];
480 if (syncword != 0x0b77) {
481 return AP4_ERROR_INVALID_FORMAT; // unexpected!
482 }
483 unsigned int frmsiz = 1+(((data[2]<<8)|(data[3]))&0x7FF);
484 unsigned int frame_size = 2*frmsiz;
485 if (data_size < frame_size) {
486 return AP4_ERROR_INVALID_FORMAT; // unexpected!
487 }
488
489 // encrypt the syncframe
490 if (frame_size > 16) {
491 unsigned int encrypted_block_count = (frame_size-16)/16;
492 AP4_Size encrypted_size = encrypted_block_count*16;
493 m_StreamCipher->SetIV(m_IV);
494 m_StreamCipher->ProcessBuffer(data+16, encrypted_size, data+16, &encrypted_size);
495 }
496
497 data += frame_size;
498 data_size -= frame_size;
499 }
500 } else {
501 unsigned int encrypted_block_count = (sample.GetDataSize()-16)/16;
502 AP4_Size encrypted_size = encrypted_block_count*16;
503 m_StreamCipher->SetIV(m_IV);
504 m_StreamCipher->ProcessBuffer(sample.UseData()+16, encrypted_size, sample.UseData()+16, &encrypted_size);
505 }
506
507 return AP4_SUCCESS;
508 }
509
510 /*----------------------------------------------------------------------
511 | SampleEncrypter::EncryptVideoSample
512 |
513 | Sequence of NAL Units:
514 | NAL_unit_type_byte // 1 byte
515 | unencrypted_leader // 31 bytes
516 | while (bytes_remaining() > 16) {
517 | protected_block_one_in_ten // 16 bytes
518 | }
519 | unencrypted_trailer // 1-16 bytes
520 +---------------------------------------------------------------------*/
521 AP4_Result
522 SampleEncrypter::EncryptVideoSample(AP4_DataBuffer& sample, AP4_UI08 nalu_length_size)
523 {
524 AP4_DataBuffer encrypted;
525
526 AP4_UI08* nalu = sample.UseData();
527 AP4_Size bytes_remaining = sample.GetDataSize();
528 while (bytes_remaining > nalu_length_size) {
529 AP4_Size nalu_length = 0;
530 switch (nalu_length_size) {
531 case 1:
532 nalu_length = nalu[0];
533 break;
534
535 case 2:
536 nalu_length = AP4_BytesToUInt16BE(nalu);
537 break;
538
539 case 4:
540 nalu_length = AP4_BytesToUInt32BE(nalu);
541 break;
542
543 default:
544 break;
545 }
546
547 if (bytes_remaining < nalu_length_size+nalu_length) {
548 break;
549 }
550
551 AP4_UI08 nalu_type = nalu[nalu_length_size] & 0x1F;
552 if (nalu_length > 48 && (nalu_type == 1 || nalu_type == 5)) {
553 AP4_Size encrypted_size = 16*((nalu_length-32)/16);
554 if ((nalu_length%16) == 0) {
555 encrypted_size -= 16;
556 }
557 m_StreamCipher->SetIV(m_IV);
558 for (unsigned int i=0; i<encrypted_size; i += 10*16) {
559 AP4_Size one_block_size = 16;
560 m_StreamCipher->ProcessBuffer(nalu+nalu_length_size+32+i, one_block_size,
561 nalu+nalu_length_size+32+i, &one_block_size);
562 }
563
564 // perform startcode emulation prevention
565 AP4_DataBuffer escaped_nalu;
566 PreventStartCodeEmulation(nalu+nalu_length_size, nalu_length, escaped_nalu);
567
568 // the size may have changed
569 // TODO: this could overflow if nalu_length_size is too small
570 switch (nalu_length_size) {
571 case 1:
572 nalu[0] = (AP4_UI08)(escaped_nalu.GetDataSize()&0xFF);
573 break;
574
575 case 2:
576 AP4_BytesFromUInt16BE(nalu, escaped_nalu.GetDataSize());
577 break;
578
579 case 4:
580 AP4_BytesFromUInt32BE(nalu, escaped_nalu.GetDataSize());
581 break;
582
583 default:
584 break;
585 }
586
587 encrypted.AppendData(nalu, nalu_length_size);
588 encrypted.AppendData(escaped_nalu.GetData(), escaped_nalu.GetDataSize());
589 } else {
590 encrypted.AppendData(nalu, nalu_length_size);
591 encrypted.AppendData(nalu+nalu_length_size, nalu_length);
592 }
593
594 nalu += nalu_length_size+nalu_length;
595 bytes_remaining -= nalu_length_size+nalu_length;
596 }
597
598 sample.SetData(encrypted.GetData(), encrypted.GetDataSize());
599
600 return AP4_SUCCESS;
601 }
602
603 /*----------------------------------------------------------------------
604 | GetSamplingFrequencyIndex
605 +---------------------------------------------------------------------*/
606 static unsigned int
607 GetSamplingFrequencyIndex(unsigned int sampling_frequency)
608 {
609 switch (sampling_frequency) {
610 case 96000: return 0;
611 case 88200: return 1;
612 case 64000: return 2;
613 case 48000: return 3;
614 case 44100: return 4;
615 case 32000: return 5;
616 case 24000: return 6;
617 case 22050: return 7;
618 case 16000: return 8;
619 case 12000: return 9;
620 case 11025: return 10;
621 case 8000: return 11;
622 case 7350: return 12;
623 default: return 0;
624 }
625 }
626
627 /*----------------------------------------------------------------------
628 | WriteAdtsHeader
629 +---------------------------------------------------------------------*/
630 static AP4_Result
631 WriteAdtsHeader(AP4_ByteStream& output,
632 unsigned int frame_size,
633 unsigned int sampling_frequency_index,
634 unsigned int channel_configuration)
635 {
636 unsigned char bits[7];
637
638 bits[0] = 0xFF;
639 bits[1] = 0xF1; // 0xF9 (MPEG2)
640 bits[2] = 0x40 | (sampling_frequency_index << 2) | (channel_configuration >> 2);
641 bits[3] = ((channel_configuration&0x3)<<6) | ((frame_size+7) >> 11);
642 bits[4] = ((frame_size+7) >> 3)&0xFF;
643 bits[5] = (((frame_size+7) << 5)&0xFF) | 0x1F;
644 bits[6] = 0xFC;
645
646 return output.Write(bits, 7);
647
648 /*
649 0: syncword 12 always: '111111111111'
650 12: ID 1 0: MPEG-4, 1: MPEG-2
651 13: layer 2 always: '00'
652 15: protection_absent 1
653 16: profile 2
654 18: sampling_frequency_index 4
655 22: private_bit 1
656 23: channel_configuration 3
657 26: original/copy 1
658 27: home 1
659 28: emphasis 2 only if ID == 0
660
661 ADTS Variable header: these can change from frame to frame
662 28: copyright_identification_bit 1
663 29: copyright_identification_start 1
664 30: aac_frame_length 13 length of the frame including header (in bytes)
665 43: adts_buffer_fullness 11 0x7FF indicates VBR
666 54: no_raw_data_blocks_in_frame 2
667 ADTS Error check
668 crc_check 16 only if protection_absent == 0
669 */
670 }
671
672 /*----------------------------------------------------------------------
673 | WriteAc4Header
674 +---------------------------------------------------------------------*/
675 static AP4_Result
676 WriteAc4Header(AP4_ByteStream& output,
677 unsigned int frame_size)
678 {
679 unsigned char bits[7];
680
681 bits[0] = 0xac;
682 bits[1] = 0x40;
683 bits[2] = 0xff;
684 bits[3] = 0xff;
685 bits[4] = (frame_size>>16)&0xFF;
686 bits[5] = (frame_size>>8 )&0xFF;
687 bits[6] = (frame_size )&0xFF;
688
689 return output.Write(bits, 7);
690 }
691
692 /*----------------------------------------------------------------------
693 | MakeAudioSetupData
694 +---------------------------------------------------------------------*/
695 static AP4_Result
696 MakeAudioSetupData(AP4_DataBuffer& audio_setup_data,
697 AP4_SampleDescription* sample_description,
698 AP4_DataBuffer& sample_data /* needed for encrypted AC3 */)
699 {
700 AP4_UI08 audio_type[4];
701 AP4_DataBuffer setup_data;
702
703 if (sample_description->GetFormat() == AP4_SAMPLE_FORMAT_MP4A) {
704 AP4_MpegAudioSampleDescription* mpeg_audio_desc = AP4_DYNAMIC_CAST(AP4_MpegAudioSampleDescription, sample_description);
705 if (mpeg_audio_desc == NULL ||
706 !(mpeg_audio_desc->GetObjectTypeId() == AP4_OTI_MPEG4_AUDIO ||
707 mpeg_audio_desc->GetObjectTypeId() == AP4_OTI_MPEG2_AAC_AUDIO_LC ||
708 mpeg_audio_desc->GetObjectTypeId() == AP4_OTI_MPEG2_AAC_AUDIO_MAIN)) {
709 return AP4_ERROR_NOT_SUPPORTED;
710 }
711 const AP4_DataBuffer& dsi = mpeg_audio_desc->GetDecoderInfo();
712 setup_data.SetData(dsi.GetData(), dsi.GetDataSize());
713
714 AP4_Mp4AudioDecoderConfig dec_config;
715 AP4_Result result = dec_config.Parse(dsi.GetData(), dsi.GetDataSize());
716 if (AP4_FAILED(result)) {
717 return AP4_ERROR_INVALID_FORMAT;
718 }
719
720 if (dec_config.m_Extension.m_SbrPresent || dec_config.m_Extension.m_PsPresent) {
721 if (dec_config.m_Extension.m_PsPresent) {
722 audio_type[0] = 'z';
723 audio_type[1] = 'a';
724 audio_type[2] = 'c';
725 audio_type[3] = 'p';
726 } else {
727 audio_type[0] = 'z';
728 audio_type[1] = 'a';
729 audio_type[2] = 'c';
730 audio_type[3] = 'h';
731 }
732 } else {
733 audio_type[0] = 'z';
734 audio_type[1] = 'a';
735 audio_type[2] = 'a';
736 audio_type[3] = 'c';
737 }
738 } else if (sample_description->GetFormat() == AP4_SAMPLE_FORMAT_AC_3) {
739 audio_type[0] = 'z';
740 audio_type[1] = 'a';
741 audio_type[2] = 'c';
742 audio_type[3] = '3';
743
744 // the setup data is the first 10 bytes of a syncframe
745 if (sample_data.GetDataSize() >= 10) {
746 setup_data.SetData(sample_data.GetData(), 10);
747 }
748 } else if (sample_description->GetFormat() == AP4_SAMPLE_FORMAT_EC_3) {
749 audio_type[0] = 'z';
750 audio_type[1] = 'e';
751 audio_type[2] = 'c';
752 audio_type[3] = '3';
753
754 AP4_Dec3Atom* dec3 = AP4_DYNAMIC_CAST(AP4_Dec3Atom, sample_description->GetDetails().GetChild(AP4_ATOM_TYPE_DEC3));
755 if (dec3 == NULL) {
756 fprintf(stderr, "ERROR: failed to find 'dec3' atom in sample description\n");
757 return 1;
758 }
759 setup_data.SetData(dec3->GetRawBytes().GetData(), dec3->GetRawBytes().GetDataSize());
760 } else {
761 return AP4_SUCCESS;
762 }
763
764 audio_setup_data.SetDataSize(8+setup_data.GetDataSize());
765 AP4_UI08* payload = audio_setup_data.UseData();
766 payload[0] = audio_type[0];
767 payload[1] = audio_type[1];
768 payload[2] = audio_type[2];
769 payload[3] = audio_type[3];
770 payload[4] = 0; // priming
771 payload[5] = 0; // priming
772 payload[6] = 1; // version
773 payload[7] = setup_data.GetDataSize(); // setup_data_length
774 if (setup_data.GetDataSize()) {
775 AP4_CopyMemory(&payload[8], setup_data.GetData(), setup_data.GetDataSize());
776 }
777
778 return AP4_SUCCESS;
779 }
780
781 /*----------------------------------------------------------------------
782 | MakeSampleAesAudioDescriptor
783 +---------------------------------------------------------------------*/
784 static AP4_Result
785 MakeSampleAesAudioDescriptor(AP4_DataBuffer& descriptor,
786 AP4_SampleDescription* sample_description,
787 AP4_DataBuffer& sample_data /* needed for encrypted AC3 */)
788 {
789 // descriptor
790 descriptor.SetDataSize(6);
791 AP4_UI08* payload = descriptor.UseData();
792 payload[0] = AP4_MPEG2_PRIVATE_DATA_INDICATOR_DESCRIPTOR_TAG;
793 payload[1] = 4;
794 if (sample_description->GetFormat() == AP4_SAMPLE_FORMAT_MP4A) {
795 payload[2] = 'a';
796 payload[3] = 'a';
797 payload[4] = 'c';
798 payload[5] = 'd';
799 } else if (sample_description->GetFormat() == AP4_SAMPLE_FORMAT_AC_3) {
800 payload[2] = 'a';
801 payload[3] = 'c';
802 payload[4] = '3';
803 payload[5] = 'd';
804 } else if (sample_description->GetFormat() == AP4_SAMPLE_FORMAT_EC_3) {
805 payload[2] = 'e';
806 payload[3] = 'c';
807 payload[4] = '3';
808 payload[5] = 'd';
809 }
810
811 // compute the audio setup data
812 AP4_DataBuffer audio_setup_data;
813 AP4_Result result = MakeAudioSetupData(audio_setup_data, sample_description, sample_data);
814 if (AP4_FAILED(result)) {
815 fprintf(stderr, "ERROR: failed to make audio setup data (%d)\n", result);
816 return result;
817 }
818
819 descriptor.SetDataSize(descriptor.GetDataSize()+6+audio_setup_data.GetDataSize());
820 payload = descriptor.UseData()+6;
821 payload[0] = AP4_MPEG2_REGISTRATION_DESCRIPTOR_TAG;
822 payload[1] = 4+audio_setup_data.GetDataSize();
823 payload[2] = 'a';
824 payload[3] = 'p';
825 payload[4] = 'a';
826 payload[5] = 'd';
827 AP4_CopyMemory(&payload[6], audio_setup_data.GetData(), audio_setup_data.GetDataSize());
828
829 return AP4_SUCCESS;
830 }
831
832 /*----------------------------------------------------------------------
833 | MakeSampleAesVideoDescriptor
834 +---------------------------------------------------------------------*/
835 static AP4_Result
836 MakeSampleAesVideoDescriptor(AP4_DataBuffer& descriptor)
837 {
838 descriptor.SetDataSize(6);
839 AP4_UI08* payload = descriptor.UseData();
840 payload[0] = AP4_MPEG2_PRIVATE_DATA_INDICATOR_DESCRIPTOR_TAG;
841 payload[1] = 4;
842 payload[2] = 'z';
843 payload[3] = 'a';
844 payload[4] = 'v';
845 payload[5] = 'c';
846
847 return AP4_SUCCESS;
848 }
849
850 /*----------------------------------------------------------------------
851 | PackedAudioWriter
852 +---------------------------------------------------------------------*/
853 class PackedAudioWriter {
854 public:
855 AP4_Result WriteHeader(double timestamp,
856 const char* private_extension_name,
857 const AP4_UI08* private_extension_data,
858 unsigned int private_extension_data_size,
859 AP4_ByteStream& output);
860 AP4_Result WriteSample(AP4_Sample& sample,
861 AP4_DataBuffer& sample_data,
862 AP4_SampleDescription* sample_description,
863 AP4_ByteStream& output);
864
865 };
866
867 /*----------------------------------------------------------------------
868 | PackedAudioWriter::WriteHeader
869 +---------------------------------------------------------------------*/
870 AP4_Result
871 PackedAudioWriter::WriteHeader(double timestamp,
872 const char* private_extension_name,
873 const AP4_UI08* private_extension_data,
874 unsigned int private_extension_data_size,
875 AP4_ByteStream& output)
876 {
877 unsigned int header_size = 10+10+45+8;
878 unsigned int private_extension_name_size = private_extension_name?(unsigned int)AP4_StringLength(private_extension_name)+1:0;
879 if (private_extension_name) {
880 header_size += 10+private_extension_name_size+private_extension_data_size;;
881 }
882 AP4_UI08* header = new AP4_UI08[header_size];
883
884 /* ID3 Tag Header
885 ID3v2/file identifier "ID3"
886 ID3v2 version $04 00
887 ID3v2 flags %abcd0000
888 ID3v2 size 4 * %0xxxxxxx
889 */
890 header[0] = 'I';
891 header[1] = 'D';
892 header[2] = '3';
893 header[3] = 4;
894 header[4] = 0;
895 header[5] = 0;
896 header[6] = 0;
897 header[7] = 0;
898 header[8] = ((header_size-10)>>7) & 0x7F;
899 header[9] = (header_size-10) & 0x7F;
900
901 /* PRIV frame
902 Frame ID $xx xx xx xx (four characters)
903 Size $xx xx xx xx
904 Flags $xx xx
905
906 Owner identifier <text string> $00
907 The private data <binary data>
908 */
909 header[10] = 'P';
910 header[11] = 'R';
911 header[12] = 'I';
912 header[13] = 'V';
913 header[14] = 0;
914 header[15] = 0;
915 header[16] = 0;
916 header[17] = 45+8;
917 header[18] = 0;
918 header[19] = 0;
919 AP4_CopyMemory(&header[20], "com.apple.streaming.transportStreamTimestamp", 45);
920 AP4_UI64 mpeg_ts = (AP4_UI64)(timestamp*90000.0);
921 AP4_BytesFromUInt64BE(&header[10+10+45], mpeg_ts);
922
923 // add the extra private extension if needed
924 if (private_extension_name) {
925 AP4_UI08* ext = &header[10+10+45+8];
926 ext[0] = 'P';
927 ext[1] = 'R';
928 ext[2] = 'I';
929 ext[3] = 'V';
930 ext[4] = 0;
931 ext[5] = 0;
932 ext[6] = ((private_extension_name_size+private_extension_data_size)>>7) & 0x7F;
933 ext[7] = (private_extension_name_size+private_extension_data_size) & 0x7F;
934 ext[8] = 0;
935 ext[9] = 0;
936 AP4_CopyMemory(&ext[10], private_extension_name, private_extension_name_size);
937 AP4_CopyMemory(&ext[10+private_extension_name_size], private_extension_data, private_extension_data_size);
938 }
939
940 // write the header out
941 AP4_Result result = output.Write(header, header_size);
942 delete[] header;
943
944 return result;
945 }
946
947 /*----------------------------------------------------------------------
948 | PackedAudioWriter::WriteSample
949 +---------------------------------------------------------------------*/
950 AP4_Result
951 PackedAudioWriter::WriteSample(AP4_Sample& sample,
952 AP4_DataBuffer& sample_data,
953 AP4_SampleDescription* sample_description,
954 AP4_ByteStream& output)
955 {
956 AP4_AudioSampleDescription* audio_desc = AP4_DYNAMIC_CAST(AP4_AudioSampleDescription, sample_description);
957 if (audio_desc == NULL) {
958 return AP4_ERROR_INVALID_FORMAT;
959 }
960 if (sample_description->GetFormat() == AP4_SAMPLE_FORMAT_MP4A) {
961 AP4_MpegAudioSampleDescription* mpeg_audio_desc = AP4_DYNAMIC_CAST(AP4_MpegAudioSampleDescription, sample_description);
962
963 if (mpeg_audio_desc == NULL) return AP4_ERROR_NOT_SUPPORTED;
964 if (mpeg_audio_desc->GetMpeg4AudioObjectType() != AP4_MPEG4_AUDIO_OBJECT_TYPE_AAC_LC &&
965 mpeg_audio_desc->GetMpeg4AudioObjectType() != AP4_MPEG4_AUDIO_OBJECT_TYPE_AAC_MAIN &&
966 mpeg_audio_desc->GetMpeg4AudioObjectType() != AP4_MPEG4_AUDIO_OBJECT_TYPE_SBR &&
967 mpeg_audio_desc->GetMpeg4AudioObjectType() != AP4_MPEG4_AUDIO_OBJECT_TYPE_PS) {
968 return AP4_ERROR_NOT_SUPPORTED;
969 }
970
971 unsigned int sample_rate = mpeg_audio_desc->GetSampleRate();
972 unsigned int channel_count = mpeg_audio_desc->GetChannelCount();
973 const AP4_DataBuffer& dsi = mpeg_audio_desc->GetDecoderInfo();
974 if (dsi.GetDataSize()) {
975 AP4_Mp4AudioDecoderConfig dec_config;
976 AP4_Result result = dec_config.Parse(dsi.GetData(), dsi.GetDataSize());
977 if (AP4_SUCCEEDED(result)) {
978 sample_rate = dec_config.m_SamplingFrequency;
979 channel_count = dec_config.m_ChannelCount;
980 }
981 }
982 unsigned int sampling_frequency_index = GetSamplingFrequencyIndex(sample_rate);
983 unsigned int channel_configuration = channel_count;
984
985 WriteAdtsHeader(output, sample.GetSize(), sampling_frequency_index, channel_configuration);
986 } else if (sample_description->GetFormat() == AP4_SAMPLE_FORMAT_AC_4) {
987 WriteAc4Header(output, sample.GetSize());
988 }
989 return output.Write(sample_data.GetData(), sample_data.GetDataSize());
990 }
991
992 /*----------------------------------------------------------------------
993 | ReadSample
994 +---------------------------------------------------------------------*/
995 static AP4_Result
996 ReadSample(SampleReader& reader,
997 AP4_Track& track,
998 AP4_Sample& sample,
999 AP4_DataBuffer& sample_data,
1000 double& ts,
1001 double& duration,
1002 bool& eos)
1003 {
1004 AP4_Result result = reader.ReadSample(sample, sample_data);
1005 if (AP4_FAILED(result)) {
1006 if (result == AP4_ERROR_EOS) {
1007 // advance the timestamp by the last sample's duration
1008 ts += duration;
1009 eos = true;
1010 return AP4_SUCCESS;
1011 } else {
1012 return result;
1013 }
1014 }
1015 ts = (double)sample.GetDts()/(double)track.GetMediaTimeScale();
1016 duration = sample.GetDuration()/(double)track.GetMediaTimeScale();
1017
1018 return AP4_SUCCESS;
1019 }
1020
1021 /*----------------------------------------------------------------------
1022 | WriteSamples
1023 +---------------------------------------------------------------------*/
1024 static AP4_Result
1025 WriteSamples(AP4_Mpeg2TsWriter* ts_writer,
1026 PackedAudioWriter* packed_writer,
1027 AP4_Track* audio_track,
1028 SampleReader* audio_reader,
1029 AP4_Mpeg2TsWriter::SampleStream* audio_stream,
1030 AP4_Track* video_track,
1031 SampleReader* video_reader,
1032 AP4_Mpeg2TsWriter::SampleStream* video_stream,
1033 unsigned int segment_duration_threshold,
1034 AP4_UI08 nalu_length_size)
1035 {
1036 AP4_Sample audio_sample;
1037 AP4_DataBuffer audio_sample_data;
1038 unsigned int audio_sample_count = 0;
1039 double audio_ts = 0.0;
1040 double audio_frame_duration = 0.0;
1041 bool audio_eos = false;
1042 AP4_Sample video_sample;
1043 AP4_DataBuffer video_sample_data;
1044 unsigned int video_sample_count = 0;
1045 double video_ts = 0.0;
1046 double video_frame_duration = 0.0;
1047 bool video_eos = false;
1048 double last_ts = 0.0;
1049 unsigned int segment_number = 0;
1050 AP4_ByteStream* segment_output = NULL;
1051 double segment_duration = 0.0;
1052 AP4_Array<double> segment_durations;
1053 AP4_Array<AP4_UI32> segment_sizes;
1054 AP4_Position segment_position = 0;
1055 AP4_Array<AP4_Position> segment_positions;
1056 AP4_Array<AP4_Position> iframe_positions;
1057 AP4_Array<AP4_UI32> iframe_sizes;
1058 AP4_Array<double> iframe_times;
1059 AP4_Array<double> iframe_durations;
1060 AP4_Array<AP4_UI32> iframe_segment_indexes;
1061 bool new_segment = true;
1062 AP4_ByteStream* raw_output = NULL;
1063 AP4_ByteStream* playlist = NULL;
1064 char string_buffer[4096];
1065 SampleEncrypter* sample_encrypter = NULL;
1066 AP4_Result result = AP4_SUCCESS;
1067
1068 // prime the samples
1069 if (audio_reader) {
1070 result = ReadSample(*audio_reader, *audio_track, audio_sample, audio_sample_data, audio_ts, audio_frame_duration, audio_eos);
1071 if (AP4_FAILED(result)) return result;
1072 }
1073 if (video_reader) {
1074 result = ReadSample(*video_reader, *video_track, video_sample, video_sample_data, video_ts, video_frame_duration, video_eos);
1075 if (AP4_FAILED(result)) return result;
1076 }
1077
1078 for (;;) {
1079 bool sync_sample = false;
1080 AP4_Track* chosen_track= NULL;
1081 if (audio_track && !audio_eos) {
1082 chosen_track = audio_track;
1083 if (video_track == NULL) {
1084 if (audio_track->GetSampleDescription(0)->GetFormat() == AP4_SAMPLE_FORMAT_AC_4) {
1085 if (audio_sample.IsSync()) {
1086 sync_sample = true;
1087 }
1088 } else {
1089 sync_sample = true;
1090 }
1091 }
1092 }
1093 if (video_track && !video_eos) {
1094 if (audio_track) {
1095 if (video_ts <= audio_ts) {
1096 chosen_track = video_track;
1097 }
1098 } else {
1099 chosen_track = video_track;
1100 }
1101 if (chosen_track == video_track && video_sample.IsSync()) {
1102 sync_sample = true;
1103 }
1104 }
1105
1106 // check if we need to start a new segment
1107 if (Options.segment_duration && (sync_sample || chosen_track == NULL)) {
1108 if (video_track) {
1109 segment_duration = video_ts - last_ts;
1110 } else {
1111 segment_duration = audio_ts - last_ts;
1112 }
1113 if ((segment_duration >= (double)Options.segment_duration - (double)segment_duration_threshold/1000.0) ||
1114 chosen_track == NULL) {
1115 if (video_track) {
1116 last_ts = video_ts;
1117 } else {
1118 last_ts = audio_ts;
1119 }
1120 if (segment_output) {
1121 // flush the output stream
1122 segment_output->Flush();
1123
1124 // compute the segment size (including padding)
1125 AP4_Position segment_end = 0;
1126 segment_output->Tell(segment_end);
1127 AP4_UI32 segment_size = 0;
1128 if (Options.encryption_mode == ENCRYPTION_MODE_AES_128) {
1129 segment_size = (AP4_UI32)segment_end;
1130 } else if (segment_end > segment_position) {
1131 segment_size = (AP4_UI32)(segment_end-segment_position);
1132 }
1133
1134 // update counters
1135 segment_sizes.Append(segment_size);
1136 segment_positions.Append(segment_position);
1137 segment_durations.Append(segment_duration);
1138
1139 if (segment_duration != 0.0) {
1140 double segment_bitrate = 8.0*(double)segment_size/segment_duration;
1141 if (segment_bitrate > Stats.max_segment_bitrate) {
1142 Stats.max_segment_bitrate = segment_bitrate;
1143 }
1144 }
1145 if (Options.verbose) {
1146 printf("Segment %d, duration=%.2f, %d audio samples, %d video samples, %d bytes @%lld\n",
1147 segment_number,
1148 segment_duration,
1149 audio_sample_count,
1150 video_sample_count,
1151 segment_size,
1152 segment_position);
1153 }
1154 if (!Options.output_single_file) {
1155 segment_output->Release();
1156 segment_output = NULL;
1157 }
1158 ++segment_number;
1159 audio_sample_count = 0;
1160 video_sample_count = 0;
1161 }
1162 new_segment = true;
1163 }
1164 }
1165
1166 // check if we're done
1167 if (chosen_track == NULL) break;
1168
1169 if (new_segment) {
1170 new_segment = false;
1171
1172 // compute the new segment position
1173 segment_position = 0;
1174 if (Options.output_single_file) {
1175 if (raw_output) {
1176 raw_output->Tell(segment_position);
1177 }
1178 }
1179
1180 // manage the new segment stream
1181 if (segment_output == NULL) {
1182 segment_output = OpenOutput(Options.segment_filename_template, segment_number);
1183 raw_output = segment_output;
1184 if (segment_output == NULL) return AP4_ERROR_CANNOT_OPEN_FILE;
1185 }
1186 if (Options.encryption_mode != ENCRYPTION_MODE_NONE) {
1187 if (Options.encryption_iv_mode == ENCRYPTION_IV_MODE_SEQUENCE) {
1188 AP4_SetMemory(Options.encryption_iv, 0, sizeof(Options.encryption_iv));
1189 AP4_BytesFromUInt32BE(&Options.encryption_iv[12], segment_number);
1190 }
1191 }
1192 if (Options.encryption_mode == ENCRYPTION_MODE_AES_128) {
1193 EncryptingStream* encrypting_stream = NULL;
1194 result = EncryptingStream::Create(Options.encryption_key, Options.encryption_iv, raw_output, encrypting_stream);
1195 if (AP4_FAILED(result)) {
1196 fprintf(stderr, "ERROR: failed to create encrypting stream (%d)\n", result);
1197 return result;
1198 }
1199 segment_output->Release();
1200 segment_output = encrypting_stream;
1201 } else if (Options.encryption_mode == ENCRYPTION_MODE_SAMPLE_AES) {
1202 delete sample_encrypter;
1203 sample_encrypter = NULL;
1204 result = SampleEncrypter::Create(Options.encryption_key, Options.encryption_iv, sample_encrypter);
1205 if (AP4_FAILED(result)) {
1206 fprintf(stderr, "ERROR: failed to create sample encrypter (%d)\n", result);
1207 return result;
1208 }
1209 }
1210
1211 // write the PAT and PMT
1212 if (ts_writer) {
1213 // update the descriptors if needed
1214 if (Options.encryption_mode == ENCRYPTION_MODE_SAMPLE_AES) {
1215 AP4_DataBuffer descriptor;
1216 if (audio_track) {
1217 result = MakeSampleAesAudioDescriptor(descriptor, audio_track->GetSampleDescription(0), audio_sample_data);
1218 if (AP4_SUCCEEDED(result) && descriptor.GetDataSize()) {
1219 audio_stream->SetDescriptor(descriptor.GetData(), descriptor.GetDataSize());
1220 } else {
1221 fprintf(stderr, "ERROR: failed to create sample-aes descriptor (%d)\n", result);
1222 return result;
1223 }
1224 }
1225 if (video_track) {
1226 result = MakeSampleAesVideoDescriptor(descriptor);
1227 if (AP4_SUCCEEDED(result) && descriptor.GetDataSize()) {
1228 video_stream->SetDescriptor(descriptor.GetData(), descriptor.GetDataSize());
1229 } else {
1230 fprintf(stderr, "ERROR: failed to create sample-aes descriptor (%d)\n", result);
1231 return result;
1232 }
1233 }
1234 }
1235
1236 ts_writer->WritePAT(*segment_output);
1237 ts_writer->WritePMT(*segment_output);
1238 } else if (packed_writer && chosen_track == audio_track) {
1239 AP4_DataBuffer private_extension_buffer;
1240 const char* private_extension_name = NULL;
1241 const unsigned char* private_extension_data = NULL;
1242 unsigned int private_extension_data_size = 0;
1243 if (Options.encryption_mode == ENCRYPTION_MODE_SAMPLE_AES) {
1244 private_extension_name = "com.apple.streaming.audioDescription";
1245 result = MakeAudioSetupData(private_extension_buffer, audio_track->GetSampleDescription(0), audio_sample_data);
1246 if (AP4_FAILED(result)) {
1247 fprintf(stderr, "ERROR: failed to make audio setup data (%d)\n", result);
1248 return 1;
1249 }
1250 private_extension_data = private_extension_buffer.GetData();
1251 private_extension_data_size = private_extension_buffer.GetDataSize();
1252 }
1253 packed_writer->WriteHeader(audio_ts,
1254 private_extension_name,
1255 private_extension_data,
1256 private_extension_data_size,
1257 *segment_output);
1258 }
1259 }
1260
1261 // write the samples out and advance to the next sample
1262 if (chosen_track == audio_track) {
1263 // perform sample-level encryption if needed
1264 if (sample_encrypter) {
1265 result = sample_encrypter->EncryptAudioSample(audio_sample_data, audio_track->GetSampleDescription(audio_sample.GetDescriptionIndex()));
1266 if (AP4_FAILED(result)) {
1267 fprintf(stderr, "ERROR: failed to encrypt audio sample (%d)\n", result);
1268 return result;
1269 }
1270 }
1271
1272 // write the sample data
1273 if (audio_stream) {
1274 result = audio_stream->WriteSample(audio_sample,
1275 audio_sample_data,
1276 audio_track->GetSampleDescription(audio_sample.GetDescriptionIndex()),
1277 video_track==NULL,
1278 *segment_output);
1279 } else if (packed_writer) {
1280 result = packed_writer->WriteSample(audio_sample,
1281 audio_sample_data,
1282 audio_track->GetSampleDescription(audio_sample.GetDescriptionIndex()),
1283 *segment_output);
1284 } else {
1285 return AP4_ERROR_INTERNAL;
1286 }
1287 if (AP4_FAILED(result)) return result;
1288
1289 result = ReadSample(*audio_reader, *audio_track, audio_sample, audio_sample_data, audio_ts, audio_frame_duration, audio_eos);
1290 if (AP4_FAILED(result)) return result;
1291 ++audio_sample_count;
1292 } else if (chosen_track == video_track) {
1293 // perform sample-level encryption if needed
1294 if (sample_encrypter) {
1295 result = sample_encrypter->EncryptVideoSample(video_sample_data, nalu_length_size);
1296 if (AP4_FAILED(result)) {
1297 fprintf(stderr, "ERROR: failed to encrypt video sample (%d)\n", result);
1298 return result;
1299 }
1300 }
1301
1302 // write the sample data
1303 AP4_Position frame_start = 0;
1304 segment_output->Tell(frame_start);
1305 result = video_stream->WriteSample(video_sample,
1306 video_sample_data,
1307 video_track->GetSampleDescription(video_sample.GetDescriptionIndex()),
1308 true,
1309 *segment_output);
1310 if (AP4_FAILED(result)) return result;
1311 AP4_Position frame_end = 0;
1312 segment_output->Tell(frame_end);
1313
1314 // measure I frames
1315 if (video_sample.IsSync()) {
1316 AP4_UI64 frame_size = 0;
1317 if (frame_end > frame_start) {
1318 frame_size = frame_end-frame_start;
1319 }
1320 if (Options.encryption_mode == ENCRYPTION_MODE_AES_128) {
1321 frame_start += segment_position;
1322 }
1323 iframe_positions.Append(frame_start);
1324 iframe_sizes.Append((AP4_UI32)frame_size);
1325 iframe_times.Append(video_ts);
1326 iframe_segment_indexes.Append(segment_number);
1327 iframe_durations.Append(0.0); // will be computed later
1328 if (Options.verbose) {
1329 printf("I-Frame: %d@%lld, t=%f\n", (AP4_UI32)frame_size, frame_start, video_ts);
1330 }
1331 }
1332
1333 // read the next sample
1334 result = ReadSample(*video_reader, *video_track, video_sample, video_sample_data, video_ts, video_frame_duration, video_eos);
1335 if (AP4_FAILED(result)) return result;
1336 ++video_sample_count;
1337 } else {
1338 break;
1339 }
1340 }
1341
1342 // create the media playlist/index file
1343 playlist = OpenOutput(Options.index_filename, 0);
1344 if (playlist == NULL) return AP4_ERROR_CANNOT_OPEN_FILE;
1345
1346 unsigned int target_duration = 0;
1347 double total_duration = 0.0;
1348 for (unsigned int i=0; i<segment_durations.ItemCount(); i++) {
1349 if ((unsigned int)(segment_durations[i]+0.5) > target_duration) {
1350 target_duration = (unsigned int)segment_durations[i];
1351 }
1352 total_duration += segment_durations[i];
1353 }
1354
1355 playlist->WriteString("#EXTM3U\r\n");
1356 if (Options.hls_version > 1) {
1357 sprintf(string_buffer, "#EXT-X-VERSION:%d\r\n", Options.hls_version);
1358 playlist->WriteString(string_buffer);
1359 }
1360 playlist->WriteString("#EXT-X-PLAYLIST-TYPE:VOD\r\n");
1361 if (video_track) {
1362 playlist->WriteString("#EXT-X-INDEPENDENT-SEGMENTS\r\n");
1363 }
1364 if (Options.allow_cache) {
1365 playlist->WriteString("#EXT-X-ALLOW-CACHE:");
1366 playlist->WriteString(Options.allow_cache);
1367 playlist->WriteString("\r\n");
1368 }
1369 playlist->WriteString("#EXT-X-TARGETDURATION:");
1370 sprintf(string_buffer, "%d\r\n", target_duration);
1371 playlist->WriteString(string_buffer);
1372 playlist->WriteString("#EXT-X-MEDIA-SEQUENCE:0\r\n");
1373
1374 if (Options.encryption_mode != ENCRYPTION_MODE_NONE) {
1375 if (Options.encryption_key_lines.ItemCount()) {
1376 for (unsigned int i=0; i<Options.encryption_key_lines.ItemCount(); i++) {
1377 AP4_String& key_line = Options.encryption_key_lines[i];
1378 const char* key_line_cstr = key_line.GetChars();
1379 bool omit_iv = false;
1380
1381 // omit the IV if the key line starts with a "!" (and skip the "!")
1382 if (key_line[0] == '!') {
1383 ++key_line_cstr;
1384 omit_iv = true;
1385 }
1386
1387 playlist->WriteString("#EXT-X-KEY:METHOD=");
1388 if (Options.encryption_mode == ENCRYPTION_MODE_AES_128) {
1389 playlist->WriteString("AES-128");
1390 } else if (Options.encryption_mode == ENCRYPTION_MODE_SAMPLE_AES) {
1391 playlist->WriteString("SAMPLE-AES");
1392 }
1393 playlist->WriteString(",");
1394 playlist->WriteString(key_line_cstr);
1395 if ((Options.encryption_iv_mode == ENCRYPTION_IV_MODE_RANDOM ||
1396 Options.encryption_iv_mode == ENCRYPTION_IV_MODE_FPS) && !omit_iv) {
1397 playlist->WriteString(",IV=0x");
1398 char iv_hex[33];
1399 iv_hex[32] = 0;
1400 AP4_FormatHex(Options.encryption_iv, 16, iv_hex);
1401 playlist->WriteString(iv_hex);
1402 }
1403 playlist->WriteString("\r\n");
1404 }
1405 } else {
1406 playlist->WriteString("#EXT-X-KEY:METHOD=");
1407 if (Options.encryption_mode == ENCRYPTION_MODE_AES_128) {
1408 playlist->WriteString("AES-128");
1409 } else if (Options.encryption_mode == ENCRYPTION_MODE_SAMPLE_AES) {
1410 playlist->WriteString("SAMPLE-AES");
1411 }
1412 playlist->WriteString(",URI=\"");
1413 playlist->WriteString(Options.encryption_key_uri);
1414 playlist->WriteString("\"");
1415 if (Options.encryption_iv_mode == ENCRYPTION_IV_MODE_RANDOM) {
1416 playlist->WriteString(",IV=0x");
1417 char iv_hex[33];
1418 iv_hex[32] = 0;
1419 AP4_FormatHex(Options.encryption_iv, 16, iv_hex);
1420 playlist->WriteString(iv_hex);
1421 }
1422 if (Options.encryption_key_format) {
1423 playlist->WriteString(",KEYFORMAT=\"");
1424 playlist->WriteString(Options.encryption_key_format);
1425 playlist->WriteString("\"");
1426 }
1427 if (Options.encryption_key_format_versions) {
1428 playlist->WriteString(",KEYFORMATVERSIONS=\"");
1429 playlist->WriteString(Options.encryption_key_format_versions);
1430 playlist->WriteString("\"");
1431 }
1432 playlist->WriteString("\r\n");
1433 }
1434 }
1435
1436 for (unsigned int i=0; i<segment_durations.ItemCount(); i++) {
1437 if (Options.hls_version >= 3) {
1438 sprintf(string_buffer, "#EXTINF:%f,\r\n", segment_durations[i]);
1439 } else {
1440 sprintf(string_buffer, "#EXTINF:%u,\r\n", (unsigned int)(segment_durations[i]+0.5));
1441 }
1442 playlist->WriteString(string_buffer);
1443 if (Options.output_single_file) {
1444 sprintf(string_buffer, "#EXT-X-BYTERANGE:%d@%lld\r\n", segment_sizes[i], segment_positions[i]);
1445 playlist->WriteString(string_buffer);
1446 }
1447 sprintf(string_buffer, Options.segment_url_template, i);
1448 playlist->WriteString(string_buffer);
1449 playlist->WriteString("\r\n");
1450 }
1451
1452 playlist->WriteString("#EXT-X-ENDLIST\r\n");
1453 playlist->Release();
1454
1455 // create the iframe playlist/index file
1456 if (video_track && Options.hls_version >= 4) {
1457 // compute the iframe durations and target duration
1458 for (unsigned int i=0; i<iframe_positions.ItemCount(); i++) {
1459 double iframe_duration = 0.0;
1460 if (i+1 < iframe_positions.ItemCount()) {
1461 iframe_duration = iframe_times[i+1]-iframe_times[i];
1462 } else if (total_duration > iframe_times[i]) {
1463 iframe_duration = total_duration-iframe_times[i];
1464 }
1465 iframe_durations[i] = iframe_duration;
1466 }
1467 unsigned int iframes_target_duration = 0;
1468 for (unsigned int i=0; i<iframe_durations.ItemCount(); i++) {
1469 if ((unsigned int)(iframe_durations[i]+0.5) > iframes_target_duration) {
1470 iframes_target_duration = (unsigned int)iframe_durations[i];
1471 }
1472 }
1473
1474 playlist = OpenOutput(Options.iframe_index_filename, 0);
1475 if (playlist == NULL) return AP4_ERROR_CANNOT_OPEN_FILE;
1476
1477 playlist->WriteString("#EXTM3U\r\n");
1478 if (Options.hls_version > 1) {
1479 sprintf(string_buffer, "#EXT-X-VERSION:%d\r\n", Options.hls_version);
1480 playlist->WriteString(string_buffer);
1481 }
1482 playlist->WriteString("#EXT-X-PLAYLIST-TYPE:VOD\r\n");
1483 playlist->WriteString("#EXT-X-I-FRAMES-ONLY\r\n");
1484 playlist->WriteString("#EXT-X-INDEPENDENT-SEGMENTS\r\n");
1485 playlist->WriteString("#EXT-X-TARGETDURATION:");
1486 sprintf(string_buffer, "%d\r\n", iframes_target_duration);
1487 playlist->WriteString(string_buffer);
1488 playlist->WriteString("#EXT-X-MEDIA-SEQUENCE:0\r\n");
1489
1490 if (Options.encryption_mode != ENCRYPTION_MODE_NONE) {
1491 playlist->WriteString("#EXT-X-KEY:METHOD=");
1492 if (Options.encryption_mode == ENCRYPTION_MODE_AES_128) {
1493 playlist->WriteString("AES-128");
1494 } else if (Options.encryption_mode == ENCRYPTION_MODE_SAMPLE_AES) {
1495 playlist->WriteString("SAMPLE-AES");
1496 }
1497 playlist->WriteString(",URI=\"");
1498 playlist->WriteString(Options.encryption_key_uri);
1499 playlist->WriteString("\"");
1500 if (Options.encryption_iv_mode == ENCRYPTION_IV_MODE_RANDOM) {
1501 playlist->WriteString(",IV=0x");
1502 char iv_hex[33];
1503 iv_hex[32] = 0;
1504 AP4_FormatHex(Options.encryption_iv, 16, iv_hex);
1505 playlist->WriteString(iv_hex);
1506 }
1507 if (Options.encryption_key_format) {
1508 playlist->WriteString(",KEYFORMAT=\"");
1509 playlist->WriteString(Options.encryption_key_format);
1510 playlist->WriteString("\"");
1511 }
1512 if (Options.encryption_key_format_versions) {
1513 playlist->WriteString(",KEYFORMATVERSIONS=\"");
1514 playlist->WriteString(Options.encryption_key_format_versions);
1515 playlist->WriteString("\"");
1516 }
1517 playlist->WriteString("\r\n");
1518 }
1519
1520 for (unsigned int i=0; i<iframe_positions.ItemCount(); i++) {
1521 sprintf(string_buffer, "#EXTINF:%f,\r\n", iframe_durations[i]);
1522 playlist->WriteString(string_buffer);
1523 sprintf(string_buffer, "#EXT-X-BYTERANGE:%d@%lld\r\n", iframe_sizes[i], iframe_positions[i]);
1524 playlist->WriteString(string_buffer);
1525 sprintf(string_buffer, Options.segment_url_template, iframe_segment_indexes[i]);
1526 playlist->WriteString(string_buffer);
1527 playlist->WriteString("\r\n");
1528 }
1529
1530 playlist->WriteString("#EXT-X-ENDLIST\r\n");
1531 playlist->Release();
1532 }
1533
1534 // update stats
1535 Stats.segment_count = segment_sizes.ItemCount();
1536 for (unsigned int i=0; i<segment_sizes.ItemCount(); i++) {
1537 Stats.segments_total_size += segment_sizes[i];
1538 Stats.segments_total_duration += segment_durations[i];
1539 }
1540 Stats.iframe_count = iframe_sizes.ItemCount();
1541 for (unsigned int i=0; i<iframe_sizes.ItemCount(); i++) {
1542 Stats.iframes_total_size += iframe_sizes[i];
1543 }
1544 for (unsigned int i=0; i<iframe_positions.ItemCount(); i++) {
1545 if (iframe_durations[i] != 0.0) {
1546 double iframe_bitrate = 8.0*(double)iframe_sizes[i]/iframe_durations[i];
1547 if (iframe_bitrate > Stats.max_iframe_bitrate) {
1548 Stats.max_iframe_bitrate = iframe_bitrate;
1549 }
1550 }
1551 }
1552
1553 if (Options.verbose) {
1554 printf("Conversion complete, total duration=%.2f secs\n", total_duration);
1555 }
1556
1557 if (segment_output) segment_output->Release();
1558 delete sample_encrypter;
1559
1560 return result;
1561 }
1562
1563 /*----------------------------------------------------------------------
1564 | main
1565 +---------------------------------------------------------------------*/
1566 int
1567 main(int argc, char** argv)
1568 {
1569 if (argc < 2) {
1570 PrintUsageAndExit();
1571 }
1572
1573 // default options
1574 Options.input = NULL;
1575 Options.verbose = false;
1576 Options.hls_version = 0;
1577 Options.pmt_pid = 0x100;
1578 Options.audio_pid = 0x101;
1579 Options.video_pid = 0x102;
1580 Options.audio_track_id = -1;
1581 Options.video_track_id = -1;
1582 Options.audio_format = AUDIO_FORMAT_TS;
1583 Options.output_single_file = false;
1584 Options.show_info = false;
1585 Options.index_filename = "stream.m3u8";
1586 Options.iframe_index_filename = NULL;
1587 Options.segment_filename_template = NULL;
1588 Options.segment_url_template = NULL;
1589 Options.segment_duration = 6;
1590 Options.segment_duration_threshold = DefaultSegmentDurationThreshold;
1591 Options.allow_cache = NULL;
1592 Options.encryption_key_hex = NULL;
1593 Options.encryption_mode = ENCRYPTION_MODE_NONE;
1594 Options.encryption_iv_mode = ENCRYPTION_IV_MODE_NONE;
1595 Options.encryption_key_uri = "key.bin";
1596 Options.encryption_key_format = NULL;
1597 Options.encryption_key_format_versions = NULL;
1598 Options.pcr_offset = AP4_MPEG2_TS_DEFAULT_PCR_OFFSET;
1599 AP4_SetMemory(Options.encryption_key, 0, sizeof(Options.encryption_key));
1600 AP4_SetMemory(Options.encryption_iv, 0, sizeof(Options.encryption_iv));
1601 AP4_SetMemory(&Stats, 0, sizeof(Stats));
1602
1603 // parse command line
1604 AP4_Result result;
1605 char** args = argv+1;
1606 while (const char* arg = *args++) {
1607 if (!strcmp(arg, "--verbose")) {
1608 Options.verbose = true;
1609 } else if (!strcmp(arg, "--hls-version")) {
1610 if (*args == NULL) {
1611 fprintf(stderr, "ERROR: --hls-version requires a number\n");
1612 return 1;
1613 }
1614 Options.hls_version = (unsigned int)strtoul(*args++, NULL, 10);
1615 if (Options.hls_version ==0) {
1616 fprintf(stderr, "ERROR: --hls-version requires number > 0\n");
1617 return 1;
1618 }
1619 } else if (!strcmp(arg, "--segment-duration")) {
1620 if (*args == NULL) {
1621 fprintf(stderr, "ERROR: --segment-duration requires a number\n");
1622 return 1;
1623 }
1624 Options.segment_duration = (unsigned int)strtoul(*args++, NULL, 10);
1625 } else if (!strcmp(arg, "--segment-duration-threshold")) {
1626 if (*args == NULL) {
1627 fprintf(stderr, "ERROR: --segment-duration-threshold requires a number\n");
1628 return 1;
1629 }
1630 Options.segment_duration_threshold = (unsigned int)strtoul(*args++, NULL, 10);
1631 } else if (!strcmp(arg, "--segment-filename-template")) {
1632 if (*args == NULL) {
1633 fprintf(stderr, "ERROR: --segment-filename-template requires an argument\n");
1634 return 1;
1635 }
1636 Options.segment_filename_template = *args++;
1637 } else if (!strcmp(arg, "--segment-url-template")) {
1638 if (*args == NULL) {
1639 fprintf(stderr, "ERROR: --segment-url-template requires an argument\n");
1640 return 1;
1641 }
1642 Options.segment_url_template = *args++;
1643 } else if (!strcmp(arg, "--allow-cache")) {
1644 if (*args == NULL || (strcmp(*args, "NO") && strcmp(*args, "YES"))) {
1645 fprintf(stderr, "ERROR: --allow-cache requires a YES or NO argument\n");
1646 return 1;
1647 }
1648 Options.allow_cache = *args++;
1649 } else if (!strcmp(arg, "--pmt-pid")) {
1650 if (*args == NULL) {
1651 fprintf(stderr, "ERROR: --pmt-pid requires a number\n");
1652 return 1;
1653 }
1654 Options.pmt_pid = (unsigned int)strtoul(*args++, NULL, 10);
1655 } else if (!strcmp(arg, "--audio-pid")) {
1656 if (*args == NULL) {
1657 fprintf(stderr, "ERROR: --audio-pid requires a number\n");
1658 return 1;
1659 }
1660 Options.audio_pid = (unsigned int)strtoul(*args++, NULL, 10);
1661 } else if (!strcmp(arg, "--video-pid")) {
1662 if (*args == NULL) {
1663 fprintf(stderr, "ERROR: --video-pid requires a number\n");
1664 return 1;
1665 }
1666 Options.video_pid = (unsigned int)strtoul(*args++, NULL, 10);
1667 } else if (!strcmp(arg, "--audio-track-id")) {
1668 if (*args == NULL) {
1669 fprintf(stderr, "ERROR: --audio-track-id requires a number\n");
1670 return 1;
1671 }
1672 Options.audio_track_id = (unsigned int)strtoul(*args++, NULL, 10);
1673 } else if (!strcmp(arg, "--audio-format")) {
1674 if (*args == NULL) {
1675 fprintf(stderr, "ERROR: --audio-format requires an argument\n");
1676 return 1;
1677 }
1678 const char* format = *args++;
1679 if (!strcmp(format, "ts")) {
1680 Options.audio_format = AUDIO_FORMAT_TS;
1681 } else if (!strcmp(format, "packed")) {
1682 Options.audio_format = AUDIO_FORMAT_PACKED;
1683 } else {
1684 fprintf(stderr, "ERROR: unknown audio format\n");
1685 return 1;
1686 }
1687 } else if (!strcmp(arg, "--video-track-id")) {
1688 if (*args == NULL) {
1689 fprintf(stderr, "ERROR: --video-track-id requires a number\n");
1690 return 1;
1691 }
1692 Options.video_track_id = (unsigned int)strtoul(*args++, NULL, 10);
1693 } else if (!strcmp(arg, "--pcr-offset")) {
1694 if (*args == NULL) {
1695 fprintf(stderr, "ERROR: --pcr-offset requires a number\n");
1696 return 1;
1697 }
1698 Options.pcr_offset = (unsigned int)strtoul(*args++, NULL, 10);
1699 } else if (!strcmp(arg, "--output-single-file")) {
1700 Options.output_single_file = true;
1701 } else if (!strcmp(arg, "--index-filename")) {
1702 if (*args == NULL) {
1703 fprintf(stderr, "ERROR: --index-filename requires a filename\n");
1704 return 1;
1705 }
1706 Options.index_filename = *args++;
1707 } else if (!strcmp(arg, "--iframe-index-filename")) {
1708 if (*args == NULL) {
1709 fprintf(stderr, "ERROR: --iframe-index-filename requires a filename\n");
1710 return 1;
1711 }
1712 Options.iframe_index_filename = *args++;
1713 } else if (!strcmp(arg, "--show-info")) {
1714 Options.show_info = true;
1715 } else if (!strcmp(arg, "--encryption-key")) {
1716 if (*args == NULL) {
1717 fprintf(stderr, "ERROR: --encryption-key requires an argument\n");
1718 return 1;
1719 }
1720 Options.encryption_key_hex = *args++;
1721 result = AP4_ParseHex(Options.encryption_key_hex, Options.encryption_key, 16);
1722 if (AP4_FAILED(result)) {
1723 fprintf(stderr, "ERROR: invalid hex key\n");
1724 return 1;
1725 }
1726 if (Options.encryption_mode == ENCRYPTION_MODE_NONE) {
1727 Options.encryption_mode = ENCRYPTION_MODE_AES_128;
1728 }
1729 } else if (!strcmp(arg, "--encryption-mode")) {
1730 if (*args == NULL) {
1731 fprintf(stderr, "ERROR: --encryption-mode requires an argument\n");
1732 return 1;
1733 }
1734 if (strncmp(*args, "AES-128", 7) == 0) {
1735 Options.encryption_mode = ENCRYPTION_MODE_AES_128;
1736 } else if (strncmp(*args, "SAMPLE-AES", 10) == 0) {
1737 Options.encryption_mode = ENCRYPTION_MODE_SAMPLE_AES;
1738 } else {
1739 fprintf(stderr, "ERROR: unknown encryption mode\n");
1740 return 1;
1741 }
1742 ++args;
1743 } else if (!strcmp(arg, "--encryption-iv-mode")) {
1744 if (*args == NULL) {
1745 fprintf(stderr, "ERROR: --encryption-iv-mode requires an argument\n");
1746 return 1;
1747 }
1748 if (strncmp(*args, "sequence", 8) == 0) {
1749 Options.encryption_iv_mode = ENCRYPTION_IV_MODE_SEQUENCE;
1750 } else if (strncmp(*args, "random", 6) == 0) {
1751 Options.encryption_iv_mode = ENCRYPTION_IV_MODE_RANDOM;
1752 } else if (strncmp(*args, "fps", 3) == 0) {
1753 Options.encryption_iv_mode = ENCRYPTION_IV_MODE_FPS;
1754 } else {
1755 fprintf(stderr, "ERROR: unknown encryption IV mode\n");
1756 return 1;
1757 }
1758 ++args;
1759 } else if (!strcmp(arg, "--encryption-key-uri")) {
1760 if (*args == NULL) {
1761 fprintf(stderr, "ERROR: --encryption-key-uri requires an argument\n");
1762 return 1;
1763 }
1764 Options.encryption_key_uri = *args++;
1765 } else if (!strcmp(arg, "--encryption-key-format")) {
1766 if (*args == NULL) {
1767 fprintf(stderr, "ERROR: --encryption-key-format requires an argument\n");
1768 return 1;
1769 }
1770 Options.encryption_key_format = *args++;
1771 } else if (!strcmp(arg, "--encryption-key-format-versions")) {
1772 if (*args == NULL) {
1773 fprintf(stderr, "ERROR: --encryption-key-format-versions requires an argument\n");
1774 return 1;
1775 }
1776 Options.encryption_key_format_versions = *args++;
1777 } else if (!strcmp(arg, "--encryption-key-line")) {
1778 if (*args == NULL) {
1779 fprintf(stderr, "ERROR: --encryption-key-line requires an argument\n");
1780 return 1;
1781 }
1782 Options.encryption_key_lines.Append(*args++);
1783 } else if (Options.input == NULL) {
1784 Options.input = arg;
1785 } else {
1786 fprintf(stderr, "ERROR: unexpected argument: %s\n", arg);
1787 return 1;
1788 }
1789 }
1790
1791 // check args
1792 if (Options.input == NULL) {
1793 fprintf(stderr, "ERROR: missing input file name\n");
1794 return 1;
1795 }
1796 if (Options.encryption_mode == ENCRYPTION_MODE_NONE && Options.encryption_key_lines.ItemCount() != 0) {
1797 fprintf(stderr, "ERROR: --encryption-key-line requires --encryption-key and --encryption-key-mode\n");
1798 return 1;
1799 }
1800 if (Options.encryption_mode != ENCRYPTION_MODE_NONE && Options.encryption_key_hex == NULL) {
1801 fprintf(stderr, "ERROR: no encryption key specified\n");
1802 return 1;
1803 }
1804 if (Options.encryption_mode == ENCRYPTION_MODE_SAMPLE_AES && Options.hls_version > 0 && Options.hls_version < 5) {
1805 Options.hls_version = 5;
1806 fprintf(stderr, "WARNING: forcing version to 5 in order to support SAMPLE-AES encryption\n");
1807 }
1808 if (Options.iframe_index_filename && Options.hls_version > 0 && Options.hls_version < 4) {
1809 fprintf(stderr, "WARNING: forcing version to 4 in order to support I-FRAME-ONLY playlists\n");
1810 Options.hls_version = 4;
1811 }
1812 if (Options.encryption_iv_mode == ENCRYPTION_IV_MODE_NONE && Options.encryption_mode != ENCRYPTION_MODE_NONE) {
1813 if (Options.encryption_mode == ENCRYPTION_MODE_SAMPLE_AES) {
1814 // sequence-mode IVs don't work well with i-frame only playlists, use random instead
1815 Options.encryption_iv_mode = ENCRYPTION_IV_MODE_RANDOM;
1816 } else {
1817 Options.encryption_iv_mode = ENCRYPTION_IV_MODE_SEQUENCE;
1818 }
1819 }
1820 if ((Options.encryption_key_format || Options.encryption_key_format_versions) && Options.hls_version > 0 && Options.hls_version < 5) {
1821 Options.hls_version = 5;
1822 fprintf(stderr, "WARNING: forcing version to 5 in order to support KEYFORMAT and/or KEYFORMATVERSIONS\n");
1823 }
1824 if (Options.output_single_file && Options.hls_version > 0 && Options.hls_version < 4) {
1825 Options.hls_version = 4;
1826 fprintf(stderr, "WARNING: forcing version to 4 in order to support single file output\n");
1827 }
1828 if (Options.hls_version == 0) {
1829 // default version is 3 for cleartext or AES-128 encryption, and 5 for SAMPLE-AES
1830 if (Options.encryption_mode == ENCRYPTION_MODE_SAMPLE_AES) {
1831 Options.hls_version = 5;
1832 } else if (Options.output_single_file || Options.iframe_index_filename) {
1833 Options.hls_version = 4;
1834 } else {
1835 Options.hls_version = 3;
1836 }
1837 }
1838
1839 if (Options.verbose && Options.show_info) {
1840 fprintf(stderr, "WARNING: --verbose will be ignored because --show-info is selected\n");
1841 Options.verbose = false;
1842 }
1843
1844 // compute some derived values
1845 if (Options.iframe_index_filename == NULL) {
1846 if (Options.hls_version >= 4) {
1847 Options.iframe_index_filename = "iframes.m3u8";
1848 }
1849 }
1850 if (Options.audio_format == AUDIO_FORMAT_TS) {
1851 if (Options.segment_filename_template == NULL) {
1852 if (Options.output_single_file) {
1853 Options.segment_filename_template = "stream.ts";
1854 } else {
1855 Options.segment_filename_template = "segment-%d.ts";
1856 }
1857 }
1858 if (Options.segment_url_template == NULL) {
1859 if (Options.output_single_file) {
1860 Options.segment_url_template = "stream.ts";
1861 } else {
1862 Options.segment_url_template = "segment-%d.ts";
1863 }
1864 }
1865 }
1866
1867 if (Options.encryption_iv_mode == ENCRYPTION_IV_MODE_FPS) {
1868 if (Options.encryption_key_hex == NULL || AP4_StringLength(Options.encryption_key_hex) != 64) {
1869 fprintf(stderr, "ERROR: 'fps' IV mode requires a 32 byte key value (64 characters in hex)\n");
1870 return 1;
1871 }
1872 result = AP4_ParseHex(Options.encryption_key_hex+32, Options.encryption_iv, 16);
1873 if (AP4_FAILED(result)) {
1874 fprintf(stderr, "ERROR: invalid hex IV\n");
1875 return 1;
1876 }
1877 } else if (Options.encryption_iv_mode == ENCRYPTION_IV_MODE_RANDOM) {
1878 result = AP4_System_GenerateRandomBytes(Options.encryption_iv, sizeof(Options.encryption_iv));
1879 if (AP4_FAILED(result)) {
1880 fprintf(stderr, "ERROR: failed to get random IV (%d)\n", result);
1881 return 1;
1882 }
1883 }
1884
1885 // create the input stream
1886 AP4_ByteStream* input = NULL;
1887 result = AP4_FileByteStream::Create(Options.input, AP4_FileByteStream::STREAM_MODE_READ, input);
1888 if (AP4_FAILED(result)) {
1889 fprintf(stderr, "ERROR: cannot open input (%d)\n", result);
1890 return 1;
1891 }
1892
1893 // open the file
1894 AP4_File* input_file = new AP4_File(*input, true);
1895
1896 // get the movie
1897 AP4_SampleDescription* sample_description;
1898 AP4_Movie* movie = input_file->GetMovie();
1899 if (movie == NULL) {
1900 fprintf(stderr, "ERROR: no movie in file\n");
1901 return 1;
1902 }
1903
1904 // get the audio and video tracks
1905 AP4_Track* audio_track = NULL;
1906 if (Options.audio_track_id == -1) {
1907 audio_track = movie->GetTrack(AP4_Track::TYPE_AUDIO);
1908 } else if (Options.audio_track_id > 0) {
1909 audio_track = movie->GetTrack((AP4_UI32)Options.audio_track_id);
1910 if (audio_track == NULL) {
1911 fprintf(stderr, "ERROR: audio track ID %d not found\n", Options.audio_track_id);
1912 return 1;
1913 }
1914 if (audio_track->GetType() != AP4_Track::TYPE_AUDIO) {
1915 fprintf(stderr, "ERROR: track ID %d is not an audio track\n", Options.audio_track_id);
1916 return 1;
1917 }
1918 }
1919 AP4_Track* video_track = NULL;
1920 if (Options.video_track_id == -1) {
1921 video_track = movie->GetTrack(AP4_Track::TYPE_VIDEO);
1922 } else if (Options.video_track_id > 0) {
1923 video_track = movie->GetTrack((AP4_UI32)Options.video_track_id);
1924 if (video_track == NULL) {
1925 fprintf(stderr, "ERROR: video track ID %d not found\n", Options.video_track_id);
1926 return 1;
1927 }
1928 if (video_track->GetType() != AP4_Track::TYPE_VIDEO) {
1929 fprintf(stderr, "ERROR: track ID %d is not a video track\n", Options.video_track_id);
1930 return 1;
1931 }
1932 }
1933 if (audio_track == NULL && video_track == NULL) {
1934 fprintf(stderr, "ERROR: no suitable tracks found\n");
1935 delete input_file;
1936 input->Release();
1937 return 1;
1938 }
1939 if (Options.audio_format == AUDIO_FORMAT_PACKED && video_track != NULL) {
1940 if (audio_track == NULL) {
1941 fprintf(stderr, "ERROR: packed audio format requires an audio track\n");
1942 return 1;
1943 }
1944 fprintf(stderr, "WARNING: ignoring video track because of the packed audio format\n");
1945 video_track = NULL;
1946 }
1947 if (video_track == NULL) {
1948 Options.segment_duration_threshold = 0;
1949 }
1950
1951 // create the appropriate readers
1952 AP4_LinearReader* linear_reader = NULL;
1953 SampleReader* audio_reader = NULL;
1954 SampleReader* video_reader = NULL;
1955 if (movie->HasFragments()) {
1956 // create a linear reader to get the samples
1957 linear_reader = new AP4_LinearReader(*movie, input);
1958
1959 if (audio_track) {
1960 linear_reader->EnableTrack(audio_track->GetId());
1961 audio_reader = new FragmentedSampleReader(*linear_reader, audio_track->GetId());
1962 }
1963 if (video_track) {
1964 linear_reader->EnableTrack(video_track->GetId());
1965 video_reader = new FragmentedSampleReader(*linear_reader, video_track->GetId());
1966 }
1967 } else {
1968 if (audio_track) {
1969 audio_reader = new TrackSampleReader(*audio_track);
1970 }
1971 if (video_track) {
1972 video_reader = new TrackSampleReader(*video_track);
1973 }
1974 }
1975
1976 AP4_Mpeg2TsWriter* ts_writer = NULL;
1977 AP4_Mpeg2TsWriter::SampleStream* audio_stream = NULL;
1978 AP4_Mpeg2TsWriter::SampleStream* video_stream = NULL;
1979 AP4_UI08 nalu_length_size = 0;
1980 PackedAudioWriter* packed_writer = NULL;
1981 if (Options.audio_format == AUDIO_FORMAT_PACKED) {
1982 packed_writer = new PackedAudioWriter();
1983
1984 // figure out the file extensions if needed
1985 sample_description = audio_track->GetSampleDescription(0);
1986 if (sample_description == NULL) {
1987 fprintf(stderr, "ERROR: unable to parse audio sample description\n");
1988 goto end;
1989 }
1990 if (Options.segment_filename_template == NULL || Options.segment_url_template == NULL) {
1991 const char* default_stream_name = "stream.es";
1992 const char* default_stream_pattern = "segment-%d.es";
1993 if (sample_description->GetFormat() == AP4_SAMPLE_FORMAT_MP4A) {
1994 AP4_MpegAudioSampleDescription* mpeg_audio_desc = AP4_DYNAMIC_CAST(AP4_MpegAudioSampleDescription, sample_description);
1995 if (mpeg_audio_desc == NULL ||
1996 !(mpeg_audio_desc->GetObjectTypeId() == AP4_OTI_MPEG4_AUDIO ||
1997 mpeg_audio_desc->GetObjectTypeId() == AP4_OTI_MPEG2_AAC_AUDIO_LC ||
1998 mpeg_audio_desc->GetObjectTypeId() == AP4_OTI_MPEG2_AAC_AUDIO_MAIN)) {
1999 fprintf(stderr, "ERROR: only AAC audio is supported\n");
2000 return 1;
2001 }
2002 default_stream_name = "stream.aac";
2003 default_stream_pattern = "segment-%d.aac";
2004 } else if (sample_description->GetFormat() == AP4_SAMPLE_FORMAT_AC_3) {
2005 default_stream_name = "stream.ac3";
2006 default_stream_pattern = "segment-%d.ac3";
2007 } else if (sample_description->GetFormat() == AP4_SAMPLE_FORMAT_EC_3) {
2008 default_stream_name = "stream.ec3";
2009 default_stream_pattern = "segment-%d.ec3";
2010 } else if (sample_description->GetFormat() == AP4_SAMPLE_FORMAT_AC_4) {
2011 default_stream_name = "stream.ac4";
2012 default_stream_pattern = "segment-%d.ac4";
2013 }
2014
2015 // override the segment names
2016 if (Options.segment_filename_template == NULL) {
2017 if (Options.output_single_file) {
2018 Options.segment_filename_template = default_stream_name;
2019 } else {
2020 Options.segment_filename_template = default_stream_pattern;
2021 }
2022 }
2023 if (Options.segment_url_template == NULL) {
2024 if (Options.output_single_file) {
2025 Options.segment_url_template = default_stream_name;
2026 } else {
2027 Options.segment_url_template = default_stream_pattern;
2028 }
2029 }
2030 }
2031 } else {
2032 // create an MPEG2 TS Writer
2033 ts_writer = new AP4_Mpeg2TsWriter(Options.pmt_pid);
2034
2035 // add the audio stream
2036 if (audio_track) {
2037 sample_description = audio_track->GetSampleDescription(0);
2038 if (sample_description == NULL) {
2039 fprintf(stderr, "ERROR: unable to parse audio sample description\n");
2040 goto end;
2041 }
2042
2043 unsigned int stream_type = 0;
2044 unsigned int stream_id = 0;
2045 if (sample_description->GetFormat() == AP4_SAMPLE_FORMAT_MP4A) {
2046 if (Options.encryption_mode == ENCRYPTION_MODE_SAMPLE_AES) {
2047 stream_type = AP4_MPEG2_STREAM_TYPE_SAMPLE_AES_ISO_IEC_13818_7;
2048 } else {
2049 stream_type = AP4_MPEG2_STREAM_TYPE_ISO_IEC_13818_7;
2050 }
2051 stream_id = AP4_MPEG2_TS_DEFAULT_STREAM_ID_AUDIO;
2052 } else if (sample_description->GetFormat() == AP4_SAMPLE_FORMAT_AC_3) {
2053 if (Options.encryption_mode == ENCRYPTION_MODE_SAMPLE_AES) {
2054 stream_type = AP4_MPEG2_STREAM_TYPE_SAMPLE_AES_ATSC_AC3;
2055 } else {
2056 stream_type = AP4_MPEG2_STREAM_TYPE_ATSC_AC3;
2057 }
2058 stream_id = AP4_MPEG2_TS_STREAM_ID_PRIVATE_STREAM_1;
2059 } else if (sample_description->GetFormat() == AP4_SAMPLE_FORMAT_EC_3) {
2060 if (Options.encryption_mode == ENCRYPTION_MODE_SAMPLE_AES) {
2061 stream_type = AP4_MPEG2_STREAM_TYPE_SAMPLE_AES_ATSC_EAC3;
2062 } else {
2063 stream_type = AP4_MPEG2_STREAM_TYPE_ATSC_EAC3;
2064 }
2065 stream_id = AP4_MPEG2_TS_STREAM_ID_PRIVATE_STREAM_1;
2066 } else {
2067 fprintf(stderr, "ERROR: audio codec not supported\n");
2068 return 1;
2069 }
2070 if (stream_type == AP4_MPEG2_STREAM_TYPE_ATSC_EAC3) {
2071 // E-AC-3 descriptor
2072 unsigned int number_of_channels = 0;
2073 AP4_String track_language;
2074 AP4_Dec3Atom* dec3 = AP4_DYNAMIC_CAST(AP4_Dec3Atom, sample_description->GetDetails().GetChild(AP4_ATOM_TYPE_DEC3));
2075 AP4_BitWriter bits(8);
2076 bits.Write(0xCC, 8);
2077 bits.Write(0x06, 8); // fixed value
2078 bits.Write(0xC0, 8); // reserved, bsid_flag, mainid_flag, asvc_flag, mixinfoexists, substream1_flag, substream2_flag and substream3_flag
2079 bits.Write(24, 5); // reserved, full_service_flag and service_type
2080 if (dec3->GetSubStreams()[0].acmod == 0) {
2081 number_of_channels = 1;
2082 } else if (dec3->GetSubStreams()[0].acmod == 1) {
2083 number_of_channels = 0;
2084 } else if (dec3->GetSubStreams()[0].acmod == 2) {
2085 number_of_channels = 2;
2086 } else {
2087 number_of_channels = 4;
2088 }
2089 if (dec3->GetSubStreams()[0].num_dep_sub > 0) {
2090 number_of_channels = 5;
2091 }
2092 bits.Write(number_of_channels, 3); // number_of_channels
2093 bits.Write(4, 3); // language_flag, language_flag_2, reserved
2094 bits.Write(dec3->GetSubStreams()[0].bsid, 5); // bsid
2095 track_language = audio_track->GetTrackLanguage();
2096 if (track_language.GetLength() == 3) {
2097 bits.Write(track_language.GetChars()[0], 8);
2098 bits.Write(track_language.GetChars()[1], 8);
2099 bits.Write(track_language.GetChars()[2], 8);
2100 } else {
2101 bits.Write(0x75, 8);
2102 bits.Write(0x6E, 8);
2103 bits.Write(0x64, 8);
2104 }
2105 // setup the audio stream
2106 result = ts_writer->SetAudioStream(audio_track->GetMediaTimeScale(),
2107 stream_type,
2108 stream_id,
2109 audio_stream,
2110 Options.audio_pid,
2111 bits.GetData(), 8,
2112 Options.pcr_offset);
2113 } else {
2114 // setup the audio stream
2115 result = ts_writer->SetAudioStream(audio_track->GetMediaTimeScale(),
2116 stream_type,
2117 stream_id,
2118 audio_stream,
2119 Options.audio_pid,
2120 NULL, 0,
2121 Options.pcr_offset);
2122 }
2123 if (AP4_FAILED(result)) {
2124 fprintf(stderr, "could not create audio stream (%d)\n", result);
2125 goto end;
2126 }
2127 }
2128
2129 // add the video stream
2130 if (video_track) {
2131 sample_description = video_track->GetSampleDescription(0);
2132 if (sample_description == NULL) {
2133 fprintf(stderr, "ERROR: unable to parse video sample description\n");
2134 goto end;
2135 }
2136
2137 // decide on the stream type
2138 unsigned int stream_type = 0;
2139 unsigned int stream_id = AP4_MPEG2_TS_DEFAULT_STREAM_ID_VIDEO;
2140 if (sample_description->GetFormat() == AP4_SAMPLE_FORMAT_AVC1 ||
2141 sample_description->GetFormat() == AP4_SAMPLE_FORMAT_AVC2 ||
2142 sample_description->GetFormat() == AP4_SAMPLE_FORMAT_AVC3 ||
2143 sample_description->GetFormat() == AP4_SAMPLE_FORMAT_AVC4 ||
2144 sample_description->GetFormat() == AP4_SAMPLE_FORMAT_DVAV ||
2145 sample_description->GetFormat() == AP4_SAMPLE_FORMAT_DVA1) {
2146 if (Options.encryption_mode == ENCRYPTION_MODE_SAMPLE_AES) {
2147 stream_type = AP4_MPEG2_STREAM_TYPE_SAMPLE_AES_AVC;
2148 AP4_AvcSampleDescription* avc_desc = AP4_DYNAMIC_CAST(AP4_AvcSampleDescription, sample_description);
2149 if (avc_desc == NULL) {
2150 fprintf(stderr, "ERROR: not a proper AVC track\n");
2151 return 1;
2152 }
2153 nalu_length_size = avc_desc->GetNaluLengthSize();
2154 } else {
2155 stream_type = AP4_MPEG2_STREAM_TYPE_AVC;
2156 }
2157 } else if (sample_description->GetFormat() == AP4_SAMPLE_FORMAT_HEV1 ||
2158 sample_description->GetFormat() == AP4_SAMPLE_FORMAT_HVC1 ||
2159 sample_description->GetFormat() == AP4_SAMPLE_FORMAT_DVHE ||
2160 sample_description->GetFormat() == AP4_SAMPLE_FORMAT_DVH1) {
2161 stream_type = AP4_MPEG2_STREAM_TYPE_HEVC;
2162 } else {
2163 fprintf(stderr, "ERROR: video codec not supported\n");
2164 return 1;
2165 }
2166 if (Options.encryption_mode == ENCRYPTION_MODE_SAMPLE_AES) {
2167 if (stream_type != AP4_MPEG2_STREAM_TYPE_SAMPLE_AES_AVC) {
2168 fprintf(stderr, "ERROR: AES-SAMPLE encryption can only be used with H.264 video\n");
2169 return 1;
2170 }
2171 }
2172
2173 // setup the video stream
2174 result = ts_writer->SetVideoStream(video_track->GetMediaTimeScale(),
2175 stream_type,
2176 stream_id,
2177 video_stream,
2178 Options.video_pid,
2179 NULL, 0,
2180 Options.pcr_offset);
2181 if (AP4_FAILED(result)) {
2182 fprintf(stderr, "could not create video stream (%d)\n", result);
2183 goto end;
2184 }
2185 }
2186 }
2187
2188 result = WriteSamples(ts_writer, packed_writer,
2189 audio_track, audio_reader, audio_stream,
2190 video_track, video_reader, video_stream,
2191 Options.segment_duration_threshold,
2192 nalu_length_size);
2193 if (AP4_FAILED(result)) {
2194 fprintf(stderr, "ERROR: failed to write samples (%d)\n", result);
2195 }
2196
2197 if (Options.show_info) {
2198 double average_segment_bitrate = 0.0;
2199 if (Stats.segments_total_duration != 0.0) {
2200 average_segment_bitrate = 8.0*(double)Stats.segments_total_size/Stats.segments_total_duration;
2201 }
2202 double average_iframe_bitrate = 0.0;
2203 if (Stats.segments_total_duration != 0.0) {
2204 average_iframe_bitrate = 8.0*(double)Stats.iframes_total_size/Stats.segments_total_duration;
2205 }
2206
2207 double frame_rate = 0.0;
2208 if (video_track && (Stats.segments_total_duration != 0.0)) {
2209 double sample_count = (double)video_track->GetSampleCount();
2210 double media_duration = (double)video_track->GetMediaDuration();
2211 double timescale = (double)video_track->GetMediaTimeScale();
2212 if (media_duration > 0.0) {
2213 frame_rate = sample_count/(media_duration/timescale);
2214 }
2215 }
2216
2217 printf(
2218 "{\n"
2219 );
2220 printf(
2221 " \"stats\": {\n"
2222 " \"duration\": %f,\n"
2223 " \"avg_segment_bitrate\": %f,\n"
2224 " \"max_segment_bitrate\": %f,\n"
2225 " \"avg_iframe_bitrate\": %f,\n"
2226 " \"max_iframe_bitrate\": %f,\n"
2227 " \"frame_rate\": %f\n"
2228 " }",
2229 (double)movie->GetDurationMs()/1000.0,
2230 average_segment_bitrate,
2231 Stats.max_segment_bitrate,
2232 average_iframe_bitrate,
2233 Stats.max_iframe_bitrate,
2234 frame_rate
2235 );
2236 if (audio_track) {
2237 AP4_String codec;
2238 AP4_SampleDescription* sdesc = audio_track->GetSampleDescription(0);
2239 if (sdesc) {
2240 sdesc->GetCodecString(codec);
2241 }
2242 printf(
2243 ",\n"
2244 " \"audio\": {\n"
2245 " \"codec\": \"%s\"\n"
2246 " }",
2247 codec.GetChars()
2248 );
2249 }
2250 if (video_track) {
2251 AP4_String codec;
2252 AP4_UI16 width = (AP4_UI16)(video_track->GetWidth()/65536.0);
2253 AP4_UI16 height = (AP4_UI16)(video_track->GetHeight()/65536.0);
2254 AP4_SampleDescription* sdesc = video_track->GetSampleDescription(0);
2255 if (sdesc) {
2256 sdesc->GetCodecString(codec);
2257 AP4_VideoSampleDescription* video_desc = AP4_DYNAMIC_CAST(AP4_VideoSampleDescription, sdesc);
2258 if (video_desc) {
2259 width = video_desc->GetWidth();
2260 height = video_desc->GetHeight();
2261 }
2262 }
2263 printf(
2264 ",\n"
2265 " \"video\": {\n"
2266 " \"codec\": \"%s\",\n"
2267 " \"width\": %d,\n"
2268 " \"height\": %d\n"
2269 " }",
2270 codec.GetChars(),
2271 width,
2272 height
2273 );
2274 }
2275 printf(
2276 "\n"
2277 "}\n"
2278 );
2279 }
2280
2281 end:
2282 delete ts_writer;
2283 delete packed_writer;
2284 delete input_file;
2285 input->Release();
2286 delete linear_reader;
2287 delete audio_reader;
2288 delete video_reader;
2289
2290 return result == AP4_SUCCESS?0:1;
2291 }
2292