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