MPEG4Writer.cpp revision b21c564ce47041f9dd3ab65e36fed57c4937a42d
1/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//#define LOG_NDEBUG 0
18#define LOG_TAG "MPEG4Writer"
19#include <utils/Log.h>
20
21#include <arpa/inet.h>
22
23#include <pthread.h>
24#include <sys/prctl.h>
25#include <sys/resource.h>
26
27#include <media/stagefright/MPEG4Writer.h>
28#include <media/stagefright/MediaBuffer.h>
29#include <media/stagefright/MetaData.h>
30#include <media/stagefright/MediaDebug.h>
31#include <media/stagefright/MediaDefs.h>
32#include <media/stagefright/MediaErrors.h>
33#include <media/stagefright/MediaSource.h>
34#include <media/stagefright/Utils.h>
35#include <media/mediarecorder.h>
36#include <sys/types.h>
37#include <sys/stat.h>
38#include <fcntl.h>
39#include <unistd.h>
40
41#include "include/ESDS.h"
42
43namespace android {
44
45static const int64_t kMax32BitFileSize = 0x007fffffffLL;
46static const uint8_t kNalUnitTypeSeqParamSet = 0x07;
47static const uint8_t kNalUnitTypePicParamSet = 0x08;
48
49// Using longer adjustment period to suppress fluctuations in
50// the audio encoding paths
51static const int64_t kVideoMediaTimeAdjustPeriodTimeUs = 600000000LL;  // 10 minutes
52
53class MPEG4Writer::Track {
54public:
55    Track(MPEG4Writer *owner, const sp<MediaSource> &source, size_t trackId);
56
57    ~Track();
58
59    status_t start(MetaData *params);
60    status_t stop();
61    status_t pause();
62    bool reachedEOS();
63
64    int64_t getDurationUs() const;
65    int64_t getEstimatedTrackSizeBytes() const;
66    void writeTrackHeader(bool use32BitOffset = true);
67    void bufferChunk(int64_t timestampUs);
68    bool isAvc() const { return mIsAvc; }
69    bool isAudio() const { return mIsAudio; }
70    bool isMPEG4() const { return mIsMPEG4; }
71    void addChunkOffset(off64_t offset);
72    status_t dump(int fd, const Vector<String16>& args) const;
73
74private:
75    MPEG4Writer *mOwner;
76    sp<MetaData> mMeta;
77    sp<MediaSource> mSource;
78    volatile bool mDone;
79    volatile bool mPaused;
80    volatile bool mResumed;
81    volatile bool mStarted;
82    bool mIsAvc;
83    bool mIsAudio;
84    bool mIsMPEG4;
85    int32_t mTrackId;
86    int64_t mTrackDurationUs;
87
88    // For realtime applications, we need to adjust the media clock
89    // for video track based on the audio media clock
90    bool mIsRealTimeRecording;
91    int64_t mMaxTimeStampUs;
92    int64_t mEstimatedTrackSizeBytes;
93    int64_t mMdatSizeBytes;
94    int32_t mTimeScale;
95
96    pthread_t mThread;
97
98    // mNumSamples is used to track how many samples in mSampleSizes List.
99    // This is to reduce the cost associated with mSampleSizes.size() call,
100    // since it is O(n). Ideally, the fix should be in List class.
101    size_t              mNumSamples;
102    List<size_t>        mSampleSizes;
103    bool                mSamplesHaveSameSize;
104
105    List<MediaBuffer *> mChunkSamples;
106
107    size_t              mNumStcoTableEntries;
108    List<off64_t>         mChunkOffsets;
109
110    size_t              mNumStscTableEntries;
111    struct StscTableEntry {
112
113        StscTableEntry(uint32_t chunk, uint32_t samples, uint32_t id)
114            : firstChunk(chunk),
115              samplesPerChunk(samples),
116              sampleDescriptionId(id) {}
117
118        uint32_t firstChunk;
119        uint32_t samplesPerChunk;
120        uint32_t sampleDescriptionId;
121    };
122    List<StscTableEntry> mStscTableEntries;
123
124    size_t        mNumStssTableEntries;
125    List<int32_t> mStssTableEntries;
126
127    size_t        mNumSttsTableEntries;
128    struct SttsTableEntry {
129
130        SttsTableEntry(uint32_t count, uint32_t durationUs)
131            : sampleCount(count), sampleDurationUs(durationUs) {}
132
133        uint32_t sampleCount;
134        uint32_t sampleDurationUs;
135    };
136    List<SttsTableEntry> mSttsTableEntries;
137
138    // Sequence parameter set or picture parameter set
139    struct AVCParamSet {
140        AVCParamSet(uint16_t length, const uint8_t *data)
141            : mLength(length), mData(data) {}
142
143        uint16_t mLength;
144        const uint8_t *mData;
145    };
146    List<AVCParamSet> mSeqParamSets;
147    List<AVCParamSet> mPicParamSets;
148    uint8_t mProfileIdc;
149    uint8_t mProfileCompatible;
150    uint8_t mLevelIdc;
151
152    void *mCodecSpecificData;
153    size_t mCodecSpecificDataSize;
154    bool mGotAllCodecSpecificData;
155    bool mTrackingProgressStatus;
156
157    bool mReachedEOS;
158    int64_t mStartTimestampUs;
159    int64_t mPreviousTrackTimeUs;
160    int64_t mTrackEveryTimeDurationUs;
161
162    // Has the media time adjustment for video started?
163    bool    mIsMediaTimeAdjustmentOn;
164    // The time stamp when previous media time adjustment period starts
165    int64_t mPrevMediaTimeAdjustTimestampUs;
166    // Number of vidoe frames whose time stamp may be adjusted
167    int64_t mMediaTimeAdjustNumFrames;
168    // The sample number when previous meida time adjustmnet period starts
169    int64_t mPrevMediaTimeAdjustSample;
170    // The total accumulated drift time within a period of
171    // kVideoMediaTimeAdjustPeriodTimeUs.
172    int64_t mTotalDriftTimeToAdjustUs;
173    // The total accumalated drift time since the start of the recording
174    // excluding the current time adjustment period
175    int64_t mPrevTotalAccumDriftTimeUs;
176
177    // Update the audio track's drift information.
178    void updateDriftTime(const sp<MetaData>& meta);
179
180    // Adjust the time stamp of the video track according to
181    // the drift time information from the audio track.
182    void adjustMediaTime(int64_t *timestampUs);
183
184    static void *ThreadWrapper(void *me);
185    status_t threadEntry();
186
187    const uint8_t *parseParamSet(
188        const uint8_t *data, size_t length, int type, size_t *paramSetLen);
189
190    status_t makeAVCCodecSpecificData(const uint8_t *data, size_t size);
191    status_t copyAVCCodecSpecificData(const uint8_t *data, size_t size);
192    status_t parseAVCCodecSpecificData(const uint8_t *data, size_t size);
193
194    // Track authoring progress status
195    void trackProgressStatus(int64_t timeUs, status_t err = OK);
196    void initTrackingProgressStatus(MetaData *params);
197
198    void getCodecSpecificDataFromInputFormatIfPossible();
199
200    // Determine the track time scale
201    // If it is an audio track, try to use the sampling rate as
202    // the time scale; however, if user chooses the overwrite
203    // value, the user-supplied time scale will be used.
204    void setTimeScale();
205
206    // Simple validation on the codec specific data
207    status_t checkCodecSpecificData() const;
208    int32_t mRotation;
209
210    void updateTrackSizeEstimate();
211    void addOneStscTableEntry(size_t chunkId, size_t sampleId);
212    void addOneStssTableEntry(size_t sampleId);
213    void addOneSttsTableEntry(size_t sampleCount, int64_t durationUs);
214
215    // Write the boxes
216    void writeStcoBox(bool use32BitOffset);
217    void writeStscBox();
218    void writeStszBox();
219    void writeStssBox();
220    void writeSttsBox();
221    void writeD263Box();
222    void writePaspBox();
223    void writeAvccBox();
224    void writeUrlBox();
225    void writeDrefBox();
226    void writeDinfBox();
227    void writeDamrBox();
228    void writeMdhdBox(time_t now);
229    void writeSmhdBox();
230    void writeVmhdBox();
231    void writeHdlrBox();
232    void writeTkhdBox(time_t now);
233    void writeMp4aEsdsBox();
234    void writeMp4vEsdsBox();
235    void writeAudioFourCCBox();
236    void writeVideoFourCCBox();
237    void writeStblBox(bool use32BitOffset);
238
239    Track(const Track &);
240    Track &operator=(const Track &);
241};
242
243MPEG4Writer::MPEG4Writer(const char *filename)
244    : mFd(-1),
245      mInitCheck(NO_INIT),
246      mUse4ByteNalLength(true),
247      mUse32BitOffset(true),
248      mIsFileSizeLimitExplicitlyRequested(false),
249      mPaused(false),
250      mStarted(false),
251      mOffset(0),
252      mMdatOffset(0),
253      mEstimatedMoovBoxSize(0),
254      mInterleaveDurationUs(1000000) {
255
256    mFd = open(filename, O_CREAT | O_LARGEFILE | O_TRUNC | O_RDWR);
257    if (mFd >= 0) {
258        mInitCheck = OK;
259    }
260}
261
262MPEG4Writer::MPEG4Writer(int fd)
263    : mFd(dup(fd)),
264      mInitCheck(mFd < 0? NO_INIT: OK),
265      mUse4ByteNalLength(true),
266      mUse32BitOffset(true),
267      mIsFileSizeLimitExplicitlyRequested(false),
268      mPaused(false),
269      mStarted(false),
270      mOffset(0),
271      mMdatOffset(0),
272      mEstimatedMoovBoxSize(0),
273      mInterleaveDurationUs(1000000) {
274}
275
276MPEG4Writer::~MPEG4Writer() {
277    stop();
278
279    while (!mTracks.empty()) {
280        List<Track *>::iterator it = mTracks.begin();
281        delete *it;
282        (*it) = NULL;
283        mTracks.erase(it);
284    }
285    mTracks.clear();
286}
287
288status_t MPEG4Writer::dump(
289        int fd, const Vector<String16>& args) {
290    const size_t SIZE = 256;
291    char buffer[SIZE];
292    String8 result;
293    snprintf(buffer, SIZE, "   MPEG4Writer %p\n", this);
294    result.append(buffer);
295    snprintf(buffer, SIZE, "     mStarted: %s\n", mStarted? "true": "false");
296    result.append(buffer);
297    ::write(fd, result.string(), result.size());
298    for (List<Track *>::iterator it = mTracks.begin();
299         it != mTracks.end(); ++it) {
300        (*it)->dump(fd, args);
301    }
302    return OK;
303}
304
305status_t MPEG4Writer::Track::dump(
306        int fd, const Vector<String16>& args) const {
307    const size_t SIZE = 256;
308    char buffer[SIZE];
309    String8 result;
310    snprintf(buffer, SIZE, "     %s track\n", mIsAudio? "Audio": "Video");
311    result.append(buffer);
312    snprintf(buffer, SIZE, "       reached EOS: %s\n",
313            mReachedEOS? "true": "false");
314    result.append(buffer);
315    ::write(fd, result.string(), result.size());
316    return OK;
317}
318
319status_t MPEG4Writer::addSource(const sp<MediaSource> &source) {
320    Mutex::Autolock l(mLock);
321    if (mStarted) {
322        LOGE("Attempt to add source AFTER recording is started");
323        return UNKNOWN_ERROR;
324    }
325    Track *track = new Track(this, source, mTracks.size());
326    mTracks.push_back(track);
327
328    return OK;
329}
330
331status_t MPEG4Writer::startTracks(MetaData *params) {
332    for (List<Track *>::iterator it = mTracks.begin();
333         it != mTracks.end(); ++it) {
334        status_t err = (*it)->start(params);
335
336        if (err != OK) {
337            for (List<Track *>::iterator it2 = mTracks.begin();
338                 it2 != it; ++it2) {
339                (*it2)->stop();
340            }
341
342            return err;
343        }
344    }
345    return OK;
346}
347
348int64_t MPEG4Writer::estimateMoovBoxSize(int32_t bitRate) {
349    // This implementation is highly experimental/heurisitic.
350    //
351    // Statistical analysis shows that metadata usually accounts
352    // for a small portion of the total file size, usually < 0.6%.
353
354    // The default MIN_MOOV_BOX_SIZE is set to 0.6% x 1MB / 2,
355    // where 1MB is the common file size limit for MMS application.
356    // The default MAX _MOOV_BOX_SIZE value is based on about 3
357    // minute video recording with a bit rate about 3 Mbps, because
358    // statistics also show that most of the video captured are going
359    // to be less than 3 minutes.
360
361    // If the estimation is wrong, we will pay the price of wasting
362    // some reserved space. This should not happen so often statistically.
363    static const int32_t factor = mUse32BitOffset? 1: 2;
364    static const int64_t MIN_MOOV_BOX_SIZE = 3 * 1024;  // 3 KB
365    static const int64_t MAX_MOOV_BOX_SIZE = (180 * 3000000 * 6LL / 8000);
366    int64_t size = MIN_MOOV_BOX_SIZE;
367
368    // Max file size limit is set
369    if (mMaxFileSizeLimitBytes != 0 && mIsFileSizeLimitExplicitlyRequested) {
370        size = mMaxFileSizeLimitBytes * 6 / 1000;
371    }
372
373    // Max file duration limit is set
374    if (mMaxFileDurationLimitUs != 0) {
375        if (bitRate > 0) {
376            int64_t size2 =
377                ((mMaxFileDurationLimitUs * bitRate * 6) / 1000 / 8000000);
378            if (mMaxFileSizeLimitBytes != 0 && mIsFileSizeLimitExplicitlyRequested) {
379                // When both file size and duration limits are set,
380                // we use the smaller limit of the two.
381                if (size > size2) {
382                    size = size2;
383                }
384            } else {
385                // Only max file duration limit is set
386                size = size2;
387            }
388        }
389    }
390
391    if (size < MIN_MOOV_BOX_SIZE) {
392        size = MIN_MOOV_BOX_SIZE;
393    }
394
395    // Any long duration recording will be probably end up with
396    // non-streamable mp4 file.
397    if (size > MAX_MOOV_BOX_SIZE) {
398        size = MAX_MOOV_BOX_SIZE;
399    }
400
401    LOGI("limits: %lld/%lld bytes/us, bit rate: %d bps and the estimated"
402         " moov size %lld bytes",
403         mMaxFileSizeLimitBytes, mMaxFileDurationLimitUs, bitRate, size);
404    return factor * size;
405}
406
407status_t MPEG4Writer::start(MetaData *param) {
408    if (mInitCheck != OK) {
409        return UNKNOWN_ERROR;
410    }
411
412    /*
413     * Check mMaxFileSizeLimitBytes at the beginning
414     * since mMaxFileSizeLimitBytes may be implicitly
415     * changed later for 32-bit file offset even if
416     * user does not ask to set it explicitly.
417     */
418    if (mMaxFileSizeLimitBytes != 0) {
419        mIsFileSizeLimitExplicitlyRequested = true;
420    }
421
422    int32_t use64BitOffset;
423    if (param &&
424        param->findInt32(kKey64BitFileOffset, &use64BitOffset) &&
425        use64BitOffset) {
426        mUse32BitOffset = false;
427    }
428
429    if (mUse32BitOffset) {
430        // Implicit 32 bit file size limit
431        if (mMaxFileSizeLimitBytes == 0) {
432            mMaxFileSizeLimitBytes = kMax32BitFileSize;
433        }
434
435        // If file size is set to be larger than the 32 bit file
436        // size limit, treat it as an error.
437        if (mMaxFileSizeLimitBytes > kMax32BitFileSize) {
438            LOGW("32-bit file size limit (%lld bytes) too big. "
439                 "It is changed to %lld bytes",
440                mMaxFileSizeLimitBytes, kMax32BitFileSize);
441            mMaxFileSizeLimitBytes = kMax32BitFileSize;
442        }
443    }
444
445    int32_t use2ByteNalLength;
446    if (param &&
447        param->findInt32(kKey2ByteNalLength, &use2ByteNalLength) &&
448        use2ByteNalLength) {
449        mUse4ByteNalLength = false;
450    }
451
452    mStartTimestampUs = -1;
453
454    if (mStarted) {
455        if (mPaused) {
456            mPaused = false;
457            return startTracks(param);
458        }
459        return OK;
460    }
461
462    if (!param ||
463        !param->findInt32(kKeyTimeScale, &mTimeScale)) {
464        mTimeScale = 1000;
465    }
466    CHECK(mTimeScale > 0);
467    LOGV("movie time scale: %d", mTimeScale);
468
469    mStreamableFile = true;
470    mWriteMoovBoxToMemory = false;
471    mMoovBoxBuffer = NULL;
472    mMoovBoxBufferOffset = 0;
473
474    writeFtypBox(param);
475
476    mFreeBoxOffset = mOffset;
477
478    if (mEstimatedMoovBoxSize == 0) {
479        int32_t bitRate = -1;
480        if (param) {
481            param->findInt32(kKeyBitRate, &bitRate);
482        }
483        mEstimatedMoovBoxSize = estimateMoovBoxSize(bitRate);
484    }
485    CHECK(mEstimatedMoovBoxSize >= 8);
486    lseek64(mFd, mFreeBoxOffset, SEEK_SET);
487    writeInt32(mEstimatedMoovBoxSize);
488    write("free", 4);
489
490    mMdatOffset = mFreeBoxOffset + mEstimatedMoovBoxSize;
491    mOffset = mMdatOffset;
492    lseek64(mFd, mMdatOffset, SEEK_SET);
493    if (mUse32BitOffset) {
494        write("????mdat", 8);
495    } else {
496        write("\x00\x00\x00\x01mdat????????", 16);
497    }
498
499    status_t err = startWriterThread();
500    if (err != OK) {
501        return err;
502    }
503
504    err = startTracks(param);
505    if (err != OK) {
506        return err;
507    }
508
509    mStarted = true;
510    return OK;
511}
512
513bool MPEG4Writer::use32BitFileOffset() const {
514    return mUse32BitOffset;
515}
516
517status_t MPEG4Writer::pause() {
518    if (mInitCheck != OK) {
519        return OK;
520    }
521    mPaused = true;
522    status_t err = OK;
523    for (List<Track *>::iterator it = mTracks.begin();
524         it != mTracks.end(); ++it) {
525        status_t status = (*it)->pause();
526        if (status != OK) {
527            err = status;
528        }
529    }
530    return err;
531}
532
533void MPEG4Writer::stopWriterThread() {
534    LOGD("Stopping writer thread");
535
536    {
537        Mutex::Autolock autolock(mLock);
538
539        mDone = true;
540        mChunkReadyCondition.signal();
541    }
542
543    void *dummy;
544    pthread_join(mThread, &dummy);
545    LOGD("Writer thread stopped");
546}
547
548/*
549 * MP4 file standard defines a composition matrix:
550 * | a  b  u |
551 * | c  d  v |
552 * | x  y  w |
553 *
554 * the element in the matrix is stored in the following
555 * order: {a, b, u, c, d, v, x, y, w},
556 * where a, b, c, d, x, and y is in 16.16 format, while
557 * u, v and w is in 2.30 format.
558 */
559void MPEG4Writer::writeCompositionMatrix(int degrees) {
560    LOGV("writeCompositionMatrix");
561    uint32_t a = 0x00010000;
562    uint32_t b = 0;
563    uint32_t c = 0;
564    uint32_t d = 0x00010000;
565    switch (degrees) {
566        case 0:
567            break;
568        case 90:
569            a = 0;
570            b = 0x00010000;
571            c = 0xFFFF0000;
572            d = 0;
573            break;
574        case 180:
575            a = 0xFFFF0000;
576            d = 0xFFFF0000;
577            break;
578        case 270:
579            a = 0;
580            b = 0xFFFF0000;
581            c = 0x00010000;
582            d = 0;
583            break;
584        default:
585            CHECK(!"Should never reach this unknown rotation");
586            break;
587    }
588
589    writeInt32(a);           // a
590    writeInt32(b);           // b
591    writeInt32(0);           // u
592    writeInt32(c);           // c
593    writeInt32(d);           // d
594    writeInt32(0);           // v
595    writeInt32(0);           // x
596    writeInt32(0);           // y
597    writeInt32(0x40000000);  // w
598}
599
600
601status_t MPEG4Writer::stop() {
602    if (mInitCheck != OK) {
603        return OK;
604    }
605
606    status_t err = OK;
607    int64_t maxDurationUs = 0;
608    int64_t minDurationUs = 0x7fffffffffffffffLL;
609    for (List<Track *>::iterator it = mTracks.begin();
610         it != mTracks.end(); ++it) {
611        status_t status = (*it)->stop();
612        if (err == OK && status != OK) {
613            err = status;
614        }
615
616        int64_t durationUs = (*it)->getDurationUs();
617        if (durationUs > maxDurationUs) {
618            maxDurationUs = durationUs;
619        }
620        if (durationUs < minDurationUs) {
621            minDurationUs = durationUs;
622        }
623    }
624
625    if (mTracks.size() > 1) {
626        LOGD("Duration from tracks range is [%lld, %lld] us",
627            minDurationUs, maxDurationUs);
628    }
629
630    stopWriterThread();
631
632    // Do not write out movie header on error.
633    if (err != OK) {
634        close(mFd);
635        mFd = -1;
636        mInitCheck = NO_INIT;
637        mStarted = false;
638        return err;
639    }
640
641    // Fix up the size of the 'mdat' chunk.
642    if (mUse32BitOffset) {
643        lseek64(mFd, mMdatOffset, SEEK_SET);
644        int32_t size = htonl(static_cast<int32_t>(mOffset - mMdatOffset));
645        ::write(mFd, &size, 4);
646    } else {
647        lseek64(mFd, mMdatOffset + 8, SEEK_SET);
648        int64_t size = mOffset - mMdatOffset;
649        size = hton64(size);
650        ::write(mFd, &size, 8);
651    }
652    lseek64(mFd, mOffset, SEEK_SET);
653
654    const off64_t moovOffset = mOffset;
655    mWriteMoovBoxToMemory = true;
656    mMoovBoxBuffer = (uint8_t *) malloc(mEstimatedMoovBoxSize);
657    mMoovBoxBufferOffset = 0;
658    CHECK(mMoovBoxBuffer != NULL);
659    writeMoovBox(maxDurationUs);
660
661    mWriteMoovBoxToMemory = false;
662    if (mStreamableFile) {
663        CHECK(mMoovBoxBufferOffset + 8 <= mEstimatedMoovBoxSize);
664
665        // Moov box
666        lseek64(mFd, mFreeBoxOffset, SEEK_SET);
667        mOffset = mFreeBoxOffset;
668        write(mMoovBoxBuffer, 1, mMoovBoxBufferOffset);
669
670        // Free box
671        lseek64(mFd, mOffset, SEEK_SET);
672        writeInt32(mEstimatedMoovBoxSize - mMoovBoxBufferOffset);
673        write("free", 4);
674
675        // Free temp memory
676        free(mMoovBoxBuffer);
677        mMoovBoxBuffer = NULL;
678        mMoovBoxBufferOffset = 0;
679    } else {
680        LOGI("The mp4 file will not be streamable.");
681    }
682
683    CHECK(mBoxes.empty());
684
685    close(mFd);
686    mFd = -1;
687    mInitCheck = NO_INIT;
688    mStarted = false;
689    return err;
690}
691
692void MPEG4Writer::writeMvhdBox(int64_t durationUs) {
693    time_t now = time(NULL);
694    beginBox("mvhd");
695    writeInt32(0);             // version=0, flags=0
696    writeInt32(now);           // creation time
697    writeInt32(now);           // modification time
698    writeInt32(mTimeScale);    // mvhd timescale
699    int32_t duration = (durationUs * mTimeScale + 5E5) / 1E6;
700    writeInt32(duration);
701    writeInt32(0x10000);       // rate: 1.0
702    writeInt16(0x100);         // volume
703    writeInt16(0);             // reserved
704    writeInt32(0);             // reserved
705    writeInt32(0);             // reserved
706    writeCompositionMatrix(0); // matrix
707    writeInt32(0);             // predefined
708    writeInt32(0);             // predefined
709    writeInt32(0);             // predefined
710    writeInt32(0);             // predefined
711    writeInt32(0);             // predefined
712    writeInt32(0);             // predefined
713    writeInt32(mTracks.size() + 1);  // nextTrackID
714    endBox();  // mvhd
715}
716
717void MPEG4Writer::writeMoovBox(int64_t durationUs) {
718    beginBox("moov");
719    writeMvhdBox(durationUs);
720    int32_t id = 1;
721    for (List<Track *>::iterator it = mTracks.begin();
722        it != mTracks.end(); ++it, ++id) {
723        (*it)->writeTrackHeader(mUse32BitOffset);
724    }
725    endBox();  // moov
726}
727
728void MPEG4Writer::writeFtypBox(MetaData *param) {
729    beginBox("ftyp");
730
731    int32_t fileType;
732    if (param && param->findInt32(kKeyFileType, &fileType) &&
733        fileType != OUTPUT_FORMAT_MPEG_4) {
734        writeFourcc("3gp4");
735    } else {
736        writeFourcc("isom");
737    }
738
739    writeInt32(0);
740    writeFourcc("isom");
741    writeFourcc("3gp4");
742    endBox();
743}
744
745status_t MPEG4Writer::setInterleaveDuration(uint32_t durationUs) {
746    mInterleaveDurationUs = durationUs;
747    return OK;
748}
749
750void MPEG4Writer::lock() {
751    mLock.lock();
752}
753
754void MPEG4Writer::unlock() {
755    mLock.unlock();
756}
757
758off64_t MPEG4Writer::addSample_l(MediaBuffer *buffer) {
759    off64_t old_offset = mOffset;
760
761    ::write(mFd,
762          (const uint8_t *)buffer->data() + buffer->range_offset(),
763          buffer->range_length());
764
765    mOffset += buffer->range_length();
766
767    return old_offset;
768}
769
770static void StripStartcode(MediaBuffer *buffer) {
771    if (buffer->range_length() < 4) {
772        return;
773    }
774
775    const uint8_t *ptr =
776        (const uint8_t *)buffer->data() + buffer->range_offset();
777
778    if (!memcmp(ptr, "\x00\x00\x00\x01", 4)) {
779        buffer->set_range(
780                buffer->range_offset() + 4, buffer->range_length() - 4);
781    }
782}
783
784off64_t MPEG4Writer::addLengthPrefixedSample_l(MediaBuffer *buffer) {
785    off64_t old_offset = mOffset;
786
787    size_t length = buffer->range_length();
788
789    if (mUse4ByteNalLength) {
790        uint8_t x = length >> 24;
791        ::write(mFd, &x, 1);
792        x = (length >> 16) & 0xff;
793        ::write(mFd, &x, 1);
794        x = (length >> 8) & 0xff;
795        ::write(mFd, &x, 1);
796        x = length & 0xff;
797        ::write(mFd, &x, 1);
798
799        ::write(mFd,
800              (const uint8_t *)buffer->data() + buffer->range_offset(),
801              length);
802
803        mOffset += length + 4;
804    } else {
805        CHECK(length < 65536);
806
807        uint8_t x = length >> 8;
808        ::write(mFd, &x, 1);
809        x = length & 0xff;
810        ::write(mFd, &x, 1);
811        ::write(mFd, (const uint8_t *)buffer->data() + buffer->range_offset(), length);
812        mOffset += length + 2;
813    }
814
815    return old_offset;
816}
817
818size_t MPEG4Writer::write(
819        const void *ptr, size_t size, size_t nmemb) {
820
821    const size_t bytes = size * nmemb;
822    if (mWriteMoovBoxToMemory) {
823        // This happens only when we write the moov box at the end of
824        // recording, not for each output video/audio frame we receive.
825        off64_t moovBoxSize = 8 + mMoovBoxBufferOffset + bytes;
826        if (moovBoxSize > mEstimatedMoovBoxSize) {
827            for (List<off64_t>::iterator it = mBoxes.begin();
828                 it != mBoxes.end(); ++it) {
829                (*it) += mOffset;
830            }
831            lseek64(mFd, mOffset, SEEK_SET);
832            ::write(mFd, mMoovBoxBuffer, mMoovBoxBufferOffset);
833            ::write(mFd, ptr, size * nmemb);
834            mOffset += (bytes + mMoovBoxBufferOffset);
835            free(mMoovBoxBuffer);
836            mMoovBoxBuffer = NULL;
837            mMoovBoxBufferOffset = 0;
838            mWriteMoovBoxToMemory = false;
839            mStreamableFile = false;
840        } else {
841            memcpy(mMoovBoxBuffer + mMoovBoxBufferOffset, ptr, bytes);
842            mMoovBoxBufferOffset += bytes;
843        }
844    } else {
845        ::write(mFd, ptr, size * nmemb);
846        mOffset += bytes;
847    }
848    return bytes;
849}
850
851void MPEG4Writer::beginBox(const char *fourcc) {
852    CHECK_EQ(strlen(fourcc), 4);
853
854    mBoxes.push_back(mWriteMoovBoxToMemory?
855            mMoovBoxBufferOffset: mOffset);
856
857    writeInt32(0);
858    writeFourcc(fourcc);
859}
860
861void MPEG4Writer::endBox() {
862    CHECK(!mBoxes.empty());
863
864    off64_t offset = *--mBoxes.end();
865    mBoxes.erase(--mBoxes.end());
866
867    if (mWriteMoovBoxToMemory) {
868       int32_t x = htonl(mMoovBoxBufferOffset - offset);
869       memcpy(mMoovBoxBuffer + offset, &x, 4);
870    } else {
871        lseek64(mFd, offset, SEEK_SET);
872        writeInt32(mOffset - offset);
873        mOffset -= 4;
874        lseek64(mFd, mOffset, SEEK_SET);
875    }
876}
877
878void MPEG4Writer::writeInt8(int8_t x) {
879    write(&x, 1, 1);
880}
881
882void MPEG4Writer::writeInt16(int16_t x) {
883    x = htons(x);
884    write(&x, 1, 2);
885}
886
887void MPEG4Writer::writeInt32(int32_t x) {
888    x = htonl(x);
889    write(&x, 1, 4);
890}
891
892void MPEG4Writer::writeInt64(int64_t x) {
893    x = hton64(x);
894    write(&x, 1, 8);
895}
896
897void MPEG4Writer::writeCString(const char *s) {
898    size_t n = strlen(s);
899    write(s, 1, n + 1);
900}
901
902void MPEG4Writer::writeFourcc(const char *s) {
903    CHECK_EQ(strlen(s), 4);
904    write(s, 1, 4);
905}
906
907void MPEG4Writer::write(const void *data, size_t size) {
908    write(data, 1, size);
909}
910
911bool MPEG4Writer::isFileStreamable() const {
912    return mStreamableFile;
913}
914
915bool MPEG4Writer::exceedsFileSizeLimit() {
916    // No limit
917    if (mMaxFileSizeLimitBytes == 0) {
918        return false;
919    }
920
921    int64_t nTotalBytesEstimate = static_cast<int64_t>(mEstimatedMoovBoxSize);
922    for (List<Track *>::iterator it = mTracks.begin();
923         it != mTracks.end(); ++it) {
924        nTotalBytesEstimate += (*it)->getEstimatedTrackSizeBytes();
925    }
926
927    // Be conservative in the estimate: do not exceed 95% of
928    // the target file limit. For small target file size limit, though,
929    // this will not help.
930    return (nTotalBytesEstimate >= (95 * mMaxFileSizeLimitBytes) / 100);
931}
932
933bool MPEG4Writer::exceedsFileDurationLimit() {
934    // No limit
935    if (mMaxFileDurationLimitUs == 0) {
936        return false;
937    }
938
939    for (List<Track *>::iterator it = mTracks.begin();
940         it != mTracks.end(); ++it) {
941        if ((*it)->getDurationUs() >= mMaxFileDurationLimitUs) {
942            return true;
943        }
944    }
945    return false;
946}
947
948bool MPEG4Writer::reachedEOS() {
949    bool allDone = true;
950    for (List<Track *>::iterator it = mTracks.begin();
951         it != mTracks.end(); ++it) {
952        if (!(*it)->reachedEOS()) {
953            allDone = false;
954            break;
955        }
956    }
957
958    return allDone;
959}
960
961void MPEG4Writer::setStartTimestampUs(int64_t timeUs) {
962    LOGI("setStartTimestampUs: %lld", timeUs);
963    CHECK(timeUs >= 0);
964    Mutex::Autolock autoLock(mLock);
965    if (mStartTimestampUs < 0 || mStartTimestampUs > timeUs) {
966        mStartTimestampUs = timeUs;
967        LOGI("Earliest track starting time: %lld", mStartTimestampUs);
968    }
969}
970
971int64_t MPEG4Writer::getStartTimestampUs() {
972    Mutex::Autolock autoLock(mLock);
973    return mStartTimestampUs;
974}
975
976size_t MPEG4Writer::numTracks() {
977    Mutex::Autolock autolock(mLock);
978    return mTracks.size();
979}
980
981////////////////////////////////////////////////////////////////////////////////
982
983MPEG4Writer::Track::Track(
984        MPEG4Writer *owner, const sp<MediaSource> &source, size_t trackId)
985    : mOwner(owner),
986      mMeta(source->getFormat()),
987      mSource(source),
988      mDone(false),
989      mPaused(false),
990      mResumed(false),
991      mStarted(false),
992      mTrackId(trackId),
993      mTrackDurationUs(0),
994      mEstimatedTrackSizeBytes(0),
995      mSamplesHaveSameSize(true),
996      mCodecSpecificData(NULL),
997      mCodecSpecificDataSize(0),
998      mGotAllCodecSpecificData(false),
999      mReachedEOS(false),
1000      mRotation(0) {
1001    getCodecSpecificDataFromInputFormatIfPossible();
1002
1003    const char *mime;
1004    mMeta->findCString(kKeyMIMEType, &mime);
1005    mIsAvc = !strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_AVC);
1006    mIsAudio = !strncasecmp(mime, "audio/", 6);
1007    mIsMPEG4 = !strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_MPEG4) ||
1008               !strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_AAC);
1009
1010    setTimeScale();
1011}
1012
1013void MPEG4Writer::Track::updateTrackSizeEstimate() {
1014
1015    int64_t stcoBoxSizeBytes = mOwner->use32BitFileOffset()
1016                                ? mNumStcoTableEntries * 4
1017                                : mNumStcoTableEntries * 8;
1018
1019    int64_t stszBoxSizeBytes = mSamplesHaveSameSize? 4: (mNumSamples * 4);
1020
1021    mEstimatedTrackSizeBytes = mMdatSizeBytes;  // media data size
1022    if (!mOwner->isFileStreamable()) {
1023        // Reserved free space is not large enough to hold
1024        // all meta data and thus wasted.
1025        mEstimatedTrackSizeBytes += mNumStscTableEntries * 12 +  // stsc box size
1026                                    mNumStssTableEntries * 4 +   // stss box size
1027                                    mNumSttsTableEntries * 8 +   // stts box size
1028                                    stcoBoxSizeBytes +           // stco box size
1029                                    stszBoxSizeBytes;            // stsz box size
1030    }
1031}
1032
1033void MPEG4Writer::Track::addOneStscTableEntry(
1034        size_t chunkId, size_t sampleId) {
1035
1036        StscTableEntry stscEntry(chunkId, sampleId, 1);
1037        mStscTableEntries.push_back(stscEntry);
1038        ++mNumStscTableEntries;
1039}
1040
1041void MPEG4Writer::Track::addOneStssTableEntry(size_t sampleId) {
1042    mStssTableEntries.push_back(sampleId);
1043    ++mNumStssTableEntries;
1044}
1045
1046void MPEG4Writer::Track::addOneSttsTableEntry(
1047        size_t sampleCount, int64_t durationUs) {
1048
1049    SttsTableEntry sttsEntry(sampleCount, durationUs);
1050    mSttsTableEntries.push_back(sttsEntry);
1051    ++mNumSttsTableEntries;
1052}
1053
1054void MPEG4Writer::Track::addChunkOffset(off64_t offset) {
1055    ++mNumStcoTableEntries;
1056    mChunkOffsets.push_back(offset);
1057}
1058
1059void MPEG4Writer::Track::setTimeScale() {
1060    LOGV("setTimeScale");
1061    // Default time scale
1062    mTimeScale = 90000;
1063
1064    if (mIsAudio) {
1065        // Use the sampling rate as the default time scale for audio track.
1066        int32_t sampleRate;
1067        bool success = mMeta->findInt32(kKeySampleRate, &sampleRate);
1068        CHECK(success);
1069        mTimeScale = sampleRate;
1070    }
1071
1072    // If someone would like to overwrite the timescale, use user-supplied value.
1073    int32_t timeScale;
1074    if (mMeta->findInt32(kKeyTimeScale, &timeScale)) {
1075        mTimeScale = timeScale;
1076    }
1077
1078    CHECK(mTimeScale > 0);
1079}
1080
1081void MPEG4Writer::Track::getCodecSpecificDataFromInputFormatIfPossible() {
1082    const char *mime;
1083    CHECK(mMeta->findCString(kKeyMIMEType, &mime));
1084
1085    if (!strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_AVC)) {
1086        uint32_t type;
1087        const void *data;
1088        size_t size;
1089        if (mMeta->findData(kKeyAVCC, &type, &data, &size)) {
1090            mCodecSpecificData = malloc(size);
1091            mCodecSpecificDataSize = size;
1092            memcpy(mCodecSpecificData, data, size);
1093            mGotAllCodecSpecificData = true;
1094        }
1095    } else if (!strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_MPEG4)
1096            || !strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_AAC)) {
1097        uint32_t type;
1098        const void *data;
1099        size_t size;
1100        if (mMeta->findData(kKeyESDS, &type, &data, &size)) {
1101            ESDS esds(data, size);
1102            if (esds.getCodecSpecificInfo(&data, &size) == OK) {
1103                mCodecSpecificData = malloc(size);
1104                mCodecSpecificDataSize = size;
1105                memcpy(mCodecSpecificData, data, size);
1106                mGotAllCodecSpecificData = true;
1107            }
1108        }
1109    }
1110}
1111
1112MPEG4Writer::Track::~Track() {
1113    stop();
1114
1115    if (mCodecSpecificData != NULL) {
1116        free(mCodecSpecificData);
1117        mCodecSpecificData = NULL;
1118    }
1119}
1120
1121void MPEG4Writer::Track::initTrackingProgressStatus(MetaData *params) {
1122    LOGV("initTrackingProgressStatus");
1123    mPreviousTrackTimeUs = -1;
1124    mTrackingProgressStatus = false;
1125    mTrackEveryTimeDurationUs = 0;
1126    {
1127        int64_t timeUs;
1128        if (params && params->findInt64(kKeyTrackTimeStatus, &timeUs)) {
1129            LOGV("Receive request to track progress status for every %lld us", timeUs);
1130            mTrackEveryTimeDurationUs = timeUs;
1131            mTrackingProgressStatus = true;
1132        }
1133    }
1134}
1135
1136// static
1137void *MPEG4Writer::ThreadWrapper(void *me) {
1138    LOGV("ThreadWrapper: %p", me);
1139    MPEG4Writer *writer = static_cast<MPEG4Writer *>(me);
1140    writer->threadFunc();
1141    return NULL;
1142}
1143
1144void MPEG4Writer::bufferChunk(const Chunk& chunk) {
1145    LOGV("bufferChunk: %p", chunk.mTrack);
1146    Mutex::Autolock autolock(mLock);
1147    CHECK_EQ(mDone, false);
1148
1149    for (List<ChunkInfo>::iterator it = mChunkInfos.begin();
1150         it != mChunkInfos.end(); ++it) {
1151
1152        if (chunk.mTrack == it->mTrack) {  // Found owner
1153            it->mChunks.push_back(chunk);
1154            mChunkReadyCondition.signal();
1155            return;
1156        }
1157    }
1158
1159    CHECK("Received a chunk for a unknown track" == 0);
1160}
1161
1162void MPEG4Writer::writeChunkToFile(Chunk* chunk) {
1163    LOGV("writeChunkToFile: %lld from %s track",
1164        chunk.mTimestampUs, chunk.mTrack->isAudio()? "audio": "video");
1165
1166    int32_t isFirstSample = true;
1167    while (!chunk->mSamples.empty()) {
1168        List<MediaBuffer *>::iterator it = chunk->mSamples.begin();
1169
1170        off64_t offset = chunk->mTrack->isAvc()
1171                                ? addLengthPrefixedSample_l(*it)
1172                                : addSample_l(*it);
1173
1174        if (isFirstSample) {
1175            chunk->mTrack->addChunkOffset(offset);
1176            isFirstSample = false;
1177        }
1178
1179        (*it)->release();
1180        (*it) = NULL;
1181        chunk->mSamples.erase(it);
1182    }
1183    chunk->mSamples.clear();
1184}
1185
1186void MPEG4Writer::writeAllChunks() {
1187    LOGV("writeAllChunks");
1188    size_t outstandingChunks = 0;
1189    while (!mChunkInfos.empty()) {
1190        List<ChunkInfo>::iterator it = mChunkInfos.begin();
1191        while (!it->mChunks.empty()) {
1192            Chunk chunk;
1193            if (findChunkToWrite(&chunk)) {
1194                writeChunkToFile(&chunk);
1195                ++outstandingChunks;
1196            }
1197        }
1198        it->mTrack = NULL;
1199        mChunkInfos.erase(it);
1200    }
1201    mChunkInfos.clear();
1202    LOGD("%d chunks are written in the last batch", outstandingChunks);
1203}
1204
1205bool MPEG4Writer::findChunkToWrite(Chunk *chunk) {
1206    LOGV("findChunkToWrite");
1207
1208    // Find the smallest timestamp, and write that chunk out
1209    // XXX: What if some track is just too slow?
1210    int64_t minTimestampUs = 0x7FFFFFFFFFFFFFFFLL;
1211    Track *track = NULL;
1212    for (List<ChunkInfo>::iterator it = mChunkInfos.begin();
1213         it != mChunkInfos.end(); ++it) {
1214        if (!it->mChunks.empty()) {
1215            List<Chunk>::iterator chunkIt = it->mChunks.begin();
1216            if (chunkIt->mTimeStampUs < minTimestampUs) {
1217                minTimestampUs = chunkIt->mTimeStampUs;
1218                track = it->mTrack;
1219            }
1220        }
1221    }
1222
1223    if (track == NULL) {
1224        LOGV("Nothing to be written after all");
1225        return false;
1226    }
1227
1228    if (mIsFirstChunk) {
1229        mIsFirstChunk = false;
1230    }
1231
1232    for (List<ChunkInfo>::iterator it = mChunkInfos.begin();
1233         it != mChunkInfos.end(); ++it) {
1234        if (it->mTrack == track) {
1235            *chunk = *(it->mChunks.begin());
1236            it->mChunks.erase(it->mChunks.begin());
1237            CHECK_EQ(chunk->mTrack, track);
1238            return true;
1239        }
1240    }
1241
1242    return false;
1243}
1244
1245void MPEG4Writer::threadFunc() {
1246    LOGV("threadFunc");
1247
1248    prctl(PR_SET_NAME, (unsigned long)"MPEG4Writer", 0, 0, 0);
1249
1250    Mutex::Autolock autoLock(mLock);
1251    while (!mDone) {
1252        Chunk chunk;
1253        bool chunkFound = false;
1254
1255        while (!mDone && !(chunkFound = findChunkToWrite(&chunk))) {
1256            mChunkReadyCondition.wait(mLock);
1257        }
1258
1259        // Actual write without holding the lock in order to
1260        // reduce the blocking time for media track threads.
1261        if (chunkFound) {
1262            mLock.unlock();
1263            writeChunkToFile(&chunk);
1264            mLock.lock();
1265        }
1266    }
1267
1268    writeAllChunks();
1269}
1270
1271status_t MPEG4Writer::startWriterThread() {
1272    LOGV("startWriterThread");
1273
1274    mDone = false;
1275    mIsFirstChunk = true;
1276    mDriftTimeUs = 0;
1277    for (List<Track *>::iterator it = mTracks.begin();
1278         it != mTracks.end(); ++it) {
1279        ChunkInfo info;
1280        info.mTrack = *it;
1281        mChunkInfos.push_back(info);
1282    }
1283
1284    pthread_attr_t attr;
1285    pthread_attr_init(&attr);
1286    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1287    pthread_create(&mThread, &attr, ThreadWrapper, this);
1288    pthread_attr_destroy(&attr);
1289    return OK;
1290}
1291
1292
1293status_t MPEG4Writer::Track::start(MetaData *params) {
1294    if (!mDone && mPaused) {
1295        mPaused = false;
1296        mResumed = true;
1297        return OK;
1298    }
1299
1300    int64_t startTimeUs;
1301    if (params == NULL || !params->findInt64(kKeyTime, &startTimeUs)) {
1302        startTimeUs = 0;
1303    }
1304
1305    int32_t rotationDegrees;
1306    if (!mIsAudio && params && params->findInt32(kKeyRotation, &rotationDegrees)) {
1307        mRotation = rotationDegrees;
1308    }
1309
1310    mIsRealTimeRecording = true;
1311    {
1312        int32_t isNotRealTime;
1313        if (params && params->findInt32(kKeyNotRealTime, &isNotRealTime)) {
1314            mIsRealTimeRecording = (isNotRealTime == 0);
1315        }
1316    }
1317
1318    initTrackingProgressStatus(params);
1319
1320    sp<MetaData> meta = new MetaData;
1321    if (mIsRealTimeRecording && mOwner->numTracks() > 1) {
1322        /*
1323         * This extra delay of accepting incoming audio/video signals
1324         * helps to align a/v start time at the beginning of a recording
1325         * session, and it also helps eliminate the "recording" sound for
1326         * camcorder applications.
1327         *
1328         * Ideally, this platform-specific value should be defined
1329         * in media_profiles.xml file
1330         */
1331        startTimeUs += 700000;
1332    }
1333
1334    meta->setInt64(kKeyTime, startTimeUs);
1335
1336    status_t err = mSource->start(meta.get());
1337    if (err != OK) {
1338        mDone = mReachedEOS = true;
1339        return err;
1340    }
1341
1342    pthread_attr_t attr;
1343    pthread_attr_init(&attr);
1344    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1345
1346    mDone = false;
1347    mStarted = true;
1348    mTrackDurationUs = 0;
1349    mReachedEOS = false;
1350    mEstimatedTrackSizeBytes = 0;
1351    mNumStcoTableEntries = 0;
1352    mNumStssTableEntries = 0;
1353    mNumStscTableEntries = 0;
1354    mNumSttsTableEntries = 0;
1355    mMdatSizeBytes = 0;
1356    mIsMediaTimeAdjustmentOn = false;
1357    mPrevMediaTimeAdjustTimestampUs = 0;
1358    mMediaTimeAdjustNumFrames = 0;
1359    mPrevMediaTimeAdjustSample = 0;
1360    mTotalDriftTimeToAdjustUs = 0;
1361    mPrevTotalAccumDriftTimeUs = 0;
1362
1363    pthread_create(&mThread, &attr, ThreadWrapper, this);
1364    pthread_attr_destroy(&attr);
1365
1366    return OK;
1367}
1368
1369status_t MPEG4Writer::Track::pause() {
1370    mPaused = true;
1371    return OK;
1372}
1373
1374status_t MPEG4Writer::Track::stop() {
1375    LOGD("Stopping %s track", mIsAudio? "Audio": "Video");
1376    if (!mStarted) {
1377        LOGE("Stop() called but track is not started");
1378        return ERROR_END_OF_STREAM;
1379    }
1380
1381    if (mDone) {
1382        return OK;
1383    }
1384    mDone = true;
1385
1386    void *dummy;
1387    pthread_join(mThread, &dummy);
1388
1389    status_t err = (status_t) dummy;
1390
1391    LOGD("Stopping %s track source", mIsAudio? "Audio": "Video");
1392    {
1393        status_t status = mSource->stop();
1394        if (err == OK && status != OK && status != ERROR_END_OF_STREAM) {
1395            err = status;
1396        }
1397    }
1398
1399    LOGD("%s track stopped", mIsAudio? "Audio": "Video");
1400    return err;
1401}
1402
1403bool MPEG4Writer::Track::reachedEOS() {
1404    return mReachedEOS;
1405}
1406
1407// static
1408void *MPEG4Writer::Track::ThreadWrapper(void *me) {
1409    Track *track = static_cast<Track *>(me);
1410
1411    status_t err = track->threadEntry();
1412    return (void *) err;
1413}
1414
1415static void getNalUnitType(uint8_t byte, uint8_t* type) {
1416    LOGV("getNalUnitType: %d", byte);
1417
1418    // nal_unit_type: 5-bit unsigned integer
1419    *type = (byte & 0x1F);
1420}
1421
1422static const uint8_t *findNextStartCode(
1423        const uint8_t *data, size_t length) {
1424
1425    LOGV("findNextStartCode: %p %d", data, length);
1426
1427    size_t bytesLeft = length;
1428    while (bytesLeft > 4  &&
1429            memcmp("\x00\x00\x00\x01", &data[length - bytesLeft], 4)) {
1430        --bytesLeft;
1431    }
1432    if (bytesLeft <= 4) {
1433        bytesLeft = 0; // Last parameter set
1434    }
1435    return &data[length - bytesLeft];
1436}
1437
1438const uint8_t *MPEG4Writer::Track::parseParamSet(
1439        const uint8_t *data, size_t length, int type, size_t *paramSetLen) {
1440
1441    LOGV("parseParamSet");
1442    CHECK(type == kNalUnitTypeSeqParamSet ||
1443          type == kNalUnitTypePicParamSet);
1444
1445    const uint8_t *nextStartCode = findNextStartCode(data, length);
1446    *paramSetLen = nextStartCode - data;
1447    if (*paramSetLen == 0) {
1448        LOGE("Param set is malformed, since its length is 0");
1449        return NULL;
1450    }
1451
1452    AVCParamSet paramSet(*paramSetLen, data);
1453    if (type == kNalUnitTypeSeqParamSet) {
1454        if (*paramSetLen < 4) {
1455            LOGE("Seq parameter set malformed");
1456            return NULL;
1457        }
1458        if (mSeqParamSets.empty()) {
1459            mProfileIdc = data[1];
1460            mProfileCompatible = data[2];
1461            mLevelIdc = data[3];
1462        } else {
1463            if (mProfileIdc != data[1] ||
1464                mProfileCompatible != data[2] ||
1465                mLevelIdc != data[3]) {
1466                LOGE("Inconsistent profile/level found in seq parameter sets");
1467                return NULL;
1468            }
1469        }
1470        mSeqParamSets.push_back(paramSet);
1471    } else {
1472        mPicParamSets.push_back(paramSet);
1473    }
1474    return nextStartCode;
1475}
1476
1477status_t MPEG4Writer::Track::copyAVCCodecSpecificData(
1478        const uint8_t *data, size_t size) {
1479    LOGV("copyAVCCodecSpecificData");
1480
1481    // 2 bytes for each of the parameter set length field
1482    // plus the 7 bytes for the header
1483    if (size < 4 + 7) {
1484        LOGE("Codec specific data length too short: %d", size);
1485        return ERROR_MALFORMED;
1486    }
1487
1488    mCodecSpecificDataSize = size;
1489    mCodecSpecificData = malloc(size);
1490    memcpy(mCodecSpecificData, data, size);
1491    return OK;
1492}
1493
1494status_t MPEG4Writer::Track::parseAVCCodecSpecificData(
1495        const uint8_t *data, size_t size) {
1496
1497    LOGV("parseAVCCodecSpecificData");
1498    // Data starts with a start code.
1499    // SPS and PPS are separated with start codes.
1500    // Also, SPS must come before PPS
1501    uint8_t type = kNalUnitTypeSeqParamSet;
1502    bool gotSps = false;
1503    bool gotPps = false;
1504    const uint8_t *tmp = data;
1505    const uint8_t *nextStartCode = data;
1506    size_t bytesLeft = size;
1507    size_t paramSetLen = 0;
1508    mCodecSpecificDataSize = 0;
1509    while (bytesLeft > 4 && !memcmp("\x00\x00\x00\x01", tmp, 4)) {
1510        getNalUnitType(*(tmp + 4), &type);
1511        if (type == kNalUnitTypeSeqParamSet) {
1512            if (gotPps) {
1513                LOGE("SPS must come before PPS");
1514                return ERROR_MALFORMED;
1515            }
1516            if (!gotSps) {
1517                gotSps = true;
1518            }
1519            nextStartCode = parseParamSet(tmp + 4, bytesLeft - 4, type, &paramSetLen);
1520        } else if (type == kNalUnitTypePicParamSet) {
1521            if (!gotSps) {
1522                LOGE("SPS must come before PPS");
1523                return ERROR_MALFORMED;
1524            }
1525            if (!gotPps) {
1526                gotPps = true;
1527            }
1528            nextStartCode = parseParamSet(tmp + 4, bytesLeft - 4, type, &paramSetLen);
1529        } else {
1530            LOGE("Only SPS and PPS Nal units are expected");
1531            return ERROR_MALFORMED;
1532        }
1533
1534        if (nextStartCode == NULL) {
1535            return ERROR_MALFORMED;
1536        }
1537
1538        // Move on to find the next parameter set
1539        bytesLeft -= nextStartCode - tmp;
1540        tmp = nextStartCode;
1541        mCodecSpecificDataSize += (2 + paramSetLen);
1542    }
1543
1544    {
1545        // Check on the number of seq parameter sets
1546        size_t nSeqParamSets = mSeqParamSets.size();
1547        if (nSeqParamSets == 0) {
1548            LOGE("Cound not find sequence parameter set");
1549            return ERROR_MALFORMED;
1550        }
1551
1552        if (nSeqParamSets > 0x1F) {
1553            LOGE("Too many seq parameter sets (%d) found", nSeqParamSets);
1554            return ERROR_MALFORMED;
1555        }
1556    }
1557
1558    {
1559        // Check on the number of pic parameter sets
1560        size_t nPicParamSets = mPicParamSets.size();
1561        if (nPicParamSets == 0) {
1562            LOGE("Cound not find picture parameter set");
1563            return ERROR_MALFORMED;
1564        }
1565        if (nPicParamSets > 0xFF) {
1566            LOGE("Too many pic parameter sets (%d) found", nPicParamSets);
1567            return ERROR_MALFORMED;
1568        }
1569    }
1570
1571    {
1572        // Check on the profiles
1573        // These profiles requires additional parameter set extensions
1574        if (mProfileIdc == 100 || mProfileIdc == 110 ||
1575            mProfileIdc == 122 || mProfileIdc == 144) {
1576            LOGE("Sorry, no support for profile_idc: %d!", mProfileIdc);
1577            return BAD_VALUE;
1578        }
1579    }
1580
1581    return OK;
1582}
1583
1584status_t MPEG4Writer::Track::makeAVCCodecSpecificData(
1585        const uint8_t *data, size_t size) {
1586
1587    if (mCodecSpecificData != NULL) {
1588        LOGE("Already have codec specific data");
1589        return ERROR_MALFORMED;
1590    }
1591
1592    if (size < 4) {
1593        LOGE("Codec specific data length too short: %d", size);
1594        return ERROR_MALFORMED;
1595    }
1596
1597    // Data is in the form of AVCCodecSpecificData
1598    if (memcmp("\x00\x00\x00\x01", data, 4)) {
1599        return copyAVCCodecSpecificData(data, size);
1600    }
1601
1602    if (parseAVCCodecSpecificData(data, size) != OK) {
1603        return ERROR_MALFORMED;
1604    }
1605
1606    // ISO 14496-15: AVC file format
1607    mCodecSpecificDataSize += 7;  // 7 more bytes in the header
1608    mCodecSpecificData = malloc(mCodecSpecificDataSize);
1609    uint8_t *header = (uint8_t *)mCodecSpecificData;
1610    header[0] = 1;                     // version
1611    header[1] = mProfileIdc;           // profile indication
1612    header[2] = mProfileCompatible;    // profile compatibility
1613    header[3] = mLevelIdc;
1614
1615    // 6-bit '111111' followed by 2-bit to lengthSizeMinuusOne
1616    if (mOwner->useNalLengthFour()) {
1617        header[4] = 0xfc | 3;  // length size == 4 bytes
1618    } else {
1619        header[4] = 0xfc | 1;  // length size == 2 bytes
1620    }
1621
1622    // 3-bit '111' followed by 5-bit numSequenceParameterSets
1623    int nSequenceParamSets = mSeqParamSets.size();
1624    header[5] = 0xe0 | nSequenceParamSets;
1625    header += 6;
1626    for (List<AVCParamSet>::iterator it = mSeqParamSets.begin();
1627         it != mSeqParamSets.end(); ++it) {
1628        // 16-bit sequence parameter set length
1629        uint16_t seqParamSetLength = it->mLength;
1630        header[0] = seqParamSetLength >> 8;
1631        header[1] = seqParamSetLength & 0xff;
1632
1633        // SPS NAL unit (sequence parameter length bytes)
1634        memcpy(&header[2], it->mData, seqParamSetLength);
1635        header += (2 + seqParamSetLength);
1636    }
1637
1638    // 8-bit nPictureParameterSets
1639    int nPictureParamSets = mPicParamSets.size();
1640    header[0] = nPictureParamSets;
1641    header += 1;
1642    for (List<AVCParamSet>::iterator it = mPicParamSets.begin();
1643         it != mPicParamSets.end(); ++it) {
1644        // 16-bit picture parameter set length
1645        uint16_t picParamSetLength = it->mLength;
1646        header[0] = picParamSetLength >> 8;
1647        header[1] = picParamSetLength & 0xff;
1648
1649        // PPS Nal unit (picture parameter set length bytes)
1650        memcpy(&header[2], it->mData, picParamSetLength);
1651        header += (2 + picParamSetLength);
1652    }
1653
1654    return OK;
1655}
1656
1657/*
1658* The video track's media time adjustment for real-time applications
1659* is described as follows:
1660*
1661* First, the media time adjustment is done for every period of
1662* kVideoMediaTimeAdjustPeriodTimeUs. kVideoMediaTimeAdjustPeriodTimeUs
1663* is currently a fixed value chosen heuristically. The value of
1664* kVideoMediaTimeAdjustPeriodTimeUs should not be very large or very small
1665* for two considerations: on one hand, a relatively large value
1666* helps reduce large fluctuation of drift time in the audio encoding
1667* path; while on the other hand, a relatively small value helps keep
1668* restoring synchronization in audio/video more frequently. Note for the
1669* very first period of kVideoMediaTimeAdjustPeriodTimeUs, there is
1670* no media time adjustment for the video track.
1671*
1672* Second, the total accumulated audio track time drift found
1673* in a period of kVideoMediaTimeAdjustPeriodTimeUs is distributed
1674* over a stream of incoming video frames. The number of video frames
1675* affected is determined based on the number of recorded video frames
1676* within the past kVideoMediaTimeAdjustPeriodTimeUs period.
1677* We choose to distribute the drift time over only a portion
1678* (rather than all) of the total number of recorded video frames
1679* in order to make sure that the video track media time adjustment is
1680* completed for the current period before the next video track media
1681* time adjustment period starts. Currently, the portion chosen is a
1682* half (0.5).
1683*
1684* Last, various additional checks are performed to ensure that
1685* the actual audio encoding path does not have too much drift.
1686* In particular, 1) we want to limit the average incremental time
1687* adjustment for each video frame to be less than a threshold
1688* for a single period of kVideoMediaTimeAdjustPeriodTimeUs.
1689* Currently, the threshold is set to 5 ms. If the average incremental
1690* media time adjustment for a video frame is larger than the
1691* threshold, the audio encoding path has too much time drift.
1692* 2) We also want to limit the total time drift in the audio
1693* encoding path to be less than a threshold for a period of
1694* kVideoMediaTimeAdjustPeriodTimeUs. Currently, the threshold
1695* is 0.5% of kVideoMediaTimeAdjustPeriodTimeUs. If the time drift of
1696* the audio encoding path is larger than the threshold, the audio
1697* encoding path has too much time drift. We treat the large time
1698* drift of the audio encoding path as errors, since there is no
1699* way to keep audio/video in synchronization for real-time
1700* applications if the time drift is too large unless we drop some
1701* video frames, which has its own problems that we don't want
1702* to get into for the time being.
1703*/
1704void MPEG4Writer::Track::adjustMediaTime(int64_t *timestampUs) {
1705    if (*timestampUs - mPrevMediaTimeAdjustTimestampUs >=
1706        kVideoMediaTimeAdjustPeriodTimeUs) {
1707
1708        LOGV("New media time adjustment period at %lld us", *timestampUs);
1709        mIsMediaTimeAdjustmentOn = true;
1710        mMediaTimeAdjustNumFrames =
1711                (mNumSamples - mPrevMediaTimeAdjustSample) >> 1;
1712
1713        mPrevMediaTimeAdjustTimestampUs = *timestampUs;
1714        mPrevMediaTimeAdjustSample = mNumSamples;
1715        int64_t totalAccumDriftTimeUs = mOwner->getDriftTimeUs();
1716        mTotalDriftTimeToAdjustUs =
1717                totalAccumDriftTimeUs - mPrevTotalAccumDriftTimeUs;
1718
1719        mPrevTotalAccumDriftTimeUs = totalAccumDriftTimeUs;
1720
1721        // Check on incremental adjusted time per frame
1722        int64_t adjustTimePerFrameUs =
1723                mTotalDriftTimeToAdjustUs / mMediaTimeAdjustNumFrames;
1724
1725        if (adjustTimePerFrameUs < 0) {
1726            adjustTimePerFrameUs = -adjustTimePerFrameUs;
1727        }
1728        if (adjustTimePerFrameUs >= 5000) {
1729            LOGE("Adjusted time per video frame is %lld us",
1730                adjustTimePerFrameUs);
1731            CHECK(!"Video frame time adjustment is too large!");
1732        }
1733
1734        // Check on total accumulated time drift within a period of
1735        // kVideoMediaTimeAdjustPeriodTimeUs.
1736        int64_t driftPercentage = (mTotalDriftTimeToAdjustUs * 1000)
1737                / kVideoMediaTimeAdjustPeriodTimeUs;
1738
1739        if (driftPercentage < 0) {
1740            driftPercentage = -driftPercentage;
1741        }
1742        if (driftPercentage > 5) {
1743            LOGE("Audio track has time drift %lld us over %lld us",
1744                mTotalDriftTimeToAdjustUs,
1745                kVideoMediaTimeAdjustPeriodTimeUs);
1746
1747            CHECK(!"The audio track media time drifts too much!");
1748        }
1749
1750    }
1751
1752    if (mIsMediaTimeAdjustmentOn) {
1753        if (mNumSamples - mPrevMediaTimeAdjustSample <=
1754            mMediaTimeAdjustNumFrames) {
1755
1756            // Do media time incremental adjustment
1757            int64_t incrementalAdjustTimeUs =
1758                        (mTotalDriftTimeToAdjustUs *
1759                            (mNumSamples - mPrevMediaTimeAdjustSample))
1760                                / mMediaTimeAdjustNumFrames;
1761
1762            *timestampUs +=
1763                (incrementalAdjustTimeUs + mPrevTotalAccumDriftTimeUs);
1764
1765            LOGV("Incremental video frame media time adjustment: %lld us",
1766                (incrementalAdjustTimeUs + mPrevTotalAccumDriftTimeUs));
1767        } else {
1768            // Within the remaining adjustment period,
1769            // no incremental adjustment is needed.
1770            *timestampUs +=
1771                (mTotalDriftTimeToAdjustUs + mPrevTotalAccumDriftTimeUs);
1772
1773            LOGV("Fixed video frame media time adjustment: %lld us",
1774                (mTotalDriftTimeToAdjustUs + mPrevTotalAccumDriftTimeUs));
1775        }
1776    }
1777}
1778
1779/*
1780 * Updates the drift time from the audio track so that
1781 * the video track can get the updated drift time information
1782 * from the file writer. The fluctuation of the drift time of the audio
1783 * encoding path is smoothed out with a simple filter by giving a larger
1784 * weight to more recently drift time. The filter coefficients, 0.5 and 0.5,
1785 * are heuristically determined.
1786 */
1787void MPEG4Writer::Track::updateDriftTime(const sp<MetaData>& meta) {
1788    int64_t driftTimeUs = 0;
1789    if (meta->findInt64(kKeyDriftTime, &driftTimeUs)) {
1790        int64_t prevDriftTimeUs = mOwner->getDriftTimeUs();
1791        int64_t timeUs = (driftTimeUs + prevDriftTimeUs) >> 1;
1792        mOwner->setDriftTimeUs(timeUs);
1793    }
1794}
1795
1796status_t MPEG4Writer::Track::threadEntry() {
1797    int32_t count = 0;
1798    const int64_t interleaveDurationUs = mOwner->interleaveDuration();
1799    int64_t chunkTimestampUs = 0;
1800    int32_t nChunks = 0;
1801    int32_t nZeroLengthFrames = 0;
1802    int64_t lastTimestampUs = 0;  // Previous sample time stamp in ms
1803    int64_t lastDurationUs = 0;   // Between the previous two samples in ms
1804    int64_t currDurationTicks = 0;  // Timescale based ticks
1805    int64_t lastDurationTicks = 0;  // Timescale based ticks
1806    int32_t sampleCount = 1;      // Sample count in the current stts table entry
1807    uint32_t previousSampleSize = 0;  // Size of the previous sample
1808    int64_t previousPausedDurationUs = 0;
1809    int64_t timestampUs;
1810
1811    if (mIsAudio) {
1812        prctl(PR_SET_NAME, (unsigned long)"AudioTrackEncoding", 0, 0, 0);
1813    } else {
1814        prctl(PR_SET_NAME, (unsigned long)"VideoTrackEncoding", 0, 0, 0);
1815    }
1816    setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_AUDIO);
1817
1818    sp<MetaData> meta_data;
1819
1820    mNumSamples = 0;
1821    status_t err = OK;
1822    MediaBuffer *buffer;
1823    while (!mDone && (err = mSource->read(&buffer)) == OK) {
1824        if (buffer->range_length() == 0) {
1825            buffer->release();
1826            buffer = NULL;
1827            ++nZeroLengthFrames;
1828            continue;
1829        }
1830
1831        // If the codec specific data has not been received yet, delay pause.
1832        // After the codec specific data is received, discard what we received
1833        // when the track is to be paused.
1834        if (mPaused && !mResumed) {
1835            buffer->release();
1836            buffer = NULL;
1837            continue;
1838        }
1839
1840        ++count;
1841
1842        int32_t isCodecConfig;
1843        if (buffer->meta_data()->findInt32(kKeyIsCodecConfig, &isCodecConfig)
1844                && isCodecConfig) {
1845            CHECK(!mGotAllCodecSpecificData);
1846
1847            if (mIsAvc) {
1848                status_t err = makeAVCCodecSpecificData(
1849                        (const uint8_t *)buffer->data()
1850                            + buffer->range_offset(),
1851                        buffer->range_length());
1852                CHECK_EQ(OK, err);
1853            } else if (mIsMPEG4) {
1854                mCodecSpecificDataSize = buffer->range_length();
1855                mCodecSpecificData = malloc(mCodecSpecificDataSize);
1856                memcpy(mCodecSpecificData,
1857                        (const uint8_t *)buffer->data()
1858                            + buffer->range_offset(),
1859                       buffer->range_length());
1860            }
1861
1862            buffer->release();
1863            buffer = NULL;
1864
1865            mGotAllCodecSpecificData = true;
1866            continue;
1867        }
1868
1869        // Make a deep copy of the MediaBuffer and Metadata and release
1870        // the original as soon as we can
1871        MediaBuffer *copy = new MediaBuffer(buffer->range_length());
1872        memcpy(copy->data(), (uint8_t *)buffer->data() + buffer->range_offset(),
1873                buffer->range_length());
1874        copy->set_range(0, buffer->range_length());
1875        meta_data = new MetaData(*buffer->meta_data().get());
1876        buffer->release();
1877        buffer = NULL;
1878
1879        if (mIsAvc) StripStartcode(copy);
1880
1881        size_t sampleSize = copy->range_length();
1882        if (mIsAvc) {
1883            if (mOwner->useNalLengthFour()) {
1884                sampleSize += 4;
1885            } else {
1886                sampleSize += 2;
1887            }
1888        }
1889
1890        // Max file size or duration handling
1891        mMdatSizeBytes += sampleSize;
1892        updateTrackSizeEstimate();
1893
1894        if (mOwner->exceedsFileSizeLimit()) {
1895            mOwner->notify(MEDIA_RECORDER_EVENT_INFO, MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED, 0);
1896            break;
1897        }
1898        if (mOwner->exceedsFileDurationLimit()) {
1899            mOwner->notify(MEDIA_RECORDER_EVENT_INFO, MEDIA_RECORDER_INFO_MAX_DURATION_REACHED, 0);
1900            break;
1901        }
1902
1903
1904        int32_t isSync = false;
1905        meta_data->findInt32(kKeyIsSyncFrame, &isSync);
1906
1907        /*
1908         * The original timestamp found in the data buffer will be modified as below:
1909         *
1910         * There is a playback offset into this track if the track's start time
1911         * is not the same as the movie start time, which will be recorded in edst
1912         * box of the output file. The playback offset is to make sure that the
1913         * starting time of the audio/video tracks are synchronized. Although the
1914         * track's media timestamp may be subject to various modifications
1915         * as outlined below, the track's playback offset time remains unchanged
1916         * once the first data buffer of the track is received.
1917         *
1918         * The media time stamp will be calculated by subtracting the playback offset
1919         * (and potential pause durations) from the original timestamp in the buffer.
1920         *
1921         * If this track is a video track for a real-time recording application with
1922         * both audio and video tracks, its media timestamp will subject to further
1923         * modification based on the media clock of the audio track. This modification
1924         * is needed for the purpose of maintaining good audio/video synchronization.
1925         *
1926         * If the recording session is paused and resumed multiple times, the track
1927         * media timestamp will be modified as if the  recording session had never been
1928         * paused at all during playback of the recorded output file. In other words,
1929         * the output file will have no memory of pause/resume durations.
1930         *
1931         */
1932        CHECK(meta_data->findInt64(kKeyTime, &timestampUs));
1933        LOGV("%s timestampUs: %lld", mIsAudio? "Audio": "Video", timestampUs);
1934
1935////////////////////////////////////////////////////////////////////////////////
1936        if (mSampleSizes.empty()) {
1937            mStartTimestampUs = timestampUs;
1938            mOwner->setStartTimestampUs(mStartTimestampUs);
1939            previousPausedDurationUs = mStartTimestampUs;
1940        }
1941
1942        if (mResumed) {
1943            int64_t durExcludingEarlierPausesUs = timestampUs - previousPausedDurationUs;
1944            CHECK(durExcludingEarlierPausesUs >= 0);
1945            int64_t pausedDurationUs = durExcludingEarlierPausesUs - mTrackDurationUs;
1946            CHECK(pausedDurationUs >= lastDurationUs);
1947            previousPausedDurationUs += pausedDurationUs - lastDurationUs;
1948            mResumed = false;
1949        }
1950
1951        timestampUs -= previousPausedDurationUs;
1952        CHECK(timestampUs >= 0);
1953
1954        // Media time adjustment for real-time applications
1955        if (mIsRealTimeRecording) {
1956            if (mIsAudio) {
1957                updateDriftTime(meta_data);
1958            } else {
1959                adjustMediaTime(&timestampUs);
1960            }
1961        }
1962
1963        CHECK(timestampUs >= 0);
1964        if (mNumSamples > 1) {
1965            if (timestampUs <= lastTimestampUs) {
1966                LOGW("Frame arrives too late!");
1967                // Don't drop the late frame, since dropping a frame may cause
1968                // problems later during playback
1969
1970                // The idea here is to avoid having two or more samples with the
1971                // same timestamp in the output file.
1972                if (mTimeScale >= 1000000LL) {
1973                    timestampUs = lastTimestampUs + 1;
1974                } else {
1975                    timestampUs = lastTimestampUs + (1000000LL + (mTimeScale >> 1)) / mTimeScale;
1976                }
1977            }
1978        }
1979
1980        LOGV("%s media time stamp: %lld and previous paused duration %lld",
1981                mIsAudio? "Audio": "Video", timestampUs, previousPausedDurationUs);
1982        if (timestampUs > mTrackDurationUs) {
1983            mTrackDurationUs = timestampUs;
1984        }
1985
1986        mSampleSizes.push_back(sampleSize);
1987        ++mNumSamples;
1988        if (mNumSamples > 2) {
1989            // We need to use the time scale based ticks, rather than the
1990            // timestamp itself to determine whether we have to use a new
1991            // stts entry, since we may have rounding errors.
1992            // The calculation is intended to reduce the accumulated
1993            // rounding errors.
1994            currDurationTicks =
1995                     ((timestampUs * mTimeScale + 500000LL) / 1000000LL -
1996                     (lastTimestampUs * mTimeScale + 500000LL) / 1000000LL);
1997
1998            // Force the first sample to have its own stts entry so that
1999            // we can adjust its value later to maintain the A/V sync.
2000            if (mNumSamples == 3 || currDurationTicks != lastDurationTicks) {
2001                LOGV("%s lastDurationUs: %lld us, currDurationTicks: %lld us",
2002                        mIsAudio? "Audio": "Video", lastDurationUs, currDurationTicks);
2003                addOneSttsTableEntry(sampleCount, lastDurationUs);
2004                sampleCount = 1;
2005            } else {
2006                ++sampleCount;
2007            }
2008        }
2009        if (mSamplesHaveSameSize) {
2010            if (mNumSamples >= 2 && previousSampleSize != sampleSize) {
2011                mSamplesHaveSameSize = false;
2012            }
2013            previousSampleSize = sampleSize;
2014        }
2015        LOGV("%s timestampUs/lastTimestampUs: %lld/%lld",
2016                mIsAudio? "Audio": "Video", timestampUs, lastTimestampUs);
2017        lastDurationUs = timestampUs - lastTimestampUs;
2018        lastDurationTicks = currDurationTicks;
2019        lastTimestampUs = timestampUs;
2020
2021        if (isSync != 0) {
2022            addOneStssTableEntry(mNumSamples);
2023        }
2024
2025        if (mTrackingProgressStatus) {
2026            if (mPreviousTrackTimeUs <= 0) {
2027                mPreviousTrackTimeUs = mStartTimestampUs;
2028            }
2029            trackProgressStatus(timestampUs);
2030        }
2031        if (mOwner->numTracks() == 1) {
2032            off64_t offset = mIsAvc? mOwner->addLengthPrefixedSample_l(copy)
2033                                 : mOwner->addSample_l(copy);
2034            if (mChunkOffsets.empty()) {
2035                addChunkOffset(offset);
2036            }
2037            copy->release();
2038            copy = NULL;
2039            continue;
2040        }
2041
2042        mChunkSamples.push_back(copy);
2043        if (interleaveDurationUs == 0) {
2044            addOneStscTableEntry(++nChunks, 1);
2045            bufferChunk(timestampUs);
2046        } else {
2047            if (chunkTimestampUs == 0) {
2048                chunkTimestampUs = timestampUs;
2049            } else {
2050                if (timestampUs - chunkTimestampUs > interleaveDurationUs) {
2051                    ++nChunks;
2052                    if (nChunks == 1 ||  // First chunk
2053                        (--(mStscTableEntries.end()))->samplesPerChunk !=
2054                         mChunkSamples.size()) {
2055                        addOneStscTableEntry(nChunks, mChunkSamples.size());
2056                    }
2057                    bufferChunk(timestampUs);
2058                    chunkTimestampUs = timestampUs;
2059                }
2060            }
2061        }
2062
2063    }
2064
2065    if (mSampleSizes.empty() ||                      // no samples written
2066        (!mIsAudio && mNumStssTableEntries == 0) ||  // no sync frames for video
2067        (OK != checkCodecSpecificData())) {          // no codec specific data
2068        err = ERROR_MALFORMED;
2069    }
2070    mOwner->trackProgressStatus(mTrackId, -1, err);
2071
2072    // Last chunk
2073    if (mOwner->numTracks() == 1) {
2074        addOneStscTableEntry(1, mNumSamples);
2075    } else if (!mChunkSamples.empty()) {
2076        addOneStscTableEntry(++nChunks, mChunkSamples.size());
2077        bufferChunk(timestampUs);
2078    }
2079
2080    // We don't really know how long the last frame lasts, since
2081    // there is no frame time after it, just repeat the previous
2082    // frame's duration.
2083    if (mNumSamples == 1) {
2084        lastDurationUs = 0;  // A single sample's duration
2085    } else {
2086        ++sampleCount;  // Count for the last sample
2087    }
2088
2089    if (mNumSamples <= 2) {
2090        addOneSttsTableEntry(1, lastDurationUs);
2091        if (sampleCount - 1 > 0) {
2092            addOneSttsTableEntry(sampleCount - 1, lastDurationUs);
2093        }
2094    } else {
2095        addOneSttsTableEntry(sampleCount, lastDurationUs);
2096    }
2097
2098    mTrackDurationUs += lastDurationUs;
2099    mReachedEOS = true;
2100    LOGI("Received total/0-length (%d/%d) buffers and encoded %d frames. - %s",
2101            count, nZeroLengthFrames, mNumSamples, mIsAudio? "audio": "video");
2102    if (mIsAudio) {
2103        LOGI("Audio track drift time: %lld us", mOwner->getDriftTimeUs());
2104    }
2105
2106    if (err == ERROR_END_OF_STREAM) {
2107        return OK;
2108    }
2109    return err;
2110}
2111
2112void MPEG4Writer::Track::trackProgressStatus(int64_t timeUs, status_t err) {
2113    LOGV("trackProgressStatus: %lld us", timeUs);
2114    if (mTrackEveryTimeDurationUs > 0 &&
2115        timeUs - mPreviousTrackTimeUs >= mTrackEveryTimeDurationUs) {
2116        LOGV("Fire time tracking progress status at %lld us", timeUs);
2117        mOwner->trackProgressStatus(mTrackId, timeUs - mPreviousTrackTimeUs, err);
2118        mPreviousTrackTimeUs = timeUs;
2119    }
2120}
2121
2122void MPEG4Writer::trackProgressStatus(
2123        size_t trackId, int64_t timeUs, status_t err) {
2124    Mutex::Autolock lock(mLock);
2125    int32_t trackNum = (trackId << 28);
2126
2127    // Error notification
2128    // Do not consider ERROR_END_OF_STREAM an error
2129    if (err != OK && err != ERROR_END_OF_STREAM) {
2130        notify(MEDIA_RECORDER_TRACK_EVENT_ERROR,
2131               trackNum | MEDIA_RECORDER_TRACK_ERROR_GENERAL,
2132               err);
2133        return;
2134    }
2135
2136    if (timeUs == -1) {
2137        // Send completion notification
2138        notify(MEDIA_RECORDER_TRACK_EVENT_INFO,
2139               trackNum | MEDIA_RECORDER_TRACK_INFO_COMPLETION_STATUS,
2140               err);
2141    } else {
2142        // Send progress status
2143        notify(MEDIA_RECORDER_TRACK_EVENT_INFO,
2144               trackNum | MEDIA_RECORDER_TRACK_INFO_PROGRESS_IN_TIME,
2145               timeUs / 1000);
2146    }
2147}
2148
2149void MPEG4Writer::setDriftTimeUs(int64_t driftTimeUs) {
2150    LOGV("setDriftTimeUs: %lld us", driftTimeUs);
2151    Mutex::Autolock autolock(mLock);
2152    mDriftTimeUs = driftTimeUs;
2153}
2154
2155int64_t MPEG4Writer::getDriftTimeUs() {
2156    LOGV("getDriftTimeUs: %lld us", mDriftTimeUs);
2157    Mutex::Autolock autolock(mLock);
2158    return mDriftTimeUs;
2159}
2160
2161bool MPEG4Writer::useNalLengthFour() {
2162    return mUse4ByteNalLength;
2163}
2164
2165void MPEG4Writer::Track::bufferChunk(int64_t timestampUs) {
2166    LOGV("bufferChunk");
2167
2168    Chunk chunk(this, timestampUs, mChunkSamples);
2169    mOwner->bufferChunk(chunk);
2170    mChunkSamples.clear();
2171}
2172
2173int64_t MPEG4Writer::Track::getDurationUs() const {
2174    return mTrackDurationUs;
2175}
2176
2177int64_t MPEG4Writer::Track::getEstimatedTrackSizeBytes() const {
2178    return mEstimatedTrackSizeBytes;
2179}
2180
2181status_t MPEG4Writer::Track::checkCodecSpecificData() const {
2182    const char *mime;
2183    CHECK(mMeta->findCString(kKeyMIMEType, &mime));
2184    if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AAC, mime) ||
2185        !strcasecmp(MEDIA_MIMETYPE_VIDEO_MPEG4, mime) ||
2186        !strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime)) {
2187        if (!mCodecSpecificData ||
2188            mCodecSpecificDataSize <= 0) {
2189            LOGE("Missing codec specific data");
2190            return ERROR_MALFORMED;
2191        }
2192    } else {
2193        if (mCodecSpecificData ||
2194            mCodecSpecificDataSize > 0) {
2195            LOGE("Unexepected codec specific data found");
2196            return ERROR_MALFORMED;
2197        }
2198    }
2199    return OK;
2200}
2201
2202void MPEG4Writer::Track::writeTrackHeader(bool use32BitOffset) {
2203
2204    LOGV("%s track time scale: %d",
2205        mIsAudio? "Audio": "Video", mTimeScale);
2206
2207    time_t now = time(NULL);
2208    mOwner->beginBox("trak");
2209        writeTkhdBox(now);
2210        mOwner->beginBox("mdia");
2211            writeMdhdBox(now);
2212            writeHdlrBox();
2213            mOwner->beginBox("minf");
2214                if (mIsAudio) {
2215                    writeSmhdBox();
2216                } else {
2217                    writeVmhdBox();
2218                }
2219                writeDinfBox();
2220                writeStblBox(use32BitOffset);
2221            mOwner->endBox();  // minf
2222        mOwner->endBox();  // mdia
2223    mOwner->endBox();  // trak
2224}
2225
2226void MPEG4Writer::Track::writeStblBox(bool use32BitOffset) {
2227    mOwner->beginBox("stbl");
2228    mOwner->beginBox("stsd");
2229    mOwner->writeInt32(0);               // version=0, flags=0
2230    mOwner->writeInt32(1);               // entry count
2231    if (mIsAudio) {
2232        writeAudioFourCCBox();
2233    } else {
2234        writeVideoFourCCBox();
2235    }
2236    mOwner->endBox();  // stsd
2237    writeSttsBox();
2238    if (!mIsAudio) {
2239        writeStssBox();
2240    }
2241    writeStszBox();
2242    writeStscBox();
2243    writeStcoBox(use32BitOffset);
2244    mOwner->endBox();  // stbl
2245}
2246
2247void MPEG4Writer::Track::writeVideoFourCCBox() {
2248    const char *mime;
2249    bool success = mMeta->findCString(kKeyMIMEType, &mime);
2250    CHECK(success);
2251    if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_MPEG4, mime)) {
2252        mOwner->beginBox("mp4v");
2253    } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_H263, mime)) {
2254        mOwner->beginBox("s263");
2255    } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime)) {
2256        mOwner->beginBox("avc1");
2257    } else {
2258        LOGE("Unknown mime type '%s'.", mime);
2259        CHECK(!"should not be here, unknown mime type.");
2260    }
2261
2262    mOwner->writeInt32(0);           // reserved
2263    mOwner->writeInt16(0);           // reserved
2264    mOwner->writeInt16(1);           // data ref index
2265    mOwner->writeInt16(0);           // predefined
2266    mOwner->writeInt16(0);           // reserved
2267    mOwner->writeInt32(0);           // predefined
2268    mOwner->writeInt32(0);           // predefined
2269    mOwner->writeInt32(0);           // predefined
2270
2271    int32_t width, height;
2272    success = mMeta->findInt32(kKeyWidth, &width);
2273    success = success && mMeta->findInt32(kKeyHeight, &height);
2274    CHECK(success);
2275
2276    mOwner->writeInt16(width);
2277    mOwner->writeInt16(height);
2278    mOwner->writeInt32(0x480000);    // horiz resolution
2279    mOwner->writeInt32(0x480000);    // vert resolution
2280    mOwner->writeInt32(0);           // reserved
2281    mOwner->writeInt16(1);           // frame count
2282    mOwner->write("                                ", 32);
2283    mOwner->writeInt16(0x18);        // depth
2284    mOwner->writeInt16(-1);          // predefined
2285
2286    CHECK(23 + mCodecSpecificDataSize < 128);
2287
2288    if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_MPEG4, mime)) {
2289        writeMp4vEsdsBox();
2290    } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_H263, mime)) {
2291        writeD263Box();
2292    } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime)) {
2293        writeAvccBox();
2294    }
2295
2296    writePaspBox();
2297    mOwner->endBox();  // mp4v, s263 or avc1
2298}
2299
2300void MPEG4Writer::Track::writeAudioFourCCBox() {
2301    const char *mime;
2302    bool success = mMeta->findCString(kKeyMIMEType, &mime);
2303    CHECK(success);
2304    const char *fourcc = NULL;
2305    if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AMR_NB, mime)) {
2306        fourcc = "samr";
2307    } else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AMR_WB, mime)) {
2308        fourcc = "sawb";
2309    } else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AAC, mime)) {
2310        fourcc = "mp4a";
2311    } else {
2312        LOGE("Unknown mime type '%s'.", mime);
2313        CHECK(!"should not be here, unknown mime type.");
2314    }
2315
2316    mOwner->beginBox(fourcc);        // audio format
2317    mOwner->writeInt32(0);           // reserved
2318    mOwner->writeInt16(0);           // reserved
2319    mOwner->writeInt16(0x1);         // data ref index
2320    mOwner->writeInt32(0);           // reserved
2321    mOwner->writeInt32(0);           // reserved
2322    int32_t nChannels;
2323    CHECK_EQ(true, mMeta->findInt32(kKeyChannelCount, &nChannels));
2324    mOwner->writeInt16(nChannels);   // channel count
2325    mOwner->writeInt16(16);          // sample size
2326    mOwner->writeInt16(0);           // predefined
2327    mOwner->writeInt16(0);           // reserved
2328
2329    int32_t samplerate;
2330    success = mMeta->findInt32(kKeySampleRate, &samplerate);
2331    CHECK(success);
2332    mOwner->writeInt32(samplerate << 16);
2333    if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AAC, mime)) {
2334        writeMp4aEsdsBox();
2335    } else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AMR_NB, mime) ||
2336               !strcasecmp(MEDIA_MIMETYPE_AUDIO_AMR_WB, mime)) {
2337        writeDamrBox();
2338    }
2339    mOwner->endBox();
2340}
2341
2342void MPEG4Writer::Track::writeMp4aEsdsBox() {
2343    mOwner->beginBox("esds");
2344    CHECK(mCodecSpecificData);
2345    CHECK(mCodecSpecificDataSize > 0);
2346
2347    // Make sure all sizes encode to a single byte.
2348    CHECK(mCodecSpecificDataSize + 23 < 128);
2349
2350    mOwner->writeInt32(0);     // version=0, flags=0
2351    mOwner->writeInt8(0x03);   // ES_DescrTag
2352    mOwner->writeInt8(23 + mCodecSpecificDataSize);
2353    mOwner->writeInt16(0x0000);// ES_ID
2354    mOwner->writeInt8(0x00);
2355
2356    mOwner->writeInt8(0x04);   // DecoderConfigDescrTag
2357    mOwner->writeInt8(15 + mCodecSpecificDataSize);
2358    mOwner->writeInt8(0x40);   // objectTypeIndication ISO/IEC 14492-2
2359    mOwner->writeInt8(0x15);   // streamType AudioStream
2360
2361    mOwner->writeInt16(0x03);  // XXX
2362    mOwner->writeInt8(0x00);   // buffer size 24-bit
2363    mOwner->writeInt32(96000); // max bit rate
2364    mOwner->writeInt32(96000); // avg bit rate
2365
2366    mOwner->writeInt8(0x05);   // DecoderSpecificInfoTag
2367    mOwner->writeInt8(mCodecSpecificDataSize);
2368    mOwner->write(mCodecSpecificData, mCodecSpecificDataSize);
2369
2370    static const uint8_t kData2[] = {
2371        0x06,  // SLConfigDescriptorTag
2372        0x01,
2373        0x02
2374    };
2375    mOwner->write(kData2, sizeof(kData2));
2376
2377    mOwner->endBox();  // esds
2378}
2379
2380void MPEG4Writer::Track::writeMp4vEsdsBox() {
2381    CHECK(mCodecSpecificData);
2382    CHECK(mCodecSpecificDataSize > 0);
2383    mOwner->beginBox("esds");
2384
2385    mOwner->writeInt32(0);    // version=0, flags=0
2386
2387    mOwner->writeInt8(0x03);  // ES_DescrTag
2388    mOwner->writeInt8(23 + mCodecSpecificDataSize);
2389    mOwner->writeInt16(0x0000);  // ES_ID
2390    mOwner->writeInt8(0x1f);
2391
2392    mOwner->writeInt8(0x04);  // DecoderConfigDescrTag
2393    mOwner->writeInt8(15 + mCodecSpecificDataSize);
2394    mOwner->writeInt8(0x20);  // objectTypeIndication ISO/IEC 14492-2
2395    mOwner->writeInt8(0x11);  // streamType VisualStream
2396
2397    static const uint8_t kData[] = {
2398        0x01, 0x77, 0x00,
2399        0x00, 0x03, 0xe8, 0x00,
2400        0x00, 0x03, 0xe8, 0x00
2401    };
2402    mOwner->write(kData, sizeof(kData));
2403
2404    mOwner->writeInt8(0x05);  // DecoderSpecificInfoTag
2405
2406    mOwner->writeInt8(mCodecSpecificDataSize);
2407    mOwner->write(mCodecSpecificData, mCodecSpecificDataSize);
2408
2409    static const uint8_t kData2[] = {
2410        0x06,  // SLConfigDescriptorTag
2411        0x01,
2412        0x02
2413    };
2414    mOwner->write(kData2, sizeof(kData2));
2415
2416    mOwner->endBox();  // esds
2417}
2418
2419void MPEG4Writer::Track::writeTkhdBox(time_t now) {
2420    mOwner->beginBox("tkhd");
2421    // Flags = 7 to indicate that the track is enabled, and
2422    // part of the presentation
2423    mOwner->writeInt32(0x07);          // version=0, flags=7
2424    mOwner->writeInt32(now);           // creation time
2425    mOwner->writeInt32(now);           // modification time
2426    mOwner->writeInt32(mTrackId);
2427    mOwner->writeInt32(0);             // reserved
2428    int64_t trakDurationUs = getDurationUs();
2429    int32_t mvhdTimeScale = mOwner->getTimeScale();
2430    int32_t tkhdDuration =
2431        (trakDurationUs * mvhdTimeScale + 5E5) / 1E6;
2432    mOwner->writeInt32(tkhdDuration);  // in mvhd timescale
2433    mOwner->writeInt32(0);             // reserved
2434    mOwner->writeInt32(0);             // reserved
2435    mOwner->writeInt16(0);             // layer
2436    mOwner->writeInt16(0);             // alternate group
2437    mOwner->writeInt16(mIsAudio ? 0x100 : 0);  // volume
2438    mOwner->writeInt16(0);             // reserved
2439
2440    mOwner->writeCompositionMatrix(mRotation);       // matrix
2441
2442    if (mIsAudio) {
2443        mOwner->writeInt32(0);
2444        mOwner->writeInt32(0);
2445    } else {
2446        int32_t width, height;
2447        bool success = mMeta->findInt32(kKeyWidth, &width);
2448        success = success && mMeta->findInt32(kKeyHeight, &height);
2449        CHECK(success);
2450
2451        mOwner->writeInt32(width << 16);   // 32-bit fixed-point value
2452        mOwner->writeInt32(height << 16);  // 32-bit fixed-point value
2453    }
2454    mOwner->endBox();  // tkhd
2455}
2456
2457void MPEG4Writer::Track::writeVmhdBox() {
2458    mOwner->beginBox("vmhd");
2459    mOwner->writeInt32(0x01);        // version=0, flags=1
2460    mOwner->writeInt16(0);           // graphics mode
2461    mOwner->writeInt16(0);           // opcolor
2462    mOwner->writeInt16(0);
2463    mOwner->writeInt16(0);
2464    mOwner->endBox();
2465}
2466
2467void MPEG4Writer::Track::writeSmhdBox() {
2468    mOwner->beginBox("smhd");
2469    mOwner->writeInt32(0);           // version=0, flags=0
2470    mOwner->writeInt16(0);           // balance
2471    mOwner->writeInt16(0);           // reserved
2472    mOwner->endBox();
2473}
2474
2475void MPEG4Writer::Track::writeHdlrBox() {
2476    mOwner->beginBox("hdlr");
2477    mOwner->writeInt32(0);             // version=0, flags=0
2478    mOwner->writeInt32(0);             // component type: should be mhlr
2479    mOwner->writeFourcc(mIsAudio ? "soun" : "vide");  // component subtype
2480    mOwner->writeInt32(0);             // reserved
2481    mOwner->writeInt32(0);             // reserved
2482    mOwner->writeInt32(0);             // reserved
2483    // Removing "r" for the name string just makes the string 4 byte aligned
2484    mOwner->writeCString(mIsAudio ? "SoundHandle": "VideoHandle");  // name
2485    mOwner->endBox();
2486}
2487
2488void MPEG4Writer::Track::writeMdhdBox(time_t now) {
2489    int64_t trakDurationUs = getDurationUs();
2490    mOwner->beginBox("mdhd");
2491    mOwner->writeInt32(0);             // version=0, flags=0
2492    mOwner->writeInt32(now);           // creation time
2493    mOwner->writeInt32(now);           // modification time
2494    mOwner->writeInt32(mTimeScale);    // media timescale
2495    int32_t mdhdDuration = (trakDurationUs * mTimeScale + 5E5) / 1E6;
2496    mOwner->writeInt32(mdhdDuration);  // use media timescale
2497    // Language follows the three letter standard ISO-639-2/T
2498    // 'e', 'n', 'g' for "English", for instance.
2499    // Each character is packed as the difference between its ASCII value and 0x60.
2500    // For "English", these are 00101, 01110, 00111.
2501    // XXX: Where is the padding bit located: 0x15C7?
2502    mOwner->writeInt16(0);             // language code
2503    mOwner->writeInt16(0);             // predefined
2504    mOwner->endBox();
2505}
2506
2507void MPEG4Writer::Track::writeDamrBox() {
2508    // 3gpp2 Spec AMRSampleEntry fields
2509    mOwner->beginBox("damr");
2510    mOwner->writeCString("   ");  // vendor: 4 bytes
2511    mOwner->writeInt8(0);         // decoder version
2512    mOwner->writeInt16(0x83FF);   // mode set: all enabled
2513    mOwner->writeInt8(0);         // mode change period
2514    mOwner->writeInt8(1);         // frames per sample
2515    mOwner->endBox();
2516}
2517
2518void MPEG4Writer::Track::writeUrlBox() {
2519    // The table index here refers to the sample description index
2520    // in the sample table entries.
2521    mOwner->beginBox("url ");
2522    mOwner->writeInt32(1);  // version=0, flags=1 (self-contained)
2523    mOwner->endBox();  // url
2524}
2525
2526void MPEG4Writer::Track::writeDrefBox() {
2527    mOwner->beginBox("dref");
2528    mOwner->writeInt32(0);  // version=0, flags=0
2529    mOwner->writeInt32(1);  // entry count (either url or urn)
2530    writeUrlBox();
2531    mOwner->endBox();  // dref
2532}
2533
2534void MPEG4Writer::Track::writeDinfBox() {
2535    mOwner->beginBox("dinf");
2536    writeDrefBox();
2537    mOwner->endBox();  // dinf
2538}
2539
2540void MPEG4Writer::Track::writeAvccBox() {
2541    CHECK(mCodecSpecificData);
2542    CHECK(mCodecSpecificDataSize >= 5);
2543
2544    // Patch avcc's lengthSize field to match the number
2545    // of bytes we use to indicate the size of a nal unit.
2546    uint8_t *ptr = (uint8_t *)mCodecSpecificData;
2547    ptr[4] = (ptr[4] & 0xfc) | (mOwner->useNalLengthFour() ? 3 : 1);
2548    mOwner->beginBox("avcC");
2549    mOwner->write(mCodecSpecificData, mCodecSpecificDataSize);
2550    mOwner->endBox();  // avcC
2551}
2552
2553void MPEG4Writer::Track::writeD263Box() {
2554    mOwner->beginBox("d263");
2555    mOwner->writeInt32(0);  // vendor
2556    mOwner->writeInt8(0);   // decoder version
2557    mOwner->writeInt8(10);  // level: 10
2558    mOwner->writeInt8(0);   // profile: 0
2559    mOwner->endBox();  // d263
2560}
2561
2562// This is useful if the pixel is not square
2563void MPEG4Writer::Track::writePaspBox() {
2564    mOwner->beginBox("pasp");
2565    mOwner->writeInt32(1 << 16);  // hspacing
2566    mOwner->writeInt32(1 << 16);  // vspacing
2567    mOwner->endBox();  // pasp
2568}
2569
2570void MPEG4Writer::Track::writeSttsBox() {
2571    mOwner->beginBox("stts");
2572    mOwner->writeInt32(0);  // version=0, flags=0
2573    mOwner->writeInt32(mNumSttsTableEntries);
2574    // Compensate for small start time difference from different media tracks
2575    int64_t trackStartTimeOffsetUs = 0;
2576    int64_t moovStartTimeUs = mOwner->getStartTimestampUs();
2577    if (mStartTimestampUs != moovStartTimeUs) {
2578        CHECK(mStartTimestampUs > moovStartTimeUs);
2579        trackStartTimeOffsetUs = mStartTimestampUs - moovStartTimeUs;
2580    }
2581    int64_t prevTimestampUs = trackStartTimeOffsetUs;
2582    for (List<SttsTableEntry>::iterator it = mSttsTableEntries.begin();
2583        it != mSttsTableEntries.end(); ++it) {
2584        mOwner->writeInt32(it->sampleCount);
2585
2586        // Make sure that we are calculating the sample duration the exactly
2587        // same way as we made decision on how to create stts entries.
2588        int64_t currTimestampUs = prevTimestampUs + it->sampleDurationUs;
2589        int32_t dur = ((currTimestampUs * mTimeScale + 500000LL) / 1000000LL -
2590            (prevTimestampUs * mTimeScale + 500000LL) / 1000000LL);
2591        prevTimestampUs += (it->sampleCount * it->sampleDurationUs);
2592
2593        mOwner->writeInt32(dur);
2594    }
2595    mOwner->endBox();  // stts
2596}
2597
2598void MPEG4Writer::Track::writeStssBox() {
2599    mOwner->beginBox("stss");
2600    mOwner->writeInt32(0);  // version=0, flags=0
2601    mOwner->writeInt32(mNumStssTableEntries);  // number of sync frames
2602    for (List<int32_t>::iterator it = mStssTableEntries.begin();
2603        it != mStssTableEntries.end(); ++it) {
2604        mOwner->writeInt32(*it);
2605    }
2606    mOwner->endBox();  // stss
2607}
2608
2609void MPEG4Writer::Track::writeStszBox() {
2610    mOwner->beginBox("stsz");
2611    mOwner->writeInt32(0);  // version=0, flags=0
2612    if (mSamplesHaveSameSize) {
2613        List<size_t>::iterator it = mSampleSizes.begin();
2614        mOwner->writeInt32(*it);  // default sample size
2615    } else {
2616        mOwner->writeInt32(0);
2617    }
2618    mOwner->writeInt32(mNumSamples);
2619    if (!mSamplesHaveSameSize) {
2620        for (List<size_t>::iterator it = mSampleSizes.begin();
2621            it != mSampleSizes.end(); ++it) {
2622            mOwner->writeInt32(*it);
2623        }
2624    }
2625    mOwner->endBox();  // stsz
2626}
2627
2628void MPEG4Writer::Track::writeStscBox() {
2629    mOwner->beginBox("stsc");
2630    mOwner->writeInt32(0);  // version=0, flags=0
2631    mOwner->writeInt32(mNumStscTableEntries);
2632    for (List<StscTableEntry>::iterator it = mStscTableEntries.begin();
2633        it != mStscTableEntries.end(); ++it) {
2634        mOwner->writeInt32(it->firstChunk);
2635        mOwner->writeInt32(it->samplesPerChunk);
2636        mOwner->writeInt32(it->sampleDescriptionId);
2637    }
2638    mOwner->endBox();  // stsc
2639}
2640
2641void MPEG4Writer::Track::writeStcoBox(bool use32BitOffset) {
2642    mOwner->beginBox(use32BitOffset? "stco": "co64");
2643    mOwner->writeInt32(0);  // version=0, flags=0
2644    mOwner->writeInt32(mNumStcoTableEntries);
2645    for (List<off64_t>::iterator it = mChunkOffsets.begin();
2646        it != mChunkOffsets.end(); ++it) {
2647        if (use32BitOffset) {
2648            mOwner->writeInt32(static_cast<int32_t>(*it));
2649        } else {
2650            mOwner->writeInt64((*it));
2651        }
2652    }
2653    mOwner->endBox();  // stco or co64
2654}
2655
2656}  // namespace android
2657