MPEG4Writer.cpp revision 607612858f3afad1ade51a098aafa2a41523b5f7
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 <algorithm>
21
22#include <arpa/inet.h>
23#include <fcntl.h>
24#include <inttypes.h>
25#include <pthread.h>
26#include <sys/prctl.h>
27#include <sys/stat.h>
28#include <sys/types.h>
29#include <unistd.h>
30
31#include <utils/Log.h>
32
33#include <functional>
34
35#include <media/stagefright/foundation/ADebug.h>
36#include <media/stagefright/foundation/AMessage.h>
37#include <media/stagefright/foundation/AUtils.h>
38#include <media/stagefright/foundation/ByteUtils.h>
39#include <media/stagefright/foundation/ColorUtils.h>
40#include <media/stagefright/MPEG4Writer.h>
41#include <media/stagefright/MediaBuffer.h>
42#include <media/stagefright/MetaData.h>
43#include <media/stagefright/MediaDefs.h>
44#include <media/stagefright/MediaErrors.h>
45#include <media/stagefright/MediaSource.h>
46#include <media/stagefright/Utils.h>
47#include <media/mediarecorder.h>
48#include <cutils/properties.h>
49
50#include "include/ESDS.h"
51#include "include/HevcUtils.h"
52#include "include/avc_utils.h"
53
54#ifndef __predict_false
55#define __predict_false(exp) __builtin_expect((exp) != 0, 0)
56#endif
57
58#define WARN_UNLESS(condition, message, ...) \
59( (__predict_false(condition)) ? false : ({ \
60    ALOGW("Condition %s failed "  message, #condition, ##__VA_ARGS__); \
61    true; \
62}))
63
64namespace android {
65
66static const int64_t kMinStreamableFileSizeInBytes = 5 * 1024 * 1024;
67static const int64_t kMax32BitFileSize = 0x00ffffffffLL; // 2^32-1 : max FAT32
68                                                         // filesystem file size
69                                                         // used by most SD cards
70static const uint8_t kNalUnitTypeSeqParamSet = 0x07;
71static const uint8_t kNalUnitTypePicParamSet = 0x08;
72static const int64_t kInitialDelayTimeUs     = 700000LL;
73static const int64_t kMaxMetadataSize = 0x4000000LL;   // 64MB max per-frame metadata size
74
75static const char kMetaKey_Version[]    = "com.android.version";
76static const char kMetaKey_Manufacturer[]      = "com.android.manufacturer";
77static const char kMetaKey_Model[]      = "com.android.model";
78
79#ifdef SHOW_BUILD
80static const char kMetaKey_Build[]      = "com.android.build";
81#endif
82static const char kMetaKey_CaptureFps[] = "com.android.capture.fps";
83static const char kMetaKey_TemporalLayerCount[] = "com.android.video.temporal_layers_count";
84
85static const int kTimestampDebugCount = 10;
86
87static const uint8_t kMandatoryHevcNalUnitTypes[3] = {
88    kHevcNalUnitTypeVps,
89    kHevcNalUnitTypeSps,
90    kHevcNalUnitTypePps,
91};
92static const uint8_t kHevcNalUnitTypes[5] = {
93    kHevcNalUnitTypeVps,
94    kHevcNalUnitTypeSps,
95    kHevcNalUnitTypePps,
96    kHevcNalUnitTypePrefixSei,
97    kHevcNalUnitTypeSuffixSei,
98};
99/* uncomment to include build in meta */
100//#define SHOW_MODEL_BUILD 1
101
102class MPEG4Writer::Track {
103public:
104    Track(MPEG4Writer *owner, const sp<MediaSource> &source, size_t trackId);
105
106    ~Track();
107
108    status_t start(MetaData *params);
109    status_t stop(bool stopSource = true);
110    status_t pause();
111    bool reachedEOS();
112
113    int64_t getDurationUs() const;
114    int64_t getEstimatedTrackSizeBytes() const;
115    void writeTrackHeader(bool use32BitOffset = true);
116    int64_t getMinCttsOffsetTimeUs();
117    void bufferChunk(int64_t timestampUs);
118    bool isAvc() const { return mIsAvc; }
119    bool isHevc() const { return mIsHevc; }
120    bool isAudio() const { return mIsAudio; }
121    bool isMPEG4() const { return mIsMPEG4; }
122    void addChunkOffset(off64_t offset);
123    int32_t getTrackId() const { return mTrackId; }
124    status_t dump(int fd, const Vector<String16>& args) const;
125    static const char *getFourCCForMime(const char *mime);
126    const char *getTrackType() const;
127    void resetInternal();
128
129private:
130    enum {
131        kMaxCttsOffsetTimeUs = 1000000LL,  // 1 second
132        kSampleArraySize = 1000,
133    };
134
135    // A helper class to handle faster write box with table entries
136    template<class TYPE, unsigned ENTRY_SIZE>
137    // ENTRY_SIZE: # of values in each entry
138    struct ListTableEntries {
139        static_assert(ENTRY_SIZE > 0, "ENTRY_SIZE must be positive");
140        ListTableEntries(uint32_t elementCapacity)
141            : mElementCapacity(elementCapacity),
142            mTotalNumTableEntries(0),
143            mNumValuesInCurrEntry(0),
144            mCurrTableEntriesElement(NULL) {
145            CHECK_GT(mElementCapacity, 0u);
146            // Ensure no integer overflow on allocation in add().
147            CHECK_LT(ENTRY_SIZE, UINT32_MAX / mElementCapacity);
148        }
149
150        // Free the allocated memory.
151        ~ListTableEntries() {
152            while (!mTableEntryList.empty()) {
153                typename List<TYPE *>::iterator it = mTableEntryList.begin();
154                delete[] (*it);
155                mTableEntryList.erase(it);
156            }
157        }
158
159        // Replace the value at the given position by the given value.
160        // There must be an existing value at the given position.
161        // @arg value must be in network byte order
162        // @arg pos location the value must be in.
163        void set(const TYPE& value, uint32_t pos) {
164            CHECK_LT(pos, mTotalNumTableEntries * ENTRY_SIZE);
165
166            typename List<TYPE *>::iterator it = mTableEntryList.begin();
167            uint32_t iterations = (pos / (mElementCapacity * ENTRY_SIZE));
168            while (it != mTableEntryList.end() && iterations > 0) {
169                ++it;
170                --iterations;
171            }
172            CHECK(it != mTableEntryList.end());
173            CHECK_EQ(iterations, 0u);
174
175            (*it)[(pos % (mElementCapacity * ENTRY_SIZE))] = value;
176        }
177
178        // Get the value at the given position by the given value.
179        // @arg value the retrieved value at the position in network byte order.
180        // @arg pos location the value must be in.
181        // @return true if a value is found.
182        bool get(TYPE& value, uint32_t pos) const {
183            if (pos >= mTotalNumTableEntries * ENTRY_SIZE) {
184                return false;
185            }
186
187            typename List<TYPE *>::iterator it = mTableEntryList.begin();
188            uint32_t iterations = (pos / (mElementCapacity * ENTRY_SIZE));
189            while (it != mTableEntryList.end() && iterations > 0) {
190                ++it;
191                --iterations;
192            }
193            CHECK(it != mTableEntryList.end());
194            CHECK_EQ(iterations, 0u);
195
196            value = (*it)[(pos % (mElementCapacity * ENTRY_SIZE))];
197            return true;
198        }
199
200        // adjusts all values by |adjust(value)|
201        void adjustEntries(
202                std::function<void(size_t /* ix */, TYPE(& /* entry */)[ENTRY_SIZE])> update) {
203            size_t nEntries = mTotalNumTableEntries + mNumValuesInCurrEntry / ENTRY_SIZE;
204            size_t ix = 0;
205            for (TYPE *entryArray : mTableEntryList) {
206                size_t num = std::min(nEntries, (size_t)mElementCapacity);
207                for (size_t i = 0; i < num; ++i) {
208                    update(ix++, (TYPE(&)[ENTRY_SIZE])(*entryArray));
209                    entryArray += ENTRY_SIZE;
210                }
211                nEntries -= num;
212            }
213        }
214
215        // Store a single value.
216        // @arg value must be in network byte order.
217        void add(const TYPE& value) {
218            CHECK_LT(mNumValuesInCurrEntry, mElementCapacity);
219            uint32_t nEntries = mTotalNumTableEntries % mElementCapacity;
220            uint32_t nValues  = mNumValuesInCurrEntry % ENTRY_SIZE;
221            if (nEntries == 0 && nValues == 0) {
222                mCurrTableEntriesElement = new TYPE[ENTRY_SIZE * mElementCapacity];
223                CHECK(mCurrTableEntriesElement != NULL);
224                mTableEntryList.push_back(mCurrTableEntriesElement);
225            }
226
227            uint32_t pos = nEntries * ENTRY_SIZE + nValues;
228            mCurrTableEntriesElement[pos] = value;
229
230            ++mNumValuesInCurrEntry;
231            if ((mNumValuesInCurrEntry % ENTRY_SIZE) == 0) {
232                ++mTotalNumTableEntries;
233                mNumValuesInCurrEntry = 0;
234            }
235        }
236
237        // Write out the table entries:
238        // 1. the number of entries goes first
239        // 2. followed by the values in the table enties in order
240        // @arg writer the writer to actual write to the storage
241        void write(MPEG4Writer *writer) const {
242            CHECK_EQ(mNumValuesInCurrEntry % ENTRY_SIZE, 0u);
243            uint32_t nEntries = mTotalNumTableEntries;
244            writer->writeInt32(nEntries);
245            for (typename List<TYPE *>::iterator it = mTableEntryList.begin();
246                it != mTableEntryList.end(); ++it) {
247                CHECK_GT(nEntries, 0u);
248                if (nEntries >= mElementCapacity) {
249                    writer->write(*it, sizeof(TYPE) * ENTRY_SIZE, mElementCapacity);
250                    nEntries -= mElementCapacity;
251                } else {
252                    writer->write(*it, sizeof(TYPE) * ENTRY_SIZE, nEntries);
253                    break;
254                }
255            }
256        }
257
258        // Return the number of entries in the table.
259        uint32_t count() const { return mTotalNumTableEntries; }
260
261    private:
262        uint32_t         mElementCapacity;  // # entries in an element
263        uint32_t         mTotalNumTableEntries;
264        uint32_t         mNumValuesInCurrEntry;  // up to ENTRY_SIZE
265        TYPE             *mCurrTableEntriesElement;
266        mutable List<TYPE *>     mTableEntryList;
267
268        DISALLOW_EVIL_CONSTRUCTORS(ListTableEntries);
269    };
270
271
272
273    MPEG4Writer *mOwner;
274    sp<MetaData> mMeta;
275    sp<MediaSource> mSource;
276    volatile bool mDone;
277    volatile bool mPaused;
278    volatile bool mResumed;
279    volatile bool mStarted;
280    bool mIsAvc;
281    bool mIsHevc;
282    bool mIsAudio;
283    bool mIsVideo;
284    bool mIsMPEG4;
285    bool mGotStartKeyFrame;
286    bool mIsMalformed;
287    int32_t mTrackId;
288    int64_t mTrackDurationUs;
289    int64_t mMaxChunkDurationUs;
290    int64_t mLastDecodingTimeUs;
291
292    int64_t mEstimatedTrackSizeBytes;
293    int64_t mMdatSizeBytes;
294    int32_t mTimeScale;
295
296    pthread_t mThread;
297
298
299    List<MediaBuffer *> mChunkSamples;
300
301    bool                mSamplesHaveSameSize;
302    ListTableEntries<uint32_t, 1> *mStszTableEntries;
303
304    ListTableEntries<uint32_t, 1> *mStcoTableEntries;
305    ListTableEntries<off64_t, 1> *mCo64TableEntries;
306    ListTableEntries<uint32_t, 3> *mStscTableEntries;
307    ListTableEntries<uint32_t, 1> *mStssTableEntries;
308    ListTableEntries<uint32_t, 2> *mSttsTableEntries;
309    ListTableEntries<uint32_t, 2> *mCttsTableEntries;
310
311    int64_t mMinCttsOffsetTimeUs;
312    int64_t mMinCttsOffsetTicks;
313    int64_t mMaxCttsOffsetTicks;
314
315    // Save the last 10 frames' timestamp and frame type for debug.
316    struct TimestampDebugHelperEntry {
317        int64_t pts;
318        int64_t dts;
319        std::string frameType;
320    };
321
322    std::list<TimestampDebugHelperEntry> mTimestampDebugHelper;
323
324    // Sequence parameter set or picture parameter set
325    struct AVCParamSet {
326        AVCParamSet(uint16_t length, const uint8_t *data)
327            : mLength(length), mData(data) {}
328
329        uint16_t mLength;
330        const uint8_t *mData;
331    };
332    List<AVCParamSet> mSeqParamSets;
333    List<AVCParamSet> mPicParamSets;
334    uint8_t mProfileIdc;
335    uint8_t mProfileCompatible;
336    uint8_t mLevelIdc;
337
338    void *mCodecSpecificData;
339    size_t mCodecSpecificDataSize;
340    bool mGotAllCodecSpecificData;
341    bool mTrackingProgressStatus;
342
343    bool mReachedEOS;
344    int64_t mStartTimestampUs;
345    int64_t mStartTimeRealUs;
346    int64_t mFirstSampleTimeRealUs;
347    int64_t mPreviousTrackTimeUs;
348    int64_t mTrackEveryTimeDurationUs;
349
350    // Update the audio track's drift information.
351    void updateDriftTime(const sp<MetaData>& meta);
352
353    void dumpTimeStamps();
354
355    int64_t getStartTimeOffsetTimeUs() const;
356    int32_t getStartTimeOffsetScaledTime() const;
357
358    static void *ThreadWrapper(void *me);
359    status_t threadEntry();
360
361    const uint8_t *parseParamSet(
362        const uint8_t *data, size_t length, int type, size_t *paramSetLen);
363
364    status_t copyCodecSpecificData(const uint8_t *data, size_t size, size_t minLength = 0);
365
366    status_t makeAVCCodecSpecificData(const uint8_t *data, size_t size);
367    status_t copyAVCCodecSpecificData(const uint8_t *data, size_t size);
368    status_t parseAVCCodecSpecificData(const uint8_t *data, size_t size);
369
370    status_t makeHEVCCodecSpecificData(const uint8_t *data, size_t size);
371    status_t copyHEVCCodecSpecificData(const uint8_t *data, size_t size);
372    status_t parseHEVCCodecSpecificData(
373            const uint8_t *data, size_t size, HevcParameterSets &paramSets);
374
375    // Track authoring progress status
376    void trackProgressStatus(int64_t timeUs, status_t err = OK);
377    void initTrackingProgressStatus(MetaData *params);
378
379    void getCodecSpecificDataFromInputFormatIfPossible();
380
381    // Determine the track time scale
382    // If it is an audio track, try to use the sampling rate as
383    // the time scale; however, if user chooses the overwrite
384    // value, the user-supplied time scale will be used.
385    void setTimeScale();
386
387    // Simple validation on the codec specific data
388    status_t checkCodecSpecificData() const;
389    int32_t mRotation;
390
391    void updateTrackSizeEstimate();
392    void addOneStscTableEntry(size_t chunkId, size_t sampleId);
393    void addOneStssTableEntry(size_t sampleId);
394
395    // Duration is time scale based
396    void addOneSttsTableEntry(size_t sampleCount, int32_t timescaledDur);
397    void addOneCttsTableEntry(size_t sampleCount, int32_t timescaledDur);
398
399    bool isTrackMalFormed() const;
400    void sendTrackSummary(bool hasMultipleTracks);
401
402    // Write the boxes
403    void writeStcoBox(bool use32BitOffset);
404    void writeStscBox();
405    void writeStszBox();
406    void writeStssBox();
407    void writeSttsBox();
408    void writeCttsBox();
409    void writeD263Box();
410    void writePaspBox();
411    void writeAvccBox();
412    void writeHvccBox();
413    void writeUrlBox();
414    void writeDrefBox();
415    void writeDinfBox();
416    void writeDamrBox();
417    void writeMdhdBox(uint32_t now);
418    void writeSmhdBox();
419    void writeVmhdBox();
420    void writeNmhdBox();
421    void writeHdlrBox();
422    void writeTkhdBox(uint32_t now);
423    void writeColrBox();
424    void writeMp4aEsdsBox();
425    void writeMp4vEsdsBox();
426    void writeAudioFourCCBox();
427    void writeVideoFourCCBox();
428    void writeMetadataFourCCBox();
429    void writeStblBox(bool use32BitOffset);
430
431    Track(const Track &);
432    Track &operator=(const Track &);
433};
434
435MPEG4Writer::MPEG4Writer(int fd) {
436    initInternal(fd, true /*isFirstSession*/);
437}
438
439MPEG4Writer::~MPEG4Writer() {
440    reset();
441
442    while (!mTracks.empty()) {
443        List<Track *>::iterator it = mTracks.begin();
444        delete *it;
445        (*it) = NULL;
446        mTracks.erase(it);
447    }
448    mTracks.clear();
449
450    if (mNextFd != -1) {
451        close(mNextFd);
452    }
453}
454
455void MPEG4Writer::initInternal(int fd, bool isFirstSession) {
456    ALOGV("initInternal");
457    mFd = dup(fd);
458    mNextFd = -1;
459    mInitCheck = mFd < 0? NO_INIT: OK;
460
461    mInterleaveDurationUs = 1000000;
462
463    mStartTimestampUs = -1ll;
464    mStartTimeOffsetMs = -1;
465    mPaused = false;
466    mStarted = false;
467    mWriterThreadStarted = false;
468    mSendNotify = false;
469
470    // Reset following variables for all the sessions and they will be
471    // initialized in start(MetaData *param).
472    mIsRealTimeRecording = true;
473    mUse4ByteNalLength = true;
474    mUse32BitOffset = true;
475    mOffset = 0;
476    mMdatOffset = 0;
477    mMoovBoxBuffer = NULL;
478    mMoovBoxBufferOffset = 0;
479    mWriteMoovBoxToMemory = false;
480    mFreeBoxOffset = 0;
481    mStreamableFile = false;
482    mEstimatedMoovBoxSize = 0;
483    mTimeScale = -1;
484
485    // Following variables only need to be set for the first recording session.
486    // And they will stay the same for all the recording sessions.
487    if (isFirstSession) {
488        mMoovExtraSize = 0;
489        mMetaKeys = new AMessage();
490        addDeviceMeta();
491        mLatitudex10000 = 0;
492        mLongitudex10000 = 0;
493        mAreGeoTagsAvailable = false;
494        mSwitchPending = false;
495        mIsFileSizeLimitExplicitlyRequested = false;
496    }
497
498    // Verify mFd is seekable
499    off64_t off = lseek64(mFd, 0, SEEK_SET);
500    if (off < 0) {
501        ALOGE("cannot seek mFd: %s (%d) %lld", strerror(errno), errno, (long long)mFd);
502        release();
503    }
504    for (List<Track *>::iterator it = mTracks.begin();
505         it != mTracks.end(); ++it) {
506        (*it)->resetInternal();
507    }
508}
509
510status_t MPEG4Writer::dump(
511        int fd, const Vector<String16>& args) {
512    const size_t SIZE = 256;
513    char buffer[SIZE];
514    String8 result;
515    snprintf(buffer, SIZE, "   MPEG4Writer %p\n", this);
516    result.append(buffer);
517    snprintf(buffer, SIZE, "     mStarted: %s\n", mStarted? "true": "false");
518    result.append(buffer);
519    ::write(fd, result.string(), result.size());
520    for (List<Track *>::iterator it = mTracks.begin();
521         it != mTracks.end(); ++it) {
522        (*it)->dump(fd, args);
523    }
524    return OK;
525}
526
527status_t MPEG4Writer::Track::dump(
528        int fd, const Vector<String16>& /* args */) const {
529    const size_t SIZE = 256;
530    char buffer[SIZE];
531    String8 result;
532    snprintf(buffer, SIZE, "     %s track\n", getTrackType());
533    result.append(buffer);
534    snprintf(buffer, SIZE, "       reached EOS: %s\n",
535            mReachedEOS? "true": "false");
536    result.append(buffer);
537    snprintf(buffer, SIZE, "       frames encoded : %d\n", mStszTableEntries->count());
538    result.append(buffer);
539    snprintf(buffer, SIZE, "       duration encoded : %" PRId64 " us\n", mTrackDurationUs);
540    result.append(buffer);
541    ::write(fd, result.string(), result.size());
542    return OK;
543}
544
545// static
546const char *MPEG4Writer::Track::getFourCCForMime(const char *mime) {
547    if (mime == NULL) {
548        return NULL;
549    }
550    if (!strncasecmp(mime, "audio/", 6)) {
551        if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AMR_NB, mime)) {
552            return "samr";
553        } else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AMR_WB, mime)) {
554            return "sawb";
555        } else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AAC, mime)) {
556            return "mp4a";
557        }
558    } else if (!strncasecmp(mime, "video/", 6)) {
559        if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_MPEG4, mime)) {
560            return "mp4v";
561        } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_H263, mime)) {
562            return "s263";
563        } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime)) {
564            return "avc1";
565        } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_HEVC, mime)) {
566            return "hvc1";
567        }
568    } else if (!strncasecmp(mime, "application/", 12)) {
569        return "mett";
570    } else {
571        ALOGE("Track (%s) other than video/audio/metadata is not supported", mime);
572    }
573    return NULL;
574}
575
576status_t MPEG4Writer::addSource(const sp<MediaSource> &source) {
577    Mutex::Autolock l(mLock);
578    if (mStarted) {
579        ALOGE("Attempt to add source AFTER recording is started");
580        return UNKNOWN_ERROR;
581    }
582
583    CHECK(source.get() != NULL);
584
585    const char *mime;
586    source->getFormat()->findCString(kKeyMIMEType, &mime);
587
588    if (Track::getFourCCForMime(mime) == NULL) {
589        ALOGE("Unsupported mime '%s'", mime);
590        return ERROR_UNSUPPORTED;
591    }
592
593    // This is a metadata track or the first track of either audio or video
594    // Go ahead to add the track.
595    Track *track = new Track(this, source, 1 + mTracks.size());
596    mTracks.push_back(track);
597
598    return OK;
599}
600
601status_t MPEG4Writer::startTracks(MetaData *params) {
602    if (mTracks.empty()) {
603        ALOGE("No source added");
604        return INVALID_OPERATION;
605    }
606
607    for (List<Track *>::iterator it = mTracks.begin();
608         it != mTracks.end(); ++it) {
609        status_t err = (*it)->start(params);
610
611        if (err != OK) {
612            for (List<Track *>::iterator it2 = mTracks.begin();
613                 it2 != it; ++it2) {
614                (*it2)->stop();
615            }
616
617            return err;
618        }
619    }
620    return OK;
621}
622
623void MPEG4Writer::addDeviceMeta() {
624    // add device info and estimate space in 'moov'
625    char val[PROPERTY_VALUE_MAX];
626    size_t n;
627    // meta size is estimated by adding up the following:
628    // - meta header structures, which occur only once (total 66 bytes)
629    // - size for each key, which consists of a fixed header (32 bytes),
630    //   plus key length and data length.
631    mMoovExtraSize += 66;
632    if (property_get("ro.build.version.release", val, NULL)
633            && (n = strlen(val)) > 0) {
634        mMetaKeys->setString(kMetaKey_Version, val, n + 1);
635        mMoovExtraSize += sizeof(kMetaKey_Version) + n + 32;
636    }
637
638    if (property_get_bool("media.recorder.show_manufacturer_and_model", false)) {
639        if (property_get("ro.product.manufacturer", val, NULL)
640                && (n = strlen(val)) > 0) {
641            mMetaKeys->setString(kMetaKey_Manufacturer, val, n + 1);
642            mMoovExtraSize += sizeof(kMetaKey_Manufacturer) + n + 32;
643        }
644        if (property_get("ro.product.model", val, NULL)
645                && (n = strlen(val)) > 0) {
646            mMetaKeys->setString(kMetaKey_Model, val, n + 1);
647            mMoovExtraSize += sizeof(kMetaKey_Model) + n + 32;
648        }
649    }
650#ifdef SHOW_MODEL_BUILD
651    if (property_get("ro.build.display.id", val, NULL)
652            && (n = strlen(val)) > 0) {
653        mMetaKeys->setString(kMetaKey_Build, val, n + 1);
654        mMoovExtraSize += sizeof(kMetaKey_Build) + n + 32;
655    }
656#endif
657}
658
659int64_t MPEG4Writer::estimateMoovBoxSize(int32_t bitRate) {
660    // This implementation is highly experimental/heurisitic.
661    //
662    // Statistical analysis shows that metadata usually accounts
663    // for a small portion of the total file size, usually < 0.6%.
664
665    // The default MIN_MOOV_BOX_SIZE is set to 0.6% x 1MB / 2,
666    // where 1MB is the common file size limit for MMS application.
667    // The default MAX _MOOV_BOX_SIZE value is based on about 3
668    // minute video recording with a bit rate about 3 Mbps, because
669    // statistics also show that most of the video captured are going
670    // to be less than 3 minutes.
671
672    // If the estimation is wrong, we will pay the price of wasting
673    // some reserved space. This should not happen so often statistically.
674    static const int32_t factor = mUse32BitOffset? 1: 2;
675    static const int64_t MIN_MOOV_BOX_SIZE = 3 * 1024;  // 3 KB
676    static const int64_t MAX_MOOV_BOX_SIZE = (180 * 3000000 * 6LL / 8000);
677    int64_t size = MIN_MOOV_BOX_SIZE;
678
679    // Max file size limit is set
680    if (mMaxFileSizeLimitBytes != 0 && mIsFileSizeLimitExplicitlyRequested) {
681        size = mMaxFileSizeLimitBytes * 6 / 1000;
682    }
683
684    // Max file duration limit is set
685    if (mMaxFileDurationLimitUs != 0) {
686        if (bitRate > 0) {
687            int64_t size2 =
688                ((mMaxFileDurationLimitUs / 1000) * bitRate * 6) / 8000000;
689            if (mMaxFileSizeLimitBytes != 0 && mIsFileSizeLimitExplicitlyRequested) {
690                // When both file size and duration limits are set,
691                // we use the smaller limit of the two.
692                if (size > size2) {
693                    size = size2;
694                }
695            } else {
696                // Only max file duration limit is set
697                size = size2;
698            }
699        }
700    }
701
702    if (size < MIN_MOOV_BOX_SIZE) {
703        size = MIN_MOOV_BOX_SIZE;
704    }
705
706    // Any long duration recording will be probably end up with
707    // non-streamable mp4 file.
708    if (size > MAX_MOOV_BOX_SIZE) {
709        size = MAX_MOOV_BOX_SIZE;
710    }
711
712    // Account for the extra stuff (Geo, meta keys, etc.)
713    size += mMoovExtraSize;
714
715    ALOGI("limits: %" PRId64 "/%" PRId64 " bytes/us, bit rate: %d bps and the"
716         " estimated moov size %" PRId64 " bytes",
717         mMaxFileSizeLimitBytes, mMaxFileDurationLimitUs, bitRate, size);
718    return factor * size;
719}
720
721status_t MPEG4Writer::start(MetaData *param) {
722    if (mInitCheck != OK) {
723        return UNKNOWN_ERROR;
724    }
725    mStartMeta = param;
726
727    /*
728     * Check mMaxFileSizeLimitBytes at the beginning
729     * since mMaxFileSizeLimitBytes may be implicitly
730     * changed later for 32-bit file offset even if
731     * user does not ask to set it explicitly.
732     */
733    if (mMaxFileSizeLimitBytes != 0) {
734        mIsFileSizeLimitExplicitlyRequested = true;
735    }
736
737    int32_t use64BitOffset;
738    if (param &&
739        param->findInt32(kKey64BitFileOffset, &use64BitOffset) &&
740        use64BitOffset) {
741        mUse32BitOffset = false;
742    }
743
744    if (mUse32BitOffset) {
745        // Implicit 32 bit file size limit
746        if (mMaxFileSizeLimitBytes == 0) {
747            mMaxFileSizeLimitBytes = kMax32BitFileSize;
748        }
749
750        // If file size is set to be larger than the 32 bit file
751        // size limit, treat it as an error.
752        if (mMaxFileSizeLimitBytes > kMax32BitFileSize) {
753            ALOGW("32-bit file size limit (%" PRId64 " bytes) too big. "
754                 "It is changed to %" PRId64 " bytes",
755                mMaxFileSizeLimitBytes, kMax32BitFileSize);
756            mMaxFileSizeLimitBytes = kMax32BitFileSize;
757        }
758    }
759
760    int32_t use2ByteNalLength;
761    if (param &&
762        param->findInt32(kKey2ByteNalLength, &use2ByteNalLength) &&
763        use2ByteNalLength) {
764        mUse4ByteNalLength = false;
765    }
766
767    int32_t isRealTimeRecording;
768    if (param && param->findInt32(kKeyRealTimeRecording, &isRealTimeRecording)) {
769        mIsRealTimeRecording = isRealTimeRecording;
770    }
771
772    mStartTimestampUs = -1;
773
774    if (mStarted) {
775        if (mPaused) {
776            mPaused = false;
777            return startTracks(param);
778        }
779        return OK;
780    }
781
782    if (!param ||
783        !param->findInt32(kKeyTimeScale, &mTimeScale)) {
784        mTimeScale = 1000;
785    }
786    CHECK_GT(mTimeScale, 0);
787    ALOGV("movie time scale: %d", mTimeScale);
788
789    /*
790     * When the requested file size limit is small, the priority
791     * is to meet the file size limit requirement, rather than
792     * to make the file streamable. mStreamableFile does not tell
793     * whether the actual recorded file is streamable or not.
794     */
795    mStreamableFile =
796        (mMaxFileSizeLimitBytes != 0 &&
797         mMaxFileSizeLimitBytes >= kMinStreamableFileSizeInBytes);
798
799    /*
800     * mWriteMoovBoxToMemory is true if the amount of data in moov box is
801     * smaller than the reserved free space at the beginning of a file, AND
802     * when the content of moov box is constructed. Note that video/audio
803     * frame data is always written to the file but not in the memory.
804     *
805     * Before stop()/reset() is called, mWriteMoovBoxToMemory is always
806     * false. When reset() is called at the end of a recording session,
807     * Moov box needs to be constructed.
808     *
809     * 1) Right before a moov box is constructed, mWriteMoovBoxToMemory
810     * to set to mStreamableFile so that if
811     * the file is intended to be streamable, it is set to true;
812     * otherwise, it is set to false. When the value is set to false,
813     * all the content of the moov box is written immediately to
814     * the end of the file. When the value is set to true, all the
815     * content of the moov box is written to an in-memory cache,
816     * mMoovBoxBuffer, util the following condition happens. Note
817     * that the size of the in-memory cache is the same as the
818     * reserved free space at the beginning of the file.
819     *
820     * 2) While the data of the moov box is written to an in-memory
821     * cache, the data size is checked against the reserved space.
822     * If the data size surpasses the reserved space, subsequent moov
823     * data could no longer be hold in the in-memory cache. This also
824     * indicates that the reserved space was too small. At this point,
825     * _all_ moov data must be written to the end of the file.
826     * mWriteMoovBoxToMemory must be set to false to direct the write
827     * to the file.
828     *
829     * 3) If the data size in moov box is smaller than the reserved
830     * space after moov box is completely constructed, the in-memory
831     * cache copy of the moov box is written to the reserved free
832     * space. Thus, immediately after the moov is completedly
833     * constructed, mWriteMoovBoxToMemory is always set to false.
834     */
835    mWriteMoovBoxToMemory = false;
836    mMoovBoxBuffer = NULL;
837    mMoovBoxBufferOffset = 0;
838
839    writeFtypBox(param);
840
841    mFreeBoxOffset = mOffset;
842
843    if (mEstimatedMoovBoxSize == 0) {
844        int32_t bitRate = -1;
845        if (param) {
846            param->findInt32(kKeyBitRate, &bitRate);
847        }
848        mEstimatedMoovBoxSize = estimateMoovBoxSize(bitRate);
849    }
850    CHECK_GE(mEstimatedMoovBoxSize, 8);
851    if (mStreamableFile) {
852        // Reserve a 'free' box only for streamable file
853        lseek64(mFd, mFreeBoxOffset, SEEK_SET);
854        writeInt32(mEstimatedMoovBoxSize);
855        write("free", 4);
856        mMdatOffset = mFreeBoxOffset + mEstimatedMoovBoxSize;
857    } else {
858        mMdatOffset = mOffset;
859    }
860
861    mOffset = mMdatOffset;
862    lseek64(mFd, mMdatOffset, SEEK_SET);
863    if (mUse32BitOffset) {
864        write("????mdat", 8);
865    } else {
866        write("\x00\x00\x00\x01mdat????????", 16);
867    }
868
869    status_t err = startWriterThread();
870    if (err != OK) {
871        return err;
872    }
873
874    err = startTracks(param);
875    if (err != OK) {
876        return err;
877    }
878
879    mStarted = true;
880    return OK;
881}
882
883bool MPEG4Writer::use32BitFileOffset() const {
884    return mUse32BitOffset;
885}
886
887status_t MPEG4Writer::pause() {
888    ALOGW("MPEG4Writer: pause is not supported");
889    return ERROR_UNSUPPORTED;
890}
891
892void MPEG4Writer::stopWriterThread() {
893    ALOGD("Stopping writer thread");
894    if (!mWriterThreadStarted) {
895        return;
896    }
897
898    {
899        Mutex::Autolock autolock(mLock);
900
901        mDone = true;
902        mChunkReadyCondition.signal();
903    }
904
905    void *dummy;
906    pthread_join(mThread, &dummy);
907    mWriterThreadStarted = false;
908    ALOGD("Writer thread stopped");
909}
910
911/*
912 * MP4 file standard defines a composition matrix:
913 * | a  b  u |
914 * | c  d  v |
915 * | x  y  w |
916 *
917 * the element in the matrix is stored in the following
918 * order: {a, b, u, c, d, v, x, y, w},
919 * where a, b, c, d, x, and y is in 16.16 format, while
920 * u, v and w is in 2.30 format.
921 */
922void MPEG4Writer::writeCompositionMatrix(int degrees) {
923    ALOGV("writeCompositionMatrix");
924    uint32_t a = 0x00010000;
925    uint32_t b = 0;
926    uint32_t c = 0;
927    uint32_t d = 0x00010000;
928    switch (degrees) {
929        case 0:
930            break;
931        case 90:
932            a = 0;
933            b = 0x00010000;
934            c = 0xFFFF0000;
935            d = 0;
936            break;
937        case 180:
938            a = 0xFFFF0000;
939            d = 0xFFFF0000;
940            break;
941        case 270:
942            a = 0;
943            b = 0xFFFF0000;
944            c = 0x00010000;
945            d = 0;
946            break;
947        default:
948            CHECK(!"Should never reach this unknown rotation");
949            break;
950    }
951
952    writeInt32(a);           // a
953    writeInt32(b);           // b
954    writeInt32(0);           // u
955    writeInt32(c);           // c
956    writeInt32(d);           // d
957    writeInt32(0);           // v
958    writeInt32(0);           // x
959    writeInt32(0);           // y
960    writeInt32(0x40000000);  // w
961}
962
963void MPEG4Writer::release() {
964    close(mFd);
965    mFd = -1;
966    mInitCheck = NO_INIT;
967    mStarted = false;
968    free(mMoovBoxBuffer);
969    mMoovBoxBuffer = NULL;
970}
971
972void MPEG4Writer::finishCurrentSession() {
973    reset(false /* stopSource */);
974}
975
976status_t MPEG4Writer::switchFd() {
977    ALOGV("switchFd");
978    Mutex::Autolock l(mLock);
979    if (mSwitchPending) {
980        return OK;
981    }
982
983    if (mNextFd == -1) {
984        ALOGW("No FileDescripter for next recording");
985        return INVALID_OPERATION;
986    }
987
988    mSwitchPending = true;
989    sp<AMessage> msg = new AMessage(kWhatSwitch, mReflector);
990    status_t err = msg->post();
991
992    return err;
993}
994
995status_t MPEG4Writer::reset(bool stopSource) {
996    if (mInitCheck != OK) {
997        return OK;
998    } else {
999        if (!mWriterThreadStarted ||
1000            !mStarted) {
1001            if (mWriterThreadStarted) {
1002                stopWriterThread();
1003            }
1004            release();
1005            return OK;
1006        }
1007    }
1008
1009    status_t err = OK;
1010    int64_t maxDurationUs = 0;
1011    int64_t minDurationUs = 0x7fffffffffffffffLL;
1012    for (List<Track *>::iterator it = mTracks.begin();
1013         it != mTracks.end(); ++it) {
1014        status_t status = (*it)->stop(stopSource);
1015        if (err == OK && status != OK) {
1016            err = status;
1017        }
1018
1019        int64_t durationUs = (*it)->getDurationUs();
1020        if (durationUs > maxDurationUs) {
1021            maxDurationUs = durationUs;
1022        }
1023        if (durationUs < minDurationUs) {
1024            minDurationUs = durationUs;
1025        }
1026    }
1027
1028    if (mTracks.size() > 1) {
1029        ALOGD("Duration from tracks range is [%" PRId64 ", %" PRId64 "] us",
1030            minDurationUs, maxDurationUs);
1031    }
1032
1033    stopWriterThread();
1034
1035    // Do not write out movie header on error.
1036    if (err != OK) {
1037        release();
1038        return err;
1039    }
1040
1041    // Fix up the size of the 'mdat' chunk.
1042    if (mUse32BitOffset) {
1043        lseek64(mFd, mMdatOffset, SEEK_SET);
1044        uint32_t size = htonl(static_cast<uint32_t>(mOffset - mMdatOffset));
1045        ::write(mFd, &size, 4);
1046    } else {
1047        lseek64(mFd, mMdatOffset + 8, SEEK_SET);
1048        uint64_t size = mOffset - mMdatOffset;
1049        size = hton64(size);
1050        ::write(mFd, &size, 8);
1051    }
1052    lseek64(mFd, mOffset, SEEK_SET);
1053
1054    // Construct moov box now
1055    mMoovBoxBufferOffset = 0;
1056    mWriteMoovBoxToMemory = mStreamableFile;
1057    if (mWriteMoovBoxToMemory) {
1058        // There is no need to allocate in-memory cache
1059        // for moov box if the file is not streamable.
1060
1061        mMoovBoxBuffer = (uint8_t *) malloc(mEstimatedMoovBoxSize);
1062        CHECK(mMoovBoxBuffer != NULL);
1063    }
1064    writeMoovBox(maxDurationUs);
1065
1066    // mWriteMoovBoxToMemory could be set to false in
1067    // MPEG4Writer::write() method
1068    if (mWriteMoovBoxToMemory) {
1069        mWriteMoovBoxToMemory = false;
1070        // Content of the moov box is saved in the cache, and the in-memory
1071        // moov box needs to be written to the file in a single shot.
1072
1073        CHECK_LE(mMoovBoxBufferOffset + 8, mEstimatedMoovBoxSize);
1074
1075        // Moov box
1076        lseek64(mFd, mFreeBoxOffset, SEEK_SET);
1077        mOffset = mFreeBoxOffset;
1078        write(mMoovBoxBuffer, 1, mMoovBoxBufferOffset);
1079
1080        // Free box
1081        lseek64(mFd, mOffset, SEEK_SET);
1082        writeInt32(mEstimatedMoovBoxSize - mMoovBoxBufferOffset);
1083        write("free", 4);
1084    } else {
1085        ALOGI("The mp4 file will not be streamable.");
1086    }
1087
1088    // Free in-memory cache for moov box
1089    if (mMoovBoxBuffer != NULL) {
1090        free(mMoovBoxBuffer);
1091        mMoovBoxBuffer = NULL;
1092        mMoovBoxBufferOffset = 0;
1093    }
1094
1095    CHECK(mBoxes.empty());
1096
1097    release();
1098    return err;
1099}
1100
1101uint32_t MPEG4Writer::getMpeg4Time() {
1102    time_t now = time(NULL);
1103    // MP4 file uses time counting seconds since midnight, Jan. 1, 1904
1104    // while time function returns Unix epoch values which starts
1105    // at 1970-01-01. Lets add the number of seconds between them
1106    static const uint32_t delta = (66 * 365 + 17) * (24 * 60 * 60);
1107    if (now < 0 || uint32_t(now) > UINT32_MAX - delta) {
1108        return 0;
1109    }
1110    uint32_t mpeg4Time = uint32_t(now) + delta;
1111    return mpeg4Time;
1112}
1113
1114void MPEG4Writer::writeMvhdBox(int64_t durationUs) {
1115    uint32_t now = getMpeg4Time();
1116    beginBox("mvhd");
1117    writeInt32(0);             // version=0, flags=0
1118    writeInt32(now);           // creation time
1119    writeInt32(now);           // modification time
1120    writeInt32(mTimeScale);    // mvhd timescale
1121    int32_t duration = (durationUs * mTimeScale + 5E5) / 1E6;
1122    writeInt32(duration);
1123    writeInt32(0x10000);       // rate: 1.0
1124    writeInt16(0x100);         // volume
1125    writeInt16(0);             // reserved
1126    writeInt32(0);             // reserved
1127    writeInt32(0);             // reserved
1128    writeCompositionMatrix(0); // matrix
1129    writeInt32(0);             // predefined
1130    writeInt32(0);             // predefined
1131    writeInt32(0);             // predefined
1132    writeInt32(0);             // predefined
1133    writeInt32(0);             // predefined
1134    writeInt32(0);             // predefined
1135    writeInt32(mTracks.size() + 1);  // nextTrackID
1136    endBox();  // mvhd
1137}
1138
1139void MPEG4Writer::writeMoovBox(int64_t durationUs) {
1140    beginBox("moov");
1141    writeMvhdBox(durationUs);
1142    if (mAreGeoTagsAvailable) {
1143        writeUdtaBox();
1144    }
1145    writeMetaBox();
1146    // Loop through all the tracks to get the global time offset if there is
1147    // any ctts table appears in a video track.
1148    int64_t minCttsOffsetTimeUs = kMaxCttsOffsetTimeUs;
1149    for (List<Track *>::iterator it = mTracks.begin();
1150        it != mTracks.end(); ++it) {
1151        minCttsOffsetTimeUs =
1152            std::min(minCttsOffsetTimeUs, (*it)->getMinCttsOffsetTimeUs());
1153    }
1154    ALOGI("Ajust the moov start time from %lld us -> %lld us",
1155            (long long)mStartTimestampUs,
1156            (long long)(mStartTimestampUs + minCttsOffsetTimeUs - kMaxCttsOffsetTimeUs));
1157    // Adjust the global start time.
1158    mStartTimestampUs += minCttsOffsetTimeUs - kMaxCttsOffsetTimeUs;
1159
1160    for (List<Track *>::iterator it = mTracks.begin();
1161        it != mTracks.end(); ++it) {
1162        (*it)->writeTrackHeader(mUse32BitOffset);
1163    }
1164    endBox();  // moov
1165}
1166
1167void MPEG4Writer::writeFtypBox(MetaData *param) {
1168    beginBox("ftyp");
1169
1170    int32_t fileType;
1171    if (param && param->findInt32(kKeyFileType, &fileType) &&
1172        fileType != OUTPUT_FORMAT_MPEG_4) {
1173        writeFourcc("3gp4");
1174        writeInt32(0);
1175        writeFourcc("isom");
1176        writeFourcc("3gp4");
1177    } else {
1178        writeFourcc("mp42");
1179        writeInt32(0);
1180        writeFourcc("isom");
1181        writeFourcc("mp42");
1182    }
1183
1184    endBox();
1185}
1186
1187static bool isTestModeEnabled() {
1188#if (PROPERTY_VALUE_MAX < 5)
1189#error "PROPERTY_VALUE_MAX must be at least 5"
1190#endif
1191
1192    // Test mode is enabled only if rw.media.record.test system
1193    // property is enabled.
1194    if (property_get_bool("rw.media.record.test", false)) {
1195        return true;
1196    }
1197    return false;
1198}
1199
1200void MPEG4Writer::sendSessionSummary() {
1201    // Send session summary only if test mode is enabled
1202    if (!isTestModeEnabled()) {
1203        return;
1204    }
1205
1206    for (List<ChunkInfo>::iterator it = mChunkInfos.begin();
1207         it != mChunkInfos.end(); ++it) {
1208        int trackNum = it->mTrack->getTrackId() << 28;
1209        notify(MEDIA_RECORDER_TRACK_EVENT_INFO,
1210                trackNum | MEDIA_RECORDER_TRACK_INTER_CHUNK_TIME_MS,
1211                it->mMaxInterChunkDurUs);
1212    }
1213}
1214
1215status_t MPEG4Writer::setInterleaveDuration(uint32_t durationUs) {
1216    mInterleaveDurationUs = durationUs;
1217    return OK;
1218}
1219
1220void MPEG4Writer::lock() {
1221    mLock.lock();
1222}
1223
1224void MPEG4Writer::unlock() {
1225    mLock.unlock();
1226}
1227
1228off64_t MPEG4Writer::addSample_l(MediaBuffer *buffer) {
1229    off64_t old_offset = mOffset;
1230
1231    ::write(mFd,
1232          (const uint8_t *)buffer->data() + buffer->range_offset(),
1233          buffer->range_length());
1234
1235    mOffset += buffer->range_length();
1236
1237    return old_offset;
1238}
1239
1240static void StripStartcode(MediaBuffer *buffer) {
1241    if (buffer->range_length() < 4) {
1242        return;
1243    }
1244
1245    const uint8_t *ptr =
1246        (const uint8_t *)buffer->data() + buffer->range_offset();
1247
1248    if (!memcmp(ptr, "\x00\x00\x00\x01", 4)) {
1249        buffer->set_range(
1250                buffer->range_offset() + 4, buffer->range_length() - 4);
1251    }
1252}
1253
1254off64_t MPEG4Writer::addMultipleLengthPrefixedSamples_l(MediaBuffer *buffer) {
1255    off64_t old_offset = mOffset;
1256
1257    const size_t kExtensionNALSearchRange = 64; // bytes to look for non-VCL NALUs
1258
1259    const uint8_t *dataStart = (const uint8_t *)buffer->data() + buffer->range_offset();
1260    const uint8_t *currentNalStart = dataStart;
1261    const uint8_t *nextNalStart;
1262    const uint8_t *data = dataStart;
1263    size_t nextNalSize;
1264    size_t searchSize = buffer->range_length() > kExtensionNALSearchRange ?
1265                   kExtensionNALSearchRange : buffer->range_length();
1266
1267    while (getNextNALUnit(&data, &searchSize, &nextNalStart,
1268            &nextNalSize, true) == OK) {
1269        size_t currentNalSize = nextNalStart - currentNalStart - 4 /* strip start-code */;
1270        MediaBuffer *nalBuf = new MediaBuffer((void *)currentNalStart, currentNalSize);
1271        addLengthPrefixedSample_l(nalBuf);
1272        nalBuf->release();
1273
1274        currentNalStart = nextNalStart;
1275    }
1276
1277    size_t currentNalOffset = currentNalStart - dataStart;
1278    buffer->set_range(buffer->range_offset() + currentNalOffset,
1279            buffer->range_length() - currentNalOffset);
1280    addLengthPrefixedSample_l(buffer);
1281
1282    return old_offset;
1283}
1284
1285off64_t MPEG4Writer::addLengthPrefixedSample_l(MediaBuffer *buffer) {
1286    off64_t old_offset = mOffset;
1287
1288    size_t length = buffer->range_length();
1289
1290    if (mUse4ByteNalLength) {
1291        uint8_t x = length >> 24;
1292        ::write(mFd, &x, 1);
1293        x = (length >> 16) & 0xff;
1294        ::write(mFd, &x, 1);
1295        x = (length >> 8) & 0xff;
1296        ::write(mFd, &x, 1);
1297        x = length & 0xff;
1298        ::write(mFd, &x, 1);
1299
1300        ::write(mFd,
1301              (const uint8_t *)buffer->data() + buffer->range_offset(),
1302              length);
1303
1304        mOffset += length + 4;
1305    } else {
1306        CHECK_LT(length, 65536u);
1307
1308        uint8_t x = length >> 8;
1309        ::write(mFd, &x, 1);
1310        x = length & 0xff;
1311        ::write(mFd, &x, 1);
1312        ::write(mFd, (const uint8_t *)buffer->data() + buffer->range_offset(), length);
1313        mOffset += length + 2;
1314    }
1315
1316    return old_offset;
1317}
1318
1319size_t MPEG4Writer::write(
1320        const void *ptr, size_t size, size_t nmemb) {
1321
1322    const size_t bytes = size * nmemb;
1323    if (mWriteMoovBoxToMemory) {
1324
1325        off64_t moovBoxSize = 8 + mMoovBoxBufferOffset + bytes;
1326        if (moovBoxSize > mEstimatedMoovBoxSize) {
1327            // The reserved moov box at the beginning of the file
1328            // is not big enough. Moov box should be written to
1329            // the end of the file from now on, but not to the
1330            // in-memory cache.
1331
1332            // We write partial moov box that is in the memory to
1333            // the file first.
1334            for (List<off64_t>::iterator it = mBoxes.begin();
1335                 it != mBoxes.end(); ++it) {
1336                (*it) += mOffset;
1337            }
1338            lseek64(mFd, mOffset, SEEK_SET);
1339            ::write(mFd, mMoovBoxBuffer, mMoovBoxBufferOffset);
1340            ::write(mFd, ptr, bytes);
1341            mOffset += (bytes + mMoovBoxBufferOffset);
1342
1343            // All subsequent moov box content will be written
1344            // to the end of the file.
1345            mWriteMoovBoxToMemory = false;
1346        } else {
1347            memcpy(mMoovBoxBuffer + mMoovBoxBufferOffset, ptr, bytes);
1348            mMoovBoxBufferOffset += bytes;
1349        }
1350    } else {
1351        ::write(mFd, ptr, size * nmemb);
1352        mOffset += bytes;
1353    }
1354    return bytes;
1355}
1356
1357void MPEG4Writer::beginBox(uint32_t id) {
1358    mBoxes.push_back(mWriteMoovBoxToMemory?
1359            mMoovBoxBufferOffset: mOffset);
1360
1361    writeInt32(0);
1362    writeInt32(id);
1363}
1364
1365void MPEG4Writer::beginBox(const char *fourcc) {
1366    CHECK_EQ(strlen(fourcc), 4u);
1367
1368    mBoxes.push_back(mWriteMoovBoxToMemory?
1369            mMoovBoxBufferOffset: mOffset);
1370
1371    writeInt32(0);
1372    writeFourcc(fourcc);
1373}
1374
1375void MPEG4Writer::endBox() {
1376    CHECK(!mBoxes.empty());
1377
1378    off64_t offset = *--mBoxes.end();
1379    mBoxes.erase(--mBoxes.end());
1380
1381    if (mWriteMoovBoxToMemory) {
1382       int32_t x = htonl(mMoovBoxBufferOffset - offset);
1383       memcpy(mMoovBoxBuffer + offset, &x, 4);
1384    } else {
1385        lseek64(mFd, offset, SEEK_SET);
1386        writeInt32(mOffset - offset);
1387        mOffset -= 4;
1388        lseek64(mFd, mOffset, SEEK_SET);
1389    }
1390}
1391
1392void MPEG4Writer::writeInt8(int8_t x) {
1393    write(&x, 1, 1);
1394}
1395
1396void MPEG4Writer::writeInt16(int16_t x) {
1397    x = htons(x);
1398    write(&x, 1, 2);
1399}
1400
1401void MPEG4Writer::writeInt32(int32_t x) {
1402    x = htonl(x);
1403    write(&x, 1, 4);
1404}
1405
1406void MPEG4Writer::writeInt64(int64_t x) {
1407    x = hton64(x);
1408    write(&x, 1, 8);
1409}
1410
1411void MPEG4Writer::writeCString(const char *s) {
1412    size_t n = strlen(s);
1413    write(s, 1, n + 1);
1414}
1415
1416void MPEG4Writer::writeFourcc(const char *s) {
1417    CHECK_EQ(strlen(s), 4u);
1418    write(s, 1, 4);
1419}
1420
1421
1422// Written in +/-DD.DDDD format
1423void MPEG4Writer::writeLatitude(int degreex10000) {
1424    bool isNegative = (degreex10000 < 0);
1425    char sign = isNegative? '-': '+';
1426
1427    // Handle the whole part
1428    char str[9];
1429    int wholePart = degreex10000 / 10000;
1430    if (wholePart == 0) {
1431        snprintf(str, 5, "%c%.2d.", sign, wholePart);
1432    } else {
1433        snprintf(str, 5, "%+.2d.", wholePart);
1434    }
1435
1436    // Handle the fractional part
1437    int fractionalPart = degreex10000 - (wholePart * 10000);
1438    if (fractionalPart < 0) {
1439        fractionalPart = -fractionalPart;
1440    }
1441    snprintf(&str[4], 5, "%.4d", fractionalPart);
1442
1443    // Do not write the null terminator
1444    write(str, 1, 8);
1445}
1446
1447// Written in +/- DDD.DDDD format
1448void MPEG4Writer::writeLongitude(int degreex10000) {
1449    bool isNegative = (degreex10000 < 0);
1450    char sign = isNegative? '-': '+';
1451
1452    // Handle the whole part
1453    char str[10];
1454    int wholePart = degreex10000 / 10000;
1455    if (wholePart == 0) {
1456        snprintf(str, 6, "%c%.3d.", sign, wholePart);
1457    } else {
1458        snprintf(str, 6, "%+.3d.", wholePart);
1459    }
1460
1461    // Handle the fractional part
1462    int fractionalPart = degreex10000 - (wholePart * 10000);
1463    if (fractionalPart < 0) {
1464        fractionalPart = -fractionalPart;
1465    }
1466    snprintf(&str[5], 5, "%.4d", fractionalPart);
1467
1468    // Do not write the null terminator
1469    write(str, 1, 9);
1470}
1471
1472/*
1473 * Geodata is stored according to ISO-6709 standard.
1474 * latitudex10000 is latitude in degrees times 10000, and
1475 * longitudex10000 is longitude in degrees times 10000.
1476 * The range for the latitude is in [-90, +90], and
1477 * The range for the longitude is in [-180, +180]
1478 */
1479status_t MPEG4Writer::setGeoData(int latitudex10000, int longitudex10000) {
1480    // Is latitude or longitude out of range?
1481    if (latitudex10000 < -900000 || latitudex10000 > 900000 ||
1482        longitudex10000 < -1800000 || longitudex10000 > 1800000) {
1483        return BAD_VALUE;
1484    }
1485
1486    mLatitudex10000 = latitudex10000;
1487    mLongitudex10000 = longitudex10000;
1488    mAreGeoTagsAvailable = true;
1489    mMoovExtraSize += 30;
1490    return OK;
1491}
1492
1493status_t MPEG4Writer::setCaptureRate(float captureFps) {
1494    if (captureFps <= 0.0f) {
1495        return BAD_VALUE;
1496    }
1497
1498    mMetaKeys->setFloat(kMetaKey_CaptureFps, captureFps);
1499    mMoovExtraSize += sizeof(kMetaKey_CaptureFps) + 4 + 32;
1500
1501    return OK;
1502}
1503
1504status_t MPEG4Writer::setTemporalLayerCount(uint32_t layerCount) {
1505    if (layerCount > 9) {
1506        return BAD_VALUE;
1507    }
1508
1509    if (layerCount > 0) {
1510        mMetaKeys->setInt32(kMetaKey_TemporalLayerCount, layerCount);
1511        mMoovExtraSize += sizeof(kMetaKey_TemporalLayerCount) + 4 + 32;
1512    }
1513
1514    return OK;
1515}
1516
1517void MPEG4Writer::notifyApproachingLimit() {
1518    Mutex::Autolock autolock(mLock);
1519    // Only notify once.
1520    if (mSendNotify) {
1521        return;
1522    }
1523    ALOGW("Recorded file size is approaching limit %" PRId64 "bytes",
1524        mMaxFileSizeLimitBytes);
1525    notify(MEDIA_RECORDER_EVENT_INFO, MEDIA_RECORDER_INFO_MAX_FILESIZE_APPROACHING, 0);
1526    mSendNotify = true;
1527}
1528
1529void MPEG4Writer::write(const void *data, size_t size) {
1530    write(data, 1, size);
1531}
1532
1533bool MPEG4Writer::isFileStreamable() const {
1534    return mStreamableFile;
1535}
1536
1537bool MPEG4Writer::exceedsFileSizeLimit() {
1538    // No limit
1539    if (mMaxFileSizeLimitBytes == 0) {
1540        return false;
1541    }
1542    int64_t nTotalBytesEstimate = static_cast<int64_t>(mEstimatedMoovBoxSize);
1543    for (List<Track *>::iterator it = mTracks.begin();
1544         it != mTracks.end(); ++it) {
1545        nTotalBytesEstimate += (*it)->getEstimatedTrackSizeBytes();
1546    }
1547
1548    if (!mStreamableFile) {
1549        // Add 1024 bytes as error tolerance
1550        return nTotalBytesEstimate + 1024 >= mMaxFileSizeLimitBytes;
1551    }
1552
1553    // Be conservative in the estimate: do not exceed 95% of
1554    // the target file limit. For small target file size limit, though,
1555    // this will not help.
1556    return (nTotalBytesEstimate >= (95 * mMaxFileSizeLimitBytes) / 100);
1557}
1558
1559bool MPEG4Writer::approachingFileSizeLimit() {
1560    // No limit
1561    if (mMaxFileSizeLimitBytes == 0) {
1562        return false;
1563    }
1564
1565    int64_t nTotalBytesEstimate = static_cast<int64_t>(mEstimatedMoovBoxSize);
1566    for (List<Track *>::iterator it = mTracks.begin();
1567         it != mTracks.end(); ++it) {
1568        nTotalBytesEstimate += (*it)->getEstimatedTrackSizeBytes();
1569    }
1570
1571    if (!mStreamableFile) {
1572        // Add 1024 bytes as error tolerance
1573        return nTotalBytesEstimate + 1024 >= (90 * mMaxFileSizeLimitBytes) / 100;
1574    }
1575
1576    return (nTotalBytesEstimate >= (90 * mMaxFileSizeLimitBytes) / 100);
1577}
1578
1579bool MPEG4Writer::exceedsFileDurationLimit() {
1580    // No limit
1581    if (mMaxFileDurationLimitUs == 0) {
1582        return false;
1583    }
1584
1585    for (List<Track *>::iterator it = mTracks.begin();
1586         it != mTracks.end(); ++it) {
1587        if ((*it)->getDurationUs() >= mMaxFileDurationLimitUs) {
1588            return true;
1589        }
1590    }
1591    return false;
1592}
1593
1594bool MPEG4Writer::reachedEOS() {
1595    bool allDone = true;
1596    for (List<Track *>::iterator it = mTracks.begin();
1597         it != mTracks.end(); ++it) {
1598        if (!(*it)->reachedEOS()) {
1599            allDone = false;
1600            break;
1601        }
1602    }
1603
1604    return allDone;
1605}
1606
1607void MPEG4Writer::setStartTimestampUs(int64_t timeUs) {
1608    ALOGI("setStartTimestampUs: %" PRId64, timeUs);
1609    CHECK_GE(timeUs, 0ll);
1610    Mutex::Autolock autoLock(mLock);
1611    if (mStartTimestampUs < 0 || mStartTimestampUs > timeUs) {
1612        mStartTimestampUs = timeUs;
1613        ALOGI("Earliest track starting time: %" PRId64, mStartTimestampUs);
1614    }
1615}
1616
1617int64_t MPEG4Writer::getStartTimestampUs() {
1618    Mutex::Autolock autoLock(mLock);
1619    return mStartTimestampUs;
1620}
1621
1622size_t MPEG4Writer::numTracks() {
1623    Mutex::Autolock autolock(mLock);
1624    return mTracks.size();
1625}
1626
1627////////////////////////////////////////////////////////////////////////////////
1628
1629MPEG4Writer::Track::Track(
1630        MPEG4Writer *owner, const sp<MediaSource> &source, size_t trackId)
1631    : mOwner(owner),
1632      mMeta(source->getFormat()),
1633      mSource(source),
1634      mDone(false),
1635      mPaused(false),
1636      mResumed(false),
1637      mStarted(false),
1638      mGotStartKeyFrame(false),
1639      mIsMalformed(false),
1640      mTrackId(trackId),
1641      mTrackDurationUs(0),
1642      mEstimatedTrackSizeBytes(0),
1643      mSamplesHaveSameSize(true),
1644      mStszTableEntries(new ListTableEntries<uint32_t, 1>(1000)),
1645      mStcoTableEntries(new ListTableEntries<uint32_t, 1>(1000)),
1646      mCo64TableEntries(new ListTableEntries<off64_t, 1>(1000)),
1647      mStscTableEntries(new ListTableEntries<uint32_t, 3>(1000)),
1648      mStssTableEntries(new ListTableEntries<uint32_t, 1>(1000)),
1649      mSttsTableEntries(new ListTableEntries<uint32_t, 2>(1000)),
1650      mCttsTableEntries(new ListTableEntries<uint32_t, 2>(1000)),
1651      mMinCttsOffsetTimeUs(0),
1652      mMinCttsOffsetTicks(0),
1653      mMaxCttsOffsetTicks(0),
1654      mCodecSpecificData(NULL),
1655      mCodecSpecificDataSize(0),
1656      mGotAllCodecSpecificData(false),
1657      mReachedEOS(false),
1658      mStartTimestampUs(-1),
1659      mRotation(0) {
1660    getCodecSpecificDataFromInputFormatIfPossible();
1661
1662    const char *mime;
1663    mMeta->findCString(kKeyMIMEType, &mime);
1664    mIsAvc = !strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_AVC);
1665    mIsHevc = !strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_HEVC);
1666    mIsAudio = !strncasecmp(mime, "audio/", 6);
1667    mIsVideo = !strncasecmp(mime, "video/", 6);
1668    mIsMPEG4 = !strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_MPEG4) ||
1669               !strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_AAC);
1670
1671    // store temporal layer count
1672    if (mIsVideo) {
1673        int32_t count;
1674        if (mMeta->findInt32(kKeyTemporalLayerCount, &count) && count > 1) {
1675            mOwner->setTemporalLayerCount(count);
1676        }
1677    }
1678
1679    setTimeScale();
1680}
1681
1682// Clear all the internal states except the CSD data.
1683void MPEG4Writer::Track::resetInternal() {
1684      mDone = false;
1685      mPaused = false;
1686      mResumed = false;
1687      mStarted = false;
1688      mGotStartKeyFrame = false;
1689      mIsMalformed = false;
1690      mTrackDurationUs = 0;
1691      mEstimatedTrackSizeBytes = 0;
1692      mSamplesHaveSameSize = 0;
1693      if (mStszTableEntries != NULL) {
1694         delete mStszTableEntries;
1695         mStszTableEntries = new ListTableEntries<uint32_t, 1>(1000);
1696      }
1697
1698      if (mStcoTableEntries != NULL) {
1699         delete mStcoTableEntries;
1700         mStcoTableEntries = new ListTableEntries<uint32_t, 1>(1000);
1701      }
1702      if (mCo64TableEntries != NULL) {
1703         delete mCo64TableEntries;
1704         mCo64TableEntries = new ListTableEntries<off64_t, 1>(1000);
1705      }
1706
1707      if (mStscTableEntries != NULL) {
1708         delete mStscTableEntries;
1709         mStscTableEntries = new ListTableEntries<uint32_t, 3>(1000);
1710      }
1711      if (mStssTableEntries != NULL) {
1712         delete mStssTableEntries;
1713         mStssTableEntries = new ListTableEntries<uint32_t, 1>(1000);
1714      }
1715      if (mSttsTableEntries != NULL) {
1716         delete mSttsTableEntries;
1717         mSttsTableEntries = new ListTableEntries<uint32_t, 2>(1000);
1718      }
1719      if (mCttsTableEntries != NULL) {
1720         delete mCttsTableEntries;
1721         mCttsTableEntries = new ListTableEntries<uint32_t, 2>(1000);
1722      }
1723      mReachedEOS = false;
1724}
1725
1726void MPEG4Writer::Track::updateTrackSizeEstimate() {
1727
1728    uint32_t stcoBoxCount = (mOwner->use32BitFileOffset()
1729                            ? mStcoTableEntries->count()
1730                            : mCo64TableEntries->count());
1731    int64_t stcoBoxSizeBytes = stcoBoxCount * 4;
1732    int64_t stszBoxSizeBytes = mSamplesHaveSameSize? 4: (mStszTableEntries->count() * 4);
1733
1734    mEstimatedTrackSizeBytes = mMdatSizeBytes;  // media data size
1735    if (!mOwner->isFileStreamable()) {
1736        // Reserved free space is not large enough to hold
1737        // all meta data and thus wasted.
1738        mEstimatedTrackSizeBytes += mStscTableEntries->count() * 12 +  // stsc box size
1739                                    mStssTableEntries->count() * 4 +   // stss box size
1740                                    mSttsTableEntries->count() * 8 +   // stts box size
1741                                    mCttsTableEntries->count() * 8 +   // ctts box size
1742                                    stcoBoxSizeBytes +           // stco box size
1743                                    stszBoxSizeBytes;            // stsz box size
1744    }
1745}
1746
1747void MPEG4Writer::Track::addOneStscTableEntry(
1748        size_t chunkId, size_t sampleId) {
1749
1750        mStscTableEntries->add(htonl(chunkId));
1751        mStscTableEntries->add(htonl(sampleId));
1752        mStscTableEntries->add(htonl(1));
1753}
1754
1755void MPEG4Writer::Track::addOneStssTableEntry(size_t sampleId) {
1756    mStssTableEntries->add(htonl(sampleId));
1757}
1758
1759void MPEG4Writer::Track::addOneSttsTableEntry(
1760        size_t sampleCount, int32_t duration) {
1761
1762    if (duration == 0) {
1763        ALOGW("0-duration samples found: %zu", sampleCount);
1764    }
1765    mSttsTableEntries->add(htonl(sampleCount));
1766    mSttsTableEntries->add(htonl(duration));
1767}
1768
1769void MPEG4Writer::Track::addOneCttsTableEntry(
1770        size_t sampleCount, int32_t duration) {
1771
1772    if (!mIsVideo) {
1773        return;
1774    }
1775    mCttsTableEntries->add(htonl(sampleCount));
1776    mCttsTableEntries->add(htonl(duration));
1777}
1778
1779status_t MPEG4Writer::setNextFd(int fd) {
1780    ALOGV("addNextFd");
1781    Mutex::Autolock l(mLock);
1782    if (mLooper == NULL) {
1783        mReflector = new AHandlerReflector<MPEG4Writer>(this);
1784        mLooper = new ALooper;
1785        mLooper->registerHandler(mReflector);
1786        mLooper->start();
1787    }
1788
1789    if (mNextFd != -1) {
1790        // No need to set a new FD yet.
1791        return INVALID_OPERATION;
1792    }
1793    mNextFd = fd;
1794    return OK;
1795}
1796
1797void MPEG4Writer::Track::addChunkOffset(off64_t offset) {
1798    if (mOwner->use32BitFileOffset()) {
1799        uint32_t value = offset;
1800        mStcoTableEntries->add(htonl(value));
1801    } else {
1802        mCo64TableEntries->add(hton64(offset));
1803    }
1804}
1805
1806void MPEG4Writer::Track::setTimeScale() {
1807    ALOGV("setTimeScale");
1808    // Default time scale
1809    mTimeScale = 90000;
1810
1811    if (mIsAudio) {
1812        // Use the sampling rate as the default time scale for audio track.
1813        int32_t sampleRate;
1814        bool success = mMeta->findInt32(kKeySampleRate, &sampleRate);
1815        CHECK(success);
1816        mTimeScale = sampleRate;
1817    }
1818
1819    // If someone would like to overwrite the timescale, use user-supplied value.
1820    int32_t timeScale;
1821    if (mMeta->findInt32(kKeyTimeScale, &timeScale)) {
1822        mTimeScale = timeScale;
1823    }
1824
1825    CHECK_GT(mTimeScale, 0);
1826}
1827
1828void MPEG4Writer::onMessageReceived(const sp<AMessage> &msg) {
1829    switch (msg->what()) {
1830        case kWhatSwitch:
1831        {
1832            finishCurrentSession();
1833            mLock.lock();
1834            int fd = mNextFd;
1835            mNextFd = -1;
1836            mLock.unlock();
1837            initInternal(fd, false /*isFirstSession*/);
1838            start(mStartMeta.get());
1839            mSwitchPending = false;
1840            notify(MEDIA_RECORDER_EVENT_INFO, MEDIA_RECORDER_INFO_NEXT_OUTPUT_FILE_STARTED, 0);
1841            break;
1842        }
1843        default:
1844        TRESPASS();
1845    }
1846}
1847
1848void MPEG4Writer::Track::getCodecSpecificDataFromInputFormatIfPossible() {
1849    const char *mime;
1850
1851    CHECK(mMeta->findCString(kKeyMIMEType, &mime));
1852
1853    uint32_t type;
1854    const void *data = NULL;
1855    size_t size = 0;
1856    if (!strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_AVC)) {
1857        mMeta->findData(kKeyAVCC, &type, &data, &size);
1858    } else if (!strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_HEVC)) {
1859        mMeta->findData(kKeyHVCC, &type, &data, &size);
1860    } else if (!strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_MPEG4)
1861            || !strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_AAC)) {
1862        if (mMeta->findData(kKeyESDS, &type, &data, &size)) {
1863            ESDS esds(data, size);
1864            if (esds.getCodecSpecificInfo(&data, &size) == OK &&
1865                    data != NULL &&
1866                    copyCodecSpecificData((uint8_t*)data, size) == OK) {
1867                mGotAllCodecSpecificData = true;
1868            }
1869            return;
1870        }
1871    }
1872    if (data != NULL && copyCodecSpecificData((uint8_t *)data, size) == OK) {
1873        mGotAllCodecSpecificData = true;
1874    }
1875}
1876
1877MPEG4Writer::Track::~Track() {
1878    stop();
1879
1880    delete mStszTableEntries;
1881    delete mStcoTableEntries;
1882    delete mCo64TableEntries;
1883    delete mStscTableEntries;
1884    delete mSttsTableEntries;
1885    delete mStssTableEntries;
1886    delete mCttsTableEntries;
1887
1888    mStszTableEntries = NULL;
1889    mStcoTableEntries = NULL;
1890    mCo64TableEntries = NULL;
1891    mStscTableEntries = NULL;
1892    mSttsTableEntries = NULL;
1893    mStssTableEntries = NULL;
1894    mCttsTableEntries = NULL;
1895
1896    if (mCodecSpecificData != NULL) {
1897        free(mCodecSpecificData);
1898        mCodecSpecificData = NULL;
1899    }
1900}
1901
1902void MPEG4Writer::Track::initTrackingProgressStatus(MetaData *params) {
1903    ALOGV("initTrackingProgressStatus");
1904    mPreviousTrackTimeUs = -1;
1905    mTrackingProgressStatus = false;
1906    mTrackEveryTimeDurationUs = 0;
1907    {
1908        int64_t timeUs;
1909        if (params && params->findInt64(kKeyTrackTimeStatus, &timeUs)) {
1910            ALOGV("Receive request to track progress status for every %" PRId64 " us", timeUs);
1911            mTrackEveryTimeDurationUs = timeUs;
1912            mTrackingProgressStatus = true;
1913        }
1914    }
1915}
1916
1917// static
1918void *MPEG4Writer::ThreadWrapper(void *me) {
1919    ALOGV("ThreadWrapper: %p", me);
1920    MPEG4Writer *writer = static_cast<MPEG4Writer *>(me);
1921    writer->threadFunc();
1922    return NULL;
1923}
1924
1925void MPEG4Writer::bufferChunk(const Chunk& chunk) {
1926    ALOGV("bufferChunk: %p", chunk.mTrack);
1927    Mutex::Autolock autolock(mLock);
1928    CHECK_EQ(mDone, false);
1929
1930    for (List<ChunkInfo>::iterator it = mChunkInfos.begin();
1931         it != mChunkInfos.end(); ++it) {
1932
1933        if (chunk.mTrack == it->mTrack) {  // Found owner
1934            it->mChunks.push_back(chunk);
1935            mChunkReadyCondition.signal();
1936            return;
1937        }
1938    }
1939
1940    CHECK(!"Received a chunk for a unknown track");
1941}
1942
1943void MPEG4Writer::writeChunkToFile(Chunk* chunk) {
1944    ALOGV("writeChunkToFile: %" PRId64 " from %s track",
1945        chunk->mTimeStampUs, chunk->mTrack->getTrackType());
1946
1947    int32_t isFirstSample = true;
1948    while (!chunk->mSamples.empty()) {
1949        List<MediaBuffer *>::iterator it = chunk->mSamples.begin();
1950
1951        off64_t offset = (chunk->mTrack->isAvc() || chunk->mTrack->isHevc())
1952                                ? addMultipleLengthPrefixedSamples_l(*it)
1953                                : addSample_l(*it);
1954
1955        if (isFirstSample) {
1956            chunk->mTrack->addChunkOffset(offset);
1957            isFirstSample = false;
1958        }
1959
1960        (*it)->release();
1961        (*it) = NULL;
1962        chunk->mSamples.erase(it);
1963    }
1964    chunk->mSamples.clear();
1965}
1966
1967void MPEG4Writer::writeAllChunks() {
1968    ALOGV("writeAllChunks");
1969    size_t outstandingChunks = 0;
1970    Chunk chunk;
1971    while (findChunkToWrite(&chunk)) {
1972        writeChunkToFile(&chunk);
1973        ++outstandingChunks;
1974    }
1975
1976    sendSessionSummary();
1977
1978    mChunkInfos.clear();
1979    ALOGD("%zu chunks are written in the last batch", outstandingChunks);
1980}
1981
1982bool MPEG4Writer::findChunkToWrite(Chunk *chunk) {
1983    ALOGV("findChunkToWrite");
1984
1985    int64_t minTimestampUs = 0x7FFFFFFFFFFFFFFFLL;
1986    Track *track = NULL;
1987    for (List<ChunkInfo>::iterator it = mChunkInfos.begin();
1988         it != mChunkInfos.end(); ++it) {
1989        if (!it->mChunks.empty()) {
1990            List<Chunk>::iterator chunkIt = it->mChunks.begin();
1991            if (chunkIt->mTimeStampUs < minTimestampUs) {
1992                minTimestampUs = chunkIt->mTimeStampUs;
1993                track = it->mTrack;
1994            }
1995        }
1996    }
1997
1998    if (track == NULL) {
1999        ALOGV("Nothing to be written after all");
2000        return false;
2001    }
2002
2003    if (mIsFirstChunk) {
2004        mIsFirstChunk = false;
2005    }
2006
2007    for (List<ChunkInfo>::iterator it = mChunkInfos.begin();
2008         it != mChunkInfos.end(); ++it) {
2009        if (it->mTrack == track) {
2010            *chunk = *(it->mChunks.begin());
2011            it->mChunks.erase(it->mChunks.begin());
2012            CHECK_EQ(chunk->mTrack, track);
2013
2014            int64_t interChunkTimeUs =
2015                chunk->mTimeStampUs - it->mPrevChunkTimestampUs;
2016            if (interChunkTimeUs > it->mPrevChunkTimestampUs) {
2017                it->mMaxInterChunkDurUs = interChunkTimeUs;
2018            }
2019
2020            return true;
2021        }
2022    }
2023
2024    return false;
2025}
2026
2027void MPEG4Writer::threadFunc() {
2028    ALOGV("threadFunc");
2029
2030    prctl(PR_SET_NAME, (unsigned long)"MPEG4Writer", 0, 0, 0);
2031
2032    Mutex::Autolock autoLock(mLock);
2033    while (!mDone) {
2034        Chunk chunk;
2035        bool chunkFound = false;
2036
2037        while (!mDone && !(chunkFound = findChunkToWrite(&chunk))) {
2038            mChunkReadyCondition.wait(mLock);
2039        }
2040
2041        // In real time recording mode, write without holding the lock in order
2042        // to reduce the blocking time for media track threads.
2043        // Otherwise, hold the lock until the existing chunks get written to the
2044        // file.
2045        if (chunkFound) {
2046            if (mIsRealTimeRecording) {
2047                mLock.unlock();
2048            }
2049            writeChunkToFile(&chunk);
2050            if (mIsRealTimeRecording) {
2051                mLock.lock();
2052            }
2053        }
2054    }
2055
2056    writeAllChunks();
2057}
2058
2059status_t MPEG4Writer::startWriterThread() {
2060    ALOGV("startWriterThread");
2061
2062    mDone = false;
2063    mIsFirstChunk = true;
2064    mDriftTimeUs = 0;
2065    for (List<Track *>::iterator it = mTracks.begin();
2066         it != mTracks.end(); ++it) {
2067        ChunkInfo info;
2068        info.mTrack = *it;
2069        info.mPrevChunkTimestampUs = 0;
2070        info.mMaxInterChunkDurUs = 0;
2071        mChunkInfos.push_back(info);
2072    }
2073
2074    pthread_attr_t attr;
2075    pthread_attr_init(&attr);
2076    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
2077    pthread_create(&mThread, &attr, ThreadWrapper, this);
2078    pthread_attr_destroy(&attr);
2079    mWriterThreadStarted = true;
2080    return OK;
2081}
2082
2083
2084status_t MPEG4Writer::Track::start(MetaData *params) {
2085    if (!mDone && mPaused) {
2086        mPaused = false;
2087        mResumed = true;
2088        return OK;
2089    }
2090
2091    int64_t startTimeUs;
2092    if (params == NULL || !params->findInt64(kKeyTime, &startTimeUs)) {
2093        startTimeUs = 0;
2094    }
2095    mStartTimeRealUs = startTimeUs;
2096
2097    int32_t rotationDegrees;
2098    if (mIsVideo && params && params->findInt32(kKeyRotation, &rotationDegrees)) {
2099        mRotation = rotationDegrees;
2100    }
2101
2102    initTrackingProgressStatus(params);
2103
2104    sp<MetaData> meta = new MetaData;
2105    if (mOwner->isRealTimeRecording() && mOwner->numTracks() > 1) {
2106        /*
2107         * This extra delay of accepting incoming audio/video signals
2108         * helps to align a/v start time at the beginning of a recording
2109         * session, and it also helps eliminate the "recording" sound for
2110         * camcorder applications.
2111         *
2112         * If client does not set the start time offset, we fall back to
2113         * use the default initial delay value.
2114         */
2115        int64_t startTimeOffsetUs = mOwner->getStartTimeOffsetMs() * 1000LL;
2116        if (startTimeOffsetUs < 0) {  // Start time offset was not set
2117            startTimeOffsetUs = kInitialDelayTimeUs;
2118        }
2119        startTimeUs += startTimeOffsetUs;
2120        ALOGI("Start time offset: %" PRId64 " us", startTimeOffsetUs);
2121    }
2122
2123    meta->setInt64(kKeyTime, startTimeUs);
2124
2125    status_t err = mSource->start(meta.get());
2126    if (err != OK) {
2127        mDone = mReachedEOS = true;
2128        return err;
2129    }
2130
2131    pthread_attr_t attr;
2132    pthread_attr_init(&attr);
2133    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
2134
2135    mDone = false;
2136    mStarted = true;
2137    mTrackDurationUs = 0;
2138    mReachedEOS = false;
2139    mEstimatedTrackSizeBytes = 0;
2140    mMdatSizeBytes = 0;
2141    mMaxChunkDurationUs = 0;
2142    mLastDecodingTimeUs = -1;
2143
2144    pthread_create(&mThread, &attr, ThreadWrapper, this);
2145    pthread_attr_destroy(&attr);
2146
2147    return OK;
2148}
2149
2150status_t MPEG4Writer::Track::pause() {
2151    mPaused = true;
2152    return OK;
2153}
2154
2155status_t MPEG4Writer::Track::stop(bool stopSource) {
2156    ALOGD("%s track stopping. %s source", getTrackType(), stopSource ? "Stop" : "Not Stop");
2157    if (!mStarted) {
2158        ALOGE("Stop() called but track is not started");
2159        return ERROR_END_OF_STREAM;
2160    }
2161
2162    if (mDone) {
2163        return OK;
2164    }
2165
2166    if (stopSource) {
2167        ALOGD("%s track source stopping", getTrackType());
2168        mSource->stop();
2169        ALOGD("%s track source stopped", getTrackType());
2170    }
2171
2172    // Set mDone to be true after sucessfully stop mSource as mSource may be still outputting
2173    // buffers to the writer.
2174    mDone = true;
2175
2176    void *dummy;
2177    pthread_join(mThread, &dummy);
2178    status_t err = static_cast<status_t>(reinterpret_cast<uintptr_t>(dummy));
2179
2180    ALOGD("%s track stopped. %s source", getTrackType(), stopSource ? "Stop" : "Not Stop");
2181    return err;
2182}
2183
2184bool MPEG4Writer::Track::reachedEOS() {
2185    return mReachedEOS;
2186}
2187
2188// static
2189void *MPEG4Writer::Track::ThreadWrapper(void *me) {
2190    Track *track = static_cast<Track *>(me);
2191
2192    status_t err = track->threadEntry();
2193    return (void *)(uintptr_t)err;
2194}
2195
2196static void getNalUnitType(uint8_t byte, uint8_t* type) {
2197    ALOGV("getNalUnitType: %d", byte);
2198
2199    // nal_unit_type: 5-bit unsigned integer
2200    *type = (byte & 0x1F);
2201}
2202
2203const uint8_t *MPEG4Writer::Track::parseParamSet(
2204        const uint8_t *data, size_t length, int type, size_t *paramSetLen) {
2205
2206    ALOGV("parseParamSet");
2207    CHECK(type == kNalUnitTypeSeqParamSet ||
2208          type == kNalUnitTypePicParamSet);
2209
2210    const uint8_t *nextStartCode = findNextNalStartCode(data, length);
2211    *paramSetLen = nextStartCode - data;
2212    if (*paramSetLen == 0) {
2213        ALOGE("Param set is malformed, since its length is 0");
2214        return NULL;
2215    }
2216
2217    AVCParamSet paramSet(*paramSetLen, data);
2218    if (type == kNalUnitTypeSeqParamSet) {
2219        if (*paramSetLen < 4) {
2220            ALOGE("Seq parameter set malformed");
2221            return NULL;
2222        }
2223        if (mSeqParamSets.empty()) {
2224            mProfileIdc = data[1];
2225            mProfileCompatible = data[2];
2226            mLevelIdc = data[3];
2227        } else {
2228            if (mProfileIdc != data[1] ||
2229                mProfileCompatible != data[2] ||
2230                mLevelIdc != data[3]) {
2231                // COULD DO: set profile/level to the lowest required to support all SPSs
2232                ALOGE("Inconsistent profile/level found in seq parameter sets");
2233                return NULL;
2234            }
2235        }
2236        mSeqParamSets.push_back(paramSet);
2237    } else {
2238        mPicParamSets.push_back(paramSet);
2239    }
2240    return nextStartCode;
2241}
2242
2243status_t MPEG4Writer::Track::copyAVCCodecSpecificData(
2244        const uint8_t *data, size_t size) {
2245    ALOGV("copyAVCCodecSpecificData");
2246
2247    // 2 bytes for each of the parameter set length field
2248    // plus the 7 bytes for the header
2249    return copyCodecSpecificData(data, size, 4 + 7);
2250}
2251
2252status_t MPEG4Writer::Track::copyHEVCCodecSpecificData(
2253        const uint8_t *data, size_t size) {
2254    ALOGV("copyHEVCCodecSpecificData");
2255
2256    // Min length of HEVC CSD is 23. (ISO/IEC 14496-15:2014 Chapter 8.3.3.1.2)
2257    return copyCodecSpecificData(data, size, 23);
2258}
2259
2260status_t MPEG4Writer::Track::copyCodecSpecificData(
2261        const uint8_t *data, size_t size, size_t minLength) {
2262    if (size < minLength) {
2263        ALOGE("Codec specific data length too short: %zu", size);
2264        return ERROR_MALFORMED;
2265    }
2266
2267    mCodecSpecificData = malloc(size);
2268    if (mCodecSpecificData == NULL) {
2269        ALOGE("Failed allocating codec specific data");
2270        return NO_MEMORY;
2271    }
2272    mCodecSpecificDataSize = size;
2273    memcpy(mCodecSpecificData, data, size);
2274    return OK;
2275}
2276
2277status_t MPEG4Writer::Track::parseAVCCodecSpecificData(
2278        const uint8_t *data, size_t size) {
2279
2280    ALOGV("parseAVCCodecSpecificData");
2281    // Data starts with a start code.
2282    // SPS and PPS are separated with start codes.
2283    // Also, SPS must come before PPS
2284    uint8_t type = kNalUnitTypeSeqParamSet;
2285    bool gotSps = false;
2286    bool gotPps = false;
2287    const uint8_t *tmp = data;
2288    const uint8_t *nextStartCode = data;
2289    size_t bytesLeft = size;
2290    size_t paramSetLen = 0;
2291    mCodecSpecificDataSize = 0;
2292    while (bytesLeft > 4 && !memcmp("\x00\x00\x00\x01", tmp, 4)) {
2293        getNalUnitType(*(tmp + 4), &type);
2294        if (type == kNalUnitTypeSeqParamSet) {
2295            if (gotPps) {
2296                ALOGE("SPS must come before PPS");
2297                return ERROR_MALFORMED;
2298            }
2299            if (!gotSps) {
2300                gotSps = true;
2301            }
2302            nextStartCode = parseParamSet(tmp + 4, bytesLeft - 4, type, &paramSetLen);
2303        } else if (type == kNalUnitTypePicParamSet) {
2304            if (!gotSps) {
2305                ALOGE("SPS must come before PPS");
2306                return ERROR_MALFORMED;
2307            }
2308            if (!gotPps) {
2309                gotPps = true;
2310            }
2311            nextStartCode = parseParamSet(tmp + 4, bytesLeft - 4, type, &paramSetLen);
2312        } else {
2313            ALOGE("Only SPS and PPS Nal units are expected");
2314            return ERROR_MALFORMED;
2315        }
2316
2317        if (nextStartCode == NULL) {
2318            return ERROR_MALFORMED;
2319        }
2320
2321        // Move on to find the next parameter set
2322        bytesLeft -= nextStartCode - tmp;
2323        tmp = nextStartCode;
2324        mCodecSpecificDataSize += (2 + paramSetLen);
2325    }
2326
2327    {
2328        // Check on the number of seq parameter sets
2329        size_t nSeqParamSets = mSeqParamSets.size();
2330        if (nSeqParamSets == 0) {
2331            ALOGE("Cound not find sequence parameter set");
2332            return ERROR_MALFORMED;
2333        }
2334
2335        if (nSeqParamSets > 0x1F) {
2336            ALOGE("Too many seq parameter sets (%zu) found", nSeqParamSets);
2337            return ERROR_MALFORMED;
2338        }
2339    }
2340
2341    {
2342        // Check on the number of pic parameter sets
2343        size_t nPicParamSets = mPicParamSets.size();
2344        if (nPicParamSets == 0) {
2345            ALOGE("Cound not find picture parameter set");
2346            return ERROR_MALFORMED;
2347        }
2348        if (nPicParamSets > 0xFF) {
2349            ALOGE("Too many pic parameter sets (%zd) found", nPicParamSets);
2350            return ERROR_MALFORMED;
2351        }
2352    }
2353// FIXME:
2354// Add chromat_format_idc, bit depth values, etc for AVC/h264 high profile and above
2355// and remove #if 0
2356#if 0
2357    {
2358        // Check on the profiles
2359        // These profiles requires additional parameter set extensions
2360        if (mProfileIdc == 100 || mProfileIdc == 110 ||
2361            mProfileIdc == 122 || mProfileIdc == 144) {
2362            ALOGE("Sorry, no support for profile_idc: %d!", mProfileIdc);
2363            return BAD_VALUE;
2364        }
2365    }
2366#endif
2367    return OK;
2368}
2369
2370status_t MPEG4Writer::Track::makeAVCCodecSpecificData(
2371        const uint8_t *data, size_t size) {
2372
2373    if (mCodecSpecificData != NULL) {
2374        ALOGE("Already have codec specific data");
2375        return ERROR_MALFORMED;
2376    }
2377
2378    if (size < 4) {
2379        ALOGE("Codec specific data length too short: %zu", size);
2380        return ERROR_MALFORMED;
2381    }
2382
2383    // Data is in the form of AVCCodecSpecificData
2384    if (memcmp("\x00\x00\x00\x01", data, 4)) {
2385        return copyAVCCodecSpecificData(data, size);
2386    }
2387
2388    if (parseAVCCodecSpecificData(data, size) != OK) {
2389        return ERROR_MALFORMED;
2390    }
2391
2392    // ISO 14496-15: AVC file format
2393    mCodecSpecificDataSize += 7;  // 7 more bytes in the header
2394    mCodecSpecificData = malloc(mCodecSpecificDataSize);
2395    if (mCodecSpecificData == NULL) {
2396        mCodecSpecificDataSize = 0;
2397        ALOGE("Failed allocating codec specific data");
2398        return NO_MEMORY;
2399    }
2400    uint8_t *header = (uint8_t *)mCodecSpecificData;
2401    header[0] = 1;                     // version
2402    header[1] = mProfileIdc;           // profile indication
2403    header[2] = mProfileCompatible;    // profile compatibility
2404    header[3] = mLevelIdc;
2405
2406    // 6-bit '111111' followed by 2-bit to lengthSizeMinuusOne
2407    if (mOwner->useNalLengthFour()) {
2408        header[4] = 0xfc | 3;  // length size == 4 bytes
2409    } else {
2410        header[4] = 0xfc | 1;  // length size == 2 bytes
2411    }
2412
2413    // 3-bit '111' followed by 5-bit numSequenceParameterSets
2414    int nSequenceParamSets = mSeqParamSets.size();
2415    header[5] = 0xe0 | nSequenceParamSets;
2416    header += 6;
2417    for (List<AVCParamSet>::iterator it = mSeqParamSets.begin();
2418         it != mSeqParamSets.end(); ++it) {
2419        // 16-bit sequence parameter set length
2420        uint16_t seqParamSetLength = it->mLength;
2421        header[0] = seqParamSetLength >> 8;
2422        header[1] = seqParamSetLength & 0xff;
2423
2424        // SPS NAL unit (sequence parameter length bytes)
2425        memcpy(&header[2], it->mData, seqParamSetLength);
2426        header += (2 + seqParamSetLength);
2427    }
2428
2429    // 8-bit nPictureParameterSets
2430    int nPictureParamSets = mPicParamSets.size();
2431    header[0] = nPictureParamSets;
2432    header += 1;
2433    for (List<AVCParamSet>::iterator it = mPicParamSets.begin();
2434         it != mPicParamSets.end(); ++it) {
2435        // 16-bit picture parameter set length
2436        uint16_t picParamSetLength = it->mLength;
2437        header[0] = picParamSetLength >> 8;
2438        header[1] = picParamSetLength & 0xff;
2439
2440        // PPS Nal unit (picture parameter set length bytes)
2441        memcpy(&header[2], it->mData, picParamSetLength);
2442        header += (2 + picParamSetLength);
2443    }
2444
2445    return OK;
2446}
2447
2448
2449status_t MPEG4Writer::Track::parseHEVCCodecSpecificData(
2450        const uint8_t *data, size_t size, HevcParameterSets &paramSets) {
2451
2452    ALOGV("parseHEVCCodecSpecificData");
2453    const uint8_t *tmp = data;
2454    const uint8_t *nextStartCode = data;
2455    size_t bytesLeft = size;
2456    while (bytesLeft > 4 && !memcmp("\x00\x00\x00\x01", tmp, 4)) {
2457        nextStartCode = findNextNalStartCode(tmp + 4, bytesLeft - 4);
2458        status_t err = paramSets.addNalUnit(tmp + 4, (nextStartCode - tmp) - 4);
2459        if (err != OK) {
2460            return ERROR_MALFORMED;
2461        }
2462
2463        // Move on to find the next parameter set
2464        bytesLeft -= nextStartCode - tmp;
2465        tmp = nextStartCode;
2466    }
2467
2468    size_t csdSize = 23;
2469    const size_t numNalUnits = paramSets.getNumNalUnits();
2470    for (size_t i = 0; i < ARRAY_SIZE(kMandatoryHevcNalUnitTypes); ++i) {
2471        int type = kMandatoryHevcNalUnitTypes[i];
2472        size_t numParamSets = paramSets.getNumNalUnitsOfType(type);
2473        if (numParamSets == 0) {
2474            ALOGE("Cound not find NAL unit of type %d", type);
2475            return ERROR_MALFORMED;
2476        }
2477    }
2478    for (size_t i = 0; i < ARRAY_SIZE(kHevcNalUnitTypes); ++i) {
2479        int type = kHevcNalUnitTypes[i];
2480        size_t numParamSets = paramSets.getNumNalUnitsOfType(type);
2481        if (numParamSets > 0xffff) {
2482            ALOGE("Too many seq parameter sets (%zu) found", numParamSets);
2483            return ERROR_MALFORMED;
2484        }
2485        csdSize += 3;
2486        for (size_t j = 0; j < numNalUnits; ++j) {
2487            if (paramSets.getType(j) != type) {
2488                continue;
2489            }
2490            csdSize += 2 + paramSets.getSize(j);
2491        }
2492    }
2493    mCodecSpecificDataSize = csdSize;
2494    return OK;
2495}
2496
2497status_t MPEG4Writer::Track::makeHEVCCodecSpecificData(
2498        const uint8_t *data, size_t size) {
2499
2500    if (mCodecSpecificData != NULL) {
2501        ALOGE("Already have codec specific data");
2502        return ERROR_MALFORMED;
2503    }
2504
2505    if (size < 4) {
2506        ALOGE("Codec specific data length too short: %zu", size);
2507        return ERROR_MALFORMED;
2508    }
2509
2510    // Data is in the form of HEVCCodecSpecificData
2511    if (memcmp("\x00\x00\x00\x01", data, 4)) {
2512        return copyHEVCCodecSpecificData(data, size);
2513    }
2514
2515    HevcParameterSets paramSets;
2516    if (parseHEVCCodecSpecificData(data, size, paramSets) != OK) {
2517        ALOGE("failed parsing codec specific data");
2518        return ERROR_MALFORMED;
2519    }
2520
2521    mCodecSpecificData = malloc(mCodecSpecificDataSize);
2522    if (mCodecSpecificData == NULL) {
2523        mCodecSpecificDataSize = 0;
2524        ALOGE("Failed allocating codec specific data");
2525        return NO_MEMORY;
2526    }
2527    status_t err = paramSets.makeHvcc((uint8_t *)mCodecSpecificData,
2528            &mCodecSpecificDataSize, mOwner->useNalLengthFour() ? 4 : 2);
2529    if (err != OK) {
2530        ALOGE("failed constructing HVCC atom");
2531        return err;
2532    }
2533
2534    return OK;
2535}
2536
2537/*
2538 * Updates the drift time from the audio track so that
2539 * the video track can get the updated drift time information
2540 * from the file writer. The fluctuation of the drift time of the audio
2541 * encoding path is smoothed out with a simple filter by giving a larger
2542 * weight to more recently drift time. The filter coefficients, 0.5 and 0.5,
2543 * are heuristically determined.
2544 */
2545void MPEG4Writer::Track::updateDriftTime(const sp<MetaData>& meta) {
2546    int64_t driftTimeUs = 0;
2547    if (meta->findInt64(kKeyDriftTime, &driftTimeUs)) {
2548        int64_t prevDriftTimeUs = mOwner->getDriftTimeUs();
2549        int64_t timeUs = (driftTimeUs + prevDriftTimeUs) >> 1;
2550        mOwner->setDriftTimeUs(timeUs);
2551    }
2552}
2553
2554void MPEG4Writer::Track::dumpTimeStamps() {
2555    ALOGE("Dumping %s track's last 10 frames timestamp and frame type ", getTrackType());
2556    std::string timeStampString;
2557    for (std::list<TimestampDebugHelperEntry>::iterator entry = mTimestampDebugHelper.begin();
2558            entry != mTimestampDebugHelper.end(); ++entry) {
2559        timeStampString += "(" + std::to_string(entry->pts)+
2560                "us, " + std::to_string(entry->dts) + "us " + entry->frameType + ") ";
2561    }
2562    ALOGE("%s", timeStampString.c_str());
2563}
2564
2565status_t MPEG4Writer::Track::threadEntry() {
2566    int32_t count = 0;
2567    const int64_t interleaveDurationUs = mOwner->interleaveDuration();
2568    const bool hasMultipleTracks = (mOwner->numTracks() > 1);
2569    int64_t chunkTimestampUs = 0;
2570    int32_t nChunks = 0;
2571    int32_t nActualFrames = 0;        // frames containing non-CSD data (non-0 length)
2572    int32_t nZeroLengthFrames = 0;
2573    int64_t lastTimestampUs = 0;      // Previous sample time stamp
2574    int64_t lastDurationUs = 0;       // Between the previous two samples
2575    int64_t currDurationTicks = 0;    // Timescale based ticks
2576    int64_t lastDurationTicks = 0;    // Timescale based ticks
2577    int32_t sampleCount = 1;          // Sample count in the current stts table entry
2578    uint32_t previousSampleSize = 0;  // Size of the previous sample
2579    int64_t previousPausedDurationUs = 0;
2580    int64_t timestampUs = 0;
2581    int64_t cttsOffsetTimeUs = 0;
2582    int64_t currCttsOffsetTimeTicks = 0;   // Timescale based ticks
2583    int64_t lastCttsOffsetTimeTicks = -1;  // Timescale based ticks
2584    int32_t cttsSampleCount = 0;           // Sample count in the current ctts table entry
2585    uint32_t lastSamplesPerChunk = 0;
2586
2587    if (mIsAudio) {
2588        prctl(PR_SET_NAME, (unsigned long)"AudioTrackEncoding", 0, 0, 0);
2589    } else if (mIsVideo) {
2590        prctl(PR_SET_NAME, (unsigned long)"VideoTrackEncoding", 0, 0, 0);
2591    } else {
2592        prctl(PR_SET_NAME, (unsigned long)"MetadataTrackEncoding", 0, 0, 0);
2593    }
2594
2595    if (mOwner->isRealTimeRecording()) {
2596        androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
2597    }
2598
2599    sp<MetaData> meta_data;
2600
2601    status_t err = OK;
2602    MediaBuffer *buffer;
2603    const char *trackName = getTrackType();
2604    while (!mDone && (err = mSource->read(&buffer)) == OK) {
2605        if (buffer->range_length() == 0) {
2606            buffer->release();
2607            buffer = NULL;
2608            ++nZeroLengthFrames;
2609            continue;
2610        }
2611
2612        // If the codec specific data has not been received yet, delay pause.
2613        // After the codec specific data is received, discard what we received
2614        // when the track is to be paused.
2615        if (mPaused && !mResumed) {
2616            buffer->release();
2617            buffer = NULL;
2618            continue;
2619        }
2620
2621        ++count;
2622
2623        int32_t isCodecConfig;
2624        if (buffer->meta_data()->findInt32(kKeyIsCodecConfig, &isCodecConfig)
2625                && isCodecConfig) {
2626            // if config format (at track addition) already had CSD, keep that
2627            // UNLESS we have not received any frames yet.
2628            // TODO: for now the entire CSD has to come in one frame for encoders, even though
2629            // they need to be spread out for decoders.
2630            if (mGotAllCodecSpecificData && nActualFrames > 0) {
2631                ALOGI("ignoring additional CSD for video track after first frame");
2632            } else {
2633                mMeta = mSource->getFormat(); // get output format after format change
2634                status_t err;
2635                if (mIsAvc) {
2636                    err = makeAVCCodecSpecificData(
2637                            (const uint8_t *)buffer->data()
2638                                + buffer->range_offset(),
2639                            buffer->range_length());
2640                } else if (mIsHevc) {
2641                    err = makeHEVCCodecSpecificData(
2642                            (const uint8_t *)buffer->data()
2643                                + buffer->range_offset(),
2644                            buffer->range_length());
2645                } else if (mIsMPEG4) {
2646                    copyCodecSpecificData((const uint8_t *)buffer->data() + buffer->range_offset(),
2647                            buffer->range_length());
2648                }
2649            }
2650
2651            buffer->release();
2652            buffer = NULL;
2653            if (OK != err) {
2654                mSource->stop();
2655                mOwner->notify(MEDIA_RECORDER_TRACK_EVENT_ERROR,
2656                       mTrackId | MEDIA_RECORDER_TRACK_ERROR_GENERAL, err);
2657                break;
2658            }
2659
2660            mGotAllCodecSpecificData = true;
2661            continue;
2662        }
2663
2664        // Per-frame metadata sample's size must be smaller than max allowed.
2665        if (!mIsVideo && !mIsAudio && buffer->range_length() >= kMaxMetadataSize) {
2666            ALOGW("Buffer size is %zu. Maximum metadata buffer size is %lld for %s track",
2667                    buffer->range_length(), (long long)kMaxMetadataSize, trackName);
2668            buffer->release();
2669            mSource->stop();
2670            mIsMalformed = true;
2671            break;
2672        }
2673
2674        ++nActualFrames;
2675
2676        // Make a deep copy of the MediaBuffer and Metadata and release
2677        // the original as soon as we can
2678        MediaBuffer *copy = new MediaBuffer(buffer->range_length());
2679        memcpy(copy->data(), (uint8_t *)buffer->data() + buffer->range_offset(),
2680                buffer->range_length());
2681        copy->set_range(0, buffer->range_length());
2682        meta_data = new MetaData(*buffer->meta_data().get());
2683        buffer->release();
2684        buffer = NULL;
2685
2686        if (mIsAvc || mIsHevc) StripStartcode(copy);
2687
2688        size_t sampleSize = copy->range_length();
2689        if (mIsAvc || mIsHevc) {
2690            if (mOwner->useNalLengthFour()) {
2691                sampleSize += 4;
2692            } else {
2693                sampleSize += 2;
2694            }
2695        }
2696
2697        // Max file size or duration handling
2698        mMdatSizeBytes += sampleSize;
2699        updateTrackSizeEstimate();
2700
2701        if (mOwner->exceedsFileSizeLimit()) {
2702            if (mOwner->switchFd() != OK) {
2703                ALOGW("Recorded file size exceeds limit %" PRId64 "bytes",
2704                        mOwner->mMaxFileSizeLimitBytes);
2705                mSource->stop();
2706                mOwner->notify(
2707                        MEDIA_RECORDER_EVENT_INFO, MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED, 0);
2708            } else {
2709                ALOGV("%s Current recorded file size exceeds limit %" PRId64 "bytes. Switching output",
2710                        getTrackType(), mOwner->mMaxFileSizeLimitBytes);
2711            }
2712            copy->release();
2713            break;
2714        }
2715
2716        if (mOwner->exceedsFileDurationLimit()) {
2717            ALOGW("Recorded file duration exceeds limit %" PRId64 "microseconds",
2718                    mOwner->mMaxFileDurationLimitUs);
2719            mOwner->notify(MEDIA_RECORDER_EVENT_INFO, MEDIA_RECORDER_INFO_MAX_DURATION_REACHED, 0);
2720            copy->release();
2721            mSource->stop();
2722            break;
2723        }
2724
2725        if (mOwner->approachingFileSizeLimit()) {
2726            mOwner->notifyApproachingLimit();
2727        }
2728
2729        int32_t isSync = false;
2730        meta_data->findInt32(kKeyIsSyncFrame, &isSync);
2731        CHECK(meta_data->findInt64(kKeyTime, &timestampUs));
2732
2733        // For video, skip the first several non-key frames until getting the first key frame.
2734        if (mIsVideo && !mGotStartKeyFrame && !isSync) {
2735            ALOGD("Video skip non-key frame");
2736            copy->release();
2737            continue;
2738        }
2739        if (mIsVideo && isSync) {
2740            mGotStartKeyFrame = true;
2741        }
2742////////////////////////////////////////////////////////////////////////////////
2743        if (mStszTableEntries->count() == 0) {
2744            mFirstSampleTimeRealUs = systemTime() / 1000;
2745            mStartTimestampUs = timestampUs;
2746            mOwner->setStartTimestampUs(mStartTimestampUs);
2747            previousPausedDurationUs = mStartTimestampUs;
2748        }
2749
2750        if (mResumed) {
2751            int64_t durExcludingEarlierPausesUs = timestampUs - previousPausedDurationUs;
2752            if (WARN_UNLESS(durExcludingEarlierPausesUs >= 0ll, "for %s track", trackName)) {
2753                copy->release();
2754                mSource->stop();
2755                mIsMalformed = true;
2756                break;
2757            }
2758
2759            int64_t pausedDurationUs = durExcludingEarlierPausesUs - mTrackDurationUs;
2760            if (WARN_UNLESS(pausedDurationUs >= lastDurationUs, "for %s track", trackName)) {
2761                copy->release();
2762                mSource->stop();
2763                mIsMalformed = true;
2764                break;
2765            }
2766
2767            previousPausedDurationUs += pausedDurationUs - lastDurationUs;
2768            mResumed = false;
2769        }
2770        TimestampDebugHelperEntry timestampDebugEntry;
2771        timestampUs -= previousPausedDurationUs;
2772        timestampDebugEntry.pts = timestampUs;
2773        if (WARN_UNLESS(timestampUs >= 0ll, "for %s track", trackName)) {
2774            copy->release();
2775            mSource->stop();
2776            mIsMalformed = true;
2777            break;
2778        }
2779
2780        if (mIsVideo) {
2781            /*
2782             * Composition time: timestampUs
2783             * Decoding time: decodingTimeUs
2784             * Composition time offset = composition time - decoding time
2785             */
2786            int64_t decodingTimeUs;
2787            CHECK(meta_data->findInt64(kKeyDecodingTime, &decodingTimeUs));
2788            decodingTimeUs -= previousPausedDurationUs;
2789
2790            // ensure non-negative, monotonic decoding time
2791            if (mLastDecodingTimeUs < 0) {
2792                decodingTimeUs = std::max((int64_t)0, decodingTimeUs);
2793            } else {
2794                // increase decoding time by at least the larger vaule of 1 tick and
2795                // 0.1 milliseconds. This needs to take into account the possible
2796                // delta adjustment in DurationTicks in below.
2797                decodingTimeUs = std::max(mLastDecodingTimeUs +
2798                        std::max(100, divUp(1000000, mTimeScale)), decodingTimeUs);
2799            }
2800
2801            mLastDecodingTimeUs = decodingTimeUs;
2802            timestampDebugEntry.dts = decodingTimeUs;
2803            timestampDebugEntry.frameType = isSync ? "Key frame" : "Non-Key frame";
2804            // Insert the timestamp into the mTimestampDebugHelper
2805            if (mTimestampDebugHelper.size() >= kTimestampDebugCount) {
2806                mTimestampDebugHelper.pop_front();
2807            }
2808            mTimestampDebugHelper.push_back(timestampDebugEntry);
2809
2810            cttsOffsetTimeUs =
2811                    timestampUs + kMaxCttsOffsetTimeUs - decodingTimeUs;
2812            if (WARN_UNLESS(cttsOffsetTimeUs >= 0ll, "for %s track", trackName)) {
2813                copy->release();
2814                mSource->stop();
2815                mIsMalformed = true;
2816                break;
2817            }
2818
2819            timestampUs = decodingTimeUs;
2820            ALOGV("decoding time: %" PRId64 " and ctts offset time: %" PRId64,
2821                timestampUs, cttsOffsetTimeUs);
2822
2823            // Update ctts box table if necessary
2824            currCttsOffsetTimeTicks =
2825                    (cttsOffsetTimeUs * mTimeScale + 500000LL) / 1000000LL;
2826            if (WARN_UNLESS(currCttsOffsetTimeTicks <= 0x0FFFFFFFFLL, "for %s track", trackName)) {
2827                copy->release();
2828                mSource->stop();
2829                mIsMalformed = true;
2830                break;
2831            }
2832
2833            if (mStszTableEntries->count() == 0) {
2834                // Force the first ctts table entry to have one single entry
2835                // so that we can do adjustment for the initial track start
2836                // time offset easily in writeCttsBox().
2837                lastCttsOffsetTimeTicks = currCttsOffsetTimeTicks;
2838                addOneCttsTableEntry(1, currCttsOffsetTimeTicks);
2839                cttsSampleCount = 0;      // No sample in ctts box is pending
2840            } else {
2841                if (currCttsOffsetTimeTicks != lastCttsOffsetTimeTicks) {
2842                    addOneCttsTableEntry(cttsSampleCount, lastCttsOffsetTimeTicks);
2843                    lastCttsOffsetTimeTicks = currCttsOffsetTimeTicks;
2844                    cttsSampleCount = 1;  // One sample in ctts box is pending
2845                } else {
2846                    ++cttsSampleCount;
2847                }
2848            }
2849
2850            // Update ctts time offset range
2851            if (mStszTableEntries->count() == 0) {
2852                mMinCttsOffsetTicks = currCttsOffsetTimeTicks;
2853                mMaxCttsOffsetTicks = currCttsOffsetTimeTicks;
2854            } else {
2855                if (currCttsOffsetTimeTicks > mMaxCttsOffsetTicks) {
2856                    mMaxCttsOffsetTicks = currCttsOffsetTimeTicks;
2857                } else if (currCttsOffsetTimeTicks < mMinCttsOffsetTicks) {
2858                    mMinCttsOffsetTicks = currCttsOffsetTimeTicks;
2859                    mMinCttsOffsetTimeUs = cttsOffsetTimeUs;
2860                }
2861            }
2862        }
2863
2864        if (mOwner->isRealTimeRecording()) {
2865            if (mIsAudio) {
2866                updateDriftTime(meta_data);
2867            }
2868        }
2869
2870        if (WARN_UNLESS(timestampUs >= 0ll, "for %s track", trackName)) {
2871            copy->release();
2872            mSource->stop();
2873            mIsMalformed = true;
2874            break;
2875        }
2876
2877        ALOGV("%s media time stamp: %" PRId64 " and previous paused duration %" PRId64,
2878                trackName, timestampUs, previousPausedDurationUs);
2879        if (timestampUs > mTrackDurationUs) {
2880            mTrackDurationUs = timestampUs;
2881        }
2882
2883        // We need to use the time scale based ticks, rather than the
2884        // timestamp itself to determine whether we have to use a new
2885        // stts entry, since we may have rounding errors.
2886        // The calculation is intended to reduce the accumulated
2887        // rounding errors.
2888        currDurationTicks =
2889            ((timestampUs * mTimeScale + 500000LL) / 1000000LL -
2890                (lastTimestampUs * mTimeScale + 500000LL) / 1000000LL);
2891        if (currDurationTicks < 0ll) {
2892            ALOGE("do not support out of order frames (timestamp: %lld < last: %lld for %s track",
2893                    (long long)timestampUs, (long long)lastTimestampUs, trackName);
2894            copy->release();
2895            mSource->stop();
2896            mIsMalformed = true;
2897            break;
2898        }
2899
2900        // if the duration is different for this sample, see if it is close enough to the previous
2901        // duration that we can fudge it and use the same value, to avoid filling the stts table
2902        // with lots of near-identical entries.
2903        // "close enough" here means that the current duration needs to be adjusted by less
2904        // than 0.1 milliseconds
2905        if (lastDurationTicks && (currDurationTicks != lastDurationTicks)) {
2906            int64_t deltaUs = ((lastDurationTicks - currDurationTicks) * 1000000LL
2907                    + (mTimeScale / 2)) / mTimeScale;
2908            if (deltaUs > -100 && deltaUs < 100) {
2909                // use previous ticks, and adjust timestamp as if it was actually that number
2910                // of ticks
2911                currDurationTicks = lastDurationTicks;
2912                timestampUs += deltaUs;
2913            }
2914        }
2915        mStszTableEntries->add(htonl(sampleSize));
2916        if (mStszTableEntries->count() > 2) {
2917
2918            // Force the first sample to have its own stts entry so that
2919            // we can adjust its value later to maintain the A/V sync.
2920            if (mStszTableEntries->count() == 3 || currDurationTicks != lastDurationTicks) {
2921                addOneSttsTableEntry(sampleCount, lastDurationTicks);
2922                sampleCount = 1;
2923            } else {
2924                ++sampleCount;
2925            }
2926
2927        }
2928        if (mSamplesHaveSameSize) {
2929            if (mStszTableEntries->count() >= 2 && previousSampleSize != sampleSize) {
2930                mSamplesHaveSameSize = false;
2931            }
2932            previousSampleSize = sampleSize;
2933        }
2934        ALOGV("%s timestampUs/lastTimestampUs: %" PRId64 "/%" PRId64,
2935                trackName, timestampUs, lastTimestampUs);
2936        lastDurationUs = timestampUs - lastTimestampUs;
2937        lastDurationTicks = currDurationTicks;
2938        lastTimestampUs = timestampUs;
2939
2940        if (isSync != 0) {
2941            addOneStssTableEntry(mStszTableEntries->count());
2942        }
2943
2944        if (mTrackingProgressStatus) {
2945            if (mPreviousTrackTimeUs <= 0) {
2946                mPreviousTrackTimeUs = mStartTimestampUs;
2947            }
2948            trackProgressStatus(timestampUs);
2949        }
2950        if (!hasMultipleTracks) {
2951            off64_t offset = (mIsAvc || mIsHevc) ? mOwner->addMultipleLengthPrefixedSamples_l(copy)
2952                                 : mOwner->addSample_l(copy);
2953
2954            uint32_t count = (mOwner->use32BitFileOffset()
2955                        ? mStcoTableEntries->count()
2956                        : mCo64TableEntries->count());
2957
2958            if (count == 0) {
2959                addChunkOffset(offset);
2960            }
2961            copy->release();
2962            copy = NULL;
2963            continue;
2964        }
2965
2966        mChunkSamples.push_back(copy);
2967        if (interleaveDurationUs == 0) {
2968            addOneStscTableEntry(++nChunks, 1);
2969            bufferChunk(timestampUs);
2970        } else {
2971            if (chunkTimestampUs == 0) {
2972                chunkTimestampUs = timestampUs;
2973            } else {
2974                int64_t chunkDurationUs = timestampUs - chunkTimestampUs;
2975                if (chunkDurationUs > interleaveDurationUs) {
2976                    if (chunkDurationUs > mMaxChunkDurationUs) {
2977                        mMaxChunkDurationUs = chunkDurationUs;
2978                    }
2979                    ++nChunks;
2980                    if (nChunks == 1 ||  // First chunk
2981                        lastSamplesPerChunk != mChunkSamples.size()) {
2982                        lastSamplesPerChunk = mChunkSamples.size();
2983                        addOneStscTableEntry(nChunks, lastSamplesPerChunk);
2984                    }
2985                    bufferChunk(timestampUs);
2986                    chunkTimestampUs = timestampUs;
2987                }
2988            }
2989        }
2990
2991    }
2992
2993    if (isTrackMalFormed()) {
2994        dumpTimeStamps();
2995        err = ERROR_MALFORMED;
2996    }
2997
2998    mOwner->trackProgressStatus(mTrackId, -1, err);
2999
3000    // Last chunk
3001    if (!hasMultipleTracks) {
3002        addOneStscTableEntry(1, mStszTableEntries->count());
3003    } else if (!mChunkSamples.empty()) {
3004        addOneStscTableEntry(++nChunks, mChunkSamples.size());
3005        bufferChunk(timestampUs);
3006    }
3007
3008    // We don't really know how long the last frame lasts, since
3009    // there is no frame time after it, just repeat the previous
3010    // frame's duration.
3011    if (mStszTableEntries->count() == 1) {
3012        lastDurationUs = 0;  // A single sample's duration
3013        lastDurationTicks = 0;
3014    } else {
3015        ++sampleCount;  // Count for the last sample
3016    }
3017
3018    if (mStszTableEntries->count() <= 2) {
3019        addOneSttsTableEntry(1, lastDurationTicks);
3020        if (sampleCount - 1 > 0) {
3021            addOneSttsTableEntry(sampleCount - 1, lastDurationTicks);
3022        }
3023    } else {
3024        addOneSttsTableEntry(sampleCount, lastDurationTicks);
3025    }
3026
3027    // The last ctts box may not have been written yet, and this
3028    // is to make sure that we write out the last ctts box.
3029    if (currCttsOffsetTimeTicks == lastCttsOffsetTimeTicks) {
3030        if (cttsSampleCount > 0) {
3031            addOneCttsTableEntry(cttsSampleCount, lastCttsOffsetTimeTicks);
3032        }
3033    }
3034
3035    mTrackDurationUs += lastDurationUs;
3036    mReachedEOS = true;
3037
3038    sendTrackSummary(hasMultipleTracks);
3039
3040    ALOGI("Received total/0-length (%d/%d) buffers and encoded %d frames. - %s",
3041            count, nZeroLengthFrames, mStszTableEntries->count(), trackName);
3042    if (mIsAudio) {
3043        ALOGI("Audio track drift time: %" PRId64 " us", mOwner->getDriftTimeUs());
3044    }
3045
3046    if (err == ERROR_END_OF_STREAM) {
3047        return OK;
3048    }
3049    return err;
3050}
3051
3052bool MPEG4Writer::Track::isTrackMalFormed() const {
3053    if (mIsMalformed) {
3054        return true;
3055    }
3056
3057    if (mStszTableEntries->count() == 0) {                      // no samples written
3058        ALOGE("The number of recorded samples is 0");
3059        return true;
3060    }
3061
3062    if (mIsVideo && mStssTableEntries->count() == 0) {  // no sync frames for video
3063        ALOGE("There are no sync frames for video track");
3064        return true;
3065    }
3066
3067    if (OK != checkCodecSpecificData()) {         // no codec specific data
3068        return true;
3069    }
3070
3071    return false;
3072}
3073
3074void MPEG4Writer::Track::sendTrackSummary(bool hasMultipleTracks) {
3075
3076    // Send track summary only if test mode is enabled.
3077    if (!isTestModeEnabled()) {
3078        return;
3079    }
3080
3081    int trackNum = (mTrackId << 28);
3082
3083    mOwner->notify(MEDIA_RECORDER_TRACK_EVENT_INFO,
3084                    trackNum | MEDIA_RECORDER_TRACK_INFO_TYPE,
3085                    mIsAudio ? 0: 1);
3086
3087    mOwner->notify(MEDIA_RECORDER_TRACK_EVENT_INFO,
3088                    trackNum | MEDIA_RECORDER_TRACK_INFO_DURATION_MS,
3089                    mTrackDurationUs / 1000);
3090
3091    mOwner->notify(MEDIA_RECORDER_TRACK_EVENT_INFO,
3092                    trackNum | MEDIA_RECORDER_TRACK_INFO_ENCODED_FRAMES,
3093                    mStszTableEntries->count());
3094
3095    {
3096        // The system delay time excluding the requested initial delay that
3097        // is used to eliminate the recording sound.
3098        int64_t startTimeOffsetUs = mOwner->getStartTimeOffsetMs() * 1000LL;
3099        if (startTimeOffsetUs < 0) {  // Start time offset was not set
3100            startTimeOffsetUs = kInitialDelayTimeUs;
3101        }
3102        int64_t initialDelayUs =
3103            mFirstSampleTimeRealUs - mStartTimeRealUs - startTimeOffsetUs;
3104
3105        mOwner->notify(MEDIA_RECORDER_TRACK_EVENT_INFO,
3106                    trackNum | MEDIA_RECORDER_TRACK_INFO_INITIAL_DELAY_MS,
3107                    (initialDelayUs) / 1000);
3108    }
3109
3110    mOwner->notify(MEDIA_RECORDER_TRACK_EVENT_INFO,
3111                    trackNum | MEDIA_RECORDER_TRACK_INFO_DATA_KBYTES,
3112                    mMdatSizeBytes / 1024);
3113
3114    if (hasMultipleTracks) {
3115        mOwner->notify(MEDIA_RECORDER_TRACK_EVENT_INFO,
3116                    trackNum | MEDIA_RECORDER_TRACK_INFO_MAX_CHUNK_DUR_MS,
3117                    mMaxChunkDurationUs / 1000);
3118
3119        int64_t moovStartTimeUs = mOwner->getStartTimestampUs();
3120        if (mStartTimestampUs != moovStartTimeUs) {
3121            int64_t startTimeOffsetUs = mStartTimestampUs - moovStartTimeUs;
3122            mOwner->notify(MEDIA_RECORDER_TRACK_EVENT_INFO,
3123                    trackNum | MEDIA_RECORDER_TRACK_INFO_START_OFFSET_MS,
3124                    startTimeOffsetUs / 1000);
3125        }
3126    }
3127}
3128
3129void MPEG4Writer::Track::trackProgressStatus(int64_t timeUs, status_t err) {
3130    ALOGV("trackProgressStatus: %" PRId64 " us", timeUs);
3131
3132    if (mTrackEveryTimeDurationUs > 0 &&
3133        timeUs - mPreviousTrackTimeUs >= mTrackEveryTimeDurationUs) {
3134        ALOGV("Fire time tracking progress status at %" PRId64 " us", timeUs);
3135        mOwner->trackProgressStatus(mTrackId, timeUs - mPreviousTrackTimeUs, err);
3136        mPreviousTrackTimeUs = timeUs;
3137    }
3138}
3139
3140void MPEG4Writer::trackProgressStatus(
3141        size_t trackId, int64_t timeUs, status_t err) {
3142    Mutex::Autolock lock(mLock);
3143    int32_t trackNum = (trackId << 28);
3144
3145    // Error notification
3146    // Do not consider ERROR_END_OF_STREAM an error
3147    if (err != OK && err != ERROR_END_OF_STREAM) {
3148        notify(MEDIA_RECORDER_TRACK_EVENT_ERROR,
3149               trackNum | MEDIA_RECORDER_TRACK_ERROR_GENERAL,
3150               err);
3151        return;
3152    }
3153
3154    if (timeUs == -1) {
3155        // Send completion notification
3156        notify(MEDIA_RECORDER_TRACK_EVENT_INFO,
3157               trackNum | MEDIA_RECORDER_TRACK_INFO_COMPLETION_STATUS,
3158               err);
3159    } else {
3160        // Send progress status
3161        notify(MEDIA_RECORDER_TRACK_EVENT_INFO,
3162               trackNum | MEDIA_RECORDER_TRACK_INFO_PROGRESS_IN_TIME,
3163               timeUs / 1000);
3164    }
3165}
3166
3167void MPEG4Writer::setDriftTimeUs(int64_t driftTimeUs) {
3168    ALOGV("setDriftTimeUs: %" PRId64 " us", driftTimeUs);
3169    Mutex::Autolock autolock(mLock);
3170    mDriftTimeUs = driftTimeUs;
3171}
3172
3173int64_t MPEG4Writer::getDriftTimeUs() {
3174    ALOGV("getDriftTimeUs: %" PRId64 " us", mDriftTimeUs);
3175    Mutex::Autolock autolock(mLock);
3176    return mDriftTimeUs;
3177}
3178
3179bool MPEG4Writer::isRealTimeRecording() const {
3180    return mIsRealTimeRecording;
3181}
3182
3183bool MPEG4Writer::useNalLengthFour() {
3184    return mUse4ByteNalLength;
3185}
3186
3187void MPEG4Writer::Track::bufferChunk(int64_t timestampUs) {
3188    ALOGV("bufferChunk");
3189
3190    Chunk chunk(this, timestampUs, mChunkSamples);
3191    mOwner->bufferChunk(chunk);
3192    mChunkSamples.clear();
3193}
3194
3195int64_t MPEG4Writer::Track::getDurationUs() const {
3196    return mTrackDurationUs + getStartTimeOffsetTimeUs();
3197}
3198
3199int64_t MPEG4Writer::Track::getEstimatedTrackSizeBytes() const {
3200    return mEstimatedTrackSizeBytes;
3201}
3202
3203status_t MPEG4Writer::Track::checkCodecSpecificData() const {
3204    const char *mime;
3205    CHECK(mMeta->findCString(kKeyMIMEType, &mime));
3206    if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AAC, mime) ||
3207        !strcasecmp(MEDIA_MIMETYPE_VIDEO_MPEG4, mime) ||
3208        !strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime) ||
3209        !strcasecmp(MEDIA_MIMETYPE_VIDEO_HEVC, mime)) {
3210        if (!mCodecSpecificData ||
3211            mCodecSpecificDataSize <= 0) {
3212            ALOGE("Missing codec specific data");
3213            return ERROR_MALFORMED;
3214        }
3215    } else {
3216        if (mCodecSpecificData ||
3217            mCodecSpecificDataSize > 0) {
3218            ALOGE("Unexepected codec specific data found");
3219            return ERROR_MALFORMED;
3220        }
3221    }
3222    return OK;
3223}
3224
3225const char *MPEG4Writer::Track::getTrackType() const {
3226    return mIsAudio ? "Audio" : (mIsVideo ? "Video" : "Metadata");
3227}
3228
3229void MPEG4Writer::Track::writeTrackHeader(bool use32BitOffset) {
3230    uint32_t now = getMpeg4Time();
3231    mOwner->beginBox("trak");
3232        writeTkhdBox(now);
3233        mOwner->beginBox("mdia");
3234            writeMdhdBox(now);
3235            writeHdlrBox();
3236            mOwner->beginBox("minf");
3237                if (mIsAudio) {
3238                    writeSmhdBox();
3239                } else if (mIsVideo) {
3240                    writeVmhdBox();
3241                } else {
3242                    writeNmhdBox();
3243                }
3244                writeDinfBox();
3245                writeStblBox(use32BitOffset);
3246            mOwner->endBox();  // minf
3247        mOwner->endBox();  // mdia
3248    mOwner->endBox();  // trak
3249}
3250
3251int64_t MPEG4Writer::Track::getMinCttsOffsetTimeUs() {
3252    // For video tracks with ctts table, this should return the minimum ctts
3253    // offset in the table. For non-video tracks or video tracks without ctts
3254    // table, this will return kMaxCttsOffsetTimeUs.
3255    if (mMinCttsOffsetTicks == mMaxCttsOffsetTicks) {
3256        return kMaxCttsOffsetTimeUs;
3257    }
3258    return mMinCttsOffsetTimeUs;
3259}
3260
3261void MPEG4Writer::Track::writeStblBox(bool use32BitOffset) {
3262    mOwner->beginBox("stbl");
3263    mOwner->beginBox("stsd");
3264    mOwner->writeInt32(0);               // version=0, flags=0
3265    mOwner->writeInt32(1);               // entry count
3266    if (mIsAudio) {
3267        writeAudioFourCCBox();
3268    } else if (mIsVideo) {
3269        writeVideoFourCCBox();
3270    } else {
3271        writeMetadataFourCCBox();
3272    }
3273    mOwner->endBox();  // stsd
3274    writeSttsBox();
3275    if (mIsVideo) {
3276        writeCttsBox();
3277        writeStssBox();
3278    }
3279    writeStszBox();
3280    writeStscBox();
3281    writeStcoBox(use32BitOffset);
3282    mOwner->endBox();  // stbl
3283}
3284
3285void MPEG4Writer::Track::writeMetadataFourCCBox() {
3286    const char *mime;
3287    bool success = mMeta->findCString(kKeyMIMEType, &mime);
3288    CHECK(success);
3289    const char *fourcc = getFourCCForMime(mime);
3290    if (fourcc == NULL) {
3291        ALOGE("Unknown mime type '%s'.", mime);
3292        TRESPASS();
3293    }
3294    mOwner->beginBox(fourcc);    // TextMetaDataSampleEntry
3295    mOwner->writeCString(mime);  // metadata mime_format
3296    mOwner->endBox(); // mett
3297}
3298
3299void MPEG4Writer::Track::writeVideoFourCCBox() {
3300    const char *mime;
3301    bool success = mMeta->findCString(kKeyMIMEType, &mime);
3302    CHECK(success);
3303    const char *fourcc = getFourCCForMime(mime);
3304    if (fourcc == NULL) {
3305        ALOGE("Unknown mime type '%s'.", mime);
3306        TRESPASS();
3307    }
3308
3309    mOwner->beginBox(fourcc);        // video format
3310    mOwner->writeInt32(0);           // reserved
3311    mOwner->writeInt16(0);           // reserved
3312    mOwner->writeInt16(1);           // data ref index
3313    mOwner->writeInt16(0);           // predefined
3314    mOwner->writeInt16(0);           // reserved
3315    mOwner->writeInt32(0);           // predefined
3316    mOwner->writeInt32(0);           // predefined
3317    mOwner->writeInt32(0);           // predefined
3318
3319    int32_t width, height;
3320    success = mMeta->findInt32(kKeyWidth, &width);
3321    success = success && mMeta->findInt32(kKeyHeight, &height);
3322    CHECK(success);
3323
3324    mOwner->writeInt16(width);
3325    mOwner->writeInt16(height);
3326    mOwner->writeInt32(0x480000);    // horiz resolution
3327    mOwner->writeInt32(0x480000);    // vert resolution
3328    mOwner->writeInt32(0);           // reserved
3329    mOwner->writeInt16(1);           // frame count
3330    mOwner->writeInt8(0);            // compressor string length
3331    mOwner->write("                               ", 31);
3332    mOwner->writeInt16(0x18);        // depth
3333    mOwner->writeInt16(-1);          // predefined
3334
3335    if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_MPEG4, mime)) {
3336        writeMp4vEsdsBox();
3337    } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_H263, mime)) {
3338        writeD263Box();
3339    } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime)) {
3340        writeAvccBox();
3341    } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_HEVC, mime)) {
3342        writeHvccBox();
3343    }
3344
3345    writePaspBox();
3346    writeColrBox();
3347    mOwner->endBox();  // mp4v, s263 or avc1
3348}
3349
3350void MPEG4Writer::Track::writeColrBox() {
3351    ColorAspects aspects;
3352    memset(&aspects, 0, sizeof(aspects));
3353    // TRICKY: using | instead of || because we want to execute all findInt32-s
3354    if (mMeta->findInt32(kKeyColorPrimaries, (int32_t*)&aspects.mPrimaries)
3355            | mMeta->findInt32(kKeyTransferFunction, (int32_t*)&aspects.mTransfer)
3356            | mMeta->findInt32(kKeyColorMatrix, (int32_t*)&aspects.mMatrixCoeffs)
3357            | mMeta->findInt32(kKeyColorRange, (int32_t*)&aspects.mRange)) {
3358        int32_t primaries, transfer, coeffs;
3359        bool fullRange;
3360        ColorUtils::convertCodecColorAspectsToIsoAspects(
3361                aspects, &primaries, &transfer, &coeffs, &fullRange);
3362        mOwner->beginBox("colr");
3363        mOwner->writeFourcc("nclx");
3364        mOwner->writeInt16(primaries);
3365        mOwner->writeInt16(transfer);
3366        mOwner->writeInt16(coeffs);
3367        mOwner->writeInt8(int8_t(fullRange ? 0x80 : 0x0));
3368        mOwner->endBox(); // colr
3369    }
3370}
3371
3372void MPEG4Writer::Track::writeAudioFourCCBox() {
3373    const char *mime;
3374    bool success = mMeta->findCString(kKeyMIMEType, &mime);
3375    CHECK(success);
3376    const char *fourcc = getFourCCForMime(mime);
3377    if (fourcc == NULL) {
3378        ALOGE("Unknown mime type '%s'.", mime);
3379        TRESPASS();
3380    }
3381
3382    mOwner->beginBox(fourcc);        // audio format
3383    mOwner->writeInt32(0);           // reserved
3384    mOwner->writeInt16(0);           // reserved
3385    mOwner->writeInt16(0x1);         // data ref index
3386    mOwner->writeInt32(0);           // reserved
3387    mOwner->writeInt32(0);           // reserved
3388    int32_t nChannels;
3389    CHECK_EQ(true, mMeta->findInt32(kKeyChannelCount, &nChannels));
3390    mOwner->writeInt16(nChannels);   // channel count
3391    mOwner->writeInt16(16);          // sample size
3392    mOwner->writeInt16(0);           // predefined
3393    mOwner->writeInt16(0);           // reserved
3394
3395    int32_t samplerate;
3396    success = mMeta->findInt32(kKeySampleRate, &samplerate);
3397    CHECK(success);
3398    mOwner->writeInt32(samplerate << 16);
3399    if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AAC, mime)) {
3400        writeMp4aEsdsBox();
3401    } else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AMR_NB, mime) ||
3402               !strcasecmp(MEDIA_MIMETYPE_AUDIO_AMR_WB, mime)) {
3403        writeDamrBox();
3404    }
3405    mOwner->endBox();
3406}
3407
3408void MPEG4Writer::Track::writeMp4aEsdsBox() {
3409    mOwner->beginBox("esds");
3410    CHECK(mCodecSpecificData);
3411    CHECK_GT(mCodecSpecificDataSize, 0u);
3412
3413    // Make sure all sizes encode to a single byte.
3414    CHECK_LT(mCodecSpecificDataSize + 23, 128u);
3415
3416    mOwner->writeInt32(0);     // version=0, flags=0
3417    mOwner->writeInt8(0x03);   // ES_DescrTag
3418    mOwner->writeInt8(23 + mCodecSpecificDataSize);
3419    mOwner->writeInt16(0x0000);// ES_ID
3420    mOwner->writeInt8(0x00);
3421
3422    mOwner->writeInt8(0x04);   // DecoderConfigDescrTag
3423    mOwner->writeInt8(15 + mCodecSpecificDataSize);
3424    mOwner->writeInt8(0x40);   // objectTypeIndication ISO/IEC 14492-2
3425    mOwner->writeInt8(0x15);   // streamType AudioStream
3426
3427    mOwner->writeInt16(0x03);  // XXX
3428    mOwner->writeInt8(0x00);   // buffer size 24-bit (0x300)
3429
3430    int32_t avgBitrate = 0;
3431    (void)mMeta->findInt32(kKeyBitRate, &avgBitrate);
3432    int32_t maxBitrate = 0;
3433    (void)mMeta->findInt32(kKeyMaxBitRate, &maxBitrate);
3434    mOwner->writeInt32(maxBitrate);
3435    mOwner->writeInt32(avgBitrate);
3436
3437    mOwner->writeInt8(0x05);   // DecoderSpecificInfoTag
3438    mOwner->writeInt8(mCodecSpecificDataSize);
3439    mOwner->write(mCodecSpecificData, mCodecSpecificDataSize);
3440
3441    static const uint8_t kData2[] = {
3442        0x06,  // SLConfigDescriptorTag
3443        0x01,
3444        0x02
3445    };
3446    mOwner->write(kData2, sizeof(kData2));
3447
3448    mOwner->endBox();  // esds
3449}
3450
3451void MPEG4Writer::Track::writeMp4vEsdsBox() {
3452    CHECK(mCodecSpecificData);
3453    CHECK_GT(mCodecSpecificDataSize, 0u);
3454
3455    // Make sure all sizes encode to a single byte.
3456    CHECK_LT(23 + mCodecSpecificDataSize, 128u);
3457
3458    mOwner->beginBox("esds");
3459
3460    mOwner->writeInt32(0);    // version=0, flags=0
3461
3462    mOwner->writeInt8(0x03);  // ES_DescrTag
3463    mOwner->writeInt8(23 + mCodecSpecificDataSize);
3464    mOwner->writeInt16(0x0000);  // ES_ID
3465    mOwner->writeInt8(0x1f);
3466
3467    mOwner->writeInt8(0x04);  // DecoderConfigDescrTag
3468    mOwner->writeInt8(15 + mCodecSpecificDataSize);
3469    mOwner->writeInt8(0x20);  // objectTypeIndication ISO/IEC 14492-2
3470    mOwner->writeInt8(0x11);  // streamType VisualStream
3471
3472    static const uint8_t kData[] = {
3473        0x01, 0x77, 0x00, // buffer size 96000 bytes
3474    };
3475    mOwner->write(kData, sizeof(kData));
3476
3477    int32_t avgBitrate = 0;
3478    (void)mMeta->findInt32(kKeyBitRate, &avgBitrate);
3479    int32_t maxBitrate = 0;
3480    (void)mMeta->findInt32(kKeyMaxBitRate, &maxBitrate);
3481    mOwner->writeInt32(maxBitrate);
3482    mOwner->writeInt32(avgBitrate);
3483
3484    mOwner->writeInt8(0x05);  // DecoderSpecificInfoTag
3485
3486    mOwner->writeInt8(mCodecSpecificDataSize);
3487    mOwner->write(mCodecSpecificData, mCodecSpecificDataSize);
3488
3489    static const uint8_t kData2[] = {
3490        0x06,  // SLConfigDescriptorTag
3491        0x01,
3492        0x02
3493    };
3494    mOwner->write(kData2, sizeof(kData2));
3495
3496    mOwner->endBox();  // esds
3497}
3498
3499void MPEG4Writer::Track::writeTkhdBox(uint32_t now) {
3500    mOwner->beginBox("tkhd");
3501    // Flags = 7 to indicate that the track is enabled, and
3502    // part of the presentation
3503    mOwner->writeInt32(0x07);          // version=0, flags=7
3504    mOwner->writeInt32(now);           // creation time
3505    mOwner->writeInt32(now);           // modification time
3506    mOwner->writeInt32(mTrackId);      // track id starts with 1
3507    mOwner->writeInt32(0);             // reserved
3508    int64_t trakDurationUs = getDurationUs();
3509    int32_t mvhdTimeScale = mOwner->getTimeScale();
3510    int32_t tkhdDuration =
3511        (trakDurationUs * mvhdTimeScale + 5E5) / 1E6;
3512    mOwner->writeInt32(tkhdDuration);  // in mvhd timescale
3513    mOwner->writeInt32(0);             // reserved
3514    mOwner->writeInt32(0);             // reserved
3515    mOwner->writeInt16(0);             // layer
3516    mOwner->writeInt16(0);             // alternate group
3517    mOwner->writeInt16(mIsAudio ? 0x100 : 0);  // volume
3518    mOwner->writeInt16(0);             // reserved
3519
3520    mOwner->writeCompositionMatrix(mRotation);       // matrix
3521
3522    if (!mIsVideo) {
3523        mOwner->writeInt32(0);
3524        mOwner->writeInt32(0);
3525    } else {
3526        int32_t width, height;
3527        bool success = mMeta->findInt32(kKeyDisplayWidth, &width);
3528        success = success && mMeta->findInt32(kKeyDisplayHeight, &height);
3529
3530        // Use width/height if display width/height are not present.
3531        if (!success) {
3532            success = mMeta->findInt32(kKeyWidth, &width);
3533            success = success && mMeta->findInt32(kKeyHeight, &height);
3534        }
3535        CHECK(success);
3536
3537        mOwner->writeInt32(width << 16);   // 32-bit fixed-point value
3538        mOwner->writeInt32(height << 16);  // 32-bit fixed-point value
3539    }
3540    mOwner->endBox();  // tkhd
3541}
3542
3543void MPEG4Writer::Track::writeVmhdBox() {
3544    mOwner->beginBox("vmhd");
3545    mOwner->writeInt32(0x01);        // version=0, flags=1
3546    mOwner->writeInt16(0);           // graphics mode
3547    mOwner->writeInt16(0);           // opcolor
3548    mOwner->writeInt16(0);
3549    mOwner->writeInt16(0);
3550    mOwner->endBox();
3551}
3552
3553void MPEG4Writer::Track::writeSmhdBox() {
3554    mOwner->beginBox("smhd");
3555    mOwner->writeInt32(0);           // version=0, flags=0
3556    mOwner->writeInt16(0);           // balance
3557    mOwner->writeInt16(0);           // reserved
3558    mOwner->endBox();
3559}
3560
3561void MPEG4Writer::Track::writeNmhdBox() {
3562    mOwner->beginBox("nmhd");
3563    mOwner->writeInt32(0);           // version=0, flags=0
3564    mOwner->endBox();
3565}
3566
3567void MPEG4Writer::Track::writeHdlrBox() {
3568    mOwner->beginBox("hdlr");
3569    mOwner->writeInt32(0);             // version=0, flags=0
3570    mOwner->writeInt32(0);             // component type: should be mhlr
3571    mOwner->writeFourcc(mIsAudio ? "soun" : (mIsVideo ? "vide" : "meta"));  // component subtype
3572    mOwner->writeInt32(0);             // reserved
3573    mOwner->writeInt32(0);             // reserved
3574    mOwner->writeInt32(0);             // reserved
3575    // Removing "r" for the name string just makes the string 4 byte aligned
3576    mOwner->writeCString(mIsAudio ? "SoundHandle": (mIsVideo ? "VideoHandle" : "MetadHandle"));
3577    mOwner->endBox();
3578}
3579
3580void MPEG4Writer::Track::writeMdhdBox(uint32_t now) {
3581    int64_t trakDurationUs = getDurationUs();
3582    int64_t mdhdDuration = (trakDurationUs * mTimeScale + 5E5) / 1E6;
3583    mOwner->beginBox("mdhd");
3584
3585    if (mdhdDuration > UINT32_MAX) {
3586        mOwner->writeInt32((1 << 24));            // version=1, flags=0
3587        mOwner->writeInt64((int64_t)now);         // creation time
3588        mOwner->writeInt64((int64_t)now);         // modification time
3589        mOwner->writeInt32(mTimeScale);           // media timescale
3590        mOwner->writeInt64(mdhdDuration);         // media timescale
3591    } else {
3592        mOwner->writeInt32(0);                      // version=0, flags=0
3593        mOwner->writeInt32(now);                    // creation time
3594        mOwner->writeInt32(now);                    // modification time
3595        mOwner->writeInt32(mTimeScale);             // media timescale
3596        mOwner->writeInt32((int32_t)mdhdDuration);  // use media timescale
3597    }
3598    // Language follows the three letter standard ISO-639-2/T
3599    // 'e', 'n', 'g' for "English", for instance.
3600    // Each character is packed as the difference between its ASCII value and 0x60.
3601    // For "English", these are 00101, 01110, 00111.
3602    // XXX: Where is the padding bit located: 0x15C7?
3603    const char *lang = NULL;
3604    int16_t langCode = 0;
3605    if (mMeta->findCString(kKeyMediaLanguage, &lang) && lang && strnlen(lang, 3) > 2) {
3606        langCode = ((lang[0] & 0x1f) << 10) | ((lang[1] & 0x1f) << 5) | (lang[2] & 0x1f);
3607    }
3608    mOwner->writeInt16(langCode);      // language code
3609    mOwner->writeInt16(0);             // predefined
3610    mOwner->endBox();
3611}
3612
3613void MPEG4Writer::Track::writeDamrBox() {
3614    // 3gpp2 Spec AMRSampleEntry fields
3615    mOwner->beginBox("damr");
3616    mOwner->writeCString("   ");  // vendor: 4 bytes
3617    mOwner->writeInt8(0);         // decoder version
3618    mOwner->writeInt16(0x83FF);   // mode set: all enabled
3619    mOwner->writeInt8(0);         // mode change period
3620    mOwner->writeInt8(1);         // frames per sample
3621    mOwner->endBox();
3622}
3623
3624void MPEG4Writer::Track::writeUrlBox() {
3625    // The table index here refers to the sample description index
3626    // in the sample table entries.
3627    mOwner->beginBox("url ");
3628    mOwner->writeInt32(1);  // version=0, flags=1 (self-contained)
3629    mOwner->endBox();  // url
3630}
3631
3632void MPEG4Writer::Track::writeDrefBox() {
3633    mOwner->beginBox("dref");
3634    mOwner->writeInt32(0);  // version=0, flags=0
3635    mOwner->writeInt32(1);  // entry count (either url or urn)
3636    writeUrlBox();
3637    mOwner->endBox();  // dref
3638}
3639
3640void MPEG4Writer::Track::writeDinfBox() {
3641    mOwner->beginBox("dinf");
3642    writeDrefBox();
3643    mOwner->endBox();  // dinf
3644}
3645
3646void MPEG4Writer::Track::writeAvccBox() {
3647    CHECK(mCodecSpecificData);
3648    CHECK_GE(mCodecSpecificDataSize, 5u);
3649
3650    // Patch avcc's lengthSize field to match the number
3651    // of bytes we use to indicate the size of a nal unit.
3652    uint8_t *ptr = (uint8_t *)mCodecSpecificData;
3653    ptr[4] = (ptr[4] & 0xfc) | (mOwner->useNalLengthFour() ? 3 : 1);
3654    mOwner->beginBox("avcC");
3655    mOwner->write(mCodecSpecificData, mCodecSpecificDataSize);
3656    mOwner->endBox();  // avcC
3657}
3658
3659
3660void MPEG4Writer::Track::writeHvccBox() {
3661    CHECK(mCodecSpecificData);
3662    CHECK_GE(mCodecSpecificDataSize, 5u);
3663
3664    // Patch avcc's lengthSize field to match the number
3665    // of bytes we use to indicate the size of a nal unit.
3666    uint8_t *ptr = (uint8_t *)mCodecSpecificData;
3667    ptr[21] = (ptr[21] & 0xfc) | (mOwner->useNalLengthFour() ? 3 : 1);
3668    mOwner->beginBox("hvcC");
3669    mOwner->write(mCodecSpecificData, mCodecSpecificDataSize);
3670    mOwner->endBox();  // hvcC
3671}
3672
3673void MPEG4Writer::Track::writeD263Box() {
3674    mOwner->beginBox("d263");
3675    mOwner->writeInt32(0);  // vendor
3676    mOwner->writeInt8(0);   // decoder version
3677    mOwner->writeInt8(10);  // level: 10
3678    mOwner->writeInt8(0);   // profile: 0
3679    mOwner->endBox();  // d263
3680}
3681
3682// This is useful if the pixel is not square
3683void MPEG4Writer::Track::writePaspBox() {
3684    mOwner->beginBox("pasp");
3685    mOwner->writeInt32(1 << 16);  // hspacing
3686    mOwner->writeInt32(1 << 16);  // vspacing
3687    mOwner->endBox();  // pasp
3688}
3689
3690int64_t MPEG4Writer::Track::getStartTimeOffsetTimeUs() const {
3691    int64_t trackStartTimeOffsetUs = 0;
3692    int64_t moovStartTimeUs = mOwner->getStartTimestampUs();
3693    if (mStartTimestampUs != -1 && mStartTimestampUs != moovStartTimeUs) {
3694        CHECK_GT(mStartTimestampUs, moovStartTimeUs);
3695        trackStartTimeOffsetUs = mStartTimestampUs - moovStartTimeUs;
3696    }
3697    return trackStartTimeOffsetUs;
3698}
3699
3700int32_t MPEG4Writer::Track::getStartTimeOffsetScaledTime() const {
3701    return (getStartTimeOffsetTimeUs() * mTimeScale + 500000LL) / 1000000LL;
3702}
3703
3704void MPEG4Writer::Track::writeSttsBox() {
3705    mOwner->beginBox("stts");
3706    mOwner->writeInt32(0);  // version=0, flags=0
3707    if (mMinCttsOffsetTicks == mMaxCttsOffsetTicks) {
3708        // For non-vdeio tracks or video tracks without ctts table,
3709        // adjust duration of first sample for tracks to account for
3710        // first sample not starting at the media start time.
3711        // TODO: consider signaling this using some offset
3712        // as this is not quite correct.
3713        uint32_t duration;
3714        CHECK(mSttsTableEntries->get(duration, 1));
3715        duration = htonl(duration);  // Back to host byte order
3716        mSttsTableEntries->set(htonl(duration + getStartTimeOffsetScaledTime()), 1);
3717    }
3718    mSttsTableEntries->write(mOwner);
3719    mOwner->endBox();  // stts
3720}
3721
3722void MPEG4Writer::Track::writeCttsBox() {
3723    // There is no B frame at all
3724    if (mMinCttsOffsetTicks == mMaxCttsOffsetTicks) {
3725        return;
3726    }
3727
3728    // Do not write ctts box when there is no need to have it.
3729    if (mCttsTableEntries->count() == 0) {
3730        return;
3731    }
3732
3733    ALOGV("ctts box has %d entries with range [%" PRId64 ", %" PRId64 "]",
3734            mCttsTableEntries->count(), mMinCttsOffsetTicks, mMaxCttsOffsetTicks);
3735
3736    mOwner->beginBox("ctts");
3737    mOwner->writeInt32(0);  // version=0, flags=0
3738    int64_t deltaTimeUs = kMaxCttsOffsetTimeUs - getStartTimeOffsetTimeUs();
3739    int64_t delta = (deltaTimeUs * mTimeScale + 500000LL) / 1000000LL;
3740    mCttsTableEntries->adjustEntries([delta](size_t /* ix */, uint32_t (&value)[2]) {
3741        // entries are <count, ctts> pairs; adjust only ctts
3742        uint32_t duration = htonl(value[1]); // back to host byte order
3743        // Prevent overflow and underflow
3744        if (delta > duration) {
3745            duration = 0;
3746        } else if (delta < 0 && UINT32_MAX + delta < duration) {
3747            duration = UINT32_MAX;
3748        } else {
3749            duration -= delta;
3750        }
3751        value[1] = htonl(duration);
3752    });
3753    mCttsTableEntries->write(mOwner);
3754    mOwner->endBox();  // ctts
3755}
3756
3757void MPEG4Writer::Track::writeStssBox() {
3758    mOwner->beginBox("stss");
3759    mOwner->writeInt32(0);  // version=0, flags=0
3760    mStssTableEntries->write(mOwner);
3761    mOwner->endBox();  // stss
3762}
3763
3764void MPEG4Writer::Track::writeStszBox() {
3765    mOwner->beginBox("stsz");
3766    mOwner->writeInt32(0);  // version=0, flags=0
3767    mOwner->writeInt32(0);
3768    mStszTableEntries->write(mOwner);
3769    mOwner->endBox();  // stsz
3770}
3771
3772void MPEG4Writer::Track::writeStscBox() {
3773    mOwner->beginBox("stsc");
3774    mOwner->writeInt32(0);  // version=0, flags=0
3775    mStscTableEntries->write(mOwner);
3776    mOwner->endBox();  // stsc
3777}
3778
3779void MPEG4Writer::Track::writeStcoBox(bool use32BitOffset) {
3780    mOwner->beginBox(use32BitOffset? "stco": "co64");
3781    mOwner->writeInt32(0);  // version=0, flags=0
3782    if (use32BitOffset) {
3783        mStcoTableEntries->write(mOwner);
3784    } else {
3785        mCo64TableEntries->write(mOwner);
3786    }
3787    mOwner->endBox();  // stco or co64
3788}
3789
3790void MPEG4Writer::writeUdtaBox() {
3791    beginBox("udta");
3792    writeGeoDataBox();
3793    endBox();
3794}
3795
3796void MPEG4Writer::writeHdlr() {
3797    beginBox("hdlr");
3798    writeInt32(0); // Version, Flags
3799    writeInt32(0); // Predefined
3800    writeFourcc("mdta");
3801    writeInt32(0); // Reserved[0]
3802    writeInt32(0); // Reserved[1]
3803    writeInt32(0); // Reserved[2]
3804    writeInt8(0);  // Name (empty)
3805    endBox();
3806}
3807
3808void MPEG4Writer::writeKeys() {
3809    size_t count = mMetaKeys->countEntries();
3810
3811    beginBox("keys");
3812    writeInt32(0);     // Version, Flags
3813    writeInt32(count); // Entry_count
3814    for (size_t i = 0; i < count; i++) {
3815        AMessage::Type type;
3816        const char *key = mMetaKeys->getEntryNameAt(i, &type);
3817        size_t n = strlen(key);
3818        writeInt32(n + 8);
3819        writeFourcc("mdta");
3820        write(key, n); // write without the \0
3821    }
3822    endBox();
3823}
3824
3825void MPEG4Writer::writeIlst() {
3826    size_t count = mMetaKeys->countEntries();
3827
3828    beginBox("ilst");
3829    for (size_t i = 0; i < count; i++) {
3830        beginBox(i + 1); // key id (1-based)
3831        beginBox("data");
3832        AMessage::Type type;
3833        const char *key = mMetaKeys->getEntryNameAt(i, &type);
3834        switch (type) {
3835            case AMessage::kTypeString:
3836            {
3837                AString val;
3838                CHECK(mMetaKeys->findString(key, &val));
3839                writeInt32(1); // type = UTF8
3840                writeInt32(0); // default country/language
3841                write(val.c_str(), strlen(val.c_str())); // write without \0
3842                break;
3843            }
3844
3845            case AMessage::kTypeFloat:
3846            {
3847                float val;
3848                CHECK(mMetaKeys->findFloat(key, &val));
3849                writeInt32(23); // type = float32
3850                writeInt32(0);  // default country/language
3851                writeInt32(*reinterpret_cast<int32_t *>(&val));
3852                break;
3853            }
3854
3855            case AMessage::kTypeInt32:
3856            {
3857                int32_t val;
3858                CHECK(mMetaKeys->findInt32(key, &val));
3859                writeInt32(67); // type = signed int32
3860                writeInt32(0);  // default country/language
3861                writeInt32(val);
3862                break;
3863            }
3864
3865            default:
3866            {
3867                ALOGW("Unsupported key type, writing 0 instead");
3868                writeInt32(77); // type = unsigned int32
3869                writeInt32(0);  // default country/language
3870                writeInt32(0);
3871                break;
3872            }
3873        }
3874        endBox(); // data
3875        endBox(); // key id
3876    }
3877    endBox(); // ilst
3878}
3879
3880void MPEG4Writer::writeMetaBox() {
3881    size_t count = mMetaKeys->countEntries();
3882    if (count == 0) {
3883        return;
3884    }
3885
3886    beginBox("meta");
3887    writeHdlr();
3888    writeKeys();
3889    writeIlst();
3890    endBox();
3891}
3892
3893/*
3894 * Geodata is stored according to ISO-6709 standard.
3895 */
3896void MPEG4Writer::writeGeoDataBox() {
3897    beginBox("\xA9xyz");
3898    /*
3899     * For historical reasons, any user data start
3900     * with "\0xA9", must be followed by its assoicated
3901     * language code.
3902     * 0x0012: text string length
3903     * 0x15c7: lang (locale) code: en
3904     */
3905    writeInt32(0x001215c7);
3906    writeLatitude(mLatitudex10000);
3907    writeLongitude(mLongitudex10000);
3908    writeInt8(0x2F);
3909    endBox();
3910}
3911
3912}  // namespace android
3913