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