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