File: Ap4SegmentBuilder.cpp

package info (click to toggle)
kodi-inputstream-adaptive 20.3.2%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 6,600 kB
  • sloc: cpp: 82,718; ansic: 503; makefile: 14
file content (880 lines) | stat: -rw-r--r-- 36,613 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
/*****************************************************************
|
|    AP4 - Segment Builder
|
|    Copyright 2002-2019 Axiomatic Systems, LLC
|
|
|    This file is part of Bento4/AP4 (MP4 Atom Processing Library).
|
|    Unless you have obtained Bento4 under a difference license,
|    this version of Bento4 is Bento4|GPL.
|    Bento4|GPL is free software; you can redistribute it and/or modify
|    it under the terms of the GNU General Public License as published by
|    the Free Software Foundation; either version 2, or (at your option)
|    any later version.
|
|    Bento4|GPL is distributed in the hope that it will be useful,
|    but WITHOUT ANY WARRANTY; without even the implied warranty of
|    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
|    GNU General Public License for more details.
|
|    You should have received a copy of the GNU General Public License
|    along with Bento4|GPL; see the file COPYING.  If not, write to the
|    Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
|    02111-1307, USA.
|
 ****************************************************************/

/*----------------------------------------------------------------------
|   includes
+---------------------------------------------------------------------*/
#include "Ap4SegmentBuilder.h"
#include "Ap4Results.h"
#include "Ap4ByteStream.h"
#include "Ap4Movie.h"
#include "Ap4MehdAtom.h"
#include "Ap4SyntheticSampleTable.h"
#include "Ap4TrexAtom.h"
#include "Ap4FtypAtom.h"
#include "Ap4File.h"
#include "Ap4TfhdAtom.h"
#include "Ap4MfhdAtom.h"
#include "Ap4TrunAtom.h"
#include "Ap4TfdtAtom.h"

/*----------------------------------------------------------------------
|   constants
+---------------------------------------------------------------------*/
const AP4_UI32     AP4_SEGMENT_BUILDER_DEFAULT_TIMESCALE = 1000;
const unsigned int AP4_STREAM_FEEDER_DEFAULT_BUFFER_SIZE = 65536;

/*----------------------------------------------------------------------
|   AP4_SegmentBuilder::AP4_SegmentBuilder
+---------------------------------------------------------------------*/
AP4_SegmentBuilder::AP4_SegmentBuilder(AP4_Track::Type track_type,
                                       AP4_UI32        track_id,
                                       AP4_UI64        media_time_origin) :
    m_TrackType(track_type),
    m_TrackId(track_id),
    m_TrackLanguage("und"),
    m_Timescale(AP4_SEGMENT_BUILDER_DEFAULT_TIMESCALE),
    m_SampleStartNumber(0),
    m_MediaTimeOrigin(media_time_origin),
    m_MediaStartTime(0),
    m_MediaDuration(0)
{
}

/*----------------------------------------------------------------------
|   AP4_SegmentBuilder::~AP4_SegmentBuilder
+---------------------------------------------------------------------*/
AP4_SegmentBuilder::~AP4_SegmentBuilder()
{
    m_Samples.Clear();
}

/*----------------------------------------------------------------------
|   AP4_SegmentBuilder::AddSample
+---------------------------------------------------------------------*/
AP4_Result
AP4_SegmentBuilder::AddSample(AP4_Sample& sample)
{
    AP4_Result result = m_Samples.Append(sample);
    if (AP4_FAILED(result)) return result;
    m_MediaDuration += sample.GetDuration();
    
    return AP4_SUCCESS;
}

/*----------------------------------------------------------------------
|   AP4_SegmentBuilder::WriteMediaSegment
+---------------------------------------------------------------------*/
AP4_Result
AP4_SegmentBuilder::WriteMediaSegment(AP4_ByteStream& stream, unsigned int sequence_number)
{
    unsigned int tfhd_flags = AP4_TFHD_FLAG_DEFAULT_BASE_IS_MOOF;
    if (m_TrackType == AP4_Track::TYPE_VIDEO) {
        tfhd_flags |= AP4_TFHD_FLAG_DEFAULT_SAMPLE_FLAGS_PRESENT;
    }
    
    // setup the moof structure
    AP4_ContainerAtom* moof = new AP4_ContainerAtom(AP4_ATOM_TYPE_MOOF);
    AP4_MfhdAtom* mfhd = new AP4_MfhdAtom(sequence_number);
    moof->AddChild(mfhd);
    AP4_ContainerAtom* traf = new AP4_ContainerAtom(AP4_ATOM_TYPE_TRAF);
    AP4_TfhdAtom* tfhd = new AP4_TfhdAtom(tfhd_flags,
                                          m_TrackId,
                                          0,
                                          1,
                                          0,
                                          0,
                                          0);
    if (tfhd_flags & AP4_TFHD_FLAG_DEFAULT_SAMPLE_FLAGS_PRESENT) {
        tfhd->SetDefaultSampleFlags(0x1010000); // sample_is_non_sync_sample=1, sample_depends_on=1 (not I frame)
    }
    
    traf->AddChild(tfhd);
    AP4_TfdtAtom* tfdt = new AP4_TfdtAtom(1, m_MediaTimeOrigin+m_MediaStartTime);
    traf->AddChild(tfdt);
    AP4_UI32 trun_flags = AP4_TRUN_FLAG_DATA_OFFSET_PRESENT     |
                          AP4_TRUN_FLAG_SAMPLE_DURATION_PRESENT |
                          AP4_TRUN_FLAG_SAMPLE_SIZE_PRESENT;
    AP4_UI32 first_sample_flags = 0;
    if (m_TrackType == AP4_Track::TYPE_VIDEO) {
        trun_flags |= AP4_TRUN_FLAG_FIRST_SAMPLE_FLAGS_PRESENT;
        first_sample_flags = 0x2000000; // sample_depends_on=2 (I frame)
    }
    AP4_TrunAtom* trun = new AP4_TrunAtom(trun_flags, 0, first_sample_flags);
    
    traf->AddChild(trun);
    moof->AddChild(traf);
    
    // add samples to the fragment
    AP4_Array<AP4_UI32>            sample_indexes;
    AP4_Array<AP4_TrunAtom::Entry> trun_entries;
    AP4_UI32                       mdat_size = AP4_ATOM_HEADER_SIZE;
    trun_entries.SetItemCount(m_Samples.ItemCount());
    for (unsigned int i=0; i<m_Samples.ItemCount(); i++) {
        // if we have one non-zero CTS delta, we'll need to express it
        if (m_Samples[i].GetCtsDelta()) {
            trun->SetFlags(trun->GetFlags() | AP4_TRUN_FLAG_SAMPLE_COMPOSITION_TIME_OFFSET_PRESENT);
        }
        
        // add one sample
        AP4_TrunAtom::Entry& trun_entry = trun_entries[i];
        trun_entry.sample_duration                = m_Samples[i].GetDuration();
        trun_entry.sample_size                    = m_Samples[i].GetSize();
        trun_entry.sample_composition_time_offset = m_Samples[i].GetCtsDelta();
        
        mdat_size += trun_entry.sample_size;
    }
    
    // update moof and children
    trun->SetEntries(trun_entries);
    trun->SetDataOffset((AP4_UI32)moof->GetSize()+AP4_ATOM_HEADER_SIZE);
    
    // write moof
    moof->Write(stream);
    
    // write mdat
    stream.WriteUI32(mdat_size);
    stream.WriteUI32(AP4_ATOM_TYPE_MDAT);
    for (unsigned int i=0; i<m_Samples.ItemCount(); i++) {
        AP4_Result result;
        AP4_ByteStream* data_stream = m_Samples[i].GetDataStream();
        result = data_stream->Seek(m_Samples[i].GetOffset());
        if (AP4_FAILED(result)) {
            data_stream->Release();
            return result;
        }
        result = data_stream->CopyTo(stream, m_Samples[i].GetSize());
        if (AP4_FAILED(result)) {
            data_stream->Release();
            return result;
        }
        
        data_stream->Release();
    }
    
    // update counters
    m_SampleStartNumber += m_Samples.ItemCount();
    m_MediaStartTime    += m_MediaDuration;
    m_MediaDuration      = 0;
    
    // cleanup
    delete moof;
    m_Samples.Clear();

    return AP4_SUCCESS;
}

/*----------------------------------------------------------------------
|   AP4_FeedSegmentBuilder::AP4_FeedSegmentBuilder
+---------------------------------------------------------------------*/
AP4_FeedSegmentBuilder::AP4_FeedSegmentBuilder(AP4_Track::Type track_type,
                                               AP4_UI32        track_id,
                                               AP4_UI64        media_time_origin) :
    AP4_SegmentBuilder(track_type, track_id, media_time_origin)
{
}

/*----------------------------------------------------------------------
|   AP4_VideoSegmentBuilder::AP4_VideoSegmentBuilder
+---------------------------------------------------------------------*/
AP4_VideoSegmentBuilder::AP4_VideoSegmentBuilder(AP4_UI32 track_id,
                                                 double   frames_per_second,
                                                 AP4_UI64 media_time_origin) :
    AP4_FeedSegmentBuilder(AP4_Track::TYPE_VIDEO, track_id, media_time_origin),
    m_FramesPerSecond(frames_per_second)
{
    m_Timescale = (unsigned int)(frames_per_second*1000.0);
}

/*----------------------------------------------------------------------
|   AP4_VideoSegmentBuilder::SortSamples
+---------------------------------------------------------------------*/
void
AP4_VideoSegmentBuilder::SortSamples(SampleOrder* array, unsigned int n)
{
    if (n < 2) {
        return;
    }
    SampleOrder pivot = array[n / 2];
    SampleOrder* left  = array;
    SampleOrder* right = array + n - 1;
    while (left <= right) {
        if (left->m_DisplayOrder < pivot.m_DisplayOrder) {
            ++left;
            continue;
        }
        if (right->m_DisplayOrder > pivot.m_DisplayOrder) {
            --right;
            continue;
        }
        SampleOrder temp = *left;
        *left++ = *right;
        *right-- = temp;
    }
    SortSamples(array, (unsigned int)(right - array + 1));
    SortSamples(left, (unsigned int)(array + n - left));
}

/*----------------------------------------------------------------------
|   AP4_VideoSegmentBuilder::WriteVideoInitSegment
+---------------------------------------------------------------------*/
AP4_Result
AP4_VideoSegmentBuilder::WriteVideoInitSegment(AP4_ByteStream&        stream,
                                               AP4_SampleDescription* sample_description,
                                               unsigned int           width,
                                               unsigned int           height,
                                               AP4_UI32               brand)
{
    // create the output file object
    AP4_Movie* output_movie = new AP4_Movie(AP4_SEGMENT_BUILDER_DEFAULT_TIMESCALE);

    // create an mvex container
    AP4_ContainerAtom* mvex = new AP4_ContainerAtom(AP4_ATOM_TYPE_MVEX);
    AP4_MehdAtom* mehd = new AP4_MehdAtom(0);
    mvex->AddChild(mehd);

    // create a sample table (with no samples) to hold the sample description
    AP4_SyntheticSampleTable* sample_table = new AP4_SyntheticSampleTable();
    sample_table->AddSampleDescription(sample_description, true);

    // create the track
    AP4_Track* output_track = new AP4_Track(AP4_Track::TYPE_VIDEO,
                                            sample_table,
                                            m_TrackId,
                                            AP4_SEGMENT_BUILDER_DEFAULT_TIMESCALE,
                                            0,
                                            m_Timescale,
                                            0,
                                            m_TrackLanguage.GetChars(),
                                            width << 16,
                                            height << 16);
    output_movie->AddTrack(output_track);

    // add a trex entry to the mvex container
    AP4_TrexAtom* trex = new AP4_TrexAtom(m_TrackId,
                                          1,
                                          0,
                                          0,
                                          0);
    mvex->AddChild(trex);

    // update the mehd duration
    // TBD mehd->SetDuration(0);

    // the mvex container to the moov container
    output_movie->GetMoovAtom()->AddChild(mvex);

    // write the ftyp atom
    AP4_Array<AP4_UI32> brands;
    brands.Append(AP4_FILE_BRAND_ISOM);
    brands.Append(AP4_FILE_BRAND_MP42);
    brands.Append(AP4_FILE_BRAND_MP41);
    brands.Append(brand);

    AP4_FtypAtom* ftyp = new AP4_FtypAtom(AP4_FILE_BRAND_MP42, 1, &brands[0], brands.ItemCount());
    ftyp->Write(stream);
    delete ftyp;

    // write the moov atom
    AP4_Result result = output_movie->GetMoovAtom()->Write(stream);
    if (AP4_FAILED(result)) {
        return result;
    }

    // cleanup
    delete output_movie;
    
    return AP4_SUCCESS;
}

/*----------------------------------------------------------------------
|   AP4_VideoSegmentBuilder::WriteMediaSegment
+---------------------------------------------------------------------*/
AP4_Result
AP4_VideoSegmentBuilder::WriteMediaSegment(AP4_ByteStream& stream, unsigned int sequence_number)
{
    if (m_SampleOrders.ItemCount() > 1) {
        // rebase the decode order
        AP4_UI32 decode_order_base = m_SampleOrders[0].m_DecodeOrder;
        for (unsigned int i=0; i<m_SampleOrders.ItemCount(); i++) {
            if (m_SampleOrders[i].m_DecodeOrder >= decode_order_base) {
                m_SampleOrders[i].m_DecodeOrder -= decode_order_base;
            }
        }
    
        // adjust the sample CTS/DTS offsets based on the sample orders
        unsigned int start = 0;
        for (unsigned int i=1; i<=m_SampleOrders.ItemCount(); i++) {
            if (i == m_SampleOrders.ItemCount() || m_SampleOrders[i].m_DisplayOrder == 0) {
                // we got to the end of the GOP, sort it by display order
                SortSamples(&m_SampleOrders[start], i-start);
                start = i;
            }
        }

        // compute the max CTS delta
        unsigned int max_delta = 0;
        for (unsigned int i=0; i<m_SampleOrders.ItemCount(); i++) {
            if (m_SampleOrders[i].m_DecodeOrder > i) {
                unsigned int delta =m_SampleOrders[i].m_DecodeOrder-i;
                if (delta > max_delta) {
                    max_delta = delta;
                }
            }
        }

        // set the CTS for all samples
        for (unsigned int i=0; i<m_SampleOrders.ItemCount(); i++) {
            AP4_UI64 dts = m_Samples[i].GetDts();
            if (m_Timescale) {
                dts = (AP4_UI64)((double)m_Timescale/m_FramesPerSecond*(double)(i+max_delta));
            }
            if (m_SampleOrders[i].m_DecodeOrder < m_Samples.ItemCount()) {
                m_Samples[m_SampleOrders[i].m_DecodeOrder].SetCts(dts);
            }
        }
    
        m_SampleOrders.Clear();
    }
    
    return AP4_SegmentBuilder::WriteMediaSegment(stream, sequence_number);
}

/*----------------------------------------------------------------------
|   AP4_AvcSegmentBuilder::AP4_AvcSegmentBuilder
+---------------------------------------------------------------------*/
AP4_AvcSegmentBuilder::AP4_AvcSegmentBuilder(AP4_UI32 track_id,
                                             double   frames_per_second,
                                             AP4_UI64 media_time_origin) :
    AP4_VideoSegmentBuilder(track_id, frames_per_second, media_time_origin)
{
}

/*----------------------------------------------------------------------
|   AP4_AvcSegmentBuilder::Feed
+---------------------------------------------------------------------*/
AP4_Result
AP4_AvcSegmentBuilder::Feed(const void* data,
                            AP4_Size    data_size,
                            AP4_Size&   bytes_consumed)
{
    AP4_Result result;
    
    AP4_AvcFrameParser::AccessUnitInfo access_unit_info;
    result = m_FrameParser.Feed(data, data_size, bytes_consumed, access_unit_info, data == NULL);
    if (AP4_FAILED(result)) return result;
    
    // check if we have an access unit
    if (access_unit_info.nal_units.ItemCount()) {
        // compute the total size of the sample data
        unsigned int sample_data_size = 0;
        for (unsigned int i=0; i<access_unit_info.nal_units.ItemCount(); i++) {
            sample_data_size += 4+access_unit_info.nal_units[i]->GetDataSize();
        }
        
        // format the sample data
        AP4_MemoryByteStream* sample_data = new AP4_MemoryByteStream(sample_data_size);
        for (unsigned int i=0; i<access_unit_info.nal_units.ItemCount(); i++) {
            sample_data->WriteUI32(access_unit_info.nal_units[i]->GetDataSize());
            sample_data->Write(access_unit_info.nal_units[i]->GetData(), access_unit_info.nal_units[i]->GetDataSize());
        }
        
        // compute the timestamp in a drift-less manner
        AP4_UI32 duration = 0;
        AP4_UI64 dts      = 0;
        if (m_Timescale !=0 && m_FramesPerSecond != 0.0) {
            AP4_UI64 this_sample_time = m_MediaStartTime+m_MediaDuration;
            AP4_UI64 next_sample_time = (AP4_UI64)((double)m_Timescale*(double)(m_SampleStartNumber+m_Samples.ItemCount()+1)/m_FramesPerSecond);
            duration = (AP4_UI32)(next_sample_time-this_sample_time);
            dts      = (AP4_UI64)((double)m_Timescale/m_FramesPerSecond*(double)m_Samples.ItemCount());
        }

        // create a new sample and add it to the list
        AP4_Sample sample(*sample_data, 0, sample_data_size, duration, 0, dts, 0, access_unit_info.is_idr);
        AddSample(sample);
        sample_data->Release();
        
        // remember the sample order
        m_SampleOrders.Append(SampleOrder(access_unit_info.decode_order, access_unit_info.display_order));
        
        // free the memory buffers
        for (unsigned int i=0; i<access_unit_info.nal_units.ItemCount(); i++) {
            delete access_unit_info.nal_units[i];
        }
        access_unit_info.nal_units.Clear();
        
        return 1; // one access unit returned
    }
    
    return AP4_SUCCESS;
}

/*----------------------------------------------------------------------
|   AP4_AvcSegmentBuilder::WriteInitSegment
+---------------------------------------------------------------------*/
AP4_Result
AP4_AvcSegmentBuilder::WriteInitSegment(AP4_ByteStream& stream)
{
    // compute the track parameters
    AP4_AvcSequenceParameterSet* sps = NULL;
    for (unsigned int i=0; i<=AP4_AVC_SPS_MAX_ID; i++) {
        if (m_FrameParser.GetSequenceParameterSets()[i]) {
            sps = m_FrameParser.GetSequenceParameterSets()[i];
            break;
        }
    }
    if (sps == NULL) {
        return AP4_ERROR_INVALID_FORMAT;
    }
    unsigned int video_width = 0;
    unsigned int video_height = 0;
    sps->GetInfo(video_width, video_height);
    
    // collect the SPS and PPS into arrays
    AP4_Array<AP4_DataBuffer> sps_array;
    for (unsigned int i=0; i<=AP4_AVC_SPS_MAX_ID; i++) {
        if (m_FrameParser.GetSequenceParameterSets()[i]) {
            sps_array.Append(m_FrameParser.GetSequenceParameterSets()[i]->raw_bytes);
        }
    }
    AP4_Array<AP4_DataBuffer> pps_array;
    for (unsigned int i=0; i<=AP4_AVC_PPS_MAX_ID; i++) {
        if (m_FrameParser.GetPictureParameterSets()[i]) {
            pps_array.Append(m_FrameParser.GetPictureParameterSets()[i]->raw_bytes);
        }
    }
    
    // setup the video the sample descripton
    AP4_AvcSampleDescription* sample_description =
        new AP4_AvcSampleDescription(AP4_SAMPLE_FORMAT_AVC1,
                                     (AP4_UI16)video_width,
                                     (AP4_UI16)video_height,
                                     24,
                                     "h264",
                                     (AP4_UI08)sps->profile_idc,
                                     (AP4_UI08)sps->level_idc,
                                     (AP4_UI08)(sps->constraint_set0_flag<<7 |
                                                sps->constraint_set1_flag<<6 |
                                                sps->constraint_set2_flag<<5 |
                                                sps->constraint_set3_flag<<4),
                                     4,
                                     sps->chroma_format_idc,
                                     sps->bit_depth_luma_minus8,
                                     sps->bit_depth_chroma_minus8,
                                     sps_array,
                                     pps_array);

    // let the base class finish the work
    return AP4_VideoSegmentBuilder::WriteVideoInitSegment(stream,
                                                          sample_description,
                                                          video_width,
                                                          video_height,
                                                          AP4_FILE_BRAND_AVC1);
}

/*----------------------------------------------------------------------
|   AP4_HevcSegmentBuilder::AP4_HevcSegmentBuilder
+---------------------------------------------------------------------*/
AP4_HevcSegmentBuilder::AP4_HevcSegmentBuilder(AP4_UI32 track_id,
                                               double   frames_per_second,
                                               AP4_UI32 video_format,
                                               AP4_UI64 media_time_origin) :
    AP4_VideoSegmentBuilder(track_id, frames_per_second, media_time_origin),
    m_VideoFormat(video_format)
{
}

/*----------------------------------------------------------------------
|   AP4_HevcSegmentBuilder::Feed
+---------------------------------------------------------------------*/
AP4_Result
AP4_HevcSegmentBuilder::Feed(const void* data,
                             AP4_Size    data_size,
                             AP4_Size&   bytes_consumed)
{
    AP4_Result result;
    
    AP4_HevcFrameParser::AccessUnitInfo access_unit_info;
    result = m_FrameParser.Feed(data, data_size, bytes_consumed, access_unit_info, data == NULL);
    if (AP4_FAILED(result)) return result;
    
    // check if we have an access unit
    if (access_unit_info.nal_units.ItemCount()) {
        // compute the total size of the sample data
        unsigned int sample_data_size = 0;
        for (unsigned int i=0; i<access_unit_info.nal_units.ItemCount(); i++) {
            sample_data_size += 4+access_unit_info.nal_units[i]->GetDataSize();
        }
        
        // format the sample data
        AP4_MemoryByteStream* sample_data = new AP4_MemoryByteStream(sample_data_size);
        for (unsigned int i=0; i<access_unit_info.nal_units.ItemCount(); i++) {
            sample_data->WriteUI32(access_unit_info.nal_units[i]->GetDataSize());
            sample_data->Write(access_unit_info.nal_units[i]->GetData(), access_unit_info.nal_units[i]->GetDataSize());
        }
        
        // compute the timestamp in a drift-less manner
        AP4_UI32 duration = 0;
        AP4_UI64 dts      = 0;
        if (m_Timescale !=0 && m_FramesPerSecond != 0.0) {
            AP4_UI64 this_sample_time = m_MediaStartTime+m_MediaDuration;
            AP4_UI64 next_sample_time = (AP4_UI64)((double)m_Timescale*(double)(m_SampleStartNumber+m_Samples.ItemCount()+1)/m_FramesPerSecond);
            duration = (AP4_UI32)(next_sample_time-this_sample_time);
            dts      = (AP4_UI64)((double)m_Timescale/m_FramesPerSecond*(double)m_Samples.ItemCount());
        }

        // create a new sample and add it to the list
        AP4_Sample sample(*sample_data, 0, sample_data_size, duration, 0, dts, 0, access_unit_info.is_random_access);
        AddSample(sample);
        sample_data->Release();
        
        // remember the sample order
        m_SampleOrders.Append(SampleOrder(access_unit_info.decode_order, access_unit_info.display_order));
        
        // free the memory buffers
        for (unsigned int i=0; i<access_unit_info.nal_units.ItemCount(); i++) {
            delete access_unit_info.nal_units[i];
        }
        access_unit_info.nal_units.Clear();
        
        return 1; // one access unit returned
    }
    
    return AP4_SUCCESS;
}

/*----------------------------------------------------------------------
|   AP4_HevcSegmentBuilder::WriteInitSegment
+---------------------------------------------------------------------*/
AP4_Result
AP4_HevcSegmentBuilder::WriteInitSegment(AP4_ByteStream& stream)
{
    // check that we have at least one SPS
    AP4_HevcSequenceParameterSet* sps = NULL;
    for (unsigned int i=0; i<=AP4_HEVC_SPS_MAX_ID; i++) {
        sps = m_FrameParser.GetSequenceParameterSets()[i];
        if (sps) break;
    }
    if (sps == NULL) {
        return AP4_ERROR_INVALID_FORMAT;
    }
    unsigned int video_width = 0;
    unsigned int video_height = 0;
    sps->GetInfo(video_width, video_height);

    // collect parameters from the first SPS entry
    // TODO: synthesize from multiple SPS entries if we have more than one
    AP4_UI08 general_profile_space =               sps->profile_tier_level.general_profile_space;
    AP4_UI08 general_tier_flag =                   sps->profile_tier_level.general_tier_flag;
    AP4_UI08 general_profile =                     sps->profile_tier_level.general_profile_idc;
    AP4_UI32 general_profile_compatibility_flags = sps->profile_tier_level.general_profile_compatibility_flags;
    AP4_UI64 general_constraint_indicator_flags =  sps->profile_tier_level.general_constraint_indicator_flags;
    AP4_UI08 general_level =                       sps->profile_tier_level.general_level_idc;
    AP4_UI32 min_spatial_segmentation =            0; // TBD (should read from VUI if present)
    AP4_UI08 parallelism_type =                    0; // unknown
    AP4_UI08 chroma_format =                       sps->chroma_format_idc;
    AP4_UI08 luma_bit_depth =                      8; // hardcoded temporarily, should be read from the bitstream
    AP4_UI08 chroma_bit_depth =                    8; // hardcoded temporarily, should be read from the bitstream
    AP4_UI16 average_frame_rate =                  0; // unknown
    AP4_UI08 constant_frame_rate =                 0; // unknown
    AP4_UI08 num_temporal_layers =                 0; // unknown
    AP4_UI08 temporal_id_nested =                  0; // unknown
    AP4_UI08 nalu_length_size =                    4;

    // collect the VPS, SPS and PPS into arrays
    AP4_Array<AP4_DataBuffer> vps_array;
    for (unsigned int i=0; i<=AP4_HEVC_VPS_MAX_ID; i++) {
        if (m_FrameParser.GetVideoParameterSets()[i]) {
            vps_array.Append(m_FrameParser.GetVideoParameterSets()[i]->raw_bytes);
        }
    }
    AP4_Array<AP4_DataBuffer> sps_array;
    for (unsigned int i=0; i<=AP4_HEVC_SPS_MAX_ID; i++) {
        if (m_FrameParser.GetSequenceParameterSets()[i]) {
            sps_array.Append(m_FrameParser.GetSequenceParameterSets()[i]->raw_bytes);
        }
    }
    AP4_Array<AP4_DataBuffer> pps_array;
    for (unsigned int i=0; i<=AP4_HEVC_PPS_MAX_ID; i++) {
        if (m_FrameParser.GetPictureParameterSets()[i]) {
            pps_array.Append(m_FrameParser.GetPictureParameterSets()[i]->raw_bytes);
        }
    }

    // setup the video the sample descripton
    AP4_UI08 parameters_completeness = (m_VideoFormat == AP4_SAMPLE_FORMAT_HVC1 ? 1 : 0);
    AP4_HevcSampleDescription* sample_description =
        new AP4_HevcSampleDescription(m_VideoFormat,
                                      video_width,
                                      video_height,
                                      24,
                                      "HEVC Coding",
                                      general_profile_space,
                                      general_tier_flag,
                                      general_profile,
                                      general_profile_compatibility_flags,
                                      general_constraint_indicator_flags,
                                      general_level,
                                      min_spatial_segmentation,
                                      parallelism_type,
                                      chroma_format,
                                      luma_bit_depth,
                                      chroma_bit_depth,
                                      average_frame_rate,
                                      constant_frame_rate,
                                      num_temporal_layers,
                                      temporal_id_nested,
                                      nalu_length_size,
                                      vps_array,
                                      parameters_completeness,
                                      sps_array,
                                      parameters_completeness,
                                      pps_array,
                                      parameters_completeness);

    // let the base class finish the work
    return AP4_VideoSegmentBuilder::WriteVideoInitSegment(stream,
                                                          sample_description,
                                                          video_width,
                                                          video_height,
                                                          AP4_FILE_BRAND_HVC1);
}

/*----------------------------------------------------------------------
|   AP4_AacSegmentBuilder::AP4_AacSegmentBuilder
+---------------------------------------------------------------------*/
AP4_AacSegmentBuilder::AP4_AacSegmentBuilder(AP4_UI32 track_id, AP4_UI64 media_time_origin) :
    AP4_FeedSegmentBuilder(AP4_Track::TYPE_AUDIO, track_id, media_time_origin),
    m_SampleDescription(NULL)
{
    m_Timescale = 0; // we will compute the real value when we get the first audio frame
}

/*----------------------------------------------------------------------
|   AP4_AacSegmentBuilder::~AP4_AacSegmentBuilder
+---------------------------------------------------------------------*/
AP4_AacSegmentBuilder::~AP4_AacSegmentBuilder()
{
    delete m_SampleDescription;
}

/*----------------------------------------------------------------------
|   AP4_AacSegmentBuilder::Feed
+---------------------------------------------------------------------*/
AP4_Result
AP4_AacSegmentBuilder::Feed(const void* data,
                            AP4_Size    data_size,
                            AP4_Size&   bytes_consumed)
{
    bytes_consumed = 0;
    
    // try to get a frame
    AP4_AacFrame frame;
    AP4_Result result = m_FrameParser.FindFrame(frame);
    if (AP4_SUCCEEDED(result)) {
        if (!m_SampleDescription) {
            // create a sample description for our samples
            AP4_DataBuffer dsi;
            unsigned char aac_dsi[2];

            unsigned int object_type = 2; // AAC LC by default
            aac_dsi[0] = (AP4_UI08)((object_type<<3) | (frame.m_Info.m_SamplingFrequencyIndex>>1));
            aac_dsi[1] = (AP4_UI08)(((frame.m_Info.m_SamplingFrequencyIndex&1)<<7) | (frame.m_Info.m_ChannelConfiguration<<3));

            dsi.SetData(aac_dsi, 2);
            m_SampleDescription =
                new AP4_MpegAudioSampleDescription(
                AP4_OTI_MPEG4_AUDIO,   // object type
                (AP4_UI32)frame.m_Info.m_SamplingFrequency,
                16,                    // sample size
                (AP4_UI16)frame.m_Info.m_ChannelConfiguration,
                &dsi,                  // decoder info
                6144,                  // buffer size
                128000,                // max bitrate
                128000);               // average bitrate
            
            m_Timescale = (AP4_UI32)frame.m_Info.m_SamplingFrequency;
        }

        // read and store the sample data
        AP4_DataBuffer sample_data(frame.m_Info.m_FrameLength);
        sample_data.SetDataSize(frame.m_Info.m_FrameLength);
        frame.m_Source->ReadBytes(sample_data.UseData(), frame.m_Info.m_FrameLength);
        AP4_MemoryByteStream* sample_data_stream = new AP4_MemoryByteStream(frame.m_Info.m_FrameLength);
        sample_data_stream->Write(sample_data.GetData(), sample_data.GetDataSize());

        // add the sample to the table
        AP4_Sample sample(*sample_data_stream, 0, frame.m_Info.m_FrameLength, 1024, 0, 0, 0, true);
        AddSample(sample);
        sample_data_stream->Release();
        
        return 1;
    }
    
    // not enough data in the parser for a frame, feed some more
    if (data == NULL) {
        m_FrameParser.Feed(NULL, NULL, AP4_BITSTREAM_FLAG_EOS);
    } else {
        AP4_Size can_feed = m_FrameParser.GetBytesFree();
        if (can_feed > data_size) {
            can_feed = data_size;
        }
        result = m_FrameParser.Feed((const AP4_UI08*)data, &can_feed);
        if (AP4_SUCCEEDED(result)) {
            bytes_consumed += can_feed;
        }
    }
    return AP4_SUCCESS;
}

/*----------------------------------------------------------------------
|   AP4_AacSegmentBuilder::WriteInitSegment
+---------------------------------------------------------------------*/
AP4_Result
AP4_AacSegmentBuilder::WriteInitSegment(AP4_ByteStream& stream)
{
    AP4_Result result;
    
    // check that we have a sample description
    if (!m_SampleDescription) {
        return AP4_ERROR_INVALID_STATE;
    }
    
    // create the output file object
    AP4_Movie* output_movie = new AP4_Movie(AP4_SEGMENT_BUILDER_DEFAULT_TIMESCALE);
    
    // create an mvex container
    AP4_ContainerAtom* mvex = new AP4_ContainerAtom(AP4_ATOM_TYPE_MVEX);
    AP4_MehdAtom* mehd = new AP4_MehdAtom(0);
    mvex->AddChild(mehd);
    
    // create a sample table (with no samples) to hold the sample description
    AP4_SyntheticSampleTable* sample_table = new AP4_SyntheticSampleTable();
    sample_table->AddSampleDescription(m_SampleDescription, false);
    
    // create the track
    AP4_Track* output_track = new AP4_Track(AP4_Track::TYPE_AUDIO,
                                            sample_table,
                                            m_TrackId,
                                            AP4_SEGMENT_BUILDER_DEFAULT_TIMESCALE,
                                            0,
                                            m_Timescale,
                                            0,
                                            m_TrackLanguage.GetChars(),
                                            0,
                                            0);
    output_movie->AddTrack(output_track);
    
    // add a trex entry to the mvex container
    AP4_TrexAtom* trex = new AP4_TrexAtom(m_TrackId,
                                          1,
                                          0,
                                          0,
                                          0);
    mvex->AddChild(trex);
    
    // the mvex container to the moov container
    output_movie->GetMoovAtom()->AddChild(mvex);
    
    // write the ftyp atom
    AP4_Array<AP4_UI32> brands;
    brands.Append(AP4_FILE_BRAND_ISOM);
    brands.Append(AP4_FILE_BRAND_MP42);
    brands.Append(AP4_FILE_BRAND_MP41);
    
    AP4_FtypAtom* ftyp = new AP4_FtypAtom(AP4_FILE_BRAND_MP42, 1, &brands[0], brands.ItemCount());
    ftyp->Write(stream);
    delete ftyp;
    
    // write the moov atom
    result = output_movie->GetMoovAtom()->Write(stream);
    
    // cleanup
    delete output_movie;
    
    return result;
}

/*----------------------------------------------------------------------
|   AP4_StreamFeeder::AP4_StreamFeeder
+---------------------------------------------------------------------*/
AP4_StreamFeeder::AP4_StreamFeeder(AP4_ByteStream* source, AP4_FeedSegmentBuilder& builder) :
    m_Source(source),
    m_Builder(builder),
    m_FeedBuffer(NULL),
    m_FeedBufferSize(0),
    m_FeedBytesPending(0),
    m_FeedBytesParsed(0)
{
    AP4_ASSERT(source);
    source->AddReference();
    m_FeedBuffer = new AP4_UI08[AP4_STREAM_FEEDER_DEFAULT_BUFFER_SIZE];
    if (m_FeedBuffer) {
        m_FeedBufferSize = AP4_STREAM_FEEDER_DEFAULT_BUFFER_SIZE;
    }
}

/*----------------------------------------------------------------------
|   AP4_StreamFeeder::~AP4_StreamFeeder
+---------------------------------------------------------------------*/
AP4_StreamFeeder::~AP4_StreamFeeder()
{
    m_Source->Release();
    delete[] m_FeedBuffer;
}

/*----------------------------------------------------------------------
|   AP4_StreamFeeder::Feed
+---------------------------------------------------------------------*/
AP4_Result
AP4_StreamFeeder::Feed()
{
    // read more data if the buffer is empty
    if (m_FeedBytesPending == 0) {
        m_FeedBytesParsed = 0;
        if (!m_FeedBufferSize) return AP4_ERROR_INTERNAL;
        AP4_Result result = m_Source->ReadPartial(m_FeedBuffer, m_FeedBufferSize, m_FeedBytesPending);
        if (AP4_FAILED(result)) {
            return result;
        }
        if (m_FeedBytesPending == 0) {
            return AP4_ERROR_EOS;
        }
    }

    // feed the builder
    AP4_Size bytes_consumed = 0;
    AP4_Result result = m_Builder.Feed(&m_FeedBuffer[m_FeedBytesParsed], m_FeedBytesPending, bytes_consumed);
    if (result < 0) return result;

    // update counters
    m_FeedBytesParsed  += bytes_consumed;
    m_FeedBytesPending -= bytes_consumed;
    
    return AP4_SUCCESS;
}