OSDN Git Service

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