OSDN Git Service

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