MPEG4Writer.cpp revision 000e18370baae60ffd9f25b509501dd8c26deabf
1/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//#define LOG_NDEBUG 0
18#define LOG_TAG "MPEG4Writer"
19#include <utils/Log.h>
20
21#include <arpa/inet.h>
22
23#include <pthread.h>
24#include <sys/prctl.h>
25
26#include <media/stagefright/MPEG4Writer.h>
27#include <media/stagefright/MediaBuffer.h>
28#include <media/stagefright/MetaData.h>
29#include <media/stagefright/MediaDebug.h>
30#include <media/stagefright/MediaDefs.h>
31#include <media/stagefright/MediaErrors.h>
32#include <media/stagefright/MediaSource.h>
33#include <media/stagefright/Utils.h>
34#include <media/mediarecorder.h>
35#include <cutils/properties.h>
36#include <sys/types.h>
37#include <sys/stat.h>
38#include <fcntl.h>
39#include <unistd.h>
40
41#include "include/ESDS.h"
42
43namespace android {
44
45static const int64_t kMax32BitFileSize = 0x007fffffffLL;
46static const uint8_t kNalUnitTypeSeqParamSet = 0x07;
47static const uint8_t kNalUnitTypePicParamSet = 0x08;
48static const int64_t kInitialDelayTimeUs     = 700000LL;
49
50class MPEG4Writer::Track {
51public:
52    Track(MPEG4Writer *owner, const sp<MediaSource> &source, size_t trackId);
53
54    ~Track();
55
56    status_t start(MetaData *params);
57    status_t stop();
58    status_t pause();
59    bool reachedEOS();
60
61    int64_t getDurationUs() const;
62    int64_t getEstimatedTrackSizeBytes() const;
63    void writeTrackHeader(bool use32BitOffset = true);
64    void bufferChunk(int64_t timestampUs);
65    bool isAvc() const { return mIsAvc; }
66    bool isAudio() const { return mIsAudio; }
67    bool isMPEG4() const { return mIsMPEG4; }
68    void addChunkOffset(off64_t offset);
69    int32_t getTrackId() const { return mTrackId; }
70    status_t dump(int fd, const Vector<String16>& args) const;
71
72private:
73    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        int32_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(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(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(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(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(timeUs >= 0);
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(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" == 0);
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 = 1;           // 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(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(durExcludingEarlierPausesUs >= 0);
1959            int64_t pausedDurationUs = durExcludingEarlierPausesUs - mTrackDurationUs;
1960            CHECK(pausedDurationUs >= lastDurationUs);
1961            previousPausedDurationUs += pausedDurationUs - lastDurationUs;
1962            mResumed = false;
1963        }
1964
1965        timestampUs -= previousPausedDurationUs;
1966        CHECK(timestampUs >= 0);
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(cttsOffsetTimeUs >= 0);
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(currCttsOffsetTimeTicks <= 0x7FFFFFFFLL);
1987#if 0
1988            // FIXME:
1989            // Optimize to reduce the number of ctts table entries.
1990            // Also, make sure that the very first ctts table entry contains
1991            // only a single sample.
1992#else
1993            addOneCttsTableEntry(1, currCttsOffsetTimeTicks);
1994#endif
1995            lastCttsOffsetTimeTicks = currCttsOffsetTimeTicks;
1996
1997            // Update ctts time offset range
1998            if (mNumSamples == 0) {
1999                mMinCttsOffsetTimeUs = currCttsOffsetTimeTicks;
2000                mMaxCttsOffsetTimeUs = currCttsOffsetTimeTicks;
2001            } else {
2002                if (currCttsOffsetTimeTicks > mMaxCttsOffsetTimeUs) {
2003                    mMaxCttsOffsetTimeUs = currCttsOffsetTimeTicks;
2004                } else if (currCttsOffsetTimeTicks < mMinCttsOffsetTimeUs) {
2005                    mMinCttsOffsetTimeUs = currCttsOffsetTimeTicks;
2006                }
2007            }
2008
2009        }
2010
2011        if (mIsRealTimeRecording) {
2012            if (mIsAudio) {
2013                updateDriftTime(meta_data);
2014            }
2015        }
2016
2017        CHECK(timestampUs >= 0);
2018        ALOGV("%s media time stamp: %lld and previous paused duration %lld",
2019                mIsAudio? "Audio": "Video", timestampUs, previousPausedDurationUs);
2020        if (timestampUs > mTrackDurationUs) {
2021            mTrackDurationUs = timestampUs;
2022        }
2023
2024        // We need to use the time scale based ticks, rather than the
2025        // timestamp itself to determine whether we have to use a new
2026        // stts entry, since we may have rounding errors.
2027        // The calculation is intended to reduce the accumulated
2028        // rounding errors.
2029        currDurationTicks =
2030            ((timestampUs * mTimeScale + 500000LL) / 1000000LL -
2031                (lastTimestampUs * mTimeScale + 500000LL) / 1000000LL);
2032        CHECK(currDurationTicks >= 0);
2033
2034        mSampleSizes.push_back(sampleSize);
2035        ++mNumSamples;
2036        if (mNumSamples > 2) {
2037
2038            // Force the first sample to have its own stts entry so that
2039            // we can adjust its value later to maintain the A/V sync.
2040            if (mNumSamples == 3 || currDurationTicks != lastDurationTicks) {
2041                addOneSttsTableEntry(sampleCount, lastDurationTicks);
2042                sampleCount = 1;
2043            } else {
2044                ++sampleCount;
2045            }
2046
2047        }
2048        if (mSamplesHaveSameSize) {
2049            if (mNumSamples >= 2 && previousSampleSize != sampleSize) {
2050                mSamplesHaveSameSize = false;
2051            }
2052            previousSampleSize = sampleSize;
2053        }
2054        ALOGV("%s timestampUs/lastTimestampUs: %lld/%lld",
2055                mIsAudio? "Audio": "Video", timestampUs, lastTimestampUs);
2056        lastDurationUs = timestampUs - lastTimestampUs;
2057        lastDurationTicks = currDurationTicks;
2058        lastTimestampUs = timestampUs;
2059
2060        if (isSync != 0) {
2061            addOneStssTableEntry(mNumSamples);
2062        }
2063
2064        if (mTrackingProgressStatus) {
2065            if (mPreviousTrackTimeUs <= 0) {
2066                mPreviousTrackTimeUs = mStartTimestampUs;
2067            }
2068            trackProgressStatus(timestampUs);
2069        }
2070        if (!hasMultipleTracks) {
2071            off64_t offset = mIsAvc? mOwner->addLengthPrefixedSample_l(copy)
2072                                 : mOwner->addSample_l(copy);
2073            if (mChunkOffsets.empty()) {
2074                addChunkOffset(offset);
2075            }
2076            copy->release();
2077            copy = NULL;
2078            continue;
2079        }
2080
2081        mChunkSamples.push_back(copy);
2082        if (interleaveDurationUs == 0) {
2083            addOneStscTableEntry(++nChunks, 1);
2084            bufferChunk(timestampUs);
2085        } else {
2086            if (chunkTimestampUs == 0) {
2087                chunkTimestampUs = timestampUs;
2088            } else {
2089                int64_t chunkDurationUs = timestampUs - chunkTimestampUs;
2090                if (chunkDurationUs > interleaveDurationUs) {
2091                    if (chunkDurationUs > mMaxChunkDurationUs) {
2092                        mMaxChunkDurationUs = chunkDurationUs;
2093                    }
2094                    ++nChunks;
2095                    if (nChunks == 1 ||  // First chunk
2096                        (--(mStscTableEntries.end()))->samplesPerChunk !=
2097                         mChunkSamples.size()) {
2098                        addOneStscTableEntry(nChunks, mChunkSamples.size());
2099                    }
2100                    bufferChunk(timestampUs);
2101                    chunkTimestampUs = timestampUs;
2102                }
2103            }
2104        }
2105
2106    }
2107
2108    if (isTrackMalFormed()) {
2109        err = ERROR_MALFORMED;
2110    }
2111
2112    mOwner->trackProgressStatus(mTrackId, -1, err);
2113
2114    // Last chunk
2115    if (!hasMultipleTracks) {
2116        addOneStscTableEntry(1, mNumSamples);
2117    } else if (!mChunkSamples.empty()) {
2118        addOneStscTableEntry(++nChunks, mChunkSamples.size());
2119        bufferChunk(timestampUs);
2120    }
2121
2122    // We don't really know how long the last frame lasts, since
2123    // there is no frame time after it, just repeat the previous
2124    // frame's duration.
2125    if (mNumSamples == 1) {
2126        lastDurationUs = 0;  // A single sample's duration
2127        lastDurationTicks = 0;
2128    } else {
2129        ++sampleCount;  // Count for the last sample
2130        ++cttsSampleCount;
2131    }
2132
2133    if (mNumSamples <= 2) {
2134        addOneSttsTableEntry(1, lastDurationTicks);
2135        if (sampleCount - 1 > 0) {
2136            addOneSttsTableEntry(sampleCount - 1, lastDurationTicks);
2137        }
2138    } else {
2139        addOneSttsTableEntry(sampleCount, lastDurationTicks);
2140    }
2141
2142    mTrackDurationUs += lastDurationUs;
2143    mReachedEOS = true;
2144
2145    sendTrackSummary(hasMultipleTracks);
2146
2147    ALOGI("Received total/0-length (%d/%d) buffers and encoded %d frames. - %s",
2148            count, nZeroLengthFrames, mNumSamples, mIsAudio? "audio": "video");
2149    if (mIsAudio) {
2150        ALOGI("Audio track drift time: %lld us", mOwner->getDriftTimeUs());
2151    }
2152
2153    if (err == ERROR_END_OF_STREAM) {
2154        return OK;
2155    }
2156    return err;
2157}
2158
2159bool MPEG4Writer::Track::isTrackMalFormed() const {
2160    if (mSampleSizes.empty()) {                      // no samples written
2161        ALOGE("The number of recorded samples is 0");
2162        return true;
2163    }
2164
2165    if (!mIsAudio && mNumStssTableEntries == 0) {  // no sync frames for video
2166        ALOGE("There are no sync frames for video track");
2167        return true;
2168    }
2169
2170    if (OK != checkCodecSpecificData()) {         // no codec specific data
2171        return true;
2172    }
2173
2174    return false;
2175}
2176
2177void MPEG4Writer::Track::sendTrackSummary(bool hasMultipleTracks) {
2178
2179    // Send track summary only if test mode is enabled.
2180    if (!isTestModeEnabled()) {
2181        return;
2182    }
2183
2184    int trackNum = (mTrackId << 28);
2185
2186    mOwner->notify(MEDIA_RECORDER_TRACK_EVENT_INFO,
2187                    trackNum | MEDIA_RECORDER_TRACK_INFO_TYPE,
2188                    mIsAudio? 0: 1);
2189
2190    mOwner->notify(MEDIA_RECORDER_TRACK_EVENT_INFO,
2191                    trackNum | MEDIA_RECORDER_TRACK_INFO_DURATION_MS,
2192                    mTrackDurationUs / 1000);
2193
2194    mOwner->notify(MEDIA_RECORDER_TRACK_EVENT_INFO,
2195                    trackNum | MEDIA_RECORDER_TRACK_INFO_ENCODED_FRAMES,
2196                    mNumSamples);
2197
2198    {
2199        // The system delay time excluding the requested initial delay that
2200        // is used to eliminate the recording sound.
2201        int64_t startTimeOffsetUs = mOwner->getStartTimeOffsetMs() * 1000LL;
2202        if (startTimeOffsetUs < 0) {  // Start time offset was not set
2203            startTimeOffsetUs = kInitialDelayTimeUs;
2204        }
2205        int64_t initialDelayUs =
2206            mFirstSampleTimeRealUs - mStartTimeRealUs - startTimeOffsetUs;
2207
2208        mOwner->notify(MEDIA_RECORDER_TRACK_EVENT_INFO,
2209                    trackNum | MEDIA_RECORDER_TRACK_INFO_INITIAL_DELAY_MS,
2210                    (initialDelayUs) / 1000);
2211    }
2212
2213    mOwner->notify(MEDIA_RECORDER_TRACK_EVENT_INFO,
2214                    trackNum | MEDIA_RECORDER_TRACK_INFO_DATA_KBYTES,
2215                    mMdatSizeBytes / 1024);
2216
2217    if (hasMultipleTracks) {
2218        mOwner->notify(MEDIA_RECORDER_TRACK_EVENT_INFO,
2219                    trackNum | MEDIA_RECORDER_TRACK_INFO_MAX_CHUNK_DUR_MS,
2220                    mMaxChunkDurationUs / 1000);
2221
2222        int64_t moovStartTimeUs = mOwner->getStartTimestampUs();
2223        if (mStartTimestampUs != moovStartTimeUs) {
2224            int64_t startTimeOffsetUs = mStartTimestampUs - moovStartTimeUs;
2225            mOwner->notify(MEDIA_RECORDER_TRACK_EVENT_INFO,
2226                    trackNum | MEDIA_RECORDER_TRACK_INFO_START_OFFSET_MS,
2227                    startTimeOffsetUs / 1000);
2228        }
2229    }
2230}
2231
2232void MPEG4Writer::Track::trackProgressStatus(int64_t timeUs, status_t err) {
2233    ALOGV("trackProgressStatus: %lld us", timeUs);
2234    if (mTrackEveryTimeDurationUs > 0 &&
2235        timeUs - mPreviousTrackTimeUs >= mTrackEveryTimeDurationUs) {
2236        ALOGV("Fire time tracking progress status at %lld us", timeUs);
2237        mOwner->trackProgressStatus(mTrackId, timeUs - mPreviousTrackTimeUs, err);
2238        mPreviousTrackTimeUs = timeUs;
2239    }
2240}
2241
2242void MPEG4Writer::trackProgressStatus(
2243        size_t trackId, int64_t timeUs, status_t err) {
2244    Mutex::Autolock lock(mLock);
2245    int32_t trackNum = (trackId << 28);
2246
2247    // Error notification
2248    // Do not consider ERROR_END_OF_STREAM an error
2249    if (err != OK && err != ERROR_END_OF_STREAM) {
2250        notify(MEDIA_RECORDER_TRACK_EVENT_ERROR,
2251               trackNum | MEDIA_RECORDER_TRACK_ERROR_GENERAL,
2252               err);
2253        return;
2254    }
2255
2256    if (timeUs == -1) {
2257        // Send completion notification
2258        notify(MEDIA_RECORDER_TRACK_EVENT_INFO,
2259               trackNum | MEDIA_RECORDER_TRACK_INFO_COMPLETION_STATUS,
2260               err);
2261    } else {
2262        // Send progress status
2263        notify(MEDIA_RECORDER_TRACK_EVENT_INFO,
2264               trackNum | MEDIA_RECORDER_TRACK_INFO_PROGRESS_IN_TIME,
2265               timeUs / 1000);
2266    }
2267}
2268
2269void MPEG4Writer::setDriftTimeUs(int64_t driftTimeUs) {
2270    ALOGV("setDriftTimeUs: %lld us", driftTimeUs);
2271    Mutex::Autolock autolock(mLock);
2272    mDriftTimeUs = driftTimeUs;
2273}
2274
2275int64_t MPEG4Writer::getDriftTimeUs() {
2276    ALOGV("getDriftTimeUs: %lld us", mDriftTimeUs);
2277    Mutex::Autolock autolock(mLock);
2278    return mDriftTimeUs;
2279}
2280
2281bool MPEG4Writer::useNalLengthFour() {
2282    return mUse4ByteNalLength;
2283}
2284
2285void MPEG4Writer::Track::bufferChunk(int64_t timestampUs) {
2286    ALOGV("bufferChunk");
2287
2288    Chunk chunk(this, timestampUs, mChunkSamples);
2289    mOwner->bufferChunk(chunk);
2290    mChunkSamples.clear();
2291}
2292
2293int64_t MPEG4Writer::Track::getDurationUs() const {
2294    return mTrackDurationUs;
2295}
2296
2297int64_t MPEG4Writer::Track::getEstimatedTrackSizeBytes() const {
2298    return mEstimatedTrackSizeBytes;
2299}
2300
2301status_t MPEG4Writer::Track::checkCodecSpecificData() const {
2302    const char *mime;
2303    CHECK(mMeta->findCString(kKeyMIMEType, &mime));
2304    if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AAC, mime) ||
2305        !strcasecmp(MEDIA_MIMETYPE_VIDEO_MPEG4, mime) ||
2306        !strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime)) {
2307        if (!mCodecSpecificData ||
2308            mCodecSpecificDataSize <= 0) {
2309            ALOGE("Missing codec specific data");
2310            return ERROR_MALFORMED;
2311        }
2312    } else {
2313        if (mCodecSpecificData ||
2314            mCodecSpecificDataSize > 0) {
2315            ALOGE("Unexepected codec specific data found");
2316            return ERROR_MALFORMED;
2317        }
2318    }
2319    return OK;
2320}
2321
2322void MPEG4Writer::Track::writeTrackHeader(bool use32BitOffset) {
2323
2324    ALOGV("%s track time scale: %d",
2325        mIsAudio? "Audio": "Video", mTimeScale);
2326
2327    time_t now = time(NULL);
2328    mOwner->beginBox("trak");
2329        writeTkhdBox(now);
2330        mOwner->beginBox("mdia");
2331            writeMdhdBox(now);
2332            writeHdlrBox();
2333            mOwner->beginBox("minf");
2334                if (mIsAudio) {
2335                    writeSmhdBox();
2336                } else {
2337                    writeVmhdBox();
2338                }
2339                writeDinfBox();
2340                writeStblBox(use32BitOffset);
2341            mOwner->endBox();  // minf
2342        mOwner->endBox();  // mdia
2343    mOwner->endBox();  // trak
2344}
2345
2346void MPEG4Writer::Track::writeStblBox(bool use32BitOffset) {
2347    mOwner->beginBox("stbl");
2348    mOwner->beginBox("stsd");
2349    mOwner->writeInt32(0);               // version=0, flags=0
2350    mOwner->writeInt32(1);               // entry count
2351    if (mIsAudio) {
2352        writeAudioFourCCBox();
2353    } else {
2354        writeVideoFourCCBox();
2355    }
2356    mOwner->endBox();  // stsd
2357    writeSttsBox();
2358    writeCttsBox();
2359    if (!mIsAudio) {
2360        writeStssBox();
2361    }
2362    writeStszBox();
2363    writeStscBox();
2364    writeStcoBox(use32BitOffset);
2365    mOwner->endBox();  // stbl
2366}
2367
2368void MPEG4Writer::Track::writeVideoFourCCBox() {
2369    const char *mime;
2370    bool success = mMeta->findCString(kKeyMIMEType, &mime);
2371    CHECK(success);
2372    if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_MPEG4, mime)) {
2373        mOwner->beginBox("mp4v");
2374    } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_H263, mime)) {
2375        mOwner->beginBox("s263");
2376    } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime)) {
2377        mOwner->beginBox("avc1");
2378    } else {
2379        ALOGE("Unknown mime type '%s'.", mime);
2380        CHECK(!"should not be here, unknown mime type.");
2381    }
2382
2383    mOwner->writeInt32(0);           // reserved
2384    mOwner->writeInt16(0);           // reserved
2385    mOwner->writeInt16(1);           // data ref index
2386    mOwner->writeInt16(0);           // predefined
2387    mOwner->writeInt16(0);           // reserved
2388    mOwner->writeInt32(0);           // predefined
2389    mOwner->writeInt32(0);           // predefined
2390    mOwner->writeInt32(0);           // predefined
2391
2392    int32_t width, height;
2393    success = mMeta->findInt32(kKeyWidth, &width);
2394    success = success && mMeta->findInt32(kKeyHeight, &height);
2395    CHECK(success);
2396
2397    mOwner->writeInt16(width);
2398    mOwner->writeInt16(height);
2399    mOwner->writeInt32(0x480000);    // horiz resolution
2400    mOwner->writeInt32(0x480000);    // vert resolution
2401    mOwner->writeInt32(0);           // reserved
2402    mOwner->writeInt16(1);           // frame count
2403    mOwner->write("                                ", 32);
2404    mOwner->writeInt16(0x18);        // depth
2405    mOwner->writeInt16(-1);          // predefined
2406
2407    CHECK(23 + mCodecSpecificDataSize < 128);
2408
2409    if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_MPEG4, mime)) {
2410        writeMp4vEsdsBox();
2411    } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_H263, mime)) {
2412        writeD263Box();
2413    } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime)) {
2414        writeAvccBox();
2415    }
2416
2417    writePaspBox();
2418    mOwner->endBox();  // mp4v, s263 or avc1
2419}
2420
2421void MPEG4Writer::Track::writeAudioFourCCBox() {
2422    const char *mime;
2423    bool success = mMeta->findCString(kKeyMIMEType, &mime);
2424    CHECK(success);
2425    const char *fourcc = NULL;
2426    if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AMR_NB, mime)) {
2427        fourcc = "samr";
2428    } else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AMR_WB, mime)) {
2429        fourcc = "sawb";
2430    } else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AAC, mime)) {
2431        fourcc = "mp4a";
2432    } else {
2433        ALOGE("Unknown mime type '%s'.", mime);
2434        CHECK(!"should not be here, unknown mime type.");
2435    }
2436
2437    mOwner->beginBox(fourcc);        // audio format
2438    mOwner->writeInt32(0);           // reserved
2439    mOwner->writeInt16(0);           // reserved
2440    mOwner->writeInt16(0x1);         // data ref index
2441    mOwner->writeInt32(0);           // reserved
2442    mOwner->writeInt32(0);           // reserved
2443    int32_t nChannels;
2444    CHECK_EQ(true, mMeta->findInt32(kKeyChannelCount, &nChannels));
2445    mOwner->writeInt16(nChannels);   // channel count
2446    mOwner->writeInt16(16);          // sample size
2447    mOwner->writeInt16(0);           // predefined
2448    mOwner->writeInt16(0);           // reserved
2449
2450    int32_t samplerate;
2451    success = mMeta->findInt32(kKeySampleRate, &samplerate);
2452    CHECK(success);
2453    mOwner->writeInt32(samplerate << 16);
2454    if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AAC, mime)) {
2455        writeMp4aEsdsBox();
2456    } else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AMR_NB, mime) ||
2457               !strcasecmp(MEDIA_MIMETYPE_AUDIO_AMR_WB, mime)) {
2458        writeDamrBox();
2459    }
2460    mOwner->endBox();
2461}
2462
2463void MPEG4Writer::Track::writeMp4aEsdsBox() {
2464    mOwner->beginBox("esds");
2465    CHECK(mCodecSpecificData);
2466    CHECK(mCodecSpecificDataSize > 0);
2467
2468    // Make sure all sizes encode to a single byte.
2469    CHECK(mCodecSpecificDataSize + 23 < 128);
2470
2471    mOwner->writeInt32(0);     // version=0, flags=0
2472    mOwner->writeInt8(0x03);   // ES_DescrTag
2473    mOwner->writeInt8(23 + mCodecSpecificDataSize);
2474    mOwner->writeInt16(0x0000);// ES_ID
2475    mOwner->writeInt8(0x00);
2476
2477    mOwner->writeInt8(0x04);   // DecoderConfigDescrTag
2478    mOwner->writeInt8(15 + mCodecSpecificDataSize);
2479    mOwner->writeInt8(0x40);   // objectTypeIndication ISO/IEC 14492-2
2480    mOwner->writeInt8(0x15);   // streamType AudioStream
2481
2482    mOwner->writeInt16(0x03);  // XXX
2483    mOwner->writeInt8(0x00);   // buffer size 24-bit
2484    mOwner->writeInt32(96000); // max bit rate
2485    mOwner->writeInt32(96000); // avg bit rate
2486
2487    mOwner->writeInt8(0x05);   // DecoderSpecificInfoTag
2488    mOwner->writeInt8(mCodecSpecificDataSize);
2489    mOwner->write(mCodecSpecificData, mCodecSpecificDataSize);
2490
2491    static const uint8_t kData2[] = {
2492        0x06,  // SLConfigDescriptorTag
2493        0x01,
2494        0x02
2495    };
2496    mOwner->write(kData2, sizeof(kData2));
2497
2498    mOwner->endBox();  // esds
2499}
2500
2501void MPEG4Writer::Track::writeMp4vEsdsBox() {
2502    CHECK(mCodecSpecificData);
2503    CHECK(mCodecSpecificDataSize > 0);
2504    mOwner->beginBox("esds");
2505
2506    mOwner->writeInt32(0);    // version=0, flags=0
2507
2508    mOwner->writeInt8(0x03);  // ES_DescrTag
2509    mOwner->writeInt8(23 + mCodecSpecificDataSize);
2510    mOwner->writeInt16(0x0000);  // ES_ID
2511    mOwner->writeInt8(0x1f);
2512
2513    mOwner->writeInt8(0x04);  // DecoderConfigDescrTag
2514    mOwner->writeInt8(15 + mCodecSpecificDataSize);
2515    mOwner->writeInt8(0x20);  // objectTypeIndication ISO/IEC 14492-2
2516    mOwner->writeInt8(0x11);  // streamType VisualStream
2517
2518    static const uint8_t kData[] = {
2519        0x01, 0x77, 0x00,
2520        0x00, 0x03, 0xe8, 0x00,
2521        0x00, 0x03, 0xe8, 0x00
2522    };
2523    mOwner->write(kData, sizeof(kData));
2524
2525    mOwner->writeInt8(0x05);  // DecoderSpecificInfoTag
2526
2527    mOwner->writeInt8(mCodecSpecificDataSize);
2528    mOwner->write(mCodecSpecificData, mCodecSpecificDataSize);
2529
2530    static const uint8_t kData2[] = {
2531        0x06,  // SLConfigDescriptorTag
2532        0x01,
2533        0x02
2534    };
2535    mOwner->write(kData2, sizeof(kData2));
2536
2537    mOwner->endBox();  // esds
2538}
2539
2540void MPEG4Writer::Track::writeTkhdBox(time_t now) {
2541    mOwner->beginBox("tkhd");
2542    // Flags = 7 to indicate that the track is enabled, and
2543    // part of the presentation
2544    mOwner->writeInt32(0x07);          // version=0, flags=7
2545    mOwner->writeInt32(now);           // creation time
2546    mOwner->writeInt32(now);           // modification time
2547    mOwner->writeInt32(mTrackId + 1);  // track id starts with 1
2548    mOwner->writeInt32(0);             // reserved
2549    int64_t trakDurationUs = getDurationUs();
2550    int32_t mvhdTimeScale = mOwner->getTimeScale();
2551    int32_t tkhdDuration =
2552        (trakDurationUs * mvhdTimeScale + 5E5) / 1E6;
2553    mOwner->writeInt32(tkhdDuration);  // in mvhd timescale
2554    mOwner->writeInt32(0);             // reserved
2555    mOwner->writeInt32(0);             // reserved
2556    mOwner->writeInt16(0);             // layer
2557    mOwner->writeInt16(0);             // alternate group
2558    mOwner->writeInt16(mIsAudio ? 0x100 : 0);  // volume
2559    mOwner->writeInt16(0);             // reserved
2560
2561    mOwner->writeCompositionMatrix(mRotation);       // matrix
2562
2563    if (mIsAudio) {
2564        mOwner->writeInt32(0);
2565        mOwner->writeInt32(0);
2566    } else {
2567        int32_t width, height;
2568        bool success = mMeta->findInt32(kKeyWidth, &width);
2569        success = success && mMeta->findInt32(kKeyHeight, &height);
2570        CHECK(success);
2571
2572        mOwner->writeInt32(width << 16);   // 32-bit fixed-point value
2573        mOwner->writeInt32(height << 16);  // 32-bit fixed-point value
2574    }
2575    mOwner->endBox();  // tkhd
2576}
2577
2578void MPEG4Writer::Track::writeVmhdBox() {
2579    mOwner->beginBox("vmhd");
2580    mOwner->writeInt32(0x01);        // version=0, flags=1
2581    mOwner->writeInt16(0);           // graphics mode
2582    mOwner->writeInt16(0);           // opcolor
2583    mOwner->writeInt16(0);
2584    mOwner->writeInt16(0);
2585    mOwner->endBox();
2586}
2587
2588void MPEG4Writer::Track::writeSmhdBox() {
2589    mOwner->beginBox("smhd");
2590    mOwner->writeInt32(0);           // version=0, flags=0
2591    mOwner->writeInt16(0);           // balance
2592    mOwner->writeInt16(0);           // reserved
2593    mOwner->endBox();
2594}
2595
2596void MPEG4Writer::Track::writeHdlrBox() {
2597    mOwner->beginBox("hdlr");
2598    mOwner->writeInt32(0);             // version=0, flags=0
2599    mOwner->writeInt32(0);             // component type: should be mhlr
2600    mOwner->writeFourcc(mIsAudio ? "soun" : "vide");  // component subtype
2601    mOwner->writeInt32(0);             // reserved
2602    mOwner->writeInt32(0);             // reserved
2603    mOwner->writeInt32(0);             // reserved
2604    // Removing "r" for the name string just makes the string 4 byte aligned
2605    mOwner->writeCString(mIsAudio ? "SoundHandle": "VideoHandle");  // name
2606    mOwner->endBox();
2607}
2608
2609void MPEG4Writer::Track::writeMdhdBox(time_t now) {
2610    int64_t trakDurationUs = getDurationUs();
2611    mOwner->beginBox("mdhd");
2612    mOwner->writeInt32(0);             // version=0, flags=0
2613    mOwner->writeInt32(now);           // creation time
2614    mOwner->writeInt32(now);           // modification time
2615    mOwner->writeInt32(mTimeScale);    // media timescale
2616    int32_t mdhdDuration = (trakDurationUs * mTimeScale + 5E5) / 1E6;
2617    mOwner->writeInt32(mdhdDuration);  // use media timescale
2618    // Language follows the three letter standard ISO-639-2/T
2619    // 'e', 'n', 'g' for "English", for instance.
2620    // Each character is packed as the difference between its ASCII value and 0x60.
2621    // For "English", these are 00101, 01110, 00111.
2622    // XXX: Where is the padding bit located: 0x15C7?
2623    mOwner->writeInt16(0);             // language code
2624    mOwner->writeInt16(0);             // predefined
2625    mOwner->endBox();
2626}
2627
2628void MPEG4Writer::Track::writeDamrBox() {
2629    // 3gpp2 Spec AMRSampleEntry fields
2630    mOwner->beginBox("damr");
2631    mOwner->writeCString("   ");  // vendor: 4 bytes
2632    mOwner->writeInt8(0);         // decoder version
2633    mOwner->writeInt16(0x83FF);   // mode set: all enabled
2634    mOwner->writeInt8(0);         // mode change period
2635    mOwner->writeInt8(1);         // frames per sample
2636    mOwner->endBox();
2637}
2638
2639void MPEG4Writer::Track::writeUrlBox() {
2640    // The table index here refers to the sample description index
2641    // in the sample table entries.
2642    mOwner->beginBox("url ");
2643    mOwner->writeInt32(1);  // version=0, flags=1 (self-contained)
2644    mOwner->endBox();  // url
2645}
2646
2647void MPEG4Writer::Track::writeDrefBox() {
2648    mOwner->beginBox("dref");
2649    mOwner->writeInt32(0);  // version=0, flags=0
2650    mOwner->writeInt32(1);  // entry count (either url or urn)
2651    writeUrlBox();
2652    mOwner->endBox();  // dref
2653}
2654
2655void MPEG4Writer::Track::writeDinfBox() {
2656    mOwner->beginBox("dinf");
2657    writeDrefBox();
2658    mOwner->endBox();  // dinf
2659}
2660
2661void MPEG4Writer::Track::writeAvccBox() {
2662    CHECK(mCodecSpecificData);
2663    CHECK(mCodecSpecificDataSize >= 5);
2664
2665    // Patch avcc's lengthSize field to match the number
2666    // of bytes we use to indicate the size of a nal unit.
2667    uint8_t *ptr = (uint8_t *)mCodecSpecificData;
2668    ptr[4] = (ptr[4] & 0xfc) | (mOwner->useNalLengthFour() ? 3 : 1);
2669    mOwner->beginBox("avcC");
2670    mOwner->write(mCodecSpecificData, mCodecSpecificDataSize);
2671    mOwner->endBox();  // avcC
2672}
2673
2674void MPEG4Writer::Track::writeD263Box() {
2675    mOwner->beginBox("d263");
2676    mOwner->writeInt32(0);  // vendor
2677    mOwner->writeInt8(0);   // decoder version
2678    mOwner->writeInt8(10);  // level: 10
2679    mOwner->writeInt8(0);   // profile: 0
2680    mOwner->endBox();  // d263
2681}
2682
2683// This is useful if the pixel is not square
2684void MPEG4Writer::Track::writePaspBox() {
2685    mOwner->beginBox("pasp");
2686    mOwner->writeInt32(1 << 16);  // hspacing
2687    mOwner->writeInt32(1 << 16);  // vspacing
2688    mOwner->endBox();  // pasp
2689}
2690
2691int32_t MPEG4Writer::Track::getStartTimeOffsetScaledTime() const {
2692    int64_t trackStartTimeOffsetUs = 0;
2693    int64_t moovStartTimeUs = mOwner->getStartTimestampUs();
2694    if (mStartTimestampUs != moovStartTimeUs) {
2695        CHECK(mStartTimestampUs > moovStartTimeUs);
2696        trackStartTimeOffsetUs = mStartTimestampUs - moovStartTimeUs;
2697    }
2698    return (trackStartTimeOffsetUs *  mTimeScale + 500000LL) / 1000000LL;
2699}
2700
2701void MPEG4Writer::Track::writeSttsBox() {
2702    mOwner->beginBox("stts");
2703    mOwner->writeInt32(0);  // version=0, flags=0
2704    mOwner->writeInt32(mNumSttsTableEntries);
2705
2706    // Compensate for small start time difference from different media tracks
2707    List<SttsTableEntry>::iterator it = mSttsTableEntries.begin();
2708    CHECK(it != mSttsTableEntries.end() && it->sampleCount == 1);
2709    mOwner->writeInt32(it->sampleCount);
2710    mOwner->writeInt32(getStartTimeOffsetScaledTime() + it->sampleDuration);
2711
2712    int64_t totalCount = 1;
2713    while (++it != mSttsTableEntries.end()) {
2714        mOwner->writeInt32(it->sampleCount);
2715        mOwner->writeInt32(it->sampleDuration);
2716        totalCount += it->sampleCount;
2717    }
2718    CHECK(totalCount == mNumSamples);
2719    mOwner->endBox();  // stts
2720}
2721
2722void MPEG4Writer::Track::writeCttsBox() {
2723    if (mIsAudio) {  // ctts is not for audio
2724        return;
2725    }
2726
2727    // There is no B frame at all
2728    if (mMinCttsOffsetTimeUs == mMaxCttsOffsetTimeUs) {
2729        return;
2730    }
2731
2732    // Do not write ctts box when there is no need to have it.
2733    if ((mNumCttsTableEntries == 1 &&
2734        mCttsTableEntries.begin()->sampleDuration == 0) ||
2735        mNumCttsTableEntries == 0) {
2736        return;
2737    }
2738
2739    ALOGD("ctts box has %d entries with range [%lld, %lld]",
2740            mNumCttsTableEntries, mMinCttsOffsetTimeUs, mMaxCttsOffsetTimeUs);
2741
2742    mOwner->beginBox("ctts");
2743    // Version 1 allows to use negative offset time value, but
2744    // we are sticking to version 0 for now.
2745    mOwner->writeInt32(0);  // version=0, flags=0
2746    mOwner->writeInt32(mNumCttsTableEntries);
2747
2748    // Compensate for small start time difference from different media tracks
2749    List<CttsTableEntry>::iterator it = mCttsTableEntries.begin();
2750    CHECK(it != mCttsTableEntries.end() && it->sampleCount == 1);
2751    mOwner->writeInt32(it->sampleCount);
2752    mOwner->writeInt32(getStartTimeOffsetScaledTime() +
2753            it->sampleDuration - mMinCttsOffsetTimeUs);
2754
2755    int64_t totalCount = 1;
2756    while (++it != mCttsTableEntries.end()) {
2757        mOwner->writeInt32(it->sampleCount);
2758        mOwner->writeInt32(it->sampleDuration - mMinCttsOffsetTimeUs);
2759        totalCount += it->sampleCount;
2760    }
2761    CHECK(totalCount == mNumSamples);
2762    mOwner->endBox();  // ctts
2763}
2764
2765void MPEG4Writer::Track::writeStssBox() {
2766    mOwner->beginBox("stss");
2767    mOwner->writeInt32(0);  // version=0, flags=0
2768    mOwner->writeInt32(mNumStssTableEntries);  // number of sync frames
2769    for (List<int32_t>::iterator it = mStssTableEntries.begin();
2770        it != mStssTableEntries.end(); ++it) {
2771        mOwner->writeInt32(*it);
2772    }
2773    mOwner->endBox();  // stss
2774}
2775
2776void MPEG4Writer::Track::writeStszBox() {
2777    mOwner->beginBox("stsz");
2778    mOwner->writeInt32(0);  // version=0, flags=0
2779    if (mSamplesHaveSameSize) {
2780        List<size_t>::iterator it = mSampleSizes.begin();
2781        mOwner->writeInt32(*it);  // default sample size
2782    } else {
2783        mOwner->writeInt32(0);
2784    }
2785    mOwner->writeInt32(mNumSamples);
2786    if (!mSamplesHaveSameSize) {
2787        for (List<size_t>::iterator it = mSampleSizes.begin();
2788            it != mSampleSizes.end(); ++it) {
2789            mOwner->writeInt32(*it);
2790        }
2791    }
2792    mOwner->endBox();  // stsz
2793}
2794
2795void MPEG4Writer::Track::writeStscBox() {
2796    mOwner->beginBox("stsc");
2797    mOwner->writeInt32(0);  // version=0, flags=0
2798    mOwner->writeInt32(mNumStscTableEntries);
2799    for (List<StscTableEntry>::iterator it = mStscTableEntries.begin();
2800        it != mStscTableEntries.end(); ++it) {
2801        mOwner->writeInt32(it->firstChunk);
2802        mOwner->writeInt32(it->samplesPerChunk);
2803        mOwner->writeInt32(it->sampleDescriptionId);
2804    }
2805    mOwner->endBox();  // stsc
2806}
2807
2808void MPEG4Writer::Track::writeStcoBox(bool use32BitOffset) {
2809    mOwner->beginBox(use32BitOffset? "stco": "co64");
2810    mOwner->writeInt32(0);  // version=0, flags=0
2811    mOwner->writeInt32(mNumStcoTableEntries);
2812    for (List<off64_t>::iterator it = mChunkOffsets.begin();
2813        it != mChunkOffsets.end(); ++it) {
2814        if (use32BitOffset) {
2815            mOwner->writeInt32(static_cast<int32_t>(*it));
2816        } else {
2817            mOwner->writeInt64((*it));
2818        }
2819    }
2820    mOwner->endBox();  // stco or co64
2821}
2822
2823void MPEG4Writer::writeUdtaBox() {
2824    beginBox("udta");
2825    writeGeoDataBox();
2826    endBox();
2827}
2828
2829/*
2830 * Geodata is stored according to ISO-6709 standard.
2831 */
2832void MPEG4Writer::writeGeoDataBox() {
2833    beginBox("\xA9xyz");
2834    /*
2835     * For historical reasons, any user data start
2836     * with "\0xA9", must be followed by its assoicated
2837     * language code.
2838     * 0x0012: text string length
2839     * 0x15c7: lang (locale) code: en
2840     */
2841    writeInt32(0x001215c7);
2842    writeLatitude(mLatitudex10000);
2843    writeLongitude(mLongitudex10000);
2844    writeInt8(0x2F);
2845    endBox();
2846}
2847
2848}  // namespace android
2849