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