MPEG4Writer.cpp revision 7b92cb6aecba28927ed5d66ec1ba0a9f496477f0
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#include <sys/resource.h>
26
27#include <media/stagefright/MPEG4Writer.h>
28#include <media/stagefright/MediaBuffer.h>
29#include <media/stagefright/MetaData.h>
30#include <media/stagefright/MediaDebug.h>
31#include <media/stagefright/MediaDefs.h>
32#include <media/stagefright/MediaErrors.h>
33#include <media/stagefright/MediaSource.h>
34#include <media/stagefright/Utils.h>
35#include <media/mediarecorder.h>
36#include <cutils/properties.h>
37#include <sys/types.h>
38#include <sys/stat.h>
39#include <fcntl.h>
40#include <unistd.h>
41
42#include "include/ESDS.h"
43
44namespace android {
45
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
51// Using longer adjustment period to suppress fluctuations in
52// the audio encoding paths
53static const int64_t kVideoMediaTimeAdjustPeriodTimeUs = 600000000LL;  // 10 minutes
54
55class MPEG4Writer::Track {
56public:
57    Track(MPEG4Writer *owner, const sp<MediaSource> &source, size_t trackId);
58
59    ~Track();
60
61    status_t start(MetaData *params);
62    status_t stop();
63    status_t pause();
64    bool reachedEOS();
65
66    int64_t getDurationUs() const;
67    int64_t getEstimatedTrackSizeBytes() const;
68    void writeTrackHeader(bool use32BitOffset = true);
69    void bufferChunk(int64_t timestampUs);
70    bool isAvc() const { return mIsAvc; }
71    bool isAudio() const { return mIsAudio; }
72    bool isMPEG4() const { return mIsMPEG4; }
73    void addChunkOffset(off64_t offset);
74    int32_t getTrackId() const { return mTrackId; }
75    status_t dump(int fd, const Vector<String16>& args) const;
76
77private:
78    MPEG4Writer *mOwner;
79    sp<MetaData> mMeta;
80    sp<MediaSource> mSource;
81    volatile bool mDone;
82    volatile bool mPaused;
83    volatile bool mResumed;
84    volatile bool mStarted;
85    bool mIsAvc;
86    bool mIsAudio;
87    bool mIsMPEG4;
88    int32_t mTrackId;
89    int64_t mTrackDurationUs;
90    int64_t mMaxChunkDurationUs;
91
92    // For realtime applications, we need to adjust the media clock
93    // for video track based on the audio media clock
94    bool mIsRealTimeRecording;
95    int64_t mMaxTimeStampUs;
96    int64_t mEstimatedTrackSizeBytes;
97    int64_t mMdatSizeBytes;
98    int32_t mTimeScale;
99
100    pthread_t mThread;
101
102    // mNumSamples is used to track how many samples in mSampleSizes List.
103    // This is to reduce the cost associated with mSampleSizes.size() call,
104    // since it is O(n). Ideally, the fix should be in List class.
105    size_t              mNumSamples;
106    List<size_t>        mSampleSizes;
107    bool                mSamplesHaveSameSize;
108
109    List<MediaBuffer *> mChunkSamples;
110
111    size_t              mNumStcoTableEntries;
112    List<off64_t>         mChunkOffsets;
113
114    size_t              mNumStscTableEntries;
115    struct StscTableEntry {
116
117        StscTableEntry(uint32_t chunk, uint32_t samples, uint32_t id)
118            : firstChunk(chunk),
119              samplesPerChunk(samples),
120              sampleDescriptionId(id) {}
121
122        uint32_t firstChunk;
123        uint32_t samplesPerChunk;
124        uint32_t sampleDescriptionId;
125    };
126    List<StscTableEntry> mStscTableEntries;
127
128    size_t        mNumStssTableEntries;
129    List<int32_t> mStssTableEntries;
130
131    struct SttsTableEntry {
132
133        SttsTableEntry(uint32_t count, uint32_t duration)
134            : sampleCount(count), sampleDuration(duration) {}
135
136        uint32_t sampleCount;
137        uint32_t sampleDuration;  // time scale based
138    };
139    size_t        mNumSttsTableEntries;
140    List<SttsTableEntry> mSttsTableEntries;
141
142    struct CttsTableEntry {
143        CttsTableEntry(uint32_t count, int32_t timescaledDur)
144            : sampleCount(count), sampleDuration(timescaledDur) {}
145
146        uint32_t sampleCount;
147        int32_t sampleDuration;  // time scale based
148    };
149    bool          mHasNegativeCttsDeltaDuration;
150    size_t        mNumCttsTableEntries;
151    List<CttsTableEntry> mCttsTableEntries;
152
153    // Sequence parameter set or picture parameter set
154    struct AVCParamSet {
155        AVCParamSet(uint16_t length, const uint8_t *data)
156            : mLength(length), mData(data) {}
157
158        uint16_t mLength;
159        const uint8_t *mData;
160    };
161    List<AVCParamSet> mSeqParamSets;
162    List<AVCParamSet> mPicParamSets;
163    uint8_t mProfileIdc;
164    uint8_t mProfileCompatible;
165    uint8_t mLevelIdc;
166
167    void *mCodecSpecificData;
168    size_t mCodecSpecificDataSize;
169    bool mGotAllCodecSpecificData;
170    bool mTrackingProgressStatus;
171
172    bool mReachedEOS;
173    int64_t mStartTimestampUs;
174    int64_t mStartTimeRealUs;
175    int64_t mFirstSampleTimeRealUs;
176    int64_t mPreviousTrackTimeUs;
177    int64_t mTrackEveryTimeDurationUs;
178
179    // Has the media time adjustment for video started?
180    bool    mIsMediaTimeAdjustmentOn;
181    // The time stamp when previous media time adjustment period starts
182    int64_t mPrevMediaTimeAdjustTimestampUs;
183    // Number of vidoe frames whose time stamp may be adjusted
184    int64_t mMediaTimeAdjustNumFrames;
185    // The sample number when previous meida time adjustmnet period starts
186    int64_t mPrevMediaTimeAdjustSample;
187    // The total accumulated drift time within a period of
188    // kVideoMediaTimeAdjustPeriodTimeUs.
189    int64_t mTotalDriftTimeToAdjustUs;
190    // The total accumalated drift time since the start of the recording
191    // excluding the current time adjustment period
192    int64_t mPrevTotalAccumDriftTimeUs;
193
194    // Update the audio track's drift information.
195    void updateDriftTime(const sp<MetaData>& meta);
196
197    // Adjust the time stamp of the video track according to
198    // the drift time information from the audio track.
199    void adjustMediaTime(int64_t *timestampUs);
200
201    static void *ThreadWrapper(void *me);
202    status_t threadEntry();
203
204    const uint8_t *parseParamSet(
205        const uint8_t *data, size_t length, int type, size_t *paramSetLen);
206
207    status_t makeAVCCodecSpecificData(const uint8_t *data, size_t size);
208    status_t copyAVCCodecSpecificData(const uint8_t *data, size_t size);
209    status_t parseAVCCodecSpecificData(const uint8_t *data, size_t size);
210
211    // Track authoring progress status
212    void trackProgressStatus(int64_t timeUs, status_t err = OK);
213    void initTrackingProgressStatus(MetaData *params);
214
215    void getCodecSpecificDataFromInputFormatIfPossible();
216
217    // Determine the track time scale
218    // If it is an audio track, try to use the sampling rate as
219    // the time scale; however, if user chooses the overwrite
220    // value, the user-supplied time scale will be used.
221    void setTimeScale();
222
223    // Simple validation on the codec specific data
224    status_t checkCodecSpecificData() const;
225    int32_t mRotation;
226
227    void updateTrackSizeEstimate();
228    void addOneStscTableEntry(size_t chunkId, size_t sampleId);
229    void addOneStssTableEntry(size_t sampleId);
230
231    // Duration is time scale based
232    void addOneSttsTableEntry(size_t sampleCount, int32_t timescaledDur);
233    void addOneCttsTableEntry(size_t sampleCount, int32_t timescaledDur);
234    void sendTrackSummary(bool hasMultipleTracks);
235
236    // Write the boxes
237    void writeStcoBox(bool use32BitOffset);
238    void writeStscBox();
239    void writeStszBox();
240    void writeStssBox();
241    void writeSttsBox();
242    void writeCttsBox();
243    void writeD263Box();
244    void writePaspBox();
245    void writeAvccBox();
246    void writeUrlBox();
247    void writeDrefBox();
248    void writeDinfBox();
249    void writeDamrBox();
250    void writeMdhdBox(time_t now);
251    void writeSmhdBox();
252    void writeVmhdBox();
253    void writeHdlrBox();
254    void writeTkhdBox(time_t now);
255    void writeMp4aEsdsBox();
256    void writeMp4vEsdsBox();
257    void writeAudioFourCCBox();
258    void writeVideoFourCCBox();
259    void writeStblBox(bool use32BitOffset);
260
261    Track(const Track &);
262    Track &operator=(const Track &);
263};
264
265MPEG4Writer::MPEG4Writer(const char *filename)
266    : mFd(-1),
267      mInitCheck(NO_INIT),
268      mUse4ByteNalLength(true),
269      mUse32BitOffset(true),
270      mIsFileSizeLimitExplicitlyRequested(false),
271      mPaused(false),
272      mStarted(false),
273      mOffset(0),
274      mMdatOffset(0),
275      mEstimatedMoovBoxSize(0),
276      mInterleaveDurationUs(1000000),
277      mLatitudex10000(0),
278      mLongitudex10000(0),
279      mAreGeoTagsAvailable(false),
280      mStartTimeOffsetMs(-1) {
281
282    mFd = open(filename, O_CREAT | O_LARGEFILE | O_TRUNC | O_RDWR);
283    if (mFd >= 0) {
284        mInitCheck = OK;
285    }
286}
287
288MPEG4Writer::MPEG4Writer(int fd)
289    : mFd(dup(fd)),
290      mInitCheck(mFd < 0? NO_INIT: OK),
291      mUse4ByteNalLength(true),
292      mUse32BitOffset(true),
293      mIsFileSizeLimitExplicitlyRequested(false),
294      mPaused(false),
295      mStarted(false),
296      mOffset(0),
297      mMdatOffset(0),
298      mEstimatedMoovBoxSize(0),
299      mInterleaveDurationUs(1000000),
300      mLatitudex10000(0),
301      mLongitudex10000(0),
302      mAreGeoTagsAvailable(false),
303      mStartTimeOffsetMs(-1) {
304}
305
306MPEG4Writer::~MPEG4Writer() {
307    stop();
308
309    while (!mTracks.empty()) {
310        List<Track *>::iterator it = mTracks.begin();
311        delete *it;
312        (*it) = NULL;
313        mTracks.erase(it);
314    }
315    mTracks.clear();
316}
317
318status_t MPEG4Writer::dump(
319        int fd, const Vector<String16>& args) {
320    const size_t SIZE = 256;
321    char buffer[SIZE];
322    String8 result;
323    snprintf(buffer, SIZE, "   MPEG4Writer %p\n", this);
324    result.append(buffer);
325    snprintf(buffer, SIZE, "     mStarted: %s\n", mStarted? "true": "false");
326    result.append(buffer);
327    ::write(fd, result.string(), result.size());
328    for (List<Track *>::iterator it = mTracks.begin();
329         it != mTracks.end(); ++it) {
330        (*it)->dump(fd, args);
331    }
332    return OK;
333}
334
335status_t MPEG4Writer::Track::dump(
336        int fd, const Vector<String16>& args) const {
337    const size_t SIZE = 256;
338    char buffer[SIZE];
339    String8 result;
340    snprintf(buffer, SIZE, "     %s track\n", mIsAudio? "Audio": "Video");
341    result.append(buffer);
342    snprintf(buffer, SIZE, "       reached EOS: %s\n",
343            mReachedEOS? "true": "false");
344    result.append(buffer);
345    ::write(fd, result.string(), result.size());
346    return OK;
347}
348
349status_t MPEG4Writer::addSource(const sp<MediaSource> &source) {
350    Mutex::Autolock l(mLock);
351    if (mStarted) {
352        LOGE("Attempt to add source AFTER recording is started");
353        return UNKNOWN_ERROR;
354    }
355    Track *track = new Track(this, source, mTracks.size());
356    mTracks.push_back(track);
357
358    return OK;
359}
360
361status_t MPEG4Writer::startTracks(MetaData *params) {
362    for (List<Track *>::iterator it = mTracks.begin();
363         it != mTracks.end(); ++it) {
364        status_t err = (*it)->start(params);
365
366        if (err != OK) {
367            for (List<Track *>::iterator it2 = mTracks.begin();
368                 it2 != it; ++it2) {
369                (*it2)->stop();
370            }
371
372            return err;
373        }
374    }
375    return OK;
376}
377
378int64_t MPEG4Writer::estimateMoovBoxSize(int32_t bitRate) {
379    // This implementation is highly experimental/heurisitic.
380    //
381    // Statistical analysis shows that metadata usually accounts
382    // for a small portion of the total file size, usually < 0.6%.
383
384    // The default MIN_MOOV_BOX_SIZE is set to 0.6% x 1MB / 2,
385    // where 1MB is the common file size limit for MMS application.
386    // The default MAX _MOOV_BOX_SIZE value is based on about 3
387    // minute video recording with a bit rate about 3 Mbps, because
388    // statistics also show that most of the video captured are going
389    // to be less than 3 minutes.
390
391    // If the estimation is wrong, we will pay the price of wasting
392    // some reserved space. This should not happen so often statistically.
393    static const int32_t factor = mUse32BitOffset? 1: 2;
394    static const int64_t MIN_MOOV_BOX_SIZE = 3 * 1024;  // 3 KB
395    static const int64_t MAX_MOOV_BOX_SIZE = (180 * 3000000 * 6LL / 8000);
396    int64_t size = MIN_MOOV_BOX_SIZE;
397
398    // Max file size limit is set
399    if (mMaxFileSizeLimitBytes != 0 && mIsFileSizeLimitExplicitlyRequested) {
400        size = mMaxFileSizeLimitBytes * 6 / 1000;
401    }
402
403    // Max file duration limit is set
404    if (mMaxFileDurationLimitUs != 0) {
405        if (bitRate > 0) {
406            int64_t size2 =
407                ((mMaxFileDurationLimitUs * bitRate * 6) / 1000 / 8000000);
408            if (mMaxFileSizeLimitBytes != 0 && mIsFileSizeLimitExplicitlyRequested) {
409                // When both file size and duration limits are set,
410                // we use the smaller limit of the two.
411                if (size > size2) {
412                    size = size2;
413                }
414            } else {
415                // Only max file duration limit is set
416                size = size2;
417            }
418        }
419    }
420
421    if (size < MIN_MOOV_BOX_SIZE) {
422        size = MIN_MOOV_BOX_SIZE;
423    }
424
425    // Any long duration recording will be probably end up with
426    // non-streamable mp4 file.
427    if (size > MAX_MOOV_BOX_SIZE) {
428        size = MAX_MOOV_BOX_SIZE;
429    }
430
431    LOGI("limits: %lld/%lld bytes/us, bit rate: %d bps and the estimated"
432         " moov size %lld bytes",
433         mMaxFileSizeLimitBytes, mMaxFileDurationLimitUs, bitRate, size);
434    return factor * size;
435}
436
437status_t MPEG4Writer::start(MetaData *param) {
438    if (mInitCheck != OK) {
439        return UNKNOWN_ERROR;
440    }
441
442    /*
443     * Check mMaxFileSizeLimitBytes at the beginning
444     * since mMaxFileSizeLimitBytes may be implicitly
445     * changed later for 32-bit file offset even if
446     * user does not ask to set it explicitly.
447     */
448    if (mMaxFileSizeLimitBytes != 0) {
449        mIsFileSizeLimitExplicitlyRequested = true;
450    }
451
452    int32_t use64BitOffset;
453    if (param &&
454        param->findInt32(kKey64BitFileOffset, &use64BitOffset) &&
455        use64BitOffset) {
456        mUse32BitOffset = false;
457    }
458
459    if (mUse32BitOffset) {
460        // Implicit 32 bit file size limit
461        if (mMaxFileSizeLimitBytes == 0) {
462            mMaxFileSizeLimitBytes = kMax32BitFileSize;
463        }
464
465        // If file size is set to be larger than the 32 bit file
466        // size limit, treat it as an error.
467        if (mMaxFileSizeLimitBytes > kMax32BitFileSize) {
468            LOGW("32-bit file size limit (%lld bytes) too big. "
469                 "It is changed to %lld bytes",
470                mMaxFileSizeLimitBytes, kMax32BitFileSize);
471            mMaxFileSizeLimitBytes = kMax32BitFileSize;
472        }
473    }
474
475    int32_t use2ByteNalLength;
476    if (param &&
477        param->findInt32(kKey2ByteNalLength, &use2ByteNalLength) &&
478        use2ByteNalLength) {
479        mUse4ByteNalLength = false;
480    }
481
482    mStartTimestampUs = -1;
483
484    if (mStarted) {
485        if (mPaused) {
486            mPaused = false;
487            return startTracks(param);
488        }
489        return OK;
490    }
491
492    if (!param ||
493        !param->findInt32(kKeyTimeScale, &mTimeScale)) {
494        mTimeScale = 1000;
495    }
496    CHECK(mTimeScale > 0);
497    LOGV("movie time scale: %d", mTimeScale);
498
499    mStreamableFile = true;
500    mWriteMoovBoxToMemory = false;
501    mMoovBoxBuffer = NULL;
502    mMoovBoxBufferOffset = 0;
503
504    writeFtypBox(param);
505
506    mFreeBoxOffset = mOffset;
507
508    if (mEstimatedMoovBoxSize == 0) {
509        int32_t bitRate = -1;
510        if (param) {
511            param->findInt32(kKeyBitRate, &bitRate);
512        }
513        mEstimatedMoovBoxSize = estimateMoovBoxSize(bitRate);
514    }
515    CHECK(mEstimatedMoovBoxSize >= 8);
516    lseek64(mFd, mFreeBoxOffset, SEEK_SET);
517    writeInt32(mEstimatedMoovBoxSize);
518    write("free", 4);
519
520    mMdatOffset = mFreeBoxOffset + mEstimatedMoovBoxSize;
521    mOffset = mMdatOffset;
522    lseek64(mFd, mMdatOffset, SEEK_SET);
523    if (mUse32BitOffset) {
524        write("????mdat", 8);
525    } else {
526        write("\x00\x00\x00\x01mdat????????", 16);
527    }
528
529    status_t err = startWriterThread();
530    if (err != OK) {
531        return err;
532    }
533
534    err = startTracks(param);
535    if (err != OK) {
536        return err;
537    }
538
539    mStarted = true;
540    return OK;
541}
542
543bool MPEG4Writer::use32BitFileOffset() const {
544    return mUse32BitOffset;
545}
546
547status_t MPEG4Writer::pause() {
548    if (mInitCheck != OK) {
549        return OK;
550    }
551    mPaused = true;
552    status_t err = OK;
553    for (List<Track *>::iterator it = mTracks.begin();
554         it != mTracks.end(); ++it) {
555        status_t status = (*it)->pause();
556        if (status != OK) {
557            err = status;
558        }
559    }
560    return err;
561}
562
563void MPEG4Writer::stopWriterThread() {
564    LOGD("Stopping writer thread");
565
566    {
567        Mutex::Autolock autolock(mLock);
568
569        mDone = true;
570        mChunkReadyCondition.signal();
571    }
572
573    void *dummy;
574    pthread_join(mThread, &dummy);
575    LOGD("Writer thread stopped");
576}
577
578/*
579 * MP4 file standard defines a composition matrix:
580 * | a  b  u |
581 * | c  d  v |
582 * | x  y  w |
583 *
584 * the element in the matrix is stored in the following
585 * order: {a, b, u, c, d, v, x, y, w},
586 * where a, b, c, d, x, and y is in 16.16 format, while
587 * u, v and w is in 2.30 format.
588 */
589void MPEG4Writer::writeCompositionMatrix(int degrees) {
590    LOGV("writeCompositionMatrix");
591    uint32_t a = 0x00010000;
592    uint32_t b = 0;
593    uint32_t c = 0;
594    uint32_t d = 0x00010000;
595    switch (degrees) {
596        case 0:
597            break;
598        case 90:
599            a = 0;
600            b = 0x00010000;
601            c = 0xFFFF0000;
602            d = 0;
603            break;
604        case 180:
605            a = 0xFFFF0000;
606            d = 0xFFFF0000;
607            break;
608        case 270:
609            a = 0;
610            b = 0xFFFF0000;
611            c = 0x00010000;
612            d = 0;
613            break;
614        default:
615            CHECK(!"Should never reach this unknown rotation");
616            break;
617    }
618
619    writeInt32(a);           // a
620    writeInt32(b);           // b
621    writeInt32(0);           // u
622    writeInt32(c);           // c
623    writeInt32(d);           // d
624    writeInt32(0);           // v
625    writeInt32(0);           // x
626    writeInt32(0);           // y
627    writeInt32(0x40000000);  // w
628}
629
630
631status_t MPEG4Writer::stop() {
632    if (mInitCheck != OK) {
633        return OK;
634    }
635
636    status_t err = OK;
637    int64_t maxDurationUs = 0;
638    int64_t minDurationUs = 0x7fffffffffffffffLL;
639    for (List<Track *>::iterator it = mTracks.begin();
640         it != mTracks.end(); ++it) {
641        status_t status = (*it)->stop();
642        if (err == OK && status != OK) {
643            err = status;
644        }
645
646        int64_t durationUs = (*it)->getDurationUs();
647        if (durationUs > maxDurationUs) {
648            maxDurationUs = durationUs;
649        }
650        if (durationUs < minDurationUs) {
651            minDurationUs = durationUs;
652        }
653    }
654
655    if (mTracks.size() > 1) {
656        LOGD("Duration from tracks range is [%lld, %lld] us",
657            minDurationUs, maxDurationUs);
658    }
659
660    stopWriterThread();
661
662    // Do not write out movie header on error.
663    if (err != OK) {
664        close(mFd);
665        mFd = -1;
666        mInitCheck = NO_INIT;
667        mStarted = false;
668        return err;
669    }
670
671    // Fix up the size of the 'mdat' chunk.
672    if (mUse32BitOffset) {
673        lseek64(mFd, mMdatOffset, SEEK_SET);
674        int32_t size = htonl(static_cast<int32_t>(mOffset - mMdatOffset));
675        ::write(mFd, &size, 4);
676    } else {
677        lseek64(mFd, mMdatOffset + 8, SEEK_SET);
678        int64_t size = mOffset - mMdatOffset;
679        size = hton64(size);
680        ::write(mFd, &size, 8);
681    }
682    lseek64(mFd, mOffset, SEEK_SET);
683
684    const off64_t moovOffset = mOffset;
685    mWriteMoovBoxToMemory = true;
686    mMoovBoxBuffer = (uint8_t *) malloc(mEstimatedMoovBoxSize);
687    mMoovBoxBufferOffset = 0;
688    CHECK(mMoovBoxBuffer != NULL);
689    writeMoovBox(maxDurationUs);
690
691    mWriteMoovBoxToMemory = false;
692    if (mStreamableFile) {
693        CHECK(mMoovBoxBufferOffset + 8 <= mEstimatedMoovBoxSize);
694
695        // Moov box
696        lseek64(mFd, mFreeBoxOffset, SEEK_SET);
697        mOffset = mFreeBoxOffset;
698        write(mMoovBoxBuffer, 1, mMoovBoxBufferOffset);
699
700        // Free box
701        lseek64(mFd, mOffset, SEEK_SET);
702        writeInt32(mEstimatedMoovBoxSize - mMoovBoxBufferOffset);
703        write("free", 4);
704
705        // Free temp memory
706        free(mMoovBoxBuffer);
707        mMoovBoxBuffer = NULL;
708        mMoovBoxBufferOffset = 0;
709    } else {
710        LOGI("The mp4 file will not be streamable.");
711    }
712
713    CHECK(mBoxes.empty());
714
715    close(mFd);
716    mFd = -1;
717    mInitCheck = NO_INIT;
718    mStarted = false;
719
720    return err;
721}
722
723void MPEG4Writer::writeMvhdBox(int64_t durationUs) {
724    time_t now = time(NULL);
725    beginBox("mvhd");
726    writeInt32(0);             // version=0, flags=0
727    writeInt32(now);           // creation time
728    writeInt32(now);           // modification time
729    writeInt32(mTimeScale);    // mvhd timescale
730    int32_t duration = (durationUs * mTimeScale + 5E5) / 1E6;
731    writeInt32(duration);
732    writeInt32(0x10000);       // rate: 1.0
733    writeInt16(0x100);         // volume
734    writeInt16(0);             // reserved
735    writeInt32(0);             // reserved
736    writeInt32(0);             // reserved
737    writeCompositionMatrix(0); // matrix
738    writeInt32(0);             // predefined
739    writeInt32(0);             // predefined
740    writeInt32(0);             // predefined
741    writeInt32(0);             // predefined
742    writeInt32(0);             // predefined
743    writeInt32(0);             // predefined
744    writeInt32(mTracks.size() + 1);  // nextTrackID
745    endBox();  // mvhd
746}
747
748void MPEG4Writer::writeMoovBox(int64_t durationUs) {
749    beginBox("moov");
750    writeMvhdBox(durationUs);
751    if (mAreGeoTagsAvailable) {
752        writeUdtaBox();
753    }
754    int32_t id = 1;
755    for (List<Track *>::iterator it = mTracks.begin();
756        it != mTracks.end(); ++it, ++id) {
757        (*it)->writeTrackHeader(mUse32BitOffset);
758    }
759    endBox();  // moov
760}
761
762void MPEG4Writer::writeFtypBox(MetaData *param) {
763    beginBox("ftyp");
764
765    int32_t fileType;
766    if (param && param->findInt32(kKeyFileType, &fileType) &&
767        fileType != OUTPUT_FORMAT_MPEG_4) {
768        writeFourcc("3gp4");
769    } else {
770        writeFourcc("isom");
771    }
772
773    writeInt32(0);
774    writeFourcc("isom");
775    writeFourcc("3gp4");
776    endBox();
777}
778
779static bool isTestModeEnabled() {
780#if (PROPERTY_VALUE_MAX < 5)
781#error "PROPERTY_VALUE_MAX must be at least 5"
782#endif
783
784    // Test mode is enabled only if rw.media.record.test system
785    // property is enabled.
786    char value[PROPERTY_VALUE_MAX];
787    if (property_get("rw.media.record.test", value, NULL) &&
788        (!strcasecmp(value, "true") || !strcasecmp(value, "1"))) {
789        return true;
790    }
791    return false;
792}
793
794void MPEG4Writer::sendSessionSummary() {
795    // Send session summary only if test mode is enabled
796    if (!isTestModeEnabled()) {
797        return;
798    }
799
800    for (List<ChunkInfo>::iterator it = mChunkInfos.begin();
801         it != mChunkInfos.end(); ++it) {
802        int trackNum = it->mTrack->getTrackId() << 28;
803        notify(MEDIA_RECORDER_TRACK_EVENT_INFO,
804                trackNum | MEDIA_RECORDER_TRACK_INTER_CHUNK_TIME_MS,
805                it->mMaxInterChunkDurUs);
806    }
807}
808
809status_t MPEG4Writer::setInterleaveDuration(uint32_t durationUs) {
810    mInterleaveDurationUs = durationUs;
811    return OK;
812}
813
814void MPEG4Writer::lock() {
815    mLock.lock();
816}
817
818void MPEG4Writer::unlock() {
819    mLock.unlock();
820}
821
822off64_t MPEG4Writer::addSample_l(MediaBuffer *buffer) {
823    off64_t old_offset = mOffset;
824
825    ::write(mFd,
826          (const uint8_t *)buffer->data() + buffer->range_offset(),
827          buffer->range_length());
828
829    mOffset += buffer->range_length();
830
831    return old_offset;
832}
833
834static void StripStartcode(MediaBuffer *buffer) {
835    if (buffer->range_length() < 4) {
836        return;
837    }
838
839    const uint8_t *ptr =
840        (const uint8_t *)buffer->data() + buffer->range_offset();
841
842    if (!memcmp(ptr, "\x00\x00\x00\x01", 4)) {
843        buffer->set_range(
844                buffer->range_offset() + 4, buffer->range_length() - 4);
845    }
846}
847
848off64_t MPEG4Writer::addLengthPrefixedSample_l(MediaBuffer *buffer) {
849    off64_t old_offset = mOffset;
850
851    size_t length = buffer->range_length();
852
853    if (mUse4ByteNalLength) {
854        uint8_t x = length >> 24;
855        ::write(mFd, &x, 1);
856        x = (length >> 16) & 0xff;
857        ::write(mFd, &x, 1);
858        x = (length >> 8) & 0xff;
859        ::write(mFd, &x, 1);
860        x = length & 0xff;
861        ::write(mFd, &x, 1);
862
863        ::write(mFd,
864              (const uint8_t *)buffer->data() + buffer->range_offset(),
865              length);
866
867        mOffset += length + 4;
868    } else {
869        CHECK(length < 65536);
870
871        uint8_t x = length >> 8;
872        ::write(mFd, &x, 1);
873        x = length & 0xff;
874        ::write(mFd, &x, 1);
875        ::write(mFd, (const uint8_t *)buffer->data() + buffer->range_offset(), length);
876        mOffset += length + 2;
877    }
878
879    return old_offset;
880}
881
882size_t MPEG4Writer::write(
883        const void *ptr, size_t size, size_t nmemb) {
884
885    const size_t bytes = size * nmemb;
886    if (mWriteMoovBoxToMemory) {
887        // This happens only when we write the moov box at the end of
888        // recording, not for each output video/audio frame we receive.
889        off64_t moovBoxSize = 8 + mMoovBoxBufferOffset + bytes;
890        if (moovBoxSize > mEstimatedMoovBoxSize) {
891            for (List<off64_t>::iterator it = mBoxes.begin();
892                 it != mBoxes.end(); ++it) {
893                (*it) += mOffset;
894            }
895            lseek64(mFd, mOffset, SEEK_SET);
896            ::write(mFd, mMoovBoxBuffer, mMoovBoxBufferOffset);
897            ::write(mFd, ptr, size * nmemb);
898            mOffset += (bytes + mMoovBoxBufferOffset);
899            free(mMoovBoxBuffer);
900            mMoovBoxBuffer = NULL;
901            mMoovBoxBufferOffset = 0;
902            mWriteMoovBoxToMemory = false;
903            mStreamableFile = false;
904        } else {
905            memcpy(mMoovBoxBuffer + mMoovBoxBufferOffset, ptr, bytes);
906            mMoovBoxBufferOffset += bytes;
907        }
908    } else {
909        ::write(mFd, ptr, size * nmemb);
910        mOffset += bytes;
911    }
912    return bytes;
913}
914
915void MPEG4Writer::beginBox(const char *fourcc) {
916    CHECK_EQ(strlen(fourcc), 4);
917
918    mBoxes.push_back(mWriteMoovBoxToMemory?
919            mMoovBoxBufferOffset: mOffset);
920
921    writeInt32(0);
922    writeFourcc(fourcc);
923}
924
925void MPEG4Writer::endBox() {
926    CHECK(!mBoxes.empty());
927
928    off64_t offset = *--mBoxes.end();
929    mBoxes.erase(--mBoxes.end());
930
931    if (mWriteMoovBoxToMemory) {
932       int32_t x = htonl(mMoovBoxBufferOffset - offset);
933       memcpy(mMoovBoxBuffer + offset, &x, 4);
934    } else {
935        lseek64(mFd, offset, SEEK_SET);
936        writeInt32(mOffset - offset);
937        mOffset -= 4;
938        lseek64(mFd, mOffset, SEEK_SET);
939    }
940}
941
942void MPEG4Writer::writeInt8(int8_t x) {
943    write(&x, 1, 1);
944}
945
946void MPEG4Writer::writeInt16(int16_t x) {
947    x = htons(x);
948    write(&x, 1, 2);
949}
950
951void MPEG4Writer::writeInt32(int32_t x) {
952    x = htonl(x);
953    write(&x, 1, 4);
954}
955
956void MPEG4Writer::writeInt64(int64_t x) {
957    x = hton64(x);
958    write(&x, 1, 8);
959}
960
961void MPEG4Writer::writeCString(const char *s) {
962    size_t n = strlen(s);
963    write(s, 1, n + 1);
964}
965
966void MPEG4Writer::writeFourcc(const char *s) {
967    CHECK_EQ(strlen(s), 4);
968    write(s, 1, 4);
969}
970
971
972// Written in +/-DD.DDDD format
973void MPEG4Writer::writeLatitude(int degreex10000) {
974    bool isNegative = (degreex10000 < 0);
975    char sign = isNegative? '-': '+';
976
977    // Handle the whole part
978    char str[9];
979    int wholePart = degreex10000 / 10000;
980    if (wholePart == 0) {
981        snprintf(str, 5, "%c%.2d.", sign, wholePart);
982    } else {
983        snprintf(str, 5, "%+.2d.", wholePart);
984    }
985
986    // Handle the fractional part
987    int fractionalPart = degreex10000 - (wholePart * 10000);
988    if (fractionalPart < 0) {
989        fractionalPart = -fractionalPart;
990    }
991    snprintf(&str[4], 5, "%.4d", fractionalPart);
992
993    // Do not write the null terminator
994    write(str, 1, 8);
995}
996
997// Written in +/- DDD.DDDD format
998void MPEG4Writer::writeLongitude(int degreex10000) {
999    bool isNegative = (degreex10000 < 0);
1000    char sign = isNegative? '-': '+';
1001
1002    // Handle the whole part
1003    char str[10];
1004    int wholePart = degreex10000 / 10000;
1005    if (wholePart == 0) {
1006        snprintf(str, 6, "%c%.3d.", sign, wholePart);
1007    } else {
1008        snprintf(str, 6, "%+.3d.", wholePart);
1009    }
1010
1011    // Handle the fractional part
1012    int fractionalPart = degreex10000 - (wholePart * 10000);
1013    if (fractionalPart < 0) {
1014        fractionalPart = -fractionalPart;
1015    }
1016    snprintf(&str[5], 5, "%.4d", fractionalPart);
1017
1018    // Do not write the null terminator
1019    write(str, 1, 9);
1020}
1021
1022/*
1023 * Geodata is stored according to ISO-6709 standard.
1024 * latitudex10000 is latitude in degrees times 10000, and
1025 * longitudex10000 is longitude in degrees times 10000.
1026 * The range for the latitude is in [-90, +90], and
1027 * The range for the longitude is in [-180, +180]
1028 */
1029status_t MPEG4Writer::setGeoData(int latitudex10000, int longitudex10000) {
1030    // Is latitude or longitude out of range?
1031    if (latitudex10000 < -900000 || latitudex10000 > 900000 ||
1032        longitudex10000 < -1800000 || longitudex10000 > 1800000) {
1033        return BAD_VALUE;
1034    }
1035
1036    mLatitudex10000 = latitudex10000;
1037    mLongitudex10000 = longitudex10000;
1038    mAreGeoTagsAvailable = true;
1039    return OK;
1040}
1041
1042void MPEG4Writer::write(const void *data, size_t size) {
1043    write(data, 1, size);
1044}
1045
1046bool MPEG4Writer::isFileStreamable() const {
1047    return mStreamableFile;
1048}
1049
1050bool MPEG4Writer::exceedsFileSizeLimit() {
1051    // No limit
1052    if (mMaxFileSizeLimitBytes == 0) {
1053        return false;
1054    }
1055
1056    int64_t nTotalBytesEstimate = static_cast<int64_t>(mEstimatedMoovBoxSize);
1057    for (List<Track *>::iterator it = mTracks.begin();
1058         it != mTracks.end(); ++it) {
1059        nTotalBytesEstimate += (*it)->getEstimatedTrackSizeBytes();
1060    }
1061
1062    // Be conservative in the estimate: do not exceed 95% of
1063    // the target file limit. For small target file size limit, though,
1064    // this will not help.
1065    return (nTotalBytesEstimate >= (95 * mMaxFileSizeLimitBytes) / 100);
1066}
1067
1068bool MPEG4Writer::exceedsFileDurationLimit() {
1069    // No limit
1070    if (mMaxFileDurationLimitUs == 0) {
1071        return false;
1072    }
1073
1074    for (List<Track *>::iterator it = mTracks.begin();
1075         it != mTracks.end(); ++it) {
1076        if ((*it)->getDurationUs() >= mMaxFileDurationLimitUs) {
1077            return true;
1078        }
1079    }
1080    return false;
1081}
1082
1083bool MPEG4Writer::reachedEOS() {
1084    bool allDone = true;
1085    for (List<Track *>::iterator it = mTracks.begin();
1086         it != mTracks.end(); ++it) {
1087        if (!(*it)->reachedEOS()) {
1088            allDone = false;
1089            break;
1090        }
1091    }
1092
1093    return allDone;
1094}
1095
1096void MPEG4Writer::setStartTimestampUs(int64_t timeUs) {
1097    LOGI("setStartTimestampUs: %lld", timeUs);
1098    CHECK(timeUs >= 0);
1099    Mutex::Autolock autoLock(mLock);
1100    if (mStartTimestampUs < 0 || mStartTimestampUs > timeUs) {
1101        mStartTimestampUs = timeUs;
1102        LOGI("Earliest track starting time: %lld", mStartTimestampUs);
1103    }
1104}
1105
1106int64_t MPEG4Writer::getStartTimestampUs() {
1107    Mutex::Autolock autoLock(mLock);
1108    return mStartTimestampUs;
1109}
1110
1111size_t MPEG4Writer::numTracks() {
1112    Mutex::Autolock autolock(mLock);
1113    return mTracks.size();
1114}
1115
1116////////////////////////////////////////////////////////////////////////////////
1117
1118MPEG4Writer::Track::Track(
1119        MPEG4Writer *owner, const sp<MediaSource> &source, size_t trackId)
1120    : mOwner(owner),
1121      mMeta(source->getFormat()),
1122      mSource(source),
1123      mDone(false),
1124      mPaused(false),
1125      mResumed(false),
1126      mStarted(false),
1127      mTrackId(trackId),
1128      mTrackDurationUs(0),
1129      mEstimatedTrackSizeBytes(0),
1130      mSamplesHaveSameSize(true),
1131      mCodecSpecificData(NULL),
1132      mCodecSpecificDataSize(0),
1133      mGotAllCodecSpecificData(false),
1134      mReachedEOS(false),
1135      mRotation(0) {
1136    getCodecSpecificDataFromInputFormatIfPossible();
1137
1138    const char *mime;
1139    mMeta->findCString(kKeyMIMEType, &mime);
1140    mIsAvc = !strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_AVC);
1141    mIsAudio = !strncasecmp(mime, "audio/", 6);
1142    mIsMPEG4 = !strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_MPEG4) ||
1143               !strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_AAC);
1144
1145    setTimeScale();
1146}
1147
1148void MPEG4Writer::Track::updateTrackSizeEstimate() {
1149
1150    int64_t stcoBoxSizeBytes = mOwner->use32BitFileOffset()
1151                                ? mNumStcoTableEntries * 4
1152                                : mNumStcoTableEntries * 8;
1153
1154    int64_t stszBoxSizeBytes = mSamplesHaveSameSize? 4: (mNumSamples * 4);
1155
1156    mEstimatedTrackSizeBytes = mMdatSizeBytes;  // media data size
1157    if (!mOwner->isFileStreamable()) {
1158        // Reserved free space is not large enough to hold
1159        // all meta data and thus wasted.
1160        mEstimatedTrackSizeBytes += mNumStscTableEntries * 12 +  // stsc box size
1161                                    mNumStssTableEntries * 4 +   // stss box size
1162                                    mNumSttsTableEntries * 8 +   // stts box size
1163                                    mNumCttsTableEntries * 8 +   // ctts box size
1164                                    stcoBoxSizeBytes +           // stco box size
1165                                    stszBoxSizeBytes;            // stsz box size
1166    }
1167}
1168
1169void MPEG4Writer::Track::addOneStscTableEntry(
1170        size_t chunkId, size_t sampleId) {
1171
1172        StscTableEntry stscEntry(chunkId, sampleId, 1);
1173        mStscTableEntries.push_back(stscEntry);
1174        ++mNumStscTableEntries;
1175}
1176
1177void MPEG4Writer::Track::addOneStssTableEntry(size_t sampleId) {
1178    mStssTableEntries.push_back(sampleId);
1179    ++mNumStssTableEntries;
1180}
1181
1182void MPEG4Writer::Track::addOneSttsTableEntry(
1183        size_t sampleCount, int32_t duration) {
1184
1185    SttsTableEntry sttsEntry(sampleCount, duration);
1186    mSttsTableEntries.push_back(sttsEntry);
1187    ++mNumSttsTableEntries;
1188}
1189
1190void MPEG4Writer::Track::addOneCttsTableEntry(
1191        size_t sampleCount, int32_t duration) {
1192
1193    if (mIsAudio) {
1194        return;
1195    }
1196    if (duration < 0 && !mHasNegativeCttsDeltaDuration) {
1197        mHasNegativeCttsDeltaDuration = true;
1198    }
1199    CttsTableEntry cttsEntry(sampleCount, duration);
1200    mCttsTableEntries.push_back(cttsEntry);
1201    ++mNumCttsTableEntries;
1202}
1203
1204void MPEG4Writer::Track::addChunkOffset(off64_t offset) {
1205    ++mNumStcoTableEntries;
1206    mChunkOffsets.push_back(offset);
1207}
1208
1209void MPEG4Writer::Track::setTimeScale() {
1210    LOGV("setTimeScale");
1211    // Default time scale
1212    mTimeScale = 90000;
1213
1214    if (mIsAudio) {
1215        // Use the sampling rate as the default time scale for audio track.
1216        int32_t sampleRate;
1217        bool success = mMeta->findInt32(kKeySampleRate, &sampleRate);
1218        CHECK(success);
1219        mTimeScale = sampleRate;
1220    }
1221
1222    // If someone would like to overwrite the timescale, use user-supplied value.
1223    int32_t timeScale;
1224    if (mMeta->findInt32(kKeyTimeScale, &timeScale)) {
1225        mTimeScale = timeScale;
1226    }
1227
1228    CHECK(mTimeScale > 0);
1229}
1230
1231void MPEG4Writer::Track::getCodecSpecificDataFromInputFormatIfPossible() {
1232    const char *mime;
1233    CHECK(mMeta->findCString(kKeyMIMEType, &mime));
1234
1235    if (!strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_AVC)) {
1236        uint32_t type;
1237        const void *data;
1238        size_t size;
1239        if (mMeta->findData(kKeyAVCC, &type, &data, &size)) {
1240            mCodecSpecificData = malloc(size);
1241            mCodecSpecificDataSize = size;
1242            memcpy(mCodecSpecificData, data, size);
1243            mGotAllCodecSpecificData = true;
1244        }
1245    } else if (!strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_MPEG4)
1246            || !strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_AAC)) {
1247        uint32_t type;
1248        const void *data;
1249        size_t size;
1250        if (mMeta->findData(kKeyESDS, &type, &data, &size)) {
1251            ESDS esds(data, size);
1252            if (esds.getCodecSpecificInfo(&data, &size) == OK) {
1253                mCodecSpecificData = malloc(size);
1254                mCodecSpecificDataSize = size;
1255                memcpy(mCodecSpecificData, data, size);
1256                mGotAllCodecSpecificData = true;
1257            }
1258        }
1259    }
1260}
1261
1262MPEG4Writer::Track::~Track() {
1263    stop();
1264
1265    if (mCodecSpecificData != NULL) {
1266        free(mCodecSpecificData);
1267        mCodecSpecificData = NULL;
1268    }
1269}
1270
1271void MPEG4Writer::Track::initTrackingProgressStatus(MetaData *params) {
1272    LOGV("initTrackingProgressStatus");
1273    mPreviousTrackTimeUs = -1;
1274    mTrackingProgressStatus = false;
1275    mTrackEveryTimeDurationUs = 0;
1276    {
1277        int64_t timeUs;
1278        if (params && params->findInt64(kKeyTrackTimeStatus, &timeUs)) {
1279            LOGV("Receive request to track progress status for every %lld us", timeUs);
1280            mTrackEveryTimeDurationUs = timeUs;
1281            mTrackingProgressStatus = true;
1282        }
1283    }
1284}
1285
1286// static
1287void *MPEG4Writer::ThreadWrapper(void *me) {
1288    LOGV("ThreadWrapper: %p", me);
1289    MPEG4Writer *writer = static_cast<MPEG4Writer *>(me);
1290    writer->threadFunc();
1291    return NULL;
1292}
1293
1294void MPEG4Writer::bufferChunk(const Chunk& chunk) {
1295    LOGV("bufferChunk: %p", chunk.mTrack);
1296    Mutex::Autolock autolock(mLock);
1297    CHECK_EQ(mDone, false);
1298
1299    for (List<ChunkInfo>::iterator it = mChunkInfos.begin();
1300         it != mChunkInfos.end(); ++it) {
1301
1302        if (chunk.mTrack == it->mTrack) {  // Found owner
1303            it->mChunks.push_back(chunk);
1304            mChunkReadyCondition.signal();
1305            return;
1306        }
1307    }
1308
1309    CHECK("Received a chunk for a unknown track" == 0);
1310}
1311
1312void MPEG4Writer::writeChunkToFile(Chunk* chunk) {
1313    LOGV("writeChunkToFile: %lld from %s track",
1314        chunk.mTimestampUs, chunk.mTrack->isAudio()? "audio": "video");
1315
1316    int32_t isFirstSample = true;
1317    while (!chunk->mSamples.empty()) {
1318        List<MediaBuffer *>::iterator it = chunk->mSamples.begin();
1319
1320        off64_t offset = chunk->mTrack->isAvc()
1321                                ? addLengthPrefixedSample_l(*it)
1322                                : addSample_l(*it);
1323
1324        if (isFirstSample) {
1325            chunk->mTrack->addChunkOffset(offset);
1326            isFirstSample = false;
1327        }
1328
1329        (*it)->release();
1330        (*it) = NULL;
1331        chunk->mSamples.erase(it);
1332    }
1333    chunk->mSamples.clear();
1334}
1335
1336void MPEG4Writer::writeAllChunks() {
1337    LOGV("writeAllChunks");
1338    size_t outstandingChunks = 0;
1339    Chunk chunk;
1340    while (findChunkToWrite(&chunk)) {
1341        writeChunkToFile(&chunk);
1342        ++outstandingChunks;
1343    }
1344
1345    sendSessionSummary();
1346
1347    mChunkInfos.clear();
1348    LOGD("%d chunks are written in the last batch", outstandingChunks);
1349}
1350
1351bool MPEG4Writer::findChunkToWrite(Chunk *chunk) {
1352    LOGV("findChunkToWrite");
1353
1354    int64_t minTimestampUs = 0x7FFFFFFFFFFFFFFFLL;
1355    Track *track = NULL;
1356    for (List<ChunkInfo>::iterator it = mChunkInfos.begin();
1357         it != mChunkInfos.end(); ++it) {
1358        if (!it->mChunks.empty()) {
1359            List<Chunk>::iterator chunkIt = it->mChunks.begin();
1360            if (chunkIt->mTimeStampUs < minTimestampUs) {
1361                minTimestampUs = chunkIt->mTimeStampUs;
1362                track = it->mTrack;
1363            }
1364        }
1365    }
1366
1367    if (track == NULL) {
1368        LOGV("Nothing to be written after all");
1369        return false;
1370    }
1371
1372    if (mIsFirstChunk) {
1373        mIsFirstChunk = false;
1374    }
1375
1376    for (List<ChunkInfo>::iterator it = mChunkInfos.begin();
1377         it != mChunkInfos.end(); ++it) {
1378        if (it->mTrack == track) {
1379            *chunk = *(it->mChunks.begin());
1380            it->mChunks.erase(it->mChunks.begin());
1381            CHECK_EQ(chunk->mTrack, track);
1382
1383            int64_t interChunkTimeUs =
1384                chunk->mTimeStampUs - it->mPrevChunkTimestampUs;
1385            if (interChunkTimeUs > it->mPrevChunkTimestampUs) {
1386                it->mMaxInterChunkDurUs = interChunkTimeUs;
1387            }
1388
1389            return true;
1390        }
1391    }
1392
1393    return false;
1394}
1395
1396void MPEG4Writer::threadFunc() {
1397    LOGV("threadFunc");
1398
1399    prctl(PR_SET_NAME, (unsigned long)"MPEG4Writer", 0, 0, 0);
1400
1401    Mutex::Autolock autoLock(mLock);
1402    while (!mDone) {
1403        Chunk chunk;
1404        bool chunkFound = false;
1405
1406        while (!mDone && !(chunkFound = findChunkToWrite(&chunk))) {
1407            mChunkReadyCondition.wait(mLock);
1408        }
1409
1410        // Actual write without holding the lock in order to
1411        // reduce the blocking time for media track threads.
1412        if (chunkFound) {
1413            mLock.unlock();
1414            writeChunkToFile(&chunk);
1415            mLock.lock();
1416        }
1417    }
1418
1419    writeAllChunks();
1420}
1421
1422status_t MPEG4Writer::startWriterThread() {
1423    LOGV("startWriterThread");
1424
1425    mDone = false;
1426    mIsFirstChunk = true;
1427    mDriftTimeUs = 0;
1428    for (List<Track *>::iterator it = mTracks.begin();
1429         it != mTracks.end(); ++it) {
1430        ChunkInfo info;
1431        info.mTrack = *it;
1432        info.mPrevChunkTimestampUs = 0;
1433        info.mMaxInterChunkDurUs = 0;
1434        mChunkInfos.push_back(info);
1435    }
1436
1437    pthread_attr_t attr;
1438    pthread_attr_init(&attr);
1439    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1440    pthread_create(&mThread, &attr, ThreadWrapper, this);
1441    pthread_attr_destroy(&attr);
1442    return OK;
1443}
1444
1445
1446status_t MPEG4Writer::Track::start(MetaData *params) {
1447    if (!mDone && mPaused) {
1448        mPaused = false;
1449        mResumed = true;
1450        return OK;
1451    }
1452
1453    int64_t startTimeUs;
1454    if (params == NULL || !params->findInt64(kKeyTime, &startTimeUs)) {
1455        startTimeUs = 0;
1456    }
1457    mStartTimeRealUs = startTimeUs;
1458
1459    int32_t rotationDegrees;
1460    if (!mIsAudio && params && params->findInt32(kKeyRotation, &rotationDegrees)) {
1461        mRotation = rotationDegrees;
1462    }
1463
1464    mIsRealTimeRecording = true;
1465    {
1466        int32_t isNotRealTime;
1467        if (params && params->findInt32(kKeyNotRealTime, &isNotRealTime)) {
1468            mIsRealTimeRecording = (isNotRealTime == 0);
1469        }
1470    }
1471
1472    initTrackingProgressStatus(params);
1473
1474    sp<MetaData> meta = new MetaData;
1475    if (mIsRealTimeRecording && mOwner->numTracks() > 1) {
1476        /*
1477         * This extra delay of accepting incoming audio/video signals
1478         * helps to align a/v start time at the beginning of a recording
1479         * session, and it also helps eliminate the "recording" sound for
1480         * camcorder applications.
1481         *
1482         * If client does not set the start time offset, we fall back to
1483         * use the default initial delay value.
1484         */
1485        int64_t startTimeOffsetUs = mOwner->getStartTimeOffsetMs() * 1000LL;
1486        if (startTimeOffsetUs < 0) {  // Start time offset was not set
1487            startTimeOffsetUs = kInitialDelayTimeUs;
1488        }
1489        startTimeUs += startTimeOffsetUs;
1490        LOGI("Start time offset: %lld us", startTimeOffsetUs);
1491    }
1492
1493    meta->setInt64(kKeyTime, startTimeUs);
1494
1495    status_t err = mSource->start(meta.get());
1496    if (err != OK) {
1497        mDone = mReachedEOS = true;
1498        return err;
1499    }
1500
1501    pthread_attr_t attr;
1502    pthread_attr_init(&attr);
1503    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1504
1505    mDone = false;
1506    mStarted = true;
1507    mTrackDurationUs = 0;
1508    mReachedEOS = false;
1509    mEstimatedTrackSizeBytes = 0;
1510    mNumStcoTableEntries = 0;
1511    mNumStssTableEntries = 0;
1512    mNumStscTableEntries = 0;
1513    mNumSttsTableEntries = 0;
1514    mNumCttsTableEntries = 0;
1515    mMdatSizeBytes = 0;
1516    mIsMediaTimeAdjustmentOn = false;
1517    mPrevMediaTimeAdjustTimestampUs = 0;
1518    mMediaTimeAdjustNumFrames = 0;
1519    mPrevMediaTimeAdjustSample = 0;
1520    mTotalDriftTimeToAdjustUs = 0;
1521    mPrevTotalAccumDriftTimeUs = 0;
1522    mMaxChunkDurationUs = 0;
1523    mHasNegativeCttsDeltaDuration = false;
1524
1525    pthread_create(&mThread, &attr, ThreadWrapper, this);
1526    pthread_attr_destroy(&attr);
1527
1528    return OK;
1529}
1530
1531status_t MPEG4Writer::Track::pause() {
1532    mPaused = true;
1533    return OK;
1534}
1535
1536status_t MPEG4Writer::Track::stop() {
1537    LOGD("Stopping %s track", mIsAudio? "Audio": "Video");
1538    if (!mStarted) {
1539        LOGE("Stop() called but track is not started");
1540        return ERROR_END_OF_STREAM;
1541    }
1542
1543    if (mDone) {
1544        return OK;
1545    }
1546    mDone = true;
1547
1548    void *dummy;
1549    pthread_join(mThread, &dummy);
1550
1551    status_t err = (status_t) dummy;
1552
1553    LOGD("Stopping %s track source", mIsAudio? "Audio": "Video");
1554    {
1555        status_t status = mSource->stop();
1556        if (err == OK && status != OK && status != ERROR_END_OF_STREAM) {
1557            err = status;
1558        }
1559    }
1560
1561    LOGD("%s track stopped", mIsAudio? "Audio": "Video");
1562    return err;
1563}
1564
1565bool MPEG4Writer::Track::reachedEOS() {
1566    return mReachedEOS;
1567}
1568
1569// static
1570void *MPEG4Writer::Track::ThreadWrapper(void *me) {
1571    Track *track = static_cast<Track *>(me);
1572
1573    status_t err = track->threadEntry();
1574    return (void *) err;
1575}
1576
1577static void getNalUnitType(uint8_t byte, uint8_t* type) {
1578    LOGV("getNalUnitType: %d", byte);
1579
1580    // nal_unit_type: 5-bit unsigned integer
1581    *type = (byte & 0x1F);
1582}
1583
1584static const uint8_t *findNextStartCode(
1585        const uint8_t *data, size_t length) {
1586
1587    LOGV("findNextStartCode: %p %d", data, length);
1588
1589    size_t bytesLeft = length;
1590    while (bytesLeft > 4  &&
1591            memcmp("\x00\x00\x00\x01", &data[length - bytesLeft], 4)) {
1592        --bytesLeft;
1593    }
1594    if (bytesLeft <= 4) {
1595        bytesLeft = 0; // Last parameter set
1596    }
1597    return &data[length - bytesLeft];
1598}
1599
1600const uint8_t *MPEG4Writer::Track::parseParamSet(
1601        const uint8_t *data, size_t length, int type, size_t *paramSetLen) {
1602
1603    LOGV("parseParamSet");
1604    CHECK(type == kNalUnitTypeSeqParamSet ||
1605          type == kNalUnitTypePicParamSet);
1606
1607    const uint8_t *nextStartCode = findNextStartCode(data, length);
1608    *paramSetLen = nextStartCode - data;
1609    if (*paramSetLen == 0) {
1610        LOGE("Param set is malformed, since its length is 0");
1611        return NULL;
1612    }
1613
1614    AVCParamSet paramSet(*paramSetLen, data);
1615    if (type == kNalUnitTypeSeqParamSet) {
1616        if (*paramSetLen < 4) {
1617            LOGE("Seq parameter set malformed");
1618            return NULL;
1619        }
1620        if (mSeqParamSets.empty()) {
1621            mProfileIdc = data[1];
1622            mProfileCompatible = data[2];
1623            mLevelIdc = data[3];
1624        } else {
1625            if (mProfileIdc != data[1] ||
1626                mProfileCompatible != data[2] ||
1627                mLevelIdc != data[3]) {
1628                LOGE("Inconsistent profile/level found in seq parameter sets");
1629                return NULL;
1630            }
1631        }
1632        mSeqParamSets.push_back(paramSet);
1633    } else {
1634        mPicParamSets.push_back(paramSet);
1635    }
1636    return nextStartCode;
1637}
1638
1639status_t MPEG4Writer::Track::copyAVCCodecSpecificData(
1640        const uint8_t *data, size_t size) {
1641    LOGV("copyAVCCodecSpecificData");
1642
1643    // 2 bytes for each of the parameter set length field
1644    // plus the 7 bytes for the header
1645    if (size < 4 + 7) {
1646        LOGE("Codec specific data length too short: %d", size);
1647        return ERROR_MALFORMED;
1648    }
1649
1650    mCodecSpecificDataSize = size;
1651    mCodecSpecificData = malloc(size);
1652    memcpy(mCodecSpecificData, data, size);
1653    return OK;
1654}
1655
1656status_t MPEG4Writer::Track::parseAVCCodecSpecificData(
1657        const uint8_t *data, size_t size) {
1658
1659    LOGV("parseAVCCodecSpecificData");
1660    // Data starts with a start code.
1661    // SPS and PPS are separated with start codes.
1662    // Also, SPS must come before PPS
1663    uint8_t type = kNalUnitTypeSeqParamSet;
1664    bool gotSps = false;
1665    bool gotPps = false;
1666    const uint8_t *tmp = data;
1667    const uint8_t *nextStartCode = data;
1668    size_t bytesLeft = size;
1669    size_t paramSetLen = 0;
1670    mCodecSpecificDataSize = 0;
1671    while (bytesLeft > 4 && !memcmp("\x00\x00\x00\x01", tmp, 4)) {
1672        getNalUnitType(*(tmp + 4), &type);
1673        if (type == kNalUnitTypeSeqParamSet) {
1674            if (gotPps) {
1675                LOGE("SPS must come before PPS");
1676                return ERROR_MALFORMED;
1677            }
1678            if (!gotSps) {
1679                gotSps = true;
1680            }
1681            nextStartCode = parseParamSet(tmp + 4, bytesLeft - 4, type, &paramSetLen);
1682        } else if (type == kNalUnitTypePicParamSet) {
1683            if (!gotSps) {
1684                LOGE("SPS must come before PPS");
1685                return ERROR_MALFORMED;
1686            }
1687            if (!gotPps) {
1688                gotPps = true;
1689            }
1690            nextStartCode = parseParamSet(tmp + 4, bytesLeft - 4, type, &paramSetLen);
1691        } else {
1692            LOGE("Only SPS and PPS Nal units are expected");
1693            return ERROR_MALFORMED;
1694        }
1695
1696        if (nextStartCode == NULL) {
1697            return ERROR_MALFORMED;
1698        }
1699
1700        // Move on to find the next parameter set
1701        bytesLeft -= nextStartCode - tmp;
1702        tmp = nextStartCode;
1703        mCodecSpecificDataSize += (2 + paramSetLen);
1704    }
1705
1706    {
1707        // Check on the number of seq parameter sets
1708        size_t nSeqParamSets = mSeqParamSets.size();
1709        if (nSeqParamSets == 0) {
1710            LOGE("Cound not find sequence parameter set");
1711            return ERROR_MALFORMED;
1712        }
1713
1714        if (nSeqParamSets > 0x1F) {
1715            LOGE("Too many seq parameter sets (%d) found", nSeqParamSets);
1716            return ERROR_MALFORMED;
1717        }
1718    }
1719
1720    {
1721        // Check on the number of pic parameter sets
1722        size_t nPicParamSets = mPicParamSets.size();
1723        if (nPicParamSets == 0) {
1724            LOGE("Cound not find picture parameter set");
1725            return ERROR_MALFORMED;
1726        }
1727        if (nPicParamSets > 0xFF) {
1728            LOGE("Too many pic parameter sets (%d) found", nPicParamSets);
1729            return ERROR_MALFORMED;
1730        }
1731    }
1732
1733    {
1734        // Check on the profiles
1735        // These profiles requires additional parameter set extensions
1736        if (mProfileIdc == 100 || mProfileIdc == 110 ||
1737            mProfileIdc == 122 || mProfileIdc == 144) {
1738            LOGE("Sorry, no support for profile_idc: %d!", mProfileIdc);
1739            return BAD_VALUE;
1740        }
1741    }
1742
1743    return OK;
1744}
1745
1746status_t MPEG4Writer::Track::makeAVCCodecSpecificData(
1747        const uint8_t *data, size_t size) {
1748
1749    if (mCodecSpecificData != NULL) {
1750        LOGE("Already have codec specific data");
1751        return ERROR_MALFORMED;
1752    }
1753
1754    if (size < 4) {
1755        LOGE("Codec specific data length too short: %d", size);
1756        return ERROR_MALFORMED;
1757    }
1758
1759    // Data is in the form of AVCCodecSpecificData
1760    if (memcmp("\x00\x00\x00\x01", data, 4)) {
1761        return copyAVCCodecSpecificData(data, size);
1762    }
1763
1764    if (parseAVCCodecSpecificData(data, size) != OK) {
1765        return ERROR_MALFORMED;
1766    }
1767
1768    // ISO 14496-15: AVC file format
1769    mCodecSpecificDataSize += 7;  // 7 more bytes in the header
1770    mCodecSpecificData = malloc(mCodecSpecificDataSize);
1771    uint8_t *header = (uint8_t *)mCodecSpecificData;
1772    header[0] = 1;                     // version
1773    header[1] = mProfileIdc;           // profile indication
1774    header[2] = mProfileCompatible;    // profile compatibility
1775    header[3] = mLevelIdc;
1776
1777    // 6-bit '111111' followed by 2-bit to lengthSizeMinuusOne
1778    if (mOwner->useNalLengthFour()) {
1779        header[4] = 0xfc | 3;  // length size == 4 bytes
1780    } else {
1781        header[4] = 0xfc | 1;  // length size == 2 bytes
1782    }
1783
1784    // 3-bit '111' followed by 5-bit numSequenceParameterSets
1785    int nSequenceParamSets = mSeqParamSets.size();
1786    header[5] = 0xe0 | nSequenceParamSets;
1787    header += 6;
1788    for (List<AVCParamSet>::iterator it = mSeqParamSets.begin();
1789         it != mSeqParamSets.end(); ++it) {
1790        // 16-bit sequence parameter set length
1791        uint16_t seqParamSetLength = it->mLength;
1792        header[0] = seqParamSetLength >> 8;
1793        header[1] = seqParamSetLength & 0xff;
1794
1795        // SPS NAL unit (sequence parameter length bytes)
1796        memcpy(&header[2], it->mData, seqParamSetLength);
1797        header += (2 + seqParamSetLength);
1798    }
1799
1800    // 8-bit nPictureParameterSets
1801    int nPictureParamSets = mPicParamSets.size();
1802    header[0] = nPictureParamSets;
1803    header += 1;
1804    for (List<AVCParamSet>::iterator it = mPicParamSets.begin();
1805         it != mPicParamSets.end(); ++it) {
1806        // 16-bit picture parameter set length
1807        uint16_t picParamSetLength = it->mLength;
1808        header[0] = picParamSetLength >> 8;
1809        header[1] = picParamSetLength & 0xff;
1810
1811        // PPS Nal unit (picture parameter set length bytes)
1812        memcpy(&header[2], it->mData, picParamSetLength);
1813        header += (2 + picParamSetLength);
1814    }
1815
1816    return OK;
1817}
1818
1819/*
1820* The video track's media time adjustment for real-time applications
1821* is described as follows:
1822*
1823* First, the media time adjustment is done for every period of
1824* kVideoMediaTimeAdjustPeriodTimeUs. kVideoMediaTimeAdjustPeriodTimeUs
1825* is currently a fixed value chosen heuristically. The value of
1826* kVideoMediaTimeAdjustPeriodTimeUs should not be very large or very small
1827* for two considerations: on one hand, a relatively large value
1828* helps reduce large fluctuation of drift time in the audio encoding
1829* path; while on the other hand, a relatively small value helps keep
1830* restoring synchronization in audio/video more frequently. Note for the
1831* very first period of kVideoMediaTimeAdjustPeriodTimeUs, there is
1832* no media time adjustment for the video track.
1833*
1834* Second, the total accumulated audio track time drift found
1835* in a period of kVideoMediaTimeAdjustPeriodTimeUs is distributed
1836* over a stream of incoming video frames. The number of video frames
1837* affected is determined based on the number of recorded video frames
1838* within the past kVideoMediaTimeAdjustPeriodTimeUs period.
1839* We choose to distribute the drift time over only a portion
1840* (rather than all) of the total number of recorded video frames
1841* in order to make sure that the video track media time adjustment is
1842* completed for the current period before the next video track media
1843* time adjustment period starts. Currently, the portion chosen is a
1844* half (0.5).
1845*
1846* Last, various additional checks are performed to ensure that
1847* the actual audio encoding path does not have too much drift.
1848* In particular, 1) we want to limit the average incremental time
1849* adjustment for each video frame to be less than a threshold
1850* for a single period of kVideoMediaTimeAdjustPeriodTimeUs.
1851* Currently, the threshold is set to 5 ms. If the average incremental
1852* media time adjustment for a video frame is larger than the
1853* threshold, the audio encoding path has too much time drift.
1854* 2) We also want to limit the total time drift in the audio
1855* encoding path to be less than a threshold for a period of
1856* kVideoMediaTimeAdjustPeriodTimeUs. Currently, the threshold
1857* is 0.5% of kVideoMediaTimeAdjustPeriodTimeUs. If the time drift of
1858* the audio encoding path is larger than the threshold, the audio
1859* encoding path has too much time drift. We treat the large time
1860* drift of the audio encoding path as errors, since there is no
1861* way to keep audio/video in synchronization for real-time
1862* applications if the time drift is too large unless we drop some
1863* video frames, which has its own problems that we don't want
1864* to get into for the time being.
1865*/
1866void MPEG4Writer::Track::adjustMediaTime(int64_t *timestampUs) {
1867    if (*timestampUs - mPrevMediaTimeAdjustTimestampUs >=
1868        kVideoMediaTimeAdjustPeriodTimeUs) {
1869
1870        LOGV("New media time adjustment period at %lld us", *timestampUs);
1871        mIsMediaTimeAdjustmentOn = true;
1872        mMediaTimeAdjustNumFrames =
1873                (mNumSamples - mPrevMediaTimeAdjustSample) >> 1;
1874
1875        mPrevMediaTimeAdjustTimestampUs = *timestampUs;
1876        mPrevMediaTimeAdjustSample = mNumSamples;
1877        int64_t totalAccumDriftTimeUs = mOwner->getDriftTimeUs();
1878        mTotalDriftTimeToAdjustUs =
1879                totalAccumDriftTimeUs - mPrevTotalAccumDriftTimeUs;
1880
1881        mPrevTotalAccumDriftTimeUs = totalAccumDriftTimeUs;
1882
1883        // Check on incremental adjusted time per frame
1884        int64_t adjustTimePerFrameUs =
1885                mTotalDriftTimeToAdjustUs / mMediaTimeAdjustNumFrames;
1886
1887        if (adjustTimePerFrameUs < 0) {
1888            adjustTimePerFrameUs = -adjustTimePerFrameUs;
1889        }
1890        if (adjustTimePerFrameUs >= 5000) {
1891            LOGE("Adjusted time per video frame is %lld us",
1892                adjustTimePerFrameUs);
1893            CHECK(!"Video frame time adjustment is too large!");
1894        }
1895
1896        // Check on total accumulated time drift within a period of
1897        // kVideoMediaTimeAdjustPeriodTimeUs.
1898        int64_t driftPercentage = (mTotalDriftTimeToAdjustUs * 1000)
1899                / kVideoMediaTimeAdjustPeriodTimeUs;
1900
1901        if (driftPercentage < 0) {
1902            driftPercentage = -driftPercentage;
1903        }
1904        if (driftPercentage > 5) {
1905            LOGE("Audio track has time drift %lld us over %lld us",
1906                mTotalDriftTimeToAdjustUs,
1907                kVideoMediaTimeAdjustPeriodTimeUs);
1908
1909            CHECK(!"The audio track media time drifts too much!");
1910        }
1911
1912    }
1913
1914    if (mIsMediaTimeAdjustmentOn) {
1915        if (mNumSamples - mPrevMediaTimeAdjustSample <=
1916            mMediaTimeAdjustNumFrames) {
1917
1918            // Do media time incremental adjustment
1919            int64_t incrementalAdjustTimeUs =
1920                        (mTotalDriftTimeToAdjustUs *
1921                            (mNumSamples - mPrevMediaTimeAdjustSample))
1922                                / mMediaTimeAdjustNumFrames;
1923
1924            *timestampUs +=
1925                (incrementalAdjustTimeUs + mPrevTotalAccumDriftTimeUs);
1926
1927            LOGV("Incremental video frame media time adjustment: %lld us",
1928                (incrementalAdjustTimeUs + mPrevTotalAccumDriftTimeUs));
1929        } else {
1930            // Within the remaining adjustment period,
1931            // no incremental adjustment is needed.
1932            *timestampUs +=
1933                (mTotalDriftTimeToAdjustUs + mPrevTotalAccumDriftTimeUs);
1934
1935            LOGV("Fixed video frame media time adjustment: %lld us",
1936                (mTotalDriftTimeToAdjustUs + mPrevTotalAccumDriftTimeUs));
1937        }
1938    }
1939}
1940
1941/*
1942 * Updates the drift time from the audio track so that
1943 * the video track can get the updated drift time information
1944 * from the file writer. The fluctuation of the drift time of the audio
1945 * encoding path is smoothed out with a simple filter by giving a larger
1946 * weight to more recently drift time. The filter coefficients, 0.5 and 0.5,
1947 * are heuristically determined.
1948 */
1949void MPEG4Writer::Track::updateDriftTime(const sp<MetaData>& meta) {
1950    int64_t driftTimeUs = 0;
1951    if (meta->findInt64(kKeyDriftTime, &driftTimeUs)) {
1952        int64_t prevDriftTimeUs = mOwner->getDriftTimeUs();
1953        int64_t timeUs = (driftTimeUs + prevDriftTimeUs) >> 1;
1954        mOwner->setDriftTimeUs(timeUs);
1955    }
1956}
1957
1958status_t MPEG4Writer::Track::threadEntry() {
1959    int32_t count = 0;
1960    const int64_t interleaveDurationUs = mOwner->interleaveDuration();
1961    const bool hasMultipleTracks = (mOwner->numTracks() > 1);
1962    int64_t chunkTimestampUs = 0;
1963    int32_t nChunks = 0;
1964    int32_t nZeroLengthFrames = 0;
1965    int64_t lastTimestampUs = 0;      // Previous sample time stamp
1966    int64_t lastCttsTimeUs = 0;       // Previous sample time stamp
1967    int64_t lastDurationUs = 0;       // Between the previous two samples
1968    int64_t currDurationTicks = 0;    // Timescale based ticks
1969    int64_t lastDurationTicks = 0;    // Timescale based ticks
1970    int32_t sampleCount = 1;          // Sample count in the current stts table entry
1971    int64_t currCttsDurTicks = 0;     // Timescale based ticks
1972    int64_t lastCttsDurTicks = 0;     // Timescale based ticks
1973    int32_t cttsSampleCount = 1;      // Sample count in the current ctts table entry
1974    uint32_t previousSampleSize = 0;      // Size of the previous sample
1975    int64_t previousPausedDurationUs = 0;
1976    int64_t timestampUs = 0;
1977    int64_t cttsDeltaTimeUs = 0;
1978
1979    if (mIsAudio) {
1980        prctl(PR_SET_NAME, (unsigned long)"AudioTrackEncoding", 0, 0, 0);
1981    } else {
1982        prctl(PR_SET_NAME, (unsigned long)"VideoTrackEncoding", 0, 0, 0);
1983    }
1984    androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
1985
1986    sp<MetaData> meta_data;
1987
1988    mNumSamples = 0;
1989    status_t err = OK;
1990    MediaBuffer *buffer;
1991    while (!mDone && (err = mSource->read(&buffer)) == OK) {
1992        if (buffer->range_length() == 0) {
1993            buffer->release();
1994            buffer = NULL;
1995            ++nZeroLengthFrames;
1996            continue;
1997        }
1998
1999        // If the codec specific data has not been received yet, delay pause.
2000        // After the codec specific data is received, discard what we received
2001        // when the track is to be paused.
2002        if (mPaused && !mResumed) {
2003            buffer->release();
2004            buffer = NULL;
2005            continue;
2006        }
2007
2008        ++count;
2009
2010        int32_t isCodecConfig;
2011        if (buffer->meta_data()->findInt32(kKeyIsCodecConfig, &isCodecConfig)
2012                && isCodecConfig) {
2013            CHECK(!mGotAllCodecSpecificData);
2014
2015            if (mIsAvc) {
2016                status_t err = makeAVCCodecSpecificData(
2017                        (const uint8_t *)buffer->data()
2018                            + buffer->range_offset(),
2019                        buffer->range_length());
2020                CHECK_EQ(OK, err);
2021            } else if (mIsMPEG4) {
2022                mCodecSpecificDataSize = buffer->range_length();
2023                mCodecSpecificData = malloc(mCodecSpecificDataSize);
2024                memcpy(mCodecSpecificData,
2025                        (const uint8_t *)buffer->data()
2026                            + buffer->range_offset(),
2027                       buffer->range_length());
2028            }
2029
2030            buffer->release();
2031            buffer = NULL;
2032
2033            mGotAllCodecSpecificData = true;
2034            continue;
2035        }
2036
2037        // Make a deep copy of the MediaBuffer and Metadata and release
2038        // the original as soon as we can
2039        MediaBuffer *copy = new MediaBuffer(buffer->range_length());
2040        memcpy(copy->data(), (uint8_t *)buffer->data() + buffer->range_offset(),
2041                buffer->range_length());
2042        copy->set_range(0, buffer->range_length());
2043        meta_data = new MetaData(*buffer->meta_data().get());
2044        buffer->release();
2045        buffer = NULL;
2046
2047        if (mIsAvc) StripStartcode(copy);
2048
2049        size_t sampleSize = copy->range_length();
2050        if (mIsAvc) {
2051            if (mOwner->useNalLengthFour()) {
2052                sampleSize += 4;
2053            } else {
2054                sampleSize += 2;
2055            }
2056        }
2057
2058        // Max file size or duration handling
2059        mMdatSizeBytes += sampleSize;
2060        updateTrackSizeEstimate();
2061
2062        if (mOwner->exceedsFileSizeLimit()) {
2063            mOwner->notify(MEDIA_RECORDER_EVENT_INFO, MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED, 0);
2064            break;
2065        }
2066        if (mOwner->exceedsFileDurationLimit()) {
2067            mOwner->notify(MEDIA_RECORDER_EVENT_INFO, MEDIA_RECORDER_INFO_MAX_DURATION_REACHED, 0);
2068            break;
2069        }
2070
2071
2072        int32_t isSync = false;
2073        meta_data->findInt32(kKeyIsSyncFrame, &isSync);
2074
2075        /*
2076         * The original timestamp found in the data buffer will be modified as below:
2077         *
2078         * There is a playback offset into this track if the track's start time
2079         * is not the same as the movie start time, which will be recorded in edst
2080         * box of the output file. The playback offset is to make sure that the
2081         * starting time of the audio/video tracks are synchronized. Although the
2082         * track's media timestamp may be subject to various modifications
2083         * as outlined below, the track's playback offset time remains unchanged
2084         * once the first data buffer of the track is received.
2085         *
2086         * The media time stamp will be calculated by subtracting the playback offset
2087         * (and potential pause durations) from the original timestamp in the buffer.
2088         *
2089         * If this track is a video track for a real-time recording application with
2090         * both audio and video tracks, its media timestamp will subject to further
2091         * modification based on the media clock of the audio track. This modification
2092         * is needed for the purpose of maintaining good audio/video synchronization.
2093         *
2094         * If the recording session is paused and resumed multiple times, the track
2095         * media timestamp will be modified as if the  recording session had never been
2096         * paused at all during playback of the recorded output file. In other words,
2097         * the output file will have no memory of pause/resume durations.
2098         *
2099         */
2100        CHECK(meta_data->findInt64(kKeyTime, &timestampUs));
2101
2102////////////////////////////////////////////////////////////////////////////////
2103        if (mNumSamples == 0) {
2104            mFirstSampleTimeRealUs = systemTime() / 1000;
2105            mStartTimestampUs = timestampUs;
2106            mOwner->setStartTimestampUs(mStartTimestampUs);
2107            previousPausedDurationUs = mStartTimestampUs;
2108        }
2109
2110        if (mResumed) {
2111            int64_t durExcludingEarlierPausesUs = timestampUs - previousPausedDurationUs;
2112            CHECK(durExcludingEarlierPausesUs >= 0);
2113            int64_t pausedDurationUs = durExcludingEarlierPausesUs - mTrackDurationUs;
2114            CHECK(pausedDurationUs >= lastDurationUs);
2115            previousPausedDurationUs += pausedDurationUs - lastDurationUs;
2116            mResumed = false;
2117        }
2118
2119        timestampUs -= previousPausedDurationUs;
2120        CHECK(timestampUs >= 0);
2121        if (!mIsAudio) {
2122            /*
2123             * Composition time: timestampUs
2124             * Decoding time: decodingTimeUs
2125             * Composition time delta = composition time - decoding time
2126             *
2127             * We save picture decoding time stamp delta in stts table entries,
2128             * and composition time delta duration in ctts table entries.
2129             */
2130            int64_t decodingTimeUs;
2131            CHECK(meta_data->findInt64(kKeyDecodingTime, &decodingTimeUs));
2132            decodingTimeUs -= previousPausedDurationUs;
2133            int64_t timeUs = decodingTimeUs;
2134            cttsDeltaTimeUs = timestampUs - decodingTimeUs;
2135            timestampUs = decodingTimeUs;
2136            LOGV("decoding time: %lld and ctts delta time: %lld",
2137                timestampUs, cttsDeltaTimeUs);
2138        }
2139
2140        // Media time adjustment for real-time applications
2141        if (mIsRealTimeRecording) {
2142            if (mIsAudio) {
2143                updateDriftTime(meta_data);
2144            } else {
2145                adjustMediaTime(&timestampUs);
2146            }
2147        }
2148
2149        CHECK(timestampUs >= 0);
2150        if (mNumSamples > 1) {
2151            if (timestampUs <= lastTimestampUs) {
2152                LOGW("Frame arrives too late!");
2153                // Don't drop the late frame, since dropping a frame may cause
2154                // problems later during playback
2155
2156                // The idea here is to avoid having two or more samples with the
2157                // same timestamp in the output file.
2158                if (mTimeScale >= 1000000LL) {
2159                    timestampUs = lastTimestampUs + 1;
2160                } else {
2161                    timestampUs = lastTimestampUs + (1000000LL + (mTimeScale >> 1)) / mTimeScale;
2162                }
2163            }
2164        }
2165
2166        LOGV("%s media time stamp: %lld and previous paused duration %lld",
2167                mIsAudio? "Audio": "Video", timestampUs, previousPausedDurationUs);
2168        if (timestampUs > mTrackDurationUs) {
2169            mTrackDurationUs = timestampUs;
2170        }
2171
2172        mSampleSizes.push_back(sampleSize);
2173        ++mNumSamples;
2174        if (mNumSamples > 2) {
2175            // We need to use the time scale based ticks, rather than the
2176            // timestamp itself to determine whether we have to use a new
2177            // stts entry, since we may have rounding errors.
2178            // The calculation is intended to reduce the accumulated
2179            // rounding errors.
2180            currDurationTicks =
2181                     ((timestampUs * mTimeScale + 500000LL) / 1000000LL -
2182                     (lastTimestampUs * mTimeScale + 500000LL) / 1000000LL);
2183
2184            // Force the first sample to have its own stts entry so that
2185            // we can adjust its value later to maintain the A/V sync.
2186            if (mNumSamples == 3 || currDurationTicks != lastDurationTicks) {
2187                LOGV("%s lastDurationUs: %lld us, currDurationTicks: %lld us",
2188                        mIsAudio? "Audio": "Video", lastDurationUs, currDurationTicks);
2189                addOneSttsTableEntry(sampleCount, lastDurationTicks);
2190                sampleCount = 1;
2191            } else {
2192                ++sampleCount;
2193            }
2194
2195            if (!mIsAudio) {
2196                currCttsDurTicks =
2197                     ((cttsDeltaTimeUs * mTimeScale + 500000LL) / 1000000LL -
2198                     (lastCttsTimeUs * mTimeScale + 500000LL) / 1000000LL);
2199                if (currCttsDurTicks != lastCttsDurTicks) {
2200                    addOneCttsTableEntry(cttsSampleCount, lastCttsDurTicks);
2201                    cttsSampleCount = 1;
2202                } else {
2203                    ++cttsSampleCount;
2204                }
2205            }
2206        }
2207        if (mSamplesHaveSameSize) {
2208            if (mNumSamples >= 2 && previousSampleSize != sampleSize) {
2209                mSamplesHaveSameSize = false;
2210            }
2211            previousSampleSize = sampleSize;
2212        }
2213        LOGV("%s timestampUs/lastTimestampUs: %lld/%lld",
2214                mIsAudio? "Audio": "Video", timestampUs, lastTimestampUs);
2215        lastDurationUs = timestampUs - lastTimestampUs;
2216        lastDurationTicks = currDurationTicks;
2217        lastTimestampUs = timestampUs;
2218
2219        if (!mIsAudio) {
2220            lastCttsDurTicks = currCttsDurTicks;
2221            lastCttsTimeUs = cttsDeltaTimeUs;
2222        }
2223
2224        if (isSync != 0) {
2225            addOneStssTableEntry(mNumSamples);
2226        }
2227
2228        if (mTrackingProgressStatus) {
2229            if (mPreviousTrackTimeUs <= 0) {
2230                mPreviousTrackTimeUs = mStartTimestampUs;
2231            }
2232            trackProgressStatus(timestampUs);
2233        }
2234        if (!hasMultipleTracks) {
2235            off64_t offset = mIsAvc? mOwner->addLengthPrefixedSample_l(copy)
2236                                 : mOwner->addSample_l(copy);
2237            if (mChunkOffsets.empty()) {
2238                addChunkOffset(offset);
2239            }
2240            copy->release();
2241            copy = NULL;
2242            continue;
2243        }
2244
2245        mChunkSamples.push_back(copy);
2246        if (interleaveDurationUs == 0) {
2247            addOneStscTableEntry(++nChunks, 1);
2248            bufferChunk(timestampUs);
2249        } else {
2250            if (chunkTimestampUs == 0) {
2251                chunkTimestampUs = timestampUs;
2252            } else {
2253                int64_t chunkDurationUs = timestampUs - chunkTimestampUs;
2254                if (chunkDurationUs > interleaveDurationUs) {
2255                    if (chunkDurationUs > mMaxChunkDurationUs) {
2256                        mMaxChunkDurationUs = chunkDurationUs;
2257                    }
2258                    ++nChunks;
2259                    if (nChunks == 1 ||  // First chunk
2260                        (--(mStscTableEntries.end()))->samplesPerChunk !=
2261                         mChunkSamples.size()) {
2262                        addOneStscTableEntry(nChunks, mChunkSamples.size());
2263                    }
2264                    bufferChunk(timestampUs);
2265                    chunkTimestampUs = timestampUs;
2266                }
2267            }
2268        }
2269
2270    }
2271
2272    if (mSampleSizes.empty() ||                      // no samples written
2273        (!mIsAudio && mNumStssTableEntries == 0) ||  // no sync frames for video
2274        (OK != checkCodecSpecificData())) {          // no codec specific data
2275        err = ERROR_MALFORMED;
2276    }
2277    mOwner->trackProgressStatus(mTrackId, -1, err);
2278
2279    // Last chunk
2280    if (!hasMultipleTracks) {
2281        addOneStscTableEntry(1, mNumSamples);
2282    } else if (!mChunkSamples.empty()) {
2283        addOneStscTableEntry(++nChunks, mChunkSamples.size());
2284        bufferChunk(timestampUs);
2285    }
2286
2287    // We don't really know how long the last frame lasts, since
2288    // there is no frame time after it, just repeat the previous
2289    // frame's duration.
2290    if (mNumSamples == 1) {
2291        lastDurationUs = 0;  // A single sample's duration
2292        lastDurationTicks = 0;
2293        lastCttsDurTicks = 0;
2294    } else {
2295        ++sampleCount;  // Count for the last sample
2296        ++cttsSampleCount;
2297    }
2298
2299    if (mNumSamples <= 2) {
2300        addOneSttsTableEntry(1, lastDurationTicks);
2301        if (sampleCount - 1 > 0) {
2302            addOneSttsTableEntry(sampleCount - 1, lastDurationTicks);
2303        }
2304    } else {
2305        addOneSttsTableEntry(sampleCount, lastDurationTicks);
2306    }
2307
2308    addOneCttsTableEntry(cttsSampleCount, lastCttsDurTicks);
2309    mTrackDurationUs += lastDurationUs;
2310    mReachedEOS = true;
2311
2312    sendTrackSummary(hasMultipleTracks);
2313
2314    LOGI("Received total/0-length (%d/%d) buffers and encoded %d frames. - %s",
2315            count, nZeroLengthFrames, mNumSamples, mIsAudio? "audio": "video");
2316    if (mIsAudio) {
2317        LOGI("Audio track drift time: %lld us", mOwner->getDriftTimeUs());
2318    }
2319
2320    if (err == ERROR_END_OF_STREAM) {
2321        return OK;
2322    }
2323    return err;
2324}
2325
2326void MPEG4Writer::Track::sendTrackSummary(bool hasMultipleTracks) {
2327
2328    // Send track summary only if test mode is enabled.
2329    if (!isTestModeEnabled()) {
2330        return;
2331    }
2332
2333    int trackNum = (mTrackId << 28);
2334
2335    mOwner->notify(MEDIA_RECORDER_TRACK_EVENT_INFO,
2336                    trackNum | MEDIA_RECORDER_TRACK_INFO_TYPE,
2337                    mIsAudio? 0: 1);
2338
2339    mOwner->notify(MEDIA_RECORDER_TRACK_EVENT_INFO,
2340                    trackNum | MEDIA_RECORDER_TRACK_INFO_DURATION_MS,
2341                    mTrackDurationUs / 1000);
2342
2343    mOwner->notify(MEDIA_RECORDER_TRACK_EVENT_INFO,
2344                    trackNum | MEDIA_RECORDER_TRACK_INFO_ENCODED_FRAMES,
2345                    mNumSamples);
2346
2347    {
2348        // The system delay time excluding the requested initial delay that
2349        // is used to eliminate the recording sound.
2350        int64_t startTimeOffsetUs = mOwner->getStartTimeOffsetMs() * 1000LL;
2351        if (startTimeOffsetUs < 0) {  // Start time offset was not set
2352            startTimeOffsetUs = kInitialDelayTimeUs;
2353        }
2354        int64_t initialDelayUs =
2355            mFirstSampleTimeRealUs - mStartTimeRealUs - startTimeOffsetUs;
2356
2357        mOwner->notify(MEDIA_RECORDER_TRACK_EVENT_INFO,
2358                    trackNum | MEDIA_RECORDER_TRACK_INFO_INITIAL_DELAY_MS,
2359                    (initialDelayUs) / 1000);
2360    }
2361
2362    mOwner->notify(MEDIA_RECORDER_TRACK_EVENT_INFO,
2363                    trackNum | MEDIA_RECORDER_TRACK_INFO_DATA_KBYTES,
2364                    mMdatSizeBytes / 1024);
2365
2366    if (hasMultipleTracks) {
2367        mOwner->notify(MEDIA_RECORDER_TRACK_EVENT_INFO,
2368                    trackNum | MEDIA_RECORDER_TRACK_INFO_MAX_CHUNK_DUR_MS,
2369                    mMaxChunkDurationUs / 1000);
2370
2371        int64_t moovStartTimeUs = mOwner->getStartTimestampUs();
2372        if (mStartTimestampUs != moovStartTimeUs) {
2373            int64_t startTimeOffsetUs = mStartTimestampUs - moovStartTimeUs;
2374            mOwner->notify(MEDIA_RECORDER_TRACK_EVENT_INFO,
2375                    trackNum | MEDIA_RECORDER_TRACK_INFO_START_OFFSET_MS,
2376                    startTimeOffsetUs / 1000);
2377        }
2378    }
2379}
2380
2381void MPEG4Writer::Track::trackProgressStatus(int64_t timeUs, status_t err) {
2382    LOGV("trackProgressStatus: %lld us", timeUs);
2383    if (mTrackEveryTimeDurationUs > 0 &&
2384        timeUs - mPreviousTrackTimeUs >= mTrackEveryTimeDurationUs) {
2385        LOGV("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    LOGV("setDriftTimeUs: %lld us", driftTimeUs);
2420    Mutex::Autolock autolock(mLock);
2421    mDriftTimeUs = driftTimeUs;
2422}
2423
2424int64_t MPEG4Writer::getDriftTimeUs() {
2425    LOGV("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    LOGV("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            LOGE("Missing codec specific data");
2459            return ERROR_MALFORMED;
2460        }
2461    } else {
2462        if (mCodecSpecificData ||
2463            mCodecSpecificDataSize > 0) {
2464            LOGE("Unexepected codec specific data found");
2465            return ERROR_MALFORMED;
2466        }
2467    }
2468    return OK;
2469}
2470
2471void MPEG4Writer::Track::writeTrackHeader(bool use32BitOffset) {
2472
2473    LOGV("%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        LOGE("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(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        LOGE("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(mCodecSpecificDataSize > 0);
2616
2617    // Make sure all sizes encode to a single byte.
2618    CHECK(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(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(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
2840void MPEG4Writer::Track::writeSttsBox() {
2841    mOwner->beginBox("stts");
2842    mOwner->writeInt32(0);  // version=0, flags=0
2843    mOwner->writeInt32(mNumSttsTableEntries);
2844
2845    // Compensate for small start time difference from different media tracks
2846    int64_t trackStartTimeOffsetUs = 0;
2847    int64_t moovStartTimeUs = mOwner->getStartTimestampUs();
2848    if (mStartTimestampUs != moovStartTimeUs) {
2849        CHECK(mStartTimestampUs > moovStartTimeUs);
2850        trackStartTimeOffsetUs = mStartTimestampUs - moovStartTimeUs;
2851    }
2852    List<SttsTableEntry>::iterator it = mSttsTableEntries.begin();
2853    CHECK(it != mSttsTableEntries.end() && it->sampleCount == 1);
2854    mOwner->writeInt32(it->sampleCount);
2855    int32_t dur = (trackStartTimeOffsetUs * mTimeScale + 500000LL) / 1000000LL;
2856    mOwner->writeInt32(dur + it->sampleDuration);
2857
2858    int64_t totalCount = 1;
2859    while (++it != mSttsTableEntries.end()) {
2860        mOwner->writeInt32(it->sampleCount);
2861        mOwner->writeInt32(it->sampleDuration);
2862        totalCount += it->sampleCount;
2863    }
2864    CHECK(totalCount == mNumSamples);
2865    mOwner->endBox();  // stts
2866}
2867
2868void MPEG4Writer::Track::writeCttsBox() {
2869    if (mIsAudio) {  // ctts is not for audio
2870        return;
2871    }
2872
2873    // Do not write ctts box when there is no need to have it.
2874    if ((mNumCttsTableEntries == 1 &&
2875        mCttsTableEntries.begin()->sampleDuration == 0) ||
2876        mNumCttsTableEntries == 0) {
2877        return;
2878    }
2879
2880    LOGV("ctts box has %d entries", mNumCttsTableEntries);
2881
2882    mOwner->beginBox("ctts");
2883    if (mHasNegativeCttsDeltaDuration) {
2884        mOwner->writeInt32(0x00010000);  // version=1, flags=0
2885    } else {
2886        mOwner->writeInt32(0);  // version=0, flags=0
2887    }
2888    mOwner->writeInt32(mNumCttsTableEntries);
2889
2890    int64_t totalCount = 0;
2891    for (List<CttsTableEntry>::iterator it = mCttsTableEntries.begin();
2892         it != mCttsTableEntries.end(); ++it) {
2893        mOwner->writeInt32(it->sampleCount);
2894        mOwner->writeInt32(it->sampleDuration);
2895        totalCount += it->sampleCount;
2896    }
2897    CHECK(totalCount == mNumSamples);
2898    mOwner->endBox();  // ctts
2899}
2900
2901void MPEG4Writer::Track::writeStssBox() {
2902    mOwner->beginBox("stss");
2903    mOwner->writeInt32(0);  // version=0, flags=0
2904    mOwner->writeInt32(mNumStssTableEntries);  // number of sync frames
2905    for (List<int32_t>::iterator it = mStssTableEntries.begin();
2906        it != mStssTableEntries.end(); ++it) {
2907        mOwner->writeInt32(*it);
2908    }
2909    mOwner->endBox();  // stss
2910}
2911
2912void MPEG4Writer::Track::writeStszBox() {
2913    mOwner->beginBox("stsz");
2914    mOwner->writeInt32(0);  // version=0, flags=0
2915    if (mSamplesHaveSameSize) {
2916        List<size_t>::iterator it = mSampleSizes.begin();
2917        mOwner->writeInt32(*it);  // default sample size
2918    } else {
2919        mOwner->writeInt32(0);
2920    }
2921    mOwner->writeInt32(mNumSamples);
2922    if (!mSamplesHaveSameSize) {
2923        for (List<size_t>::iterator it = mSampleSizes.begin();
2924            it != mSampleSizes.end(); ++it) {
2925            mOwner->writeInt32(*it);
2926        }
2927    }
2928    mOwner->endBox();  // stsz
2929}
2930
2931void MPEG4Writer::Track::writeStscBox() {
2932    mOwner->beginBox("stsc");
2933    mOwner->writeInt32(0);  // version=0, flags=0
2934    mOwner->writeInt32(mNumStscTableEntries);
2935    for (List<StscTableEntry>::iterator it = mStscTableEntries.begin();
2936        it != mStscTableEntries.end(); ++it) {
2937        mOwner->writeInt32(it->firstChunk);
2938        mOwner->writeInt32(it->samplesPerChunk);
2939        mOwner->writeInt32(it->sampleDescriptionId);
2940    }
2941    mOwner->endBox();  // stsc
2942}
2943
2944void MPEG4Writer::Track::writeStcoBox(bool use32BitOffset) {
2945    mOwner->beginBox(use32BitOffset? "stco": "co64");
2946    mOwner->writeInt32(0);  // version=0, flags=0
2947    mOwner->writeInt32(mNumStcoTableEntries);
2948    for (List<off64_t>::iterator it = mChunkOffsets.begin();
2949        it != mChunkOffsets.end(); ++it) {
2950        if (use32BitOffset) {
2951            mOwner->writeInt32(static_cast<int32_t>(*it));
2952        } else {
2953            mOwner->writeInt64((*it));
2954        }
2955    }
2956    mOwner->endBox();  // stco or co64
2957}
2958
2959void MPEG4Writer::writeUdtaBox() {
2960    beginBox("udta");
2961    writeGeoDataBox();
2962    endBox();
2963}
2964
2965/*
2966 * Geodata is stored according to ISO-6709 standard.
2967 */
2968void MPEG4Writer::writeGeoDataBox() {
2969    beginBox("\xA9xyz");
2970    /*
2971     * For historical reasons, any user data start
2972     * with "\0xA9", must be followed by its assoicated
2973     * language code.
2974     * 0x0012: text string length
2975     * 0x15c7: lang (locale) code: en
2976     */
2977    writeInt32(0x001215c7);
2978    writeLatitude(mLatitudex10000);
2979    writeLongitude(mLongitudex10000);
2980    writeInt8(0x2F);
2981    endBox();
2982}
2983
2984}  // namespace android
2985