summaryrefslogtreecommitdiffstats
path: root/media/libstagefright/FragmentedMP4Extractor.cpp
blob: 82712efd5ef308a1a9a0974d0a76e9fdc8b29d88 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

//#define LOG_NDEBUG 0
#define LOG_TAG "FragmentedMP4Extractor"
#include <utils/Log.h>

#include "include/FragmentedMP4Extractor.h"
#include "include/SampleTable.h"
#include "include/ESDS.h"

#include <arpa/inet.h>

#include <ctype.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

#include <cutils/properties.h> // for property_get

#include <media/stagefright/foundation/ABitReader.h>
#include <media/stagefright/foundation/ABuffer.h>
#include <media/stagefright/foundation/ADebug.h>
#include <media/stagefright/foundation/AMessage.h>
#include <media/stagefright/DataSource.h>
#include <media/stagefright/MediaBuffer.h>
#include <media/stagefright/MediaBufferGroup.h>
#include <media/stagefright/MediaDefs.h>
#include <media/stagefright/MediaSource.h>
#include <media/stagefright/MetaData.h>
#include <media/stagefright/Utils.h>
#include <utils/String8.h>

namespace android {

class FragmentedMPEG4Source : public MediaSource {
public:
    // Caller retains ownership of the Parser
    FragmentedMPEG4Source(bool audio,
                const sp<MetaData> &format,
                const sp<FragmentedMP4Parser> &parser,
                const sp<FragmentedMP4Extractor> &extractor);

    virtual status_t start(MetaData *params = NULL);
    virtual status_t stop();

    virtual sp<MetaData> getFormat();

    virtual status_t read(
            MediaBuffer **buffer, const ReadOptions *options = NULL);

protected:
    virtual ~FragmentedMPEG4Source();

private:
    Mutex mLock;

    sp<MetaData> mFormat;
    sp<FragmentedMP4Parser> mParser;
    sp<FragmentedMP4Extractor> mExtractor;
    bool mIsAudioTrack;
    uint32_t mCurrentSampleIndex;

    bool mIsAVC;
    size_t mNALLengthSize;

    bool mStarted;

    MediaBufferGroup *mGroup;

    bool mWantsNALFragments;

    uint8_t *mSrcBuffer;

    FragmentedMPEG4Source(const FragmentedMPEG4Source &);
    FragmentedMPEG4Source &operator=(const FragmentedMPEG4Source &);
};


FragmentedMP4Extractor::FragmentedMP4Extractor(const sp<DataSource> &source)
    : mLooper(new ALooper),
      mParser(new FragmentedMP4Parser()),
      mDataSource(source),
      mInitCheck(NO_INIT),
      mFileMetaData(new MetaData) {
    ALOGV("FragmentedMP4Extractor");
    mLooper->registerHandler(mParser);
    mLooper->start(false /* runOnCallingThread */);
    mParser->start(mDataSource);

    bool hasVideo = mParser->getFormat(false /* audio */, true /* synchronous */) != NULL;
    bool hasAudio = mParser->getFormat(true /* audio */, true /* synchronous */) != NULL;

    ALOGV("number of tracks: %d", countTracks());

    if (hasVideo) {
        mFileMetaData->setCString(
                kKeyMIMEType, MEDIA_MIMETYPE_CONTAINER_MPEG4);
    } else if (hasAudio) {
        mFileMetaData->setCString(kKeyMIMEType, "audio/mp4");
    } else {
        ALOGE("no audio and no video, no idea what file type this is");
    }
    // tracks are numbered such that video track is first, audio track is second
    if (hasAudio && hasVideo) {
        mTrackCount = 2;
        mAudioTrackIndex = 1;
    } else if (hasAudio) {
        mTrackCount = 1;
        mAudioTrackIndex = 0;
    } else if (hasVideo) {
        mTrackCount = 1;
        mAudioTrackIndex = -1;
    } else {
        mTrackCount = 0;
        mAudioTrackIndex = -1;
    }
}

FragmentedMP4Extractor::~FragmentedMP4Extractor() {
    ALOGV("~FragmentedMP4Extractor");
    mLooper->stop();
}

uint32_t FragmentedMP4Extractor::flags() const {
    return CAN_PAUSE |
            (mParser->isSeekable() ? (CAN_SEEK_BACKWARD | CAN_SEEK_FORWARD | CAN_SEEK) : 0);
}

sp<MetaData> FragmentedMP4Extractor::getMetaData() {
    return mFileMetaData;
}

size_t FragmentedMP4Extractor::countTracks() {
    return mTrackCount;
}


sp<MetaData> FragmentedMP4Extractor::getTrackMetaData(
        size_t index, uint32_t flags) {
    if (index >= countTracks()) {
        return NULL;
    }

    sp<AMessage> msg = mParser->getFormat(index == mAudioTrackIndex, true /* synchronous */);

    if (msg == NULL) {
        ALOGV("got null format for track %d", index);
        return NULL;
    }

    sp<MetaData> meta = new MetaData();
    convertMessageToMetaData(msg, meta);
    return meta;
}

static void MakeFourCCString(uint32_t x, char *s) {
    s[0] = x >> 24;
    s[1] = (x >> 16) & 0xff;
    s[2] = (x >> 8) & 0xff;
    s[3] = x & 0xff;
    s[4] = '\0';
}

sp<MediaSource> FragmentedMP4Extractor::getTrack(size_t index) {
    if (index >= countTracks()) {
        return NULL;
    }
    return new FragmentedMPEG4Source(index == mAudioTrackIndex, getTrackMetaData(index, 0), mParser, this);
}


////////////////////////////////////////////////////////////////////////////////

FragmentedMPEG4Source::FragmentedMPEG4Source(
        bool audio,
        const sp<MetaData> &format,
        const sp<FragmentedMP4Parser> &parser,
        const sp<FragmentedMP4Extractor> &extractor)
    : mFormat(format),
      mParser(parser),
      mExtractor(extractor),
      mIsAudioTrack(audio),
      mStarted(false),
      mGroup(NULL),
      mWantsNALFragments(false),
      mSrcBuffer(NULL) {
}

FragmentedMPEG4Source::~FragmentedMPEG4Source() {
    if (mStarted) {
        stop();
    }
}

status_t FragmentedMPEG4Source::start(MetaData *params) {
    Mutex::Autolock autoLock(mLock);

    CHECK(!mStarted);

    int32_t val;
    if (params && params->findInt32(kKeyWantsNALFragments, &val)
        && val != 0) {
        mWantsNALFragments = true;
    } else {
        mWantsNALFragments = false;
    }
    ALOGV("caller wants NAL fragments: %s", mWantsNALFragments ? "yes" : "no");

    mGroup = new MediaBufferGroup;

    int32_t max_size = 65536;
    // XXX CHECK(mFormat->findInt32(kKeyMaxInputSize, &max_size));

    mGroup->add_buffer(new MediaBuffer(max_size));

    mSrcBuffer = new uint8_t[max_size];

    mStarted = true;

    return OK;
}

status_t FragmentedMPEG4Source::stop() {
    Mutex::Autolock autoLock(mLock);

    CHECK(mStarted);

    delete[] mSrcBuffer;
    mSrcBuffer = NULL;

    delete mGroup;
    mGroup = NULL;

    mStarted = false;
    mCurrentSampleIndex = 0;

    return OK;
}

sp<MetaData> FragmentedMPEG4Source::getFormat() {
    Mutex::Autolock autoLock(mLock);

    return mFormat;
}


status_t FragmentedMPEG4Source::read(
        MediaBuffer **out, const ReadOptions *options) {
    int64_t seekTimeUs;
    ReadOptions::SeekMode mode;
    if (options && options->getSeekTo(&seekTimeUs, &mode)) {
        mParser->seekTo(mIsAudioTrack, seekTimeUs);
    }
    MediaBuffer *buffer = NULL;
    mGroup->acquire_buffer(&buffer);
    sp<ABuffer> parseBuffer;

    status_t ret = mParser->dequeueAccessUnit(mIsAudioTrack, &parseBuffer, true /* synchronous */);
    if (ret != OK) {
        buffer->release();
        ALOGV("returning %d", ret);
        return ret;
    }
    sp<AMessage> meta = parseBuffer->meta();
    int64_t timeUs;
    CHECK(meta->findInt64("timeUs", &timeUs));
    buffer->meta_data()->setInt64(kKeyTime, timeUs);
    buffer->set_range(0, parseBuffer->size());
    memcpy(buffer->data(), parseBuffer->data(), parseBuffer->size());
    *out = buffer;
    return OK;
}


static bool isCompatibleBrand(uint32_t fourcc) {
    static const uint32_t kCompatibleBrands[] = {
        FOURCC('i', 's', 'o', 'm'),
        FOURCC('i', 's', 'o', '2'),
        FOURCC('a', 'v', 'c', '1'),
        FOURCC('3', 'g', 'p', '4'),
        FOURCC('m', 'p', '4', '1'),
        FOURCC('m', 'p', '4', '2'),

        // Won't promise that the following file types can be played.
        // Just give these file types a chance.
        FOURCC('q', 't', ' ', ' '),  // Apple's QuickTime
        FOURCC('M', 'S', 'N', 'V'),  // Sony's PSP

        FOURCC('3', 'g', '2', 'a'),  // 3GPP2
        FOURCC('3', 'g', '2', 'b'),
    };

    for (size_t i = 0;
         i < sizeof(kCompatibleBrands) / sizeof(kCompatibleBrands[0]);
         ++i) {
        if (kCompatibleBrands[i] == fourcc) {
            return true;
        }
    }

    return false;
}

// Attempt to actually parse the 'ftyp' atom and determine if a suitable
// compatible brand is present.
// Also try to identify where this file's metadata ends
// (end of the 'moov' atom) and report it to the caller as part of
// the metadata.
static bool Sniff(
        const sp<DataSource> &source, String8 *mimeType, float *confidence,
        sp<AMessage> *meta) {
    // We scan up to 128k bytes to identify this file as an MP4.
    static const off64_t kMaxScanOffset = 128ll * 1024ll;

    off64_t offset = 0ll;
    bool foundGoodFileType = false;
    bool isFragmented = false;
    off64_t moovAtomEndOffset = -1ll;
    bool done = false;

    while (!done && offset < kMaxScanOffset) {
        uint32_t hdr[2];
        if (source->readAt(offset, hdr, 8) < 8) {
            return false;
        }

        uint64_t chunkSize = ntohl(hdr[0]);
        uint32_t chunkType = ntohl(hdr[1]);
        off64_t chunkDataOffset = offset + 8;

        if (chunkSize == 1) {
            if (source->readAt(offset + 8, &chunkSize, 8) < 8) {
                return false;
            }

            chunkSize = ntoh64(chunkSize);
            chunkDataOffset += 8;

            if (chunkSize < 16) {
                // The smallest valid chunk is 16 bytes long in this case.
                return false;
            }
        } else if (chunkSize < 8) {
            // The smallest valid chunk is 8 bytes long.
            return false;
        }

        off64_t chunkDataSize = offset + chunkSize - chunkDataOffset;

        char chunkstring[5];
        MakeFourCCString(chunkType, chunkstring);
        ALOGV("saw chunk type %s, size %lld @ %lld", chunkstring, chunkSize, offset);
        switch (chunkType) {
            case FOURCC('f', 't', 'y', 'p'):
            {
                if (chunkDataSize < 8) {
                    return false;
                }

                uint32_t numCompatibleBrands = (chunkDataSize - 8) / 4;
                for (size_t i = 0; i < numCompatibleBrands + 2; ++i) {
                    if (i == 1) {
                        // Skip this index, it refers to the minorVersion,
                        // not a brand.
                        continue;
                    }

                    uint32_t brand;
                    if (source->readAt(
                                chunkDataOffset + 4 * i, &brand, 4) < 4) {
                        return false;
                    }

                    brand = ntohl(brand);
                    char brandstring[5];
                    MakeFourCCString(brand, brandstring);
                    ALOGV("Brand: %s", brandstring);

                    if (isCompatibleBrand(brand)) {
                        foundGoodFileType = true;
                        break;
                    }
                }

                if (!foundGoodFileType) {
                    return false;
                }

                break;
            }

            case FOURCC('m', 'o', 'o', 'v'):
            {
                moovAtomEndOffset = offset + chunkSize;
                break;
            }

            case FOURCC('m', 'o', 'o', 'f'):
            {
                // this is kind of broken, since we might not actually find a
                // moof box in the first 128k.
                isFragmented = true;
                done = true;
                break;
            }

            default:
                break;
        }

        offset += chunkSize;
    }

    if (!foundGoodFileType || !isFragmented) {
        return false;
    }

    *mimeType = MEDIA_MIMETYPE_CONTAINER_MPEG4;
    *confidence = 0.5f; // slightly more than MPEG4Extractor

    if (moovAtomEndOffset >= 0) {
        *meta = new AMessage;
        (*meta)->setInt64("meta-data-size", moovAtomEndOffset);
        (*meta)->setInt32("fragmented", 1); // tell MediaExtractor what to instantiate

        ALOGV("found metadata size: %lld", moovAtomEndOffset);
    }

    return true;
}

// used by DataSource::RegisterDefaultSniffers
bool SniffFragmentedMP4(
        const sp<DataSource> &source, String8 *mimeType, float *confidence,
        sp<AMessage> *meta) {
    ALOGV("SniffFragmentedMP4");
    char prop[PROPERTY_VALUE_MAX];
    if (property_get("media.stagefright.use-fragmp4", prop, NULL)
            && (!strcmp(prop, "1") || !strcasecmp(prop, "true"))) {
        return Sniff(source, mimeType, confidence, meta);
    }

    return false;
}

}  // namespace android