OSDN Git Service

Merge branch 'jb-x86-tw' into jb-x86
[android-x86/external-stagefright-plugins.git] / libstagefright / FFmpegExtractor / FFmpegExtractor.cpp
1 /*
2  * Copyright 2012 Michael Chen <omxcodec@gmail.com>
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 "FFmpegExtractor"
19 #include <utils/Log.h>
20
21 #include <stdint.h>
22 #include <limits.h> /* INT_MAX */
23 #include <inttypes.h>
24
25 #include <media/stagefright/foundation/ABitReader.h>
26 #include <media/stagefright/foundation/ABuffer.h>
27 #include <media/stagefright/foundation/ADebug.h>
28 #include <media/stagefright/foundation/AMessage.h>
29 #include <media/stagefright/foundation/hexdump.h>
30 #include <media/stagefright/DataSource.h>
31 #include <media/stagefright/MediaBuffer.h>
32 #include <media/stagefright/foundation/ADebug.h>
33 #include <media/stagefright/MediaDefs.h>
34 #include <media/stagefright/MediaErrors.h>
35 #include <media/stagefright/MediaSource.h>
36 #include <media/stagefright/MetaData.h>
37 #include <media/stagefright/Utils.h>
38 #include <cutils/properties.h>
39 #include <utils/String8.h>
40 #include <utils/misc.h>
41
42 #include "include/avc_utils.h"
43 #include "utils/ffmpeg_utils.h"
44 #include "utils/ffmpeg_cmdutils.h"
45 #include "FFmpegExtractor.h"
46
47 #define MAX_QUEUE_SIZE (15 * 1024 * 1024)
48 #define MIN_AUDIOQ_SIZE (20 * 16 * 1024)
49 #define MIN_FRAMES 5
50 #define EXTRACTOR_MAX_PROBE_PACKETS 200
51 #define FF_MAX_EXTRADATA_SIZE ((1 << 28) - FF_INPUT_BUFFER_PADDING_SIZE)
52
53 //debug
54 #define DEBUG_READ_ENTRY           0
55 #define DEBUG_DISABLE_VIDEO        0
56 #define DEBUG_DISABLE_AUDIO        0
57 #define WAIT_KEY_PACKET_AFTER_SEEK 1
58 #define DISABLE_NAL_TO_ANNEXB      0
59 #define DEBUG_PKT                  0
60
61 enum {
62     NO_SEEK = 0,
63     SEEK,
64 };
65
66 static AVPacket flush_pkt;
67
68 namespace android {
69
70 struct FFmpegExtractor::Track : public MediaSource {
71     Track(FFmpegExtractor *extractor, sp<MetaData> meta, bool isAVC,
72           AVStream *stream, PacketQueue *queue);
73
74     virtual status_t start(MetaData *params);
75     virtual status_t stop();
76     virtual sp<MetaData> getFormat();
77
78     virtual status_t read(
79             MediaBuffer **buffer, const ReadOptions *options);
80
81 protected:
82     virtual ~Track();
83
84 private:
85     friend struct FFmpegExtractor;
86
87     FFmpegExtractor *mExtractor;
88     sp<MetaData> mMeta;
89
90     enum AVMediaType mMediaType;
91
92     mutable Mutex mLock;
93
94     bool mIsAVC;
95     size_t mNALLengthSize;
96     bool mNal2AnnexB;
97
98     AVStream *mStream;
99     PacketQueue *mQueue;
100
101     int64_t mFirstKeyPktTimestamp;
102
103     DISALLOW_EVIL_CONSTRUCTORS(Track);
104 };
105
106 ////////////////////////////////////////////////////////////////////////////////
107
108 FFmpegExtractor::FFmpegExtractor(const sp<DataSource> &source)
109     : mDataSource(source),
110       mInitCheck(NO_INIT),
111       mFFmpegInited(false),
112       mFormatCtx(NULL),
113       mReaderThreadStarted(false) {
114     ALOGV("FFmpegExtractor::FFmpegExtractor");
115
116     buildFileName(source);
117
118     int err = initStreams();
119     if (err < 0) {
120         ALOGE("failed to init ffmpeg");
121         return;
122     }
123
124     // start reader here, as we want to extract extradata from bitstream if no extradata
125     startReaderThread();
126
127     while(mProbePkts <= EXTRACTOR_MAX_PROBE_PACKETS && !mEOF &&
128         (mFormatCtx->pb ? !mFormatCtx->pb->error : 1) &&
129         (mDefersToCreateVideoTrack || mDefersToCreateAudioTrack)) {
130         // FIXME, i am so lazy! Should use pthread_cond_wait to wait conditions
131         usleep(5000);
132     }
133
134     ALOGV("mProbePkts: %d, mEOF: %d, pb->error(if has): %d, mDefersToCreateVideoTrack: %d, mDefersToCreateAudioTrack: %d",
135         mProbePkts, mEOF, mFormatCtx->pb ? mFormatCtx->pb->error : 0, mDefersToCreateVideoTrack, mDefersToCreateAudioTrack);
136
137     mInitCheck = OK;
138 }
139
140 FFmpegExtractor::~FFmpegExtractor() {
141     ALOGV("FFmpegExtractor::~FFmpegExtractor");
142
143     // stop reader here if no track!
144     stopReaderThread();
145
146     deInitStreams();
147 }
148
149 size_t FFmpegExtractor::countTracks() {
150     return mInitCheck == OK ? mTracks.size() : 0;
151 }
152
153 sp<MediaSource> FFmpegExtractor::getTrack(size_t index) {
154     ALOGV("FFmpegExtractor::getTrack[%d]", index);
155
156     if (mInitCheck != OK) {
157         return NULL;
158     }
159
160     if (index >= mTracks.size()) {
161         return NULL;
162     }
163
164     return mTracks.valueAt(index);
165 }
166
167 sp<MetaData> FFmpegExtractor::getTrackMetaData(size_t index, uint32_t flags) {
168     ALOGV("FFmpegExtractor::getTrackMetaData[%d]", index);
169
170     if (mInitCheck != OK) {
171         return NULL;
172     }
173
174     if (index >= mTracks.size()) {
175         return NULL;
176     }
177
178     return mTracks.valueAt(index)->getFormat();
179 }
180
181 sp<MetaData> FFmpegExtractor::getMetaData() {
182     ALOGV("FFmpegExtractor::getMetaData");
183
184     if (mInitCheck != OK) {
185         return NULL;
186     }
187
188     sp<MetaData> meta = new MetaData;
189     // TODO
190     meta->setCString(kKeyMIMEType, "video/ffmpeg");
191
192     return meta;
193 }
194
195 uint32_t FFmpegExtractor::flags() const {
196     ALOGV("FFmpegExtractor::flags");
197
198     if (mInitCheck != OK) {
199         return 0;
200     }
201
202     uint32_t flags = CAN_PAUSE;
203
204     if (mFormatCtx->duration != AV_NOPTS_VALUE) {
205         flags |= CAN_SEEK_BACKWARD | CAN_SEEK_FORWARD | CAN_SEEK;
206     }
207
208     return flags;
209 }
210
211 void FFmpegExtractor::packet_queue_init(PacketQueue *q)
212 {
213     memset(q, 0, sizeof(PacketQueue));
214     pthread_mutex_init(&q->mutex, NULL);
215     pthread_cond_init(&q->cond, NULL);
216     packet_queue_put(q, &flush_pkt);
217 }
218
219 void FFmpegExtractor::packet_queue_flush(PacketQueue *q)
220 {
221     AVPacketList *pkt, *pkt1;
222
223     pthread_mutex_lock(&q->mutex);
224     for (pkt = q->first_pkt; pkt != NULL; pkt = pkt1) {
225         pkt1 = pkt->next;
226         av_free_packet(&pkt->pkt);
227         av_freep(&pkt);
228     }
229     q->last_pkt = NULL;
230     q->first_pkt = NULL;
231     q->nb_packets = 0;
232     q->size = 0;
233     pthread_mutex_unlock(&q->mutex);
234 }
235
236 void FFmpegExtractor::packet_queue_end(PacketQueue *q)
237 {
238     packet_queue_flush(q);
239 }
240
241 void FFmpegExtractor::packet_queue_abort(PacketQueue *q)
242 {
243     pthread_mutex_lock(&q->mutex);
244
245     q->abort_request = 1;
246
247     pthread_cond_signal(&q->cond);
248
249     pthread_mutex_unlock(&q->mutex);
250 }
251
252 int FFmpegExtractor::packet_queue_put(PacketQueue *q, AVPacket *pkt)
253 {
254     AVPacketList *pkt1;
255
256     /* duplicate the packet */
257     if (pkt != &flush_pkt && av_dup_packet(pkt) < 0)
258         return -1;
259
260     pkt1 = (AVPacketList *)av_malloc(sizeof(AVPacketList));
261     if (!pkt1)
262         return -1;
263     pkt1->pkt = *pkt;
264     pkt1->next = NULL;
265
266     pthread_mutex_lock(&q->mutex);
267
268     if (!q->last_pkt)
269
270         q->first_pkt = pkt1;
271     else
272         q->last_pkt->next = pkt1;
273     q->last_pkt = pkt1;
274     q->nb_packets++;
275     //q->size += pkt1->pkt.size + sizeof(*pkt1);
276     q->size += pkt1->pkt.size;
277     pthread_cond_signal(&q->cond);
278
279     pthread_mutex_unlock(&q->mutex);
280     return 0;
281 }
282
283 /* packet queue handling */
284 /* return < 0 if aborted, 0 if no packet and > 0 if packet.  */
285 int FFmpegExtractor::packet_queue_get(PacketQueue *q, AVPacket *pkt, int block)
286 {
287     AVPacketList *pkt1;
288     int ret;
289
290     pthread_mutex_lock(&q->mutex);
291
292     for (;;) {
293         if (q->abort_request) {
294             ret = -1;
295             break;
296         }
297
298         pkt1 = q->first_pkt;
299         if (pkt1) {
300             q->first_pkt = pkt1->next;
301             if (!q->first_pkt)
302                 q->last_pkt = NULL;
303             q->nb_packets--;
304             //q->size -= pkt1->pkt.size + sizeof(*pkt1);
305             q->size -= pkt1->pkt.size;
306             *pkt = pkt1->pkt;
307             av_free(pkt1);
308             ret = 1;
309             break;
310         } else if (!block) {
311             ret = 0;
312             break;
313         } else {
314             pthread_cond_wait(&q->cond, &q->mutex);
315         }
316     }
317     pthread_mutex_unlock(&q->mutex);
318     return ret;
319 }
320
321 static void EncodeSize14(uint8_t **_ptr, size_t size) {
322     CHECK_LE(size, 0x3fff);
323
324     uint8_t *ptr = *_ptr;
325
326     *ptr++ = 0x80 | (size >> 7);
327     *ptr++ = size & 0x7f;
328
329     *_ptr = ptr;
330 }
331
332 static sp<ABuffer> MakeMPEGVideoESDS(const sp<ABuffer> &csd) {
333     sp<ABuffer> esds = new ABuffer(csd->size() + 25);
334
335     uint8_t *ptr = esds->data();
336     *ptr++ = 0x03;
337     EncodeSize14(&ptr, 22 + csd->size());
338
339     *ptr++ = 0x00;  // ES_ID
340     *ptr++ = 0x00;
341
342     *ptr++ = 0x00;  // streamDependenceFlag, URL_Flag, OCRstreamFlag
343
344     *ptr++ = 0x04;
345     EncodeSize14(&ptr, 16 + csd->size());
346
347     *ptr++ = 0x40;  // Audio ISO/IEC 14496-3
348
349     for (size_t i = 0; i < 12; ++i) {
350         *ptr++ = 0x00;
351     }
352
353     *ptr++ = 0x05;
354     EncodeSize14(&ptr, csd->size());
355
356     memcpy(ptr, csd->data(), csd->size());
357
358     return esds;
359 }
360
361 // Returns the sample rate based on the sampling frequency index
362 static uint32_t get_sample_rate(const uint8_t sf_index)
363 {
364     static const uint32_t sample_rates[] =
365     {
366         96000, 88200, 64000, 48000, 44100, 32000,
367         24000, 22050, 16000, 12000, 11025, 8000
368     };
369
370     if (sf_index < sizeof(sample_rates) / sizeof(sample_rates[0])) {
371         return sample_rates[sf_index];
372     }
373
374     return 0;
375 }
376
377 int FFmpegExtractor::check_extradata(AVCodecContext *avctx)
378 {
379     const char *name = NULL;
380     bool *defersToCreateTrack = NULL;
381     AVBitStreamFilterContext **bsfc = NULL;
382
383     // init
384     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
385         bsfc = &mVideoBsfc;
386         defersToCreateTrack = &mDefersToCreateVideoTrack;
387     } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO){
388         bsfc = &mAudioBsfc;
389         defersToCreateTrack = &mDefersToCreateAudioTrack;
390     }
391
392     // ignore extradata
393     if (avctx->codec_id == CODEC_ID_MP3 ||
394             avctx->codec_id == CODEC_ID_MP1  ||
395             avctx->codec_id == CODEC_ID_MP2  ||
396             avctx->codec_id == CODEC_ID_AC3  ||
397             avctx->codec_id == CODEC_ID_DTS  ||
398             avctx->codec_id == CODEC_ID_H263  ||
399             avctx->codec_id == CODEC_ID_H263P ||
400             avctx->codec_id == CODEC_ID_H263I ||
401             avctx->codec_id == CODEC_ID_WMV1)
402         return 1;
403
404     // is extradata compatible with android?
405     if (avctx->codec_id != CODEC_ID_AAC) {
406         int is_compatible = is_extradata_compatible_with_android(avctx);
407         if (!is_compatible) {
408             ALOGI("%s extradata is not compatible with android, should to extract it from bitstream",
409                     av_get_media_type_string(avctx->codec_type));
410             *defersToCreateTrack = true;
411             *bsfc = NULL; // H264 don't need bsfc, only AAC?
412             return 0;
413         }
414         return 1;
415     }
416
417     if (avctx->codec_id == CODEC_ID_AAC) {
418         name = "aac_adtstoasc";
419     }
420
421     if (avctx->extradata_size <= 0) {
422         ALOGI("No %s extradata found, should to extract it from bitstream",
423                 av_get_media_type_string(avctx->codec_type));
424         *defersToCreateTrack = true;
425          //CHECK(name != NULL);
426         if (!*bsfc && name) {
427             *bsfc = av_bitstream_filter_init(name);
428             if (!*bsfc) {
429                 ALOGE("Cannot open the %s BSF!", name);
430                 *defersToCreateTrack = false;
431                 return -1;
432             } else {
433                 ALOGV("open the %s bsf", name);
434                 return 0;
435             }
436         } else {
437             return 0;
438         }
439     }
440     return 1;
441 }
442
443 void FFmpegExtractor::printTime(int64_t time)
444 {
445     int hours, mins, secs, us;
446
447     if (time == AV_NOPTS_VALUE)
448         return;
449
450     secs = time / AV_TIME_BASE;
451     us = time % AV_TIME_BASE;
452     mins = secs / 60;
453     secs %= 60;
454     hours = mins / 60;
455     mins %= 60;
456     ALOGI("the time is %02d:%02d:%02d.%02d",
457         hours, mins, secs, (100 * us) / AV_TIME_BASE);
458 }
459
460 int FFmpegExtractor::stream_component_open(int stream_index)
461 {
462     AVCodecContext *avctx = NULL;
463     sp<MetaData> meta = NULL;
464     bool isAVC = false;
465     bool supported = false;
466     uint32_t type = 0;
467     const void *data = NULL;
468     size_t size = 0;
469     int ret = 0;
470
471     ALOGI("stream_index: %d", stream_index);
472     if (stream_index < 0 || stream_index >= (int)mFormatCtx->nb_streams)
473         return -1;
474     avctx = mFormatCtx->streams[stream_index]->codec;
475
476     switch(avctx->codec_id) {
477     case CODEC_ID_H264:
478     case CODEC_ID_MPEG4:
479     case CODEC_ID_H263:
480     case CODEC_ID_H263P:
481     case CODEC_ID_H263I:
482     case CODEC_ID_AAC:
483     case CODEC_ID_AC3:
484     case CODEC_ID_MP1:
485     case CODEC_ID_MP2:
486     case CODEC_ID_MP3:
487     case CODEC_ID_MPEG2VIDEO:
488     case CODEC_ID_WMV1:
489     case CODEC_ID_WMV2:
490     case CODEC_ID_WMV3:
491     case CODEC_ID_VC1:
492     case CODEC_ID_WMAV1:
493     case CODEC_ID_WMAV2:
494     case CODEC_ID_WMAPRO:
495     case CODEC_ID_WMALOSSLESS:
496     case CODEC_ID_RV40:
497     case CODEC_ID_COOK:
498     case CODEC_ID_APE:
499     case CODEC_ID_DTS:
500     case CODEC_ID_FLAC:
501         supported = true;
502         break;
503     default:
504         supported = false;
505         break;
506     }
507
508     if (!supported) {
509         ALOGE("unsupport the codec, id: 0x%0x", avctx->codec_id);
510         return -1;
511     }
512     ALOGV("support the codec");
513
514     unsigned streamType;
515     ssize_t index = mTracks.indexOfKey(stream_index);
516
517     if (index >= 0) {
518         ALOGE("this track already exists");
519         return 0;
520     }
521
522     mFormatCtx->streams[stream_index]->discard = AVDISCARD_DEFAULT;
523
524     char tagbuf[32];
525     av_get_codec_tag_string(tagbuf, sizeof(tagbuf), avctx->codec_tag);
526     ALOGV("Tag %s/0x%08x with codec id '%d'\n", tagbuf, avctx->codec_tag, avctx->codec_id);
527
528     switch (avctx->codec_type) {
529     case AVMEDIA_TYPE_VIDEO:
530         if (mVideoStreamIdx == -1)
531             mVideoStreamIdx = stream_index;
532         if (mVideoStream == NULL)
533             mVideoStream = mFormatCtx->streams[stream_index];
534         if (!mVideoQInited) {
535             packet_queue_init(&mVideoQ);
536             mVideoQInited = true;
537         }
538
539         ret = check_extradata(avctx);
540         if (ret != 1) {
541             if (ret == -1) {
542                 // disable the stream
543                 mVideoStreamIdx = -1;
544                 mVideoStream = NULL;
545                 packet_queue_end(&mVideoQ);
546                 mVideoQInited =  false;
547                 mFormatCtx->streams[stream_index]->discard = AVDISCARD_ALL;
548             }
549             return ret;
550          }
551
552         if (avctx->extradata) {
553             ALOGV("video stream extradata:");
554             hexdump(avctx->extradata, avctx->extradata_size);
555         } else {
556             ALOGV("video stream no extradata, but we can ignore it.");
557         }
558
559         meta = new MetaData;
560
561         switch(avctx->codec_id) {
562         case CODEC_ID_H264:
563             /**
564              * H.264 Video Types
565              * http://msdn.microsoft.com/en-us/library/dd757808(v=vs.85).aspx
566              */
567             //if (avctx->codec_tag && avctx->codec_tag == AV_RL32("avc1")) {
568             if (avctx->extradata[0] == 1 /* configurationVersion */) {
569                 // H.264 bitstream without start codes.
570                 isAVC = true;
571                 ALOGV("AVC");
572
573                 if (avctx->width == 0 || avctx->height == 0) {
574                     int32_t width, height;
575                     sp<ABuffer> seqParamSet = new ABuffer(avctx->extradata_size - 8);
576                     memcpy(seqParamSet->data(), avctx->extradata + 8, avctx->extradata_size - 8);
577                     FindAVCDimensions(seqParamSet, &width, &height);
578                     avctx->width  = width;
579                     avctx->height = height;
580                 }
581
582                 meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
583                 meta->setData(kKeyAVCC, kTypeAVCC, avctx->extradata, avctx->extradata_size);
584             } else {
585                 // H.264 bitstream with start codes.
586                 isAVC = false;
587                 ALOGV("H264");
588
589                 /* set NULL to release meta as we will new a meta in MakeAVCCodecSpecificData() fxn */
590                 meta->clear();
591                 meta = NULL;
592
593                 sp<ABuffer> buffer = new ABuffer(avctx->extradata_size);
594                 memcpy(buffer->data(), avctx->extradata, avctx->extradata_size);
595                 meta = MakeAVCCodecSpecificData(buffer);
596             }
597             break;
598         case CODEC_ID_MPEG4:
599             ALOGV("MPEG4");
600             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4);
601             {
602                 sp<ABuffer> csd = new ABuffer(avctx->extradata_size);
603                 memcpy(csd->data(), avctx->extradata, avctx->extradata_size);
604                 sp<ABuffer> esds = MakeMPEGVideoESDS(csd);
605                 meta->setData(kKeyESDS, kTypeESDS, esds->data(), esds->size());
606             }
607             break;
608         case CODEC_ID_H263:
609         case CODEC_ID_H263P:
610         case CODEC_ID_H263I:
611             ALOGV("H263");
612             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263);
613             break;
614         case CODEC_ID_MPEG2VIDEO:
615             ALOGV("MPEG2VIDEO");
616             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG2);
617             {
618                 sp<ABuffer> csd = new ABuffer(avctx->extradata_size);
619                 memcpy(csd->data(), avctx->extradata, avctx->extradata_size);
620                 sp<ABuffer> esds = MakeMPEGVideoESDS(csd);
621                 meta->setData(kKeyESDS, kTypeESDS, esds->data(), esds->size());
622             }
623             break;
624         case CODEC_ID_VC1:
625             ALOGV("VC1");
626             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_VC1);
627             meta->setData(kKeyRawCodecSpecificData, 0, avctx->extradata, avctx->extradata_size);
628             break;
629         case CODEC_ID_WMV1:
630             ALOGV("WMV1");
631             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_WMV);
632             meta->setInt32(kKeyWMVVersion, kTypeWMVVer_7);
633             break;
634         case CODEC_ID_WMV2:
635             ALOGV("WMV2");
636             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_WMV);
637             meta->setData(kKeyRawCodecSpecificData, 0, avctx->extradata, avctx->extradata_size);
638             meta->setInt32(kKeyWMVVersion, kTypeWMVVer_8);
639             break;
640         case CODEC_ID_WMV3:
641             ALOGV("WMV3");
642             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_WMV);
643             meta->setData(kKeyRawCodecSpecificData, 0, avctx->extradata, avctx->extradata_size);
644             meta->setInt32(kKeyWMVVersion, kTypeWMVVer_9);
645             break;
646         case CODEC_ID_RV40:
647             ALOGV("RV40");
648             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_RV);
649             meta->setData(kKeyRawCodecSpecificData, 0, avctx->extradata, avctx->extradata_size);
650             break;
651         default:
652             CHECK(!"Should not be here. Unsupported codec.");
653             break;
654         }
655
656         ALOGI("width: %d, height: %d, bit_rate: %d",
657              avctx->width, avctx->height, avctx->bit_rate);
658
659         meta->setInt32(kKeyWidth, avctx->width);
660         meta->setInt32(kKeyHeight, avctx->height);
661         if (avctx->bit_rate > 0)
662             meta->setInt32(kKeyBitRate, avctx->bit_rate);
663         if (mVideoStream->duration != AV_NOPTS_VALUE) {
664             int64_t duration = mVideoStream->duration * av_q2d(mVideoStream->time_base) * 1000000;
665             printTime(duration);
666             ALOGV("video startTime: %lld", mVideoStream->start_time);
667             meta->setInt64(kKeyDuration, duration);
668         } else {
669             // default when no stream duration
670             meta->setInt64(kKeyDuration, mFormatCtx->duration);
671         }
672
673         ALOGV("create a video track");
674         index = mTracks.add(
675             stream_index, new Track(this, meta, isAVC, mVideoStream, &mVideoQ));
676
677         mDefersToCreateVideoTrack = false;
678
679         break;
680     case AVMEDIA_TYPE_AUDIO:
681         if (mAudioStreamIdx == -1)
682             mAudioStreamIdx = stream_index;
683         if (mAudioStream == NULL)
684             mAudioStream = mFormatCtx->streams[stream_index];
685         if (!mAudioQInited) {
686             packet_queue_init(&mAudioQ);
687             mAudioQInited = true;
688         }
689
690         ret = check_extradata(avctx);
691         if (ret != 1) {
692             if (ret == -1) {
693                 // disable the stream
694                 mAudioStreamIdx = -1;
695                 mAudioStream = NULL;
696                 packet_queue_end(&mAudioQ);
697                 mAudioQInited =  false;
698                 mFormatCtx->streams[stream_index]->discard = AVDISCARD_ALL;
699             }
700             return ret;
701         }
702
703         if (avctx->extradata) {
704             ALOGV("audio stream extradata:");
705             hexdump(avctx->extradata, avctx->extradata_size);
706         } else {
707             ALOGV("audio stream no extradata, but we can ignore it.");
708         }
709
710         switch(avctx->codec_id) {
711         case CODEC_ID_MP1:
712             ALOGV("MP1");
713             meta = new MetaData;
714             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_I);
715             break;
716         case CODEC_ID_MP2:
717             ALOGV("MP2");
718             meta = new MetaData;
719             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_II);
720             break;
721         case CODEC_ID_MP3:
722             ALOGV("MP3");
723             meta = new MetaData;
724             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_MPEG);
725             break;
726         case CODEC_ID_AC3:
727             ALOGV("AC3");
728             meta = new MetaData;
729             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AC3);
730             break;
731         case CODEC_ID_AAC:
732             ALOGV("AAC");
733             uint32_t sr;
734             const uint8_t *header;
735             uint8_t profile, sf_index, channel;
736
737             header = avctx->extradata;
738             CHECK(header != NULL);
739
740             // AudioSpecificInfo follows
741             // oooo offf fccc c000
742             // o - audioObjectType
743             // f - samplingFreqIndex
744             // c - channelConfig
745             profile = ((header[0] & 0xf8) >> 3) - 1;
746             sf_index = (header[0] & 0x07) << 1 | (header[1] & 0x80) >> 7;
747             sr = get_sample_rate(sf_index);
748             if (sr == 0) {
749                 ALOGE("unsupport the sample rate");
750                 return -1;
751             }
752             channel = (header[1] >> 3) & 0xf;
753             ALOGV("profile: %d, sf_index: %d, channel: %d", profile, sf_index, channel);
754
755             meta = MakeAACCodecSpecificData(profile, sf_index, channel);
756             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AAC);
757             break;
758         case CODEC_ID_WMAV1:  // TODO, version?
759             ALOGV("WMAV1");
760             meta = new MetaData;
761             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_WMA);
762             meta->setData(kKeyRawCodecSpecificData, 0, avctx->extradata, avctx->extradata_size);
763             break;
764         case CODEC_ID_WMAV2:
765             ALOGV("WMAV2");
766             meta = new MetaData;
767             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_WMA);
768             meta->setData(kKeyRawCodecSpecificData, 0, avctx->extradata, avctx->extradata_size);
769             meta->setInt32(kKeyWMAVersion, kTypeWMA);
770             break;
771         case CODEC_ID_WMAPRO:
772             ALOGV("WMAPRO");
773             meta = new MetaData;
774             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_WMA);
775             meta->setData(kKeyRawCodecSpecificData, 0, avctx->extradata, avctx->extradata_size);
776             meta->setInt32(kKeyWMAVersion, kTypeWMAPro);
777             break;
778         case CODEC_ID_WMALOSSLESS:
779             ALOGV("WMALOSSLESS");
780             meta = new MetaData;
781             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_WMA);
782             meta->setData(kKeyRawCodecSpecificData, 0, avctx->extradata, avctx->extradata_size);
783             meta->setInt32(kKeyWMAVersion, kTypeWMALossLess);
784             break;
785         case CODEC_ID_COOK: // audio codec in RMVB
786             ALOGV("COOK");
787             meta = new MetaData;
788             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_RA);
789             meta->setData(kKeyRawCodecSpecificData, 0, avctx->extradata, avctx->extradata_size);
790             break;
791         case CODEC_ID_APE:
792             ALOGV("APE");
793             meta = new MetaData;
794             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_APE);
795             meta->setData(kKeyRawCodecSpecificData, 0, avctx->extradata, avctx->extradata_size);
796             break;
797         case CODEC_ID_DTS:
798             ALOGV("DTS");
799             meta = new MetaData;
800             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_DTS);
801             meta->setData(kKeyRawCodecSpecificData, 0, avctx->extradata, avctx->extradata_size);
802             break;
803         case CODEC_ID_FLAC:
804             ALOGV("FLAC");
805             meta = new MetaData;
806             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_FLAC);
807             meta->setData(kKeyRawCodecSpecificData, 0, avctx->extradata, avctx->extradata_size);
808             break;
809         default:
810             CHECK(!"Should not be here. Unsupported codec.");
811             break;
812         }
813
814         ALOGI("bit_rate: %d, sample_rate: %d, channels: %d, bits_per_coded_sample: %d",
815              avctx->bit_rate, avctx->sample_rate, avctx->channels, avctx->bits_per_coded_sample);
816
817         meta->setInt32(kKeySampleRate, avctx->sample_rate);
818         meta->setInt32(kKeyChannelCount, avctx->channels);
819         meta->setInt32(kKeyBitspersample, avctx->bits_per_coded_sample);
820         meta->setInt32(kKeyBitRate, avctx->bit_rate);
821         meta->setInt32(kKeyBlockAlign, avctx->block_align);
822         if (mAudioStream->duration != AV_NOPTS_VALUE) {
823             int64_t duration = mAudioStream->duration * av_q2d(mAudioStream->time_base) * 1000000;
824             printTime(duration);
825             ALOGV("audio startTime: %lld", mAudioStream->start_time);
826             meta->setInt64(kKeyDuration, duration);
827         } else {
828             // default when no stream duration
829             meta->setInt64(kKeyDuration, mFormatCtx->duration);
830         }
831
832         ALOGV("create a audio track");
833         index = mTracks.add(
834             stream_index, new Track(this, meta, false, mAudioStream, &mAudioQ));
835
836         mDefersToCreateAudioTrack = false;
837
838         break;
839     case AVMEDIA_TYPE_SUBTITLE:
840         /* Unsupport now */
841         CHECK(!"Should not be here. Unsupported media type.");
842         break;
843     default:
844         CHECK(!"Should not be here. Unsupported media type.");
845         break;
846     }
847     return 0;
848 }
849
850 void FFmpegExtractor::stream_component_close(int stream_index)
851 {
852     AVCodecContext *avctx;
853
854     if (stream_index < 0 || stream_index >= (int)mFormatCtx->nb_streams)
855         return;
856     avctx = mFormatCtx->streams[stream_index]->codec;
857
858     switch (avctx->codec_type) {
859     case AVMEDIA_TYPE_VIDEO:
860         ALOGV("packet_queue_abort videoq");
861         packet_queue_abort(&mVideoQ);
862         /* wait until the end */
863         while (!mAbortRequest && !mVideoEOSReceived) {
864             ALOGV("wait for video received");
865             usleep(10000);
866         }
867         ALOGV("packet_queue_end videoq");
868         packet_queue_end(&mVideoQ);
869         break;
870     case AVMEDIA_TYPE_AUDIO:
871         ALOGV("packet_queue_abort audioq");
872         packet_queue_abort(&mAudioQ);
873         while (!mAbortRequest && !mAudioEOSReceived) {
874             ALOGV("wait for audio received");
875             usleep(10000);
876         }
877         ALOGV("packet_queue_end audioq");
878         packet_queue_end(&mAudioQ);
879         break;
880     case AVMEDIA_TYPE_SUBTITLE:
881         break;
882     default:
883         break;
884     }
885
886     mFormatCtx->streams[stream_index]->discard = AVDISCARD_ALL;
887     switch (avctx->codec_type) {
888     case AVMEDIA_TYPE_VIDEO:
889         mVideoStream    = NULL;
890         mVideoStreamIdx = -1;
891         if (mVideoBsfc) {
892             av_bitstream_filter_close(mVideoBsfc);
893             mVideoBsfc  = NULL;
894         }
895         break;
896     case AVMEDIA_TYPE_AUDIO:
897         mAudioStream    = NULL;
898         mAudioStreamIdx = -1;
899         if (mAudioBsfc) {
900             av_bitstream_filter_close(mAudioBsfc);
901             mAudioBsfc  = NULL;
902         }
903         break;
904     case AVMEDIA_TYPE_SUBTITLE:
905         break;
906     default:
907         break;
908     }
909 }
910
911 void FFmpegExtractor::reachedEOS(enum AVMediaType media_type)
912 {
913     Mutex::Autolock autoLock(mLock);
914
915     if (media_type == AVMEDIA_TYPE_VIDEO) {
916         mVideoEOSReceived = true;
917     } else if (media_type == AVMEDIA_TYPE_AUDIO) {
918         mAudioEOSReceived = true;
919     }
920 }
921
922 /* seek in the stream */
923 int FFmpegExtractor::stream_seek(int64_t pos, enum AVMediaType media_type)
924 {
925     Mutex::Autolock autoLock(mLock);
926
927     if (mVideoStreamIdx >= 0 &&
928         mAudioStreamIdx >= 0 &&
929         media_type == AVMEDIA_TYPE_AUDIO &&
930         !mVideoEOSReceived) {
931        return NO_SEEK;
932     }
933
934     // flush immediately
935     if (mAudioStreamIdx >= 0)
936         packet_queue_flush(&mAudioQ);
937     if (mVideoStreamIdx >= 0)
938         packet_queue_flush(&mVideoQ);
939
940     mSeekPos = pos;
941     mSeekFlags &= ~AVSEEK_FLAG_BYTE;
942     mSeekReq = 1;
943
944     return SEEK;
945 }
946
947 // staitc
948 int FFmpegExtractor::decode_interrupt_cb(void *ctx)
949 {
950     FFmpegExtractor *extrator = static_cast<FFmpegExtractor *>(ctx);
951     return extrator->mAbortRequest;
952 }
953
954 void FFmpegExtractor::print_error_ex(const char *filename, int err)
955 {
956     char errbuf[128];
957     const char *errbuf_ptr = errbuf;
958
959     if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
960         errbuf_ptr = strerror(AVUNERROR(err));
961     ALOGI("%s: %s\n", filename, errbuf_ptr);
962 }
963
964 void FFmpegExtractor::buildFileName(const sp<DataSource> &source)
965 {
966 #if 1
967     ALOGI("android-source:%p", source.get());
968     // pass the addr of smart pointer("source")
969     snprintf(mFilename, sizeof(mFilename), "android-source:%p", source.get());
970     ALOGI("build mFilename: %s", mFilename);
971 #else
972     const char *url = mDataSource->getNamURI();
973     if (url == NULL) {
974         ALOGI("url is error!");
975         return;
976     }
977     // is it right?
978     if (!strcmp(url, "-")) {
979         av_strlcpy(mFilename, "pipe:", strlen("pipe:") + 1);
980     } else {
981         av_strlcpy(mFilename, url, strlen(url) + 1);
982     }
983     ALOGI("build url: %s, mFilename: %s", url, mFilename);
984 #endif
985 }
986
987 void FFmpegExtractor::setFFmpegDefaultOpts()
988 {
989     mGenPTS       = 0;
990 #if DEBUG_DISABLE_VIDEO
991     mVideoDisable = 1;
992 #else
993     mVideoDisable = 0;
994 #endif
995 #if DEBUG_DISABLE_AUDIO
996     mAudioDisable = 1;
997 #else
998     mAudioDisable = 0;
999 #endif
1000     mShowStatus   = 0;
1001     mSeekByBytes  = 0; /* seek by bytes 0=off 1=on -1=auto" */
1002     mDuration     = AV_NOPTS_VALUE;
1003     mSeekPos      = AV_NOPTS_VALUE;
1004     mAutoExit     = 1;
1005     mLoop         = 1;
1006
1007     mVideoStreamIdx = -1;
1008     mAudioStreamIdx = -1;
1009     mVideoStream  = NULL;
1010     mAudioStream  = NULL;
1011     mVideoQInited = false;
1012     mAudioQInited = false;
1013     mDefersToCreateVideoTrack = false;
1014     mDefersToCreateAudioTrack = false;
1015     mVideoBsfc = NULL;
1016     mAudioBsfc = NULL;
1017
1018     mAbortRequest = 0;
1019     mPaused       = 0;
1020     mLastPaused   = 0;
1021     mSeekReq      = 0;
1022
1023     mProbePkts    = 0;
1024     mEOF          = false;
1025 }
1026
1027 int FFmpegExtractor::initStreams()
1028 {
1029     int err = 0;
1030         int i = 0;
1031     status_t status = UNKNOWN_ERROR;
1032     int eof = 0;
1033     int ret = 0, audio_ret = -1, video_ret = -1;
1034     int pkt_in_play_range = 0;
1035     AVDictionaryEntry *t = NULL;
1036     AVDictionary **opts = NULL;
1037     int orig_nb_streams = 0;
1038     int st_index[AVMEDIA_TYPE_NB] = {0};
1039     int wanted_stream[AVMEDIA_TYPE_NB] = {0};
1040     st_index[AVMEDIA_TYPE_AUDIO]  = -1;
1041     st_index[AVMEDIA_TYPE_VIDEO]  = -1;
1042     wanted_stream[AVMEDIA_TYPE_AUDIO]  = -1;
1043     wanted_stream[AVMEDIA_TYPE_VIDEO]  = -1;
1044
1045     setFFmpegDefaultOpts();
1046
1047     status = initFFmpeg();
1048     if (status != OK) {
1049         ret = -1;
1050         goto fail;
1051     }
1052     mFFmpegInited = true;
1053
1054     av_init_packet(&flush_pkt);
1055     flush_pkt.data = (uint8_t *)"FLUSH";
1056     flush_pkt.size = 0;
1057
1058     mFormatCtx = avformat_alloc_context();
1059         if (!mFormatCtx)
1060         {
1061         ALOGE("oom for alloc avformat context");
1062         ret = -1;
1063         goto fail;
1064         }
1065     mFormatCtx->interrupt_callback.callback = decode_interrupt_cb;
1066     mFormatCtx->interrupt_callback.opaque = this;
1067     ALOGV("mFilename: %s", mFilename);
1068     err = avformat_open_input(&mFormatCtx, mFilename, NULL, &format_opts);
1069     if (err < 0) {
1070         print_error_ex(mFilename, err);
1071         ret = -1;
1072         goto fail;
1073     }
1074     if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
1075         ALOGE("Option %s not found.\n", t->key);
1076         //ret = AVERROR_OPTION_NOT_FOUND;
1077         ret = -1;
1078         goto fail;
1079     }
1080
1081     if (mGenPTS)
1082         mFormatCtx->flags |= AVFMT_FLAG_GENPTS;
1083
1084     opts = setup_find_stream_info_opts(mFormatCtx, codec_opts);
1085     orig_nb_streams = mFormatCtx->nb_streams;
1086
1087     err = avformat_find_stream_info(mFormatCtx, opts);
1088     if (err < 0) {
1089         ALOGE("%s: could not find codec parameters\n", mFilename);
1090         ret = -1;
1091         goto fail;
1092     }
1093     for (i = 0; i < orig_nb_streams; i++)
1094         av_dict_free(&opts[i]);
1095     av_freep(&opts);
1096
1097     if (mFormatCtx->pb)
1098         mFormatCtx->pb->eof_reached = 0; // FIXME hack, ffplay maybe should not use url_feof() to test for the end
1099
1100     if (mSeekByBytes < 0)
1101         mSeekByBytes = !!(mFormatCtx->iformat->flags & AVFMT_TS_DISCONT);
1102
1103     for (i = 0; i < (int)mFormatCtx->nb_streams; i++)
1104         mFormatCtx->streams[i]->discard = AVDISCARD_ALL;
1105     if (!mVideoDisable)
1106         st_index[AVMEDIA_TYPE_VIDEO] =
1107             av_find_best_stream(mFormatCtx, AVMEDIA_TYPE_VIDEO,
1108                                 wanted_stream[AVMEDIA_TYPE_VIDEO], -1, NULL, 0);
1109     if (!mAudioDisable)
1110         st_index[AVMEDIA_TYPE_AUDIO] =
1111             av_find_best_stream(mFormatCtx, AVMEDIA_TYPE_AUDIO,
1112                                 wanted_stream[AVMEDIA_TYPE_AUDIO],
1113                                 st_index[AVMEDIA_TYPE_VIDEO],
1114                                 NULL, 0);
1115     if (mShowStatus) {
1116         av_dump_format(mFormatCtx, 0, mFilename, 0);
1117     }
1118
1119     if (mFormatCtx->duration != AV_NOPTS_VALUE &&
1120             mFormatCtx->start_time != AV_NOPTS_VALUE) {
1121         int hours, mins, secs, us;
1122
1123         ALOGV("file startTime: %lld", mFormatCtx->start_time);
1124
1125         mDuration = mFormatCtx->duration;
1126
1127         secs = mDuration / AV_TIME_BASE;
1128         us = mDuration % AV_TIME_BASE;
1129         mins = secs / 60;
1130         secs %= 60;
1131         hours = mins / 60;
1132         mins %= 60;
1133         ALOGI("the duration is %02d:%02d:%02d.%02d",
1134             hours, mins, secs, (100 * us) / AV_TIME_BASE);
1135     }
1136
1137     if (st_index[AVMEDIA_TYPE_AUDIO] >= 0) {
1138         audio_ret = stream_component_open(st_index[AVMEDIA_TYPE_AUDIO]);
1139     }
1140
1141     if (st_index[AVMEDIA_TYPE_VIDEO] >= 0) {
1142         video_ret = stream_component_open(st_index[AVMEDIA_TYPE_VIDEO]);
1143     }
1144
1145     if ( audio_ret < 0 && video_ret < 0) {
1146         ALOGE("%s: could not open codecs\n", mFilename);
1147         ret = -1;
1148         goto fail;
1149     }
1150
1151     ret = 0;
1152
1153 fail:
1154     return ret;
1155 }
1156
1157 void FFmpegExtractor::deInitStreams()
1158 {
1159     if (mFormatCtx) {
1160         avformat_close_input(&mFormatCtx);
1161     }
1162
1163     if (mFFmpegInited) {
1164         deInitFFmpeg();
1165     }
1166 }
1167
1168 status_t FFmpegExtractor::startReaderThread() {
1169     ALOGV("Starting reader thread");
1170     Mutex::Autolock autoLock(mLock);
1171
1172     if (mReaderThreadStarted)
1173         return OK;
1174
1175     pthread_attr_t attr;
1176     pthread_attr_init(&attr);
1177     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1178     pthread_create(&mReaderThread, &attr, ReaderWrapper, this);
1179     pthread_attr_destroy(&attr);
1180     mReaderThreadStarted = true;
1181     ALOGD("Reader thread started");
1182
1183     return OK;
1184 }
1185
1186 void FFmpegExtractor::stopReaderThread() {
1187     ALOGV("Stopping reader thread");
1188     Mutex::Autolock autoLock(mLock);
1189
1190     if (!mReaderThreadStarted) {
1191         ALOGD("Reader thread have been stopped");
1192         return;
1193     }
1194
1195     mAbortRequest = 1;
1196
1197     void *dummy;
1198     pthread_join(mReaderThread, &dummy);
1199     mReaderThreadStarted = false;
1200     ALOGD("Reader thread stopped");
1201 }
1202
1203 // static
1204 void *FFmpegExtractor::ReaderWrapper(void *me) {
1205     ((FFmpegExtractor *)me)->readerEntry();
1206
1207     return NULL;
1208 }
1209
1210 void FFmpegExtractor::readerEntry() {
1211     int err, i, ret;
1212     AVPacket pkt1, *pkt = &pkt1;
1213     int eof = 0;
1214     int pkt_in_play_range = 0;
1215
1216     ALOGV("FFmpegExtractor enter thread(readerEntry)");
1217
1218     mVideoEOSReceived = false;
1219     mAudioEOSReceived = false;
1220
1221     for (;;) {
1222         if (mAbortRequest)
1223             break;
1224
1225         if (mPaused != mLastPaused) {
1226             mLastPaused = mPaused;
1227             if (mPaused)
1228                 mReadPauseReturn = av_read_pause(mFormatCtx);
1229             else
1230                 av_read_play(mFormatCtx);
1231         }
1232 #if CONFIG_RTSP_DEMUXER || CONFIG_MMSH_PROTOCOL
1233         if (mPaused &&
1234                 (!strcmp(mFormatCtx->iformat->name, "rtsp") ||
1235                  (mFormatCtx->pb && !strncmp(mFilename, "mmsh:", 5)))) {
1236             /* wait 10 ms to avoid trying to get another packet */
1237             /* XXX: horrible */
1238             usleep(10000);
1239             continue;
1240         }
1241 #endif
1242
1243         if (mSeekReq) {
1244             ALOGV("readerEntry, mSeekReq: %d", mSeekReq);
1245             ret = avformat_seek_file(mFormatCtx, -1, INT64_MIN, mSeekPos, INT64_MAX, mSeekFlags);
1246             if (ret < 0) {
1247                 ALOGE("%s: error while seeking", mFormatCtx->filename);
1248             } else {
1249                 if (mAudioStreamIdx >= 0) {
1250                     packet_queue_flush(&mAudioQ);
1251                     packet_queue_put(&mAudioQ, &flush_pkt);
1252                 }
1253                 if (mVideoStreamIdx >= 0) {
1254                     packet_queue_flush(&mVideoQ);
1255                     packet_queue_put(&mVideoQ, &flush_pkt);
1256                 }
1257             }
1258             mSeekReq = 0;
1259             eof = 0;
1260         }
1261
1262         /* if the queue are full, no need to read more */
1263         if (   mAudioQ.size + mVideoQ.size > MAX_QUEUE_SIZE
1264             || (   (mAudioQ   .size  > MIN_AUDIOQ_SIZE || mAudioStreamIdx < 0)
1265                 && (mVideoQ   .nb_packets > MIN_FRAMES || mVideoStreamIdx < 0))) {
1266 #if DEBUG_READ_ENTRY
1267             ALOGV("readerEntry, is full, fuck");
1268 #endif
1269             /* wait 10 ms */
1270             usleep(10000);
1271             continue;
1272         }
1273
1274         if (eof) {
1275             if (mVideoStreamIdx >= 0) {
1276                 av_init_packet(pkt);
1277                 pkt->data = NULL;
1278                 pkt->size = 0;
1279                 pkt->stream_index = mVideoStreamIdx;
1280                 packet_queue_put(&mVideoQ, pkt);
1281             }
1282             if (mAudioStreamIdx >= 0) {
1283                 av_init_packet(pkt);
1284                 pkt->data = NULL;
1285                 pkt->size = 0;
1286                 pkt->stream_index = mAudioStreamIdx;
1287                 packet_queue_put(&mAudioQ, pkt);
1288             }
1289             usleep(10000);
1290 #if DEBUG_READ_ENTRY
1291             ALOGV("readerEntry, eof = 1, mVideoQ.size: %d, mVideoQ.nb_packets: %d, mAudioQ.size: %d, mAudioQ.nb_packets: %d",
1292                     mVideoQ.size, mVideoQ.nb_packets, mAudioQ.size, mAudioQ.nb_packets);
1293 #endif
1294             if (mAudioQ.size + mVideoQ.size  == 0) {
1295                 if (mAutoExit) {
1296                     ret = AVERROR_EOF;
1297                     goto fail;
1298                 }
1299             }
1300             eof=0;
1301             continue;
1302         }
1303
1304         ret = av_read_frame(mFormatCtx, pkt);
1305         mProbePkts++;
1306         if (ret < 0) {
1307             if (ret == AVERROR_EOF || url_feof(mFormatCtx->pb))
1308                 if (ret == AVERROR_EOF) {
1309                     //ALOGV("ret == AVERROR_EOF");
1310                 }
1311                 if (url_feof(mFormatCtx->pb)) {
1312                     //ALOGV("url_feof(mFormatCtx->pb)");
1313                 }
1314
1315                 eof = 1;
1316                 mEOF = true;
1317             if (mFormatCtx->pb && mFormatCtx->pb->error) {
1318                 ALOGE("mFormatCtx->pb->error: %d", mFormatCtx->pb->error);
1319                 break;
1320             }
1321             usleep(100000);
1322             continue;
1323         }
1324
1325         if (pkt->stream_index == mVideoStreamIdx) {
1326              if (mDefersToCreateVideoTrack) {
1327                 AVCodecContext *avctx = mFormatCtx->streams[mVideoStreamIdx]->codec;
1328
1329                 int i = parser_split(avctx, pkt->data, pkt->size);
1330                 if (i > 0 && i < FF_MAX_EXTRADATA_SIZE) {
1331                     if (avctx->extradata)
1332                         av_freep(&avctx->extradata);
1333                     avctx->extradata_size= i;
1334                     avctx->extradata = (uint8_t *)av_malloc(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
1335                     if (!avctx->extradata) {
1336                         //return AVERROR(ENOMEM);
1337                         ret = AVERROR(ENOMEM);
1338                         goto fail;
1339                     }
1340                     // sps + pps(there may be sei in it)
1341                     memcpy(avctx->extradata, pkt->data, avctx->extradata_size);
1342                     memset(avctx->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
1343                 } else {
1344                     av_free_packet(pkt);
1345                     continue;
1346                 }
1347
1348                 stream_component_open(mVideoStreamIdx);
1349                 if (!mDefersToCreateVideoTrack)
1350                     ALOGI("probe packet counter: %d when create video track ok", mProbePkts);
1351                 if (mProbePkts == EXTRACTOR_MAX_PROBE_PACKETS)
1352                     ALOGI("probe packet counter to max: %d, create video track: %d",
1353                         mProbePkts, !mDefersToCreateVideoTrack);
1354             }
1355         } else if (pkt->stream_index == mAudioStreamIdx) {
1356             int ret;
1357             uint8_t *outbuf;
1358             int   outbuf_size;
1359             AVCodecContext *avctx = mFormatCtx->streams[mAudioStreamIdx]->codec;
1360             if (mAudioBsfc && pkt && pkt->data) {
1361                 ret = av_bitstream_filter_filter(mAudioBsfc, avctx, NULL, &outbuf, &outbuf_size,
1362                                    pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY);
1363
1364                 if (ret < 0 ||!outbuf_size) {
1365                     av_free_packet(pkt);
1366                     continue;
1367                 }
1368                 if (outbuf && outbuf != pkt->data) {
1369                     memmove(pkt->data, outbuf, outbuf_size);
1370                     pkt->size = outbuf_size;
1371                 }
1372             }
1373             if (mDefersToCreateAudioTrack) {
1374                 if (avctx->extradata_size <= 0) {
1375                     av_free_packet(pkt);
1376                     continue;
1377                 }
1378                 stream_component_open(mAudioStreamIdx);
1379                 if (!mDefersToCreateAudioTrack)
1380                     ALOGI("probe packet counter: %d when create audio track ok", mProbePkts);
1381                 if (mProbePkts == EXTRACTOR_MAX_PROBE_PACKETS)
1382                     ALOGI("probe packet counter to max: %d, create audio track: %d",
1383                         mProbePkts, !mDefersToCreateAudioTrack);
1384             }
1385         }
1386
1387         if (pkt->stream_index == mAudioStreamIdx) {
1388             packet_queue_put(&mAudioQ, pkt);
1389         } else if (pkt->stream_index == mVideoStreamIdx) {
1390             packet_queue_put(&mVideoQ, pkt);
1391         } else {
1392             av_free_packet(pkt);
1393         }
1394     }
1395     /* wait until the end */
1396     while (!mAbortRequest) {
1397         usleep(100000);
1398     }
1399
1400     ret = 0;
1401 fail:
1402     ALOGI("reader thread goto end...");
1403
1404     /* close each stream */
1405     if (mAudioStreamIdx >= 0)
1406         stream_component_close(mAudioStreamIdx);
1407     if (mVideoStreamIdx >= 0)
1408         stream_component_close(mVideoStreamIdx);
1409     if (mFormatCtx) {
1410         avformat_close_input(&mFormatCtx);
1411     }
1412
1413     ALOGV("FFmpegExtractor exit thread(readerEntry)");
1414 }
1415
1416 ////////////////////////////////////////////////////////////////////////////////
1417
1418 FFmpegExtractor::Track::Track(
1419         FFmpegExtractor *extractor, sp<MetaData> meta, bool isAVC,
1420         AVStream *stream, PacketQueue *queue)
1421     : mExtractor(extractor),
1422       mMeta(meta),
1423       mIsAVC(isAVC),
1424       mStream(stream),
1425       mQueue(queue) {
1426     const char *mime;
1427
1428     /* H.264 Video Types */
1429     {
1430         mNal2AnnexB = false;
1431
1432         if (mIsAVC) {
1433             uint32_t type;
1434             const void *data;
1435             size_t size;
1436             CHECK(meta->findData(kKeyAVCC, &type, &data, &size));
1437
1438             const uint8_t *ptr = (const uint8_t *)data;
1439
1440             CHECK(size >= 7);
1441             CHECK_EQ((unsigned)ptr[0], 1u);  // configurationVersion == 1
1442
1443             // The number of bytes used to encode the length of a NAL unit.
1444             mNALLengthSize = 1 + (ptr[4] & 3);
1445
1446             ALOGV("the stream is AVC, the length of a NAL unit: %d", mNALLengthSize);
1447
1448             mNal2AnnexB = true;
1449         }
1450     }
1451
1452     mMediaType = mStream->codec->codec_type;
1453     mFirstKeyPktTimestamp = AV_NOPTS_VALUE;
1454 }
1455
1456 FFmpegExtractor::Track::~Track() {
1457     ALOGV("FFmpegExtractor::Track::~Track %s",
1458             av_get_media_type_string(mMediaType));
1459         mExtractor = NULL;
1460         mMeta = NULL;
1461 }
1462
1463 status_t FFmpegExtractor::Track::start(MetaData *params) {
1464     ALOGV("FFmpegExtractor::Track::start %s",
1465             av_get_media_type_string(mMediaType));
1466     Mutex::Autolock autoLock(mLock);
1467     //mExtractor->startReaderThread();
1468     return OK;
1469 }
1470
1471 status_t FFmpegExtractor::Track::stop() {
1472     ALOGV("FFmpegExtractor::Track::stop %s",
1473             av_get_media_type_string(mMediaType));
1474     Mutex::Autolock autoLock(mLock);
1475     //mExtractor->stopReaderThread();
1476     return OK;
1477 }
1478
1479 sp<MetaData> FFmpegExtractor::Track::getFormat() {
1480     Mutex::Autolock autoLock(mLock);
1481
1482     return mMeta;
1483 }
1484
1485 status_t FFmpegExtractor::Track::read(
1486         MediaBuffer **buffer, const ReadOptions *options) {
1487     *buffer = NULL;
1488
1489     Mutex::Autolock autoLock(mLock);
1490
1491     AVPacket pkt;
1492     bool seeking = false;
1493     bool waitKeyPkt = false;
1494     ReadOptions::SeekMode mode;
1495     int64_t pktTS = AV_NOPTS_VALUE;
1496     int64_t seekTimeUs = AV_NOPTS_VALUE;
1497     int64_t timeUs;
1498     int key;
1499     status_t status = OK;
1500
1501     if (options && options->getSeekTo(&seekTimeUs, &mode)) {
1502         ALOGV("~~~%s seekTimeUs: %lld, mode: %d", av_get_media_type_string(mMediaType), seekTimeUs, mode);
1503         /* add the stream start time */
1504         if (mStream->start_time != AV_NOPTS_VALUE)
1505             seekTimeUs += mStream->start_time * av_q2d(mStream->time_base) * 1000000;
1506         ALOGV("~~~%s seekTimeUs[+startTime]: %lld, mode: %d", av_get_media_type_string(mMediaType), seekTimeUs, mode);
1507
1508         if (mExtractor->stream_seek(seekTimeUs, mMediaType) == SEEK)
1509             seeking = true;
1510     }
1511
1512 retry:
1513     if (mExtractor->packet_queue_get(mQueue, &pkt, 1) < 0) {
1514         mExtractor->reachedEOS(mMediaType);
1515         return ERROR_END_OF_STREAM;
1516     }
1517
1518     if (seeking) {
1519         if (pkt.data != flush_pkt.data) {
1520             av_free_packet(&pkt);
1521             goto retry;
1522         } else {
1523             seeking = false;
1524 #if WAIT_KEY_PACKET_AFTER_SEEK
1525             waitKeyPkt = true;
1526 #endif
1527         }
1528     }
1529
1530     if (pkt.data == flush_pkt.data) {
1531         ALOGV("read %s flush pkt", av_get_media_type_string(mMediaType));
1532         av_free_packet(&pkt);
1533         mFirstKeyPktTimestamp = AV_NOPTS_VALUE;
1534         goto retry;
1535     } else if (pkt.data == NULL && pkt.size == 0) {
1536         ALOGD("read %s eos pkt", av_get_media_type_string(mMediaType));
1537         av_free_packet(&pkt);
1538         mExtractor->reachedEOS(mMediaType);
1539             return ERROR_END_OF_STREAM;
1540     }
1541
1542     key = pkt.flags & AV_PKT_FLAG_KEY ? 1 : 0;
1543     pktTS = pkt.pts;
1544     // use dts when AVI
1545     if (pkt.pts == AV_NOPTS_VALUE)
1546         pktTS = pkt.dts;
1547
1548     if (waitKeyPkt) {
1549         if (!key) {
1550             ALOGV("drop the no key packet");
1551             av_free_packet(&pkt);
1552             goto retry;
1553         } else {
1554             ALOGV("~~~~~~ got the key packet");
1555             waitKeyPkt = false;
1556         }
1557     }
1558
1559     if (mFirstKeyPktTimestamp == AV_NOPTS_VALUE) {
1560         // update the first key timestamp
1561         mFirstKeyPktTimestamp = pktTS;
1562     }
1563      
1564     if (pktTS < mFirstKeyPktTimestamp) {
1565             ALOGV("drop the packet with the backward timestamp, maybe they are B-frames after I-frame ^_^");
1566             av_free_packet(&pkt);
1567             goto retry;
1568     }
1569
1570     MediaBuffer *mediaBuffer = new MediaBuffer(pkt.size + FF_INPUT_BUFFER_PADDING_SIZE);
1571     mediaBuffer->meta_data()->clear();
1572     mediaBuffer->set_range(0, pkt.size);
1573 #if DISABLE_NAL_TO_ANNEXB
1574     mNal2AnnexB = false;
1575 #endif
1576     if (mIsAVC && mNal2AnnexB) {
1577         /* Convert H.264 NAL format to annex b */
1578         if (mNALLengthSize >= 3 && mNALLengthSize <= 4 )
1579         {
1580             uint8_t *dst = (uint8_t *)mediaBuffer->data();
1581
1582             /* This only works for NAL sizes 3-4 */
1583             size_t len = pkt.size, i;
1584             uint8_t *ptr = pkt.data;
1585             while (len >= mNALLengthSize) {
1586                 uint32_t nal_len = 0;
1587                 for( i = 0; i < mNALLengthSize; i++ ) {
1588                     nal_len = (nal_len << 8) | ptr[i];
1589                     dst[i] = 0;
1590                 }
1591                 dst[mNALLengthSize - 1] = 1;
1592                 if (nal_len > INT_MAX || nal_len > (unsigned int)len) {
1593                     status = ERROR_MALFORMED;
1594                     break;
1595                 }
1596                                 dst += mNALLengthSize;
1597                                 ptr += mNALLengthSize;
1598                 len -= mNALLengthSize;
1599
1600                 memcpy(dst, ptr, nal_len);
1601
1602                 dst += nal_len;
1603                 ptr += nal_len;
1604                 len -= nal_len;
1605             }
1606         } else {
1607              status = ERROR_MALFORMED;
1608         }
1609
1610         if (status != OK) {
1611             ALOGV("status != OK");
1612             mediaBuffer->release();
1613             mediaBuffer = NULL;
1614             av_free_packet(&pkt);
1615             return ERROR_MALFORMED;
1616         }
1617     } else {
1618         memcpy(mediaBuffer->data(), pkt.data, pkt.size);
1619     }
1620
1621     int64_t start_time = mStream->start_time != AV_NOPTS_VALUE ? mStream->start_time : 0;
1622     timeUs = (int64_t)((pktTS - start_time) * av_q2d(mStream->time_base) * 1000000);
1623
1624 #if DEBUG_PKT
1625     ALOGV("read %s pkt, size: %d, key: %d, pts: %lld, dts: %lld, timeUs[-startTime]: %llu us (%.2f secs)",
1626         av_get_media_type_string(mMediaType), pkt.size, key, pkt.pts, pkt.dts, timeUs, timeUs/1E6);
1627 #endif
1628
1629     mediaBuffer->meta_data()->setInt64(kKeyTime, timeUs);
1630     mediaBuffer->meta_data()->setInt32(kKeyIsSyncFrame, key);
1631
1632     *buffer = mediaBuffer;
1633
1634     av_free_packet(&pkt);
1635
1636     return OK;
1637 }
1638
1639 ////////////////////////////////////////////////////////////////////////////////
1640
1641 typedef struct {
1642     const char *format;
1643     const char *container;
1644 } formatmap;
1645
1646 static formatmap FILE_FORMATS[] = {
1647         {"mpeg",                    MEDIA_MIMETYPE_CONTAINER_MPEG2PS  },
1648         {"mpegts",                  MEDIA_MIMETYPE_CONTAINER_TS       },
1649         {"mov,mp4,m4a,3gp,3g2,mj2", MEDIA_MIMETYPE_CONTAINER_MPEG4    },
1650         {"matroska,webm",           MEDIA_MIMETYPE_CONTAINER_MATROSKA },
1651         {"asf",                     MEDIA_MIMETYPE_CONTAINER_ASF      },
1652         {"rm",                      MEDIA_MIMETYPE_CONTAINER_RM       },
1653         {"flv",                     MEDIA_MIMETYPE_CONTAINER_FLV      },
1654         {"avi",                     MEDIA_MIMETYPE_CONTAINER_AVI      },
1655         {"ape",                     MEDIA_MIMETYPE_CONTAINER_APE      },
1656         {"dts",                     MEDIA_MIMETYPE_CONTAINER_DTS      },
1657         {"flac",                    MEDIA_MIMETYPE_CONTAINER_FLAC     },
1658 #if 0
1659         {"wav",                     MEDIA_MIMETYPE_CONTAINER_WAV      },
1660 #endif
1661 };
1662
1663 static void adjustMPEG4Confidence(AVFormatContext *ic, float *confidence)
1664 {
1665         AVDictionary *tags = NULL;
1666         AVDictionaryEntry *tag = NULL;
1667
1668         tags = ic->metadata;
1669
1670         //NOTE: You can use command to show these tags,
1671         //e.g. "ffprobe -show_format 2012.mov"
1672
1673         tag = av_dict_get(tags, "major_brand", NULL, 0);
1674         if (!tag) {
1675                 return;
1676         }
1677
1678         ALOGV("major_brand tag is:%s", tag->value);
1679
1680         //when MEDIA_MIMETYPE_CONTAINER_MPEG4
1681         //WTF, MPEG4Extractor.cpp can not extractor mov format
1682         //NOTE: isCompatibleBrand(MPEG4Extractor.cpp)
1683         //  Won't promise that the following file types can be played.
1684         //  Just give these file types a chance.
1685         //  FOURCC('q', 't', ' ', ' '),  // Apple's QuickTime
1686         //So......
1687         if (!strcmp(tag->value, "qt  ")) {
1688                 ALOGI("format is mov, confidence should be larger than mpeg4");
1689                 //the MEDIA_MIMETYPE_CONTAINER_MPEG4 of confidence is 0.4f
1690                 *confidence = 0.41f;
1691         }
1692 }
1693
1694 static void adjustVideoCodecConfidence(AVFormatContext *ic,
1695                 enum AVCodecID codec_id, float *confidence)
1696 {
1697         //add to here
1698 }
1699
1700 static void adjustAudioCodecConfidence(AVFormatContext *ic,
1701                 enum AVCodecID codec_id, float *confidence)
1702 {
1703         switch (codec_id) {
1704         case CODEC_ID_AC3:
1705                 //TODO. if the other stream(e.g. mp3) is supported by stagefright
1706                 ALOGI("ffmpeg can demux ac3 only");
1707                 *confidence = 0.88f;
1708         default:
1709                 break;
1710         }
1711 }
1712
1713 static void adjustCodecConfidence(AVFormatContext *ic, float *confidence)
1714 {
1715         unsigned int idx = 0;
1716         AVCodecContext *avctx = NULL;
1717         AVMediaType     codec_type = AVMEDIA_TYPE_UNKNOWN;
1718         enum AVCodecID codec_id = AV_CODEC_ID_NONE;
1719
1720         for (idx = 0; idx < ic->nb_streams; idx++)
1721         {
1722                 avctx = ic->streams[idx]->codec;
1723                 codec_type = avctx->codec_type;
1724                 codec_id = avctx->codec_id;
1725
1726                 if (codec_type == AVMEDIA_TYPE_VIDEO) {
1727                         adjustVideoCodecConfidence(ic, codec_id, confidence);
1728                 } else if (codec_type == AVMEDIA_TYPE_AUDIO) {
1729                         adjustAudioCodecConfidence(ic, codec_id, confidence);
1730                 }
1731         }
1732 }
1733
1734 static void adjustConfidenceIfNeeded(const char *mime,
1735                 AVFormatContext *ic, float *confidence)
1736 {
1737         //check mime
1738         if (!strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_MPEG4)) {
1739                 adjustMPEG4Confidence(ic, confidence);
1740         } else {
1741                 //add to here;
1742         }
1743
1744         //check codec
1745         adjustCodecConfidence(ic, confidence);
1746 }
1747
1748 static const char *SniffFFMPEGCommon(const char *url, float *confidence)
1749 {
1750         size_t i = 0;
1751         int err = 0;
1752         const char *container = NULL;
1753         AVFormatContext *ic = NULL;
1754
1755         status_t status = initFFmpeg();
1756         if (status != OK) {
1757                 ALOGE("could not init ffmpeg");
1758                 return NULL;
1759         }
1760
1761         ic = avformat_alloc_context();
1762         if (!ic)
1763         {
1764                 ALOGE("oom for alloc avformat context");
1765                 goto fail;
1766         }
1767
1768         err = avformat_open_input(&ic, url, NULL, NULL);
1769         if (err < 0) {
1770                 ALOGE("avformat_open_input faild, url: %s err: %d", url, err);
1771                 goto fail;
1772         }
1773
1774         av_dump_format(ic, 0, url, 0);
1775
1776         ALOGI("FFmpegExtrator, url: %s, format_name: %s, format_long_name: %s",
1777                         url, ic->iformat->name, ic->iformat->long_name);
1778
1779         ALOGI("list the formats suppoted by ffmpeg: ");
1780         ALOGI("========================================");
1781         for (i = 0; i < NELEM(FILE_FORMATS); ++i) {
1782                 ALOGV("format_names[%02d]: %s", i, FILE_FORMATS[i].format);
1783         }
1784         ALOGI("========================================");
1785
1786         for (i = 0; i < NELEM(FILE_FORMATS); ++i) {
1787                 int len = strlen(FILE_FORMATS[i].format);
1788                 if (!av_strncasecmp(ic->iformat->name, FILE_FORMATS[i].format, len)) {
1789                         container = FILE_FORMATS[i].container;
1790                         break;
1791                 }
1792         }
1793
1794         if (container) {
1795                 adjustConfidenceIfNeeded(container, ic, confidence);
1796         }
1797
1798 fail:
1799         if (ic) {
1800                 avformat_close_input(&ic);
1801                 av_free(ic);
1802         }
1803         if (status == OK) {
1804                 deInitFFmpeg();
1805         }
1806
1807         return container;
1808 }
1809
1810 static const char *LegacySniffFFMPEG(const sp<DataSource> &source, float *confidence)
1811 {
1812         String8 uri = source->getUri();
1813         if (uri.empty()) {
1814                 return NULL;
1815         }
1816
1817         ALOGI("source url:%s", uri.string());
1818
1819         return SniffFFMPEGCommon(uri.string(), confidence);
1820 }
1821
1822 static const char *BetterSniffFFMPEG(const sp<DataSource> &source, float *confidence)
1823 {
1824         char url[128] = {0};
1825
1826         ALOGI("android-source:%p", source.get());
1827
1828         // pass the addr of smart pointer("source")
1829         snprintf(url, sizeof(url), "android-source:%p", source.get());
1830
1831         return SniffFFMPEGCommon(url, confidence);
1832 }
1833
1834 bool SniffFFMPEG(
1835         const sp<DataSource> &source, String8 *mimeType, float *confidence,
1836         sp<AMessage> *meta) {
1837         ALOGV("SniffFFMPEG");
1838
1839         *confidence = 0.08f;  // be the last resort, by default
1840
1841         const char *container = BetterSniffFFMPEG(source, confidence);
1842         if (!container) {
1843                 ALOGW("sniff through BetterSniffFFMPEG failed, try LegacySniffFFMPEG");
1844                 container = LegacySniffFFMPEG(source, confidence);
1845                 if (container) {
1846                         ALOGI("sniff through LegacySniffFFMPEG success");
1847                 }
1848         } else {
1849                 ALOGI("sniff through BetterSniffFFMPEG success");
1850         }
1851
1852         if (container == NULL) {
1853                 ALOGD("SniffFFMPEG failed to sniff this source");
1854                 return false;
1855         }
1856
1857         ALOGD("ffmpeg detected media content as '%s' with confidence %.2f",
1858                         container, *confidence);
1859
1860         /* use MPEG4Extractor(not extended extractor) for HTTP source only */
1861         if (!strcasecmp(container, MEDIA_MIMETYPE_CONTAINER_MPEG4)
1862                         && (source->flags() & DataSource::kIsCachingDataSource)) {
1863                 ALOGI("support container: %s, but it is caching data source, "
1864                                 "Don't use ffmpegextractor", container);
1865                 return false;
1866         }
1867
1868         mimeType->setTo(container);
1869
1870         *meta = new AMessage;
1871         (*meta)->setString("extended-extractor", "extended-extractor");
1872         (*meta)->setString("extended-extractor-subtype", "ffmpegextractor");
1873
1874         //debug only
1875         char value[PROPERTY_VALUE_MAX];
1876         property_get("sys.media.parser.ffmpeg", value, "0");
1877         if (atoi(value)) {
1878                 ALOGI("[debug] parser use ffmpeg");
1879                 *confidence = 0.88f;
1880         }
1881
1882         if (*confidence > 0.08f) {
1883                 (*meta)->setString("extended-extractor-use", "ffmpegextractor");
1884         }
1885
1886         return true;
1887 }
1888
1889 MediaExtractor *CreateFFmpegExtractor(const sp<DataSource> &source, const char *mime, const sp<AMessage> &meta) {
1890     MediaExtractor *ret = NULL;
1891     AString notuse;
1892     if (meta.get() && meta->findString("extended-extractor", &notuse) && (
1893             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_MPEG4)     ||
1894             !strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_MPEG)          ||
1895             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_MOV)       ||
1896             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_MATROSKA)  ||
1897             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_TS)        ||
1898             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_MPEG2PS)   ||
1899             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_AVI)       ||
1900             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_ASF)       ||
1901             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_WEBM)      ||
1902             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_WMV)       ||
1903             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_MPG)       ||
1904             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_FLV)       ||
1905             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_DIVX)      ||
1906             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_RM)        ||
1907             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_WAV)       ||
1908             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_FLAC)      ||
1909             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_APE)       ||
1910             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_DTS)       ||
1911             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_MP2)       ||
1912             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_RA)        ||
1913             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_WMA))) {
1914         ret = new FFmpegExtractor(source);
1915     }
1916
1917     ALOGD("%ssupported mime: %s", (ret ? "" : "un"), mime);
1918     return ret;
1919 }
1920
1921 }  // namespace android
1922
1923 extern "C" void getExtractorPlugin(android::MediaExtractor::Plugin *plugin)
1924 {
1925     plugin->sniff = android::SniffFFMPEG;
1926     plugin->create = android::CreateFFmpegExtractor;
1927 }