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