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