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