OSDN Git Service

stagefright-plugins: Use native sample format
[android-x86/external-stagefright-plugins.git] / extractor / FFmpegExtractor.cpp
1 /*
2  * Copyright 2012 Michael Chen <omxcodec@gmail.com>
3  * Copyright 2015 The CyanogenMod Project
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 //#define LOG_NDEBUG 0
19 #define LOG_TAG "FFmpegExtractor"
20 #include <utils/Log.h>
21
22 #include <stdint.h>
23 #include <limits.h> /* INT_MAX */
24 #include <inttypes.h>
25 #include <sys/prctl.h>
26
27 #include <utils/misc.h>
28 #include <utils/String8.h>
29 #include <cutils/properties.h>
30 #include <media/stagefright/foundation/ABitReader.h>
31 #include <media/stagefright/foundation/ABuffer.h>
32 #include <media/stagefright/foundation/ADebug.h>
33 #include <media/stagefright/foundation/AMessage.h>
34 #include <media/stagefright/foundation/hexdump.h>
35 #include <media/stagefright/DataSource.h>
36 #include <media/stagefright/MediaBuffer.h>
37 #include <media/stagefright/foundation/ADebug.h>
38 #include <media/stagefright/MediaDefs.h>
39 #include <media/stagefright/MediaErrors.h>
40 #include <media/stagefright/MediaSource.h>
41 #include <media/stagefright/MetaData.h>
42 #include <media/stagefright/Utils.h>
43 #include "include/avc_utils.h"
44
45 #include "utils/codec_utils.h"
46 #include "utils/ffmpeg_cmdutils.h"
47
48 #include "FFmpegExtractor.h"
49
50 #define MAX_QUEUE_SIZE (15 * 1024 * 1024)
51 #define MIN_AUDIOQ_SIZE (20 * 16 * 1024)
52 #define MIN_FRAMES 5
53 #define EXTRACTOR_MAX_PROBE_PACKETS 200
54 #define FF_MAX_EXTRADATA_SIZE ((1 << 28) - FF_INPUT_BUFFER_PADDING_SIZE)
55
56 #define WAIT_KEY_PACKET_AFTER_SEEK 1
57 #define SUPPOURT_UNKNOWN_FORMAT    1
58
59 //debug
60 #define DEBUG_READ_ENTRY           0
61 #define DEBUG_DISABLE_VIDEO        0
62 #define DEBUG_DISABLE_AUDIO        0
63 #define DEBUG_PKT                  0
64 #define DEBUG_FORMATS              0
65
66 enum {
67     NO_SEEK = 0,
68     SEEK,
69 };
70
71 namespace android {
72
73 struct FFmpegSource : public MediaSource {
74     FFmpegSource(const sp<FFmpegExtractor> &extractor, size_t index);
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 ~FFmpegSource();
85
86 private:
87     friend struct FFmpegExtractor;
88
89     sp<FFmpegExtractor> mExtractor;
90     size_t mTrackIndex;
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     int64_t mLastPTS;
105     int64_t mTargetTime;
106
107     DISALLOW_EVIL_CONSTRUCTORS(FFmpegSource);
108 };
109
110 ////////////////////////////////////////////////////////////////////////////////
111
112 FFmpegExtractor::FFmpegExtractor(const sp<DataSource> &source, const sp<AMessage> &meta)
113     : mDataSource(source),
114       mMeta(new MetaData),
115       mInitCheck(NO_INIT),
116       mFFmpegInited(false),
117       mFormatCtx(NULL),
118       mReaderThreadStarted(false) {
119     ALOGV("FFmpegExtractor::FFmpegExtractor");
120
121     fetchStuffsFromSniffedMeta(meta);
122
123     int err = initStreams();
124     if (err < 0) {
125         ALOGE("failed to init ffmpeg");
126         return;
127     }
128
129     // start reader here, as we want to extract extradata from bitstream if no extradata
130     startReaderThread();
131
132     while(mProbePkts <= EXTRACTOR_MAX_PROBE_PACKETS && !mEOF &&
133         (mFormatCtx->pb ? !mFormatCtx->pb->error : 1) &&
134         (mDefersToCreateVideoTrack || mDefersToCreateAudioTrack)) {
135         ALOGV("mProbePkts=%d", mProbePkts);
136         usleep(5000);
137     }
138
139     ALOGV("mProbePkts: %d, mEOF: %d, pb->error(if has): %d, mDefersToCreateVideoTrack: %d, mDefersToCreateAudioTrack: %d",
140         mProbePkts, mEOF, mFormatCtx->pb ? mFormatCtx->pb->error : 0, mDefersToCreateVideoTrack, mDefersToCreateAudioTrack);
141
142     mInitCheck = OK;
143 }
144
145 FFmpegExtractor::~FFmpegExtractor() {
146     ALOGV("FFmpegExtractor::~FFmpegExtractor");
147     // stop reader here if no track!
148     stopReaderThread();
149
150     Mutex::Autolock autoLock(mLock);
151     deInitStreams();
152 }
153
154 size_t FFmpegExtractor::countTracks() {
155     return mInitCheck == OK ? mTracks.size() : 0;
156 }
157
158 sp<MediaSource> FFmpegExtractor::getTrack(size_t index) {
159     ALOGV("FFmpegExtractor::getTrack[%d]", index);
160
161     if (mInitCheck != OK) {
162         return NULL;
163     }
164
165     if (index >= mTracks.size()) {
166         return NULL;
167     }
168
169     return new FFmpegSource(this, index);
170 }
171
172 sp<MetaData> FFmpegExtractor::getTrackMetaData(size_t index, uint32_t flags __unused) {
173     ALOGV("FFmpegExtractor::getTrackMetaData[%d]", index);
174
175     if (mInitCheck != OK) {
176         return NULL;
177     }
178
179     if (index >= mTracks.size()) {
180         return NULL;
181     }
182
183     /* Quick and dirty, just get a frame 1/4 in */
184     if (mTracks.itemAt(index).mIndex == mVideoStreamIdx) {
185         int64_t thumb_ts = av_rescale_q((mFormatCtx->streams[mVideoStreamIdx]->duration / 4),
186                 mFormatCtx->streams[mVideoStreamIdx]->time_base, AV_TIME_BASE_Q);
187         mTracks.itemAt(index).mMeta->setInt64(kKeyThumbnailTime, thumb_ts);
188     }
189
190     return mTracks.itemAt(index).mMeta;
191 }
192
193 sp<MetaData> FFmpegExtractor::getMetaData() {
194     ALOGV("FFmpegExtractor::getMetaData");
195
196     if (mInitCheck != OK) {
197         return NULL;
198     }
199
200     return mMeta;
201 }
202
203 uint32_t FFmpegExtractor::flags() const {
204     ALOGV("FFmpegExtractor::flags");
205
206     if (mInitCheck != OK) {
207         return 0;
208     }
209
210     uint32_t flags = CAN_PAUSE;
211
212     if (mFormatCtx->duration != AV_NOPTS_VALUE) {
213         flags |= CAN_SEEK_BACKWARD | CAN_SEEK_FORWARD | CAN_SEEK;
214     }
215
216     return flags;
217 }
218
219 int FFmpegExtractor::check_extradata(AVCodecContext *avctx)
220 {
221     enum AVCodecID codec_id = AV_CODEC_ID_NONE;
222     const char *name = NULL;
223     bool *defersToCreateTrack = NULL;
224     AVBitStreamFilterContext **bsfc = NULL;
225
226     // init
227     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
228         bsfc = &mVideoBsfc;
229         defersToCreateTrack = &mDefersToCreateVideoTrack;
230     } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO){
231         bsfc = &mAudioBsfc;
232         defersToCreateTrack = &mDefersToCreateAudioTrack;
233     }
234
235     codec_id = avctx->codec_id;
236
237     // ignore extradata
238     if (codec_id != AV_CODEC_ID_H264
239             && codec_id != AV_CODEC_ID_MPEG4
240             && codec_id != AV_CODEC_ID_MPEG1VIDEO
241             && codec_id != AV_CODEC_ID_MPEG2VIDEO
242             && codec_id != AV_CODEC_ID_AAC) {
243         return 1;
244     }
245
246     // is extradata compatible with android?
247     if (codec_id != AV_CODEC_ID_AAC) {
248         int is_compatible = is_extradata_compatible_with_android(avctx);
249         if (!is_compatible) {
250             ALOGI("%s extradata is not compatible with android, should to extract it from bitstream",
251                     av_get_media_type_string(avctx->codec_type));
252             *defersToCreateTrack = true;
253             *bsfc = NULL; // H264 don't need bsfc, only AAC?
254             return 0;
255         }
256         return 1;
257     }
258
259     if (codec_id == AV_CODEC_ID_AAC) {
260         name = "aac_adtstoasc";
261     }
262
263     if (avctx->extradata_size <= 0) {
264         ALOGI("No %s extradata found, should to extract it from bitstream",
265                 av_get_media_type_string(avctx->codec_type));
266         *defersToCreateTrack = true;
267          //CHECK(name != NULL);
268         if (!*bsfc && name) {
269             *bsfc = av_bitstream_filter_init(name);
270             if (!*bsfc) {
271                 ALOGE("Cannot open the %s BSF!", name);
272                 *defersToCreateTrack = false;
273                 return -1;
274             } else {
275                 ALOGV("open the %s bsf", name);
276                 return 0;
277             }
278         } else {
279             return 0;
280         }
281     }
282     return 1;
283 }
284
285 void FFmpegExtractor::printTime(int64_t time)
286 {
287     int hours, mins, secs, us;
288
289     if (time == AV_NOPTS_VALUE)
290         return;
291
292     secs = time / AV_TIME_BASE;
293     us = time % AV_TIME_BASE;
294     mins = secs / 60;
295     secs %= 60;
296     hours = mins / 60;
297     mins %= 60;
298     ALOGI("the time is %02d:%02d:%02d.%02d",
299         hours, mins, secs, (100 * us) / AV_TIME_BASE);
300 }
301
302 bool FFmpegExtractor::is_codec_supported(enum AVCodecID codec_id)
303 {
304     bool supported = false;
305
306     switch(codec_id) {
307     case AV_CODEC_ID_H264:
308     case AV_CODEC_ID_MPEG4:
309     case AV_CODEC_ID_H263:
310     case AV_CODEC_ID_H263P:
311     case AV_CODEC_ID_H263I:
312     case AV_CODEC_ID_AAC:
313     case AV_CODEC_ID_AC3:
314     case AV_CODEC_ID_MP2:
315     case AV_CODEC_ID_MP3:
316     case AV_CODEC_ID_MPEG1VIDEO:
317     case AV_CODEC_ID_MPEG2VIDEO:
318     case AV_CODEC_ID_WMV1:
319     case AV_CODEC_ID_WMV2:
320     case AV_CODEC_ID_WMV3:
321     case AV_CODEC_ID_VC1:
322     case AV_CODEC_ID_WMAV1:
323     case AV_CODEC_ID_WMAV2:
324     case AV_CODEC_ID_WMAPRO:
325     case AV_CODEC_ID_WMALOSSLESS:
326     case AV_CODEC_ID_RV20:
327     case AV_CODEC_ID_RV30:
328     case AV_CODEC_ID_RV40:
329     case AV_CODEC_ID_COOK:
330     case AV_CODEC_ID_APE:
331     case AV_CODEC_ID_DTS:
332     case AV_CODEC_ID_FLAC:
333     case AV_CODEC_ID_FLV1:
334     case AV_CODEC_ID_VORBIS:
335     case AV_CODEC_ID_HEVC:
336
337         supported = true;
338         break;
339     default:
340         ALOGD("unsuppoted codec(%s), but give it a chance",
341                 avcodec_get_name(codec_id));
342         //Won't promise that the following codec id can be supported.
343         //Just give these codecs a chance.
344         supported = true;
345         break;
346     }
347
348     return supported;
349 }
350
351 sp<MetaData> FFmpegExtractor::setVideoFormat(AVStream *stream)
352 {
353     AVCodecContext *avctx = NULL;
354     sp<MetaData> meta = NULL;
355
356     avctx = stream->codec;
357     CHECK_EQ(avctx->codec_type, AVMEDIA_TYPE_VIDEO);
358
359     switch(avctx->codec_id) {
360     case AV_CODEC_ID_H264:
361         if (avctx->extradata[0] == 1) {
362             meta = setAVCFormat(avctx);
363         } else {
364             meta = setH264Format(avctx);
365         }
366         break;
367     case AV_CODEC_ID_MPEG4:
368         meta = setMPEG4Format(avctx);
369         break;
370     case AV_CODEC_ID_H263:
371     case AV_CODEC_ID_H263P:
372     case AV_CODEC_ID_H263I:
373         meta = setH263Format(avctx);
374         break;
375     case AV_CODEC_ID_MPEG1VIDEO:
376     case AV_CODEC_ID_MPEG2VIDEO:
377         meta = setMPEG2VIDEOFormat(avctx);
378         break;
379     case AV_CODEC_ID_VC1:
380         meta = setVC1Format(avctx);
381         break;
382     case AV_CODEC_ID_WMV1:
383         meta = setWMV1Format(avctx);
384         break;
385     case AV_CODEC_ID_WMV2:
386         meta = setWMV2Format(avctx);
387         break;
388     case AV_CODEC_ID_WMV3:
389         meta = setWMV3Format(avctx);
390         break;
391     case AV_CODEC_ID_RV20:
392         meta = setRV20Format(avctx);
393         break;
394     case AV_CODEC_ID_RV30:
395         meta = setRV30Format(avctx);
396         break;
397     case AV_CODEC_ID_RV40:
398         meta = setRV40Format(avctx);
399         break;
400     case AV_CODEC_ID_FLV1:
401         meta = setFLV1Format(avctx);
402         break;
403     case AV_CODEC_ID_HEVC:
404         meta = setHEVCFormat(avctx);
405         break;
406     case AV_CODEC_ID_VP8:
407         meta = setVP8Format(avctx);
408         break;
409     case AV_CODEC_ID_VP9:
410         meta = setVP9Format(avctx);
411         break;
412     default:
413         ALOGD("unsuppoted video codec(id:%d, name:%s), but give it a chance",
414                 avctx->codec_id, avcodec_get_name(avctx->codec_id));
415         meta = new MetaData;
416         meta->setInt32(kKeyCodecId, avctx->codec_id);
417         meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_FFMPEG);
418         if (avctx->extradata_size > 0) {
419             meta->setData(kKeyRawCodecSpecificData, 0, avctx->extradata, avctx->extradata_size);
420         }
421         //CHECK(!"Should not be here. Unsupported codec.");
422         break;
423     }
424
425     if (meta != NULL) {
426         ALOGI("width: %d, height: %d, bit_rate: %d",
427                 avctx->width, avctx->height, avctx->bit_rate);
428
429         meta->setInt32(kKeyWidth, avctx->width);
430         meta->setInt32(kKeyHeight, avctx->height);
431         if (avctx->bit_rate > 0) {
432             meta->setInt32(kKeyBitRate, avctx->bit_rate);
433         }
434         setDurationMetaData(stream, meta);
435     }
436
437     return meta;
438 }
439
440 sp<MetaData> FFmpegExtractor::setAudioFormat(AVStream *stream)
441 {
442     AVCodecContext *avctx = NULL;
443     sp<MetaData> meta = NULL;
444
445     avctx = stream->codec;
446     CHECK_EQ(avctx->codec_type, AVMEDIA_TYPE_AUDIO);
447
448     switch(avctx->codec_id) {
449     case AV_CODEC_ID_MP2:
450         meta = setMP2Format(avctx);
451         break;
452     case AV_CODEC_ID_MP3:
453         meta = setMP3Format(avctx);
454         break;
455     case AV_CODEC_ID_VORBIS:
456         meta = setVORBISFormat(avctx);
457         break;
458     case AV_CODEC_ID_AC3:
459         meta = setAC3Format(avctx);
460         break;
461     case AV_CODEC_ID_AAC:
462         meta = setAACFormat(avctx);
463         break;
464     case AV_CODEC_ID_WMAV1:
465         meta = setWMAV1Format(avctx);
466         break;
467     case AV_CODEC_ID_WMAV2:
468         meta = setWMAV2Format(avctx);
469         break;
470     case AV_CODEC_ID_WMAPRO:
471         meta = setWMAProFormat(avctx);
472         break;
473     case AV_CODEC_ID_WMALOSSLESS:
474         meta = setWMALossLessFormat(avctx);
475         break;
476     case AV_CODEC_ID_COOK:
477         meta = setRAFormat(avctx);
478         break;
479     case AV_CODEC_ID_APE:
480         meta = setAPEFormat(avctx);
481         break;
482     case AV_CODEC_ID_DTS:
483         meta = setDTSFormat(avctx);
484         break;
485     case AV_CODEC_ID_FLAC:
486         meta = setFLACFormat(avctx);
487         break;
488     default:
489         ALOGD("unsuppoted audio codec(id:%d, name:%s), but give it a chance",
490                 avctx->codec_id, avcodec_get_name(avctx->codec_id));
491         meta = new MetaData;
492         meta->setInt32(kKeyCodecId, avctx->codec_id);
493         meta->setInt32(kKeyCodedSampleBits, avctx->bits_per_coded_sample);
494         meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_FFMPEG);
495         if (avctx->extradata_size > 0) {
496             meta->setData(kKeyRawCodecSpecificData, 0, avctx->extradata, avctx->extradata_size);
497         }
498         //CHECK(!"Should not be here. Unsupported codec.");
499         break;
500     }
501
502     if (meta != NULL) {
503         ALOGD("bit_rate: %d, sample_rate: %d, channels: %d, "
504                 "bits_per_coded_sample: %d, block_align: %d "
505                 "bits_per_raw_sample: %d, sample_format: %d",
506                 avctx->bit_rate, avctx->sample_rate, avctx->channels,
507                 avctx->bits_per_coded_sample, avctx->block_align,
508                 avctx->bits_per_raw_sample, avctx->sample_fmt);
509
510         meta->setInt32(kKeyChannelCount, avctx->channels);
511         meta->setInt32(kKeyBitRate, avctx->bit_rate);
512         int32_t bits = avctx->bits_per_raw_sample > 0 ?
513                 avctx->bits_per_raw_sample :
514                 av_get_bytes_per_sample(avctx->sample_fmt) * 8;
515         meta->setInt32(kKeyBitsPerSample, bits > 0 ? bits : 16);
516         meta->setInt32(kKeySampleRate, avctx->sample_rate);
517         meta->setInt32(kKeyBlockAlign, avctx->block_align);
518         meta->setInt32(kKeySampleFormat, avctx->sample_fmt);
519         meta->setInt32('pfmt', to_android_audio_format(avctx->sample_fmt));
520         setDurationMetaData(stream, meta);
521     }
522
523     return meta;
524 }
525
526 void FFmpegExtractor::setDurationMetaData(AVStream *stream, sp<MetaData> &meta)
527 {
528     AVCodecContext *avctx = stream->codec;
529
530     if (stream->duration != AV_NOPTS_VALUE) {
531         int64_t duration = av_rescale_q(stream->duration, stream->time_base, AV_TIME_BASE_Q);
532         printTime(duration);
533         const char *s = av_get_media_type_string(avctx->codec_type);
534         if (stream->start_time != AV_NOPTS_VALUE) {
535             ALOGV("%s startTime:%lld", s, stream->start_time);
536         } else {
537             ALOGV("%s startTime:N/A", s);
538         }
539         meta->setInt64(kKeyDuration, duration);
540     } else {
541         // default when no stream duration
542         meta->setInt64(kKeyDuration, mFormatCtx->duration);
543     }
544 }
545
546 int FFmpegExtractor::stream_component_open(int stream_index)
547 {
548     TrackInfo *trackInfo = NULL;
549     AVCodecContext *avctx = NULL;
550     sp<MetaData> meta = NULL;
551     bool supported = false;
552     uint32_t type = 0;
553     const void *data = NULL;
554     size_t size = 0;
555     int ret = 0;
556
557     ALOGI("stream_index: %d", stream_index);
558     if (stream_index < 0 || stream_index >= (int)mFormatCtx->nb_streams)
559         return -1;
560     avctx = mFormatCtx->streams[stream_index]->codec;
561
562     supported = is_codec_supported(avctx->codec_id);
563
564     if (!supported) {
565         ALOGE("unsupport the codec(%s)", avcodec_get_name(avctx->codec_id));
566         return -1;
567     }
568     ALOGI("support the codec(%s)", avcodec_get_name(avctx->codec_id));
569
570     unsigned streamType;
571     for (size_t i = 0; i < mTracks.size(); ++i) {
572         if (stream_index == mTracks.editItemAt(i).mIndex) {
573             ALOGE("this track already exists");
574             return 0;
575         }
576     }
577
578     mFormatCtx->streams[stream_index]->discard = AVDISCARD_DEFAULT;
579
580     char tagbuf[32];
581     av_get_codec_tag_string(tagbuf, sizeof(tagbuf), avctx->codec_tag);
582     ALOGV("Tag %s/0x%08x with codec(%s)\n", tagbuf, avctx->codec_tag, avcodec_get_name(avctx->codec_id));
583
584     switch (avctx->codec_type) {
585     case AVMEDIA_TYPE_VIDEO:
586         if (mVideoStreamIdx == -1)
587             mVideoStreamIdx = stream_index;
588         if (mVideoStream == NULL)
589             mVideoStream = mFormatCtx->streams[stream_index];
590
591         ret = check_extradata(avctx);
592         if (ret != 1) {
593             if (ret == -1) {
594                 // disable the stream
595                 mVideoStreamIdx = -1;
596                 mVideoStream = NULL;
597                 packet_queue_flush(&mVideoQ);
598                 mFormatCtx->streams[stream_index]->discard = AVDISCARD_ALL;
599             }
600             return ret;
601          }
602
603         if (avctx->extradata) {
604             ALOGV("video stream extradata:");
605             hexdump(avctx->extradata, avctx->extradata_size);
606         } else {
607             ALOGV("video stream no extradata, but we can ignore it.");
608         }
609
610         meta = setVideoFormat(mVideoStream);
611         if (meta == NULL) {
612             ALOGE("setVideoFormat failed");
613             return -1;
614         }
615
616         ALOGV("create a video track");
617         mTracks.push();
618         trackInfo = &mTracks.editItemAt(mTracks.size() - 1);
619         trackInfo->mIndex  = stream_index;
620         trackInfo->mMeta   = meta;
621         trackInfo->mStream = mVideoStream;
622         trackInfo->mQueue  = &mVideoQ;
623
624         mDefersToCreateVideoTrack = false;
625
626         break;
627     case AVMEDIA_TYPE_AUDIO:
628         if (mAudioStreamIdx == -1)
629             mAudioStreamIdx = stream_index;
630         if (mAudioStream == NULL)
631             mAudioStream = mFormatCtx->streams[stream_index];
632
633         ret = check_extradata(avctx);
634         if (ret != 1) {
635             if (ret == -1) {
636                 // disable the stream
637                 mAudioStreamIdx = -1;
638                 mAudioStream = NULL;
639                 packet_queue_flush(&mAudioQ);
640                 mFormatCtx->streams[stream_index]->discard = AVDISCARD_ALL;
641             }
642             return ret;
643         }
644
645         if (avctx->extradata) {
646             ALOGV("audio stream extradata(%d):", avctx->extradata_size);
647             hexdump(avctx->extradata, avctx->extradata_size);
648         } else {
649             ALOGV("audio stream no extradata, but we can ignore it.");
650         }
651
652         meta = setAudioFormat(mAudioStream);
653         if (meta == NULL) {
654             ALOGE("setAudioFormat failed");
655             return -1;
656         }
657
658         ALOGV("create a audio track");
659         mTracks.push();
660         trackInfo = &mTracks.editItemAt(mTracks.size() - 1);
661         trackInfo->mIndex  = stream_index;
662         trackInfo->mMeta   = meta;
663         trackInfo->mStream = mAudioStream;
664         trackInfo->mQueue  = &mAudioQ;
665
666         mDefersToCreateAudioTrack = false;
667
668         break;
669     case AVMEDIA_TYPE_SUBTITLE:
670         /* Unsupport now */
671         CHECK(!"Should not be here. Unsupported media type.");
672         break;
673     default:
674         CHECK(!"Should not be here. Unsupported media type.");
675         break;
676     }
677     return 0;
678 }
679
680 void FFmpegExtractor::stream_component_close(int stream_index)
681 {
682     AVCodecContext *avctx;
683
684     if (stream_index < 0 || stream_index >= (int)mFormatCtx->nb_streams)
685         return;
686     avctx = mFormatCtx->streams[stream_index]->codec;
687
688     switch (avctx->codec_type) {
689     case AVMEDIA_TYPE_VIDEO:
690         ALOGV("packet_queue_abort videoq");
691         packet_queue_abort(&mVideoQ);
692         ALOGV("packet_queue_end videoq");
693         packet_queue_flush(&mVideoQ);
694         break;
695     case AVMEDIA_TYPE_AUDIO:
696         ALOGV("packet_queue_abort audioq");
697         packet_queue_abort(&mAudioQ);
698         ALOGV("packet_queue_end audioq");
699         packet_queue_flush(&mAudioQ);
700         break;
701     case AVMEDIA_TYPE_SUBTITLE:
702         break;
703     default:
704         break;
705     }
706
707     mFormatCtx->streams[stream_index]->discard = AVDISCARD_ALL;
708     switch (avctx->codec_type) {
709     case AVMEDIA_TYPE_VIDEO:
710         mVideoStream    = NULL;
711         mVideoStreamIdx = -1;
712         if (mVideoBsfc) {
713             av_bitstream_filter_close(mVideoBsfc);
714             mVideoBsfc  = NULL;
715         }
716         break;
717     case AVMEDIA_TYPE_AUDIO:
718         mAudioStream    = NULL;
719         mAudioStreamIdx = -1;
720         if (mAudioBsfc) {
721             av_bitstream_filter_close(mAudioBsfc);
722             mAudioBsfc  = NULL;
723         }
724         break;
725     case AVMEDIA_TYPE_SUBTITLE:
726         break;
727     default:
728         break;
729     }
730 }
731
732 void FFmpegExtractor::reachedEOS(enum AVMediaType media_type)
733 {
734     Mutex::Autolock autoLock(mLock);
735
736     if (media_type == AVMEDIA_TYPE_VIDEO) {
737         mVideoEOSReceived = true;
738     } else if (media_type == AVMEDIA_TYPE_AUDIO) {
739         mAudioEOSReceived = true;
740     }
741     mCondition.signal();
742 }
743
744 /* seek in the stream */
745 int FFmpegExtractor::stream_seek(int64_t pos, enum AVMediaType media_type,
746         MediaSource::ReadOptions::SeekMode mode)
747 {
748     Mutex::Autolock _l(mLock);
749
750     if (mSeekIdx >= 0 || (mVideoStreamIdx >= 0
751             && mAudioStreamIdx >= 0
752             && media_type == AVMEDIA_TYPE_AUDIO
753             && !mVideoEOSReceived)) {
754        return NO_SEEK;
755     }
756
757     // flush immediately
758     if (mAudioStreamIdx >= 0)
759         packet_queue_flush(&mAudioQ);
760     if (mVideoStreamIdx >= 0)
761         packet_queue_flush(&mVideoQ);
762
763     mSeekIdx = media_type == AVMEDIA_TYPE_VIDEO ? mVideoStreamIdx : mAudioStreamIdx;
764     mSeekPos = pos;
765
766     //mSeekFlags &= ~AVSEEK_FLAG_BYTE;
767     //if (mSeekByBytes) {
768     //    mSeekFlags |= AVSEEK_FLAG_BYTE;
769     //}
770
771     switch (mode) {
772         case MediaSource::ReadOptions::SEEK_PREVIOUS_SYNC:
773             mSeekMin = INT64_MIN;
774             mSeekMax = mSeekPos;
775             break;
776         case MediaSource::ReadOptions::SEEK_NEXT_SYNC:
777             mSeekMin = mSeekPos;
778             mSeekMax = INT64_MAX;
779             break;
780         case MediaSource::ReadOptions::SEEK_CLOSEST_SYNC:
781             mSeekMin = INT64_MIN;
782             mSeekMax = INT64_MAX;
783             break;
784         case MediaSource::ReadOptions::SEEK_CLOSEST:
785             mSeekMin = INT64_MIN;
786             mSeekMax = mSeekPos;
787             break;
788         default:
789             TRESPASS();
790     }
791
792     mCondition.wait(mLock);
793     return SEEK;
794 }
795
796 // staitc
797 int FFmpegExtractor::decode_interrupt_cb(void *ctx)
798 {
799     FFmpegExtractor *extractor = static_cast<FFmpegExtractor *>(ctx);
800     return extractor->mAbortRequest;
801 }
802
803 void FFmpegExtractor::fetchStuffsFromSniffedMeta(const sp<AMessage> &meta)
804 {
805     AString url;
806     AString mime;
807
808     //url
809     CHECK(meta->findString("extended-extractor-url", &url));
810     CHECK(url.c_str() != NULL);
811     CHECK(url.size() < PATH_MAX);
812
813     memcpy(mFilename, url.c_str(), url.size());
814     mFilename[url.size()] = '\0';
815
816     //mime
817     CHECK(meta->findString("extended-extractor-mime", &mime));
818     CHECK(mime.c_str() != NULL);
819     mMeta->setCString(kKeyMIMEType, mime.c_str());
820 }
821
822 void FFmpegExtractor::setFFmpegDefaultOpts()
823 {
824     mGenPTS       = 0;
825 #if DEBUG_DISABLE_VIDEO
826     mVideoDisable = 1;
827 #else
828     mVideoDisable = 0;
829 #endif
830 #if DEBUG_DISABLE_AUDIO
831     mAudioDisable = 1;
832 #else
833     mAudioDisable = 0;
834 #endif
835     mShowStatus   = 0;
836     mSeekByBytes  = 0; /* seek by bytes 0=off 1=on -1=auto" */
837     mDuration     = AV_NOPTS_VALUE;
838     mSeekPos      = AV_NOPTS_VALUE;
839     mSeekMin      = INT64_MIN;
840     mSeekMax      = INT64_MAX;
841     mLoop         = 1;
842
843     mVideoStreamIdx = -1;
844     mAudioStreamIdx = -1;
845     mVideoStream  = NULL;
846     mAudioStream  = NULL;
847     mDefersToCreateVideoTrack = false;
848     mDefersToCreateAudioTrack = false;
849     mVideoBsfc = NULL;
850     mAudioBsfc = NULL;
851
852     mAbortRequest = 0;
853     mPaused       = 0;
854     mLastPaused   = 0;
855     mProbePkts    = 0;
856     mEOF          = false;
857
858     mSeekIdx      = -1;
859 }
860
861 int FFmpegExtractor::initStreams()
862 {
863     int err = 0;
864     int i = 0;
865     status_t status = UNKNOWN_ERROR;
866     int eof = 0;
867     int ret = 0, audio_ret = -1, video_ret = -1;
868     int pkt_in_play_range = 0;
869     AVDictionaryEntry *t = NULL;
870     AVDictionary **opts = NULL;
871     int orig_nb_streams = 0;
872     int st_index[AVMEDIA_TYPE_NB] = {0};
873     int wanted_stream[AVMEDIA_TYPE_NB] = {0};
874     st_index[AVMEDIA_TYPE_AUDIO]  = -1;
875     st_index[AVMEDIA_TYPE_VIDEO]  = -1;
876     wanted_stream[AVMEDIA_TYPE_AUDIO]  = -1;
877     wanted_stream[AVMEDIA_TYPE_VIDEO]  = -1;
878     const char *mime = NULL;
879
880     setFFmpegDefaultOpts();
881
882     status = initFFmpeg();
883     if (status != OK) {
884         ret = -1;
885         goto fail;
886     }
887     mFFmpegInited = true;
888
889     mFormatCtx = avformat_alloc_context();
890     if (!mFormatCtx)
891     {
892         ALOGE("oom for alloc avformat context");
893         ret = -1;
894         goto fail;
895     }
896     mFormatCtx->interrupt_callback.callback = decode_interrupt_cb;
897     mFormatCtx->interrupt_callback.opaque = this;
898     ALOGV("mFilename: %s", mFilename);
899     err = avformat_open_input(&mFormatCtx, mFilename, NULL, &format_opts);
900     if (err < 0) {
901         ALOGE("%s: avformat_open_input failed, err:%s", mFilename, av_err2str(err));
902         ret = -1;
903         goto fail;
904     }
905
906     if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
907         ALOGE("Option %s not found.\n", t->key);
908         //ret = AVERROR_OPTION_NOT_FOUND;
909         ret = -1;
910         goto fail;
911     }
912
913     if (mGenPTS)
914         mFormatCtx->flags |= AVFMT_FLAG_GENPTS;
915
916     opts = setup_find_stream_info_opts(mFormatCtx, codec_opts);
917     orig_nb_streams = mFormatCtx->nb_streams;
918
919     err = avformat_find_stream_info(mFormatCtx, opts);
920     if (err < 0) {
921         ALOGE("%s: could not find stream info, err:%s", mFilename, av_err2str(err));
922         ret = -1;
923         goto fail;
924     }
925     for (i = 0; i < orig_nb_streams; i++)
926         av_dict_free(&opts[i]);
927     av_freep(&opts);
928
929     if (mFormatCtx->pb)
930         mFormatCtx->pb->eof_reached = 0; // FIXME hack, ffplay maybe should not use url_feof() to test for the end
931
932     if (mSeekByBytes < 0)
933         mSeekByBytes = !!(mFormatCtx->iformat->flags & AVFMT_TS_DISCONT)
934             && strcmp("ogg", mFormatCtx->iformat->name);
935
936     for (i = 0; i < (int)mFormatCtx->nb_streams; i++)
937         mFormatCtx->streams[i]->discard = AVDISCARD_ALL;
938     if (!mVideoDisable)
939         st_index[AVMEDIA_TYPE_VIDEO] =
940             av_find_best_stream(mFormatCtx, AVMEDIA_TYPE_VIDEO,
941                                 wanted_stream[AVMEDIA_TYPE_VIDEO], -1, NULL, 0);
942     if (!mAudioDisable)
943         st_index[AVMEDIA_TYPE_AUDIO] =
944             av_find_best_stream(mFormatCtx, AVMEDIA_TYPE_AUDIO,
945                                 wanted_stream[AVMEDIA_TYPE_AUDIO],
946                                 st_index[AVMEDIA_TYPE_VIDEO],
947                                 NULL, 0);
948     if (mShowStatus) {
949         av_dump_format(mFormatCtx, 0, mFilename, 0);
950     }
951
952     if (mFormatCtx->duration != AV_NOPTS_VALUE &&
953             mFormatCtx->start_time != AV_NOPTS_VALUE) {
954         int hours, mins, secs, us;
955
956         ALOGV("file startTime: %lld", mFormatCtx->start_time);
957
958         mDuration = mFormatCtx->duration;
959
960         secs = mDuration / AV_TIME_BASE;
961         us = mDuration % AV_TIME_BASE;
962         mins = secs / 60;
963         secs %= 60;
964         hours = mins / 60;
965         mins %= 60;
966         ALOGI("the duration is %02d:%02d:%02d.%02d",
967             hours, mins, secs, (100 * us) / AV_TIME_BASE);
968     }
969
970     packet_queue_init(&mVideoQ);
971     packet_queue_init(&mAudioQ);
972
973     if (st_index[AVMEDIA_TYPE_AUDIO] >= 0) {
974         audio_ret = stream_component_open(st_index[AVMEDIA_TYPE_AUDIO]);
975         if (audio_ret >= 0)
976             packet_queue_start(&mAudioQ);
977     }
978
979     if (st_index[AVMEDIA_TYPE_VIDEO] >= 0) {
980         video_ret = stream_component_open(st_index[AVMEDIA_TYPE_VIDEO]);
981         if (video_ret >= 0)
982             packet_queue_start(&mVideoQ);
983     }
984
985     if ( audio_ret < 0 && video_ret < 0) {
986         ALOGE("%s: could not open codecs\n", mFilename);
987         ret = -1;
988         goto fail;
989     }
990
991     ret = 0;
992
993 fail:
994     return ret;
995 }
996
997 void FFmpegExtractor::deInitStreams()
998 {
999     packet_queue_destroy(&mVideoQ);
1000     packet_queue_destroy(&mAudioQ);
1001
1002     if (mFormatCtx) {
1003         avformat_close_input(&mFormatCtx);
1004     }
1005
1006     if (mFFmpegInited) {
1007         deInitFFmpeg();
1008     }
1009 }
1010
1011 status_t FFmpegExtractor::startReaderThread() {
1012     ALOGV("Starting reader thread");
1013
1014     if (mReaderThreadStarted)
1015         return OK;
1016
1017     pthread_attr_t attr;
1018     pthread_attr_init(&attr);
1019     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1020
1021     ALOGD("Reader thread starting");
1022
1023     pthread_create(&mReaderThread, &attr, ReaderWrapper, this);
1024     pthread_attr_destroy(&attr);
1025
1026     mReaderThreadStarted = true;
1027     mCondition.signal();
1028
1029     return OK;
1030 }
1031
1032 void FFmpegExtractor::stopReaderThread() {
1033     ALOGV("Stopping reader thread");
1034
1035     mLock.lock();
1036
1037     if (!mReaderThreadStarted) {
1038         ALOGD("Reader thread have been stopped");
1039         mLock.unlock();
1040         return;
1041     }
1042
1043     mAbortRequest = 1;
1044     mCondition.signal();
1045
1046     /* close each stream */
1047     if (mAudioStreamIdx >= 0)
1048         stream_component_close(mAudioStreamIdx);
1049     if (mVideoStreamIdx >= 0)
1050         stream_component_close(mVideoStreamIdx);
1051
1052     mLock.unlock();
1053     pthread_join(mReaderThread, NULL);
1054     mLock.lock();
1055
1056     if (mFormatCtx) {
1057         avformat_close_input(&mFormatCtx);
1058     }
1059
1060     mReaderThreadStarted = false;
1061     ALOGD("Reader thread stopped");
1062
1063     mLock.unlock();
1064 }
1065
1066 // static
1067 void *FFmpegExtractor::ReaderWrapper(void *me) {
1068     ((FFmpegExtractor *)me)->readerEntry();
1069
1070     return NULL;
1071 }
1072
1073 void FFmpegExtractor::readerEntry() {
1074     int err, i, ret;
1075     AVPacket pkt1, *pkt = &pkt1;
1076     int eof = 0;
1077     int pkt_in_play_range = 0;
1078
1079     mLock.lock();
1080
1081     pid_t tid  = gettid();
1082     androidSetThreadPriority(tid,
1083             mVideoStreamIdx >= 0 ? ANDROID_PRIORITY_NORMAL : ANDROID_PRIORITY_AUDIO);
1084     prctl(PR_SET_NAME, (unsigned long)"FFmpegExtractor Thread", 0, 0, 0);
1085
1086     ALOGV("FFmpegExtractor wait for signal");
1087     while (!mReaderThreadStarted && !mAbortRequest) {
1088         mCondition.wait(mLock);
1089     }
1090     ALOGV("FFmpegExtractor ready to run");
1091     mLock.unlock();
1092     if (mAbortRequest) {
1093         return;
1094     }
1095
1096     mVideoEOSReceived = false;
1097     mAudioEOSReceived = false;
1098
1099     while (!mAbortRequest) {
1100
1101         if (mPaused != mLastPaused) {
1102             mLastPaused = mPaused;
1103             if (mPaused)
1104                 mReadPauseReturn = av_read_pause(mFormatCtx);
1105             else
1106                 av_read_play(mFormatCtx);
1107         }
1108 #if CONFIG_RTSP_DEMUXER || CONFIG_MMSH_PROTOCOL
1109         if (mPaused &&
1110                 (!strcmp(mFormatCtx->iformat->name, "rtsp") ||
1111                  (mFormatCtx->pb && !strncmp(mFilename, "mmsh:", 5)))) {
1112             /* wait 10 ms to avoid trying to get another packet */
1113             /* XXX: horrible */
1114             usleep(10000);
1115             continue;
1116         }
1117 #endif
1118
1119         if (mSeekIdx >= 0) {
1120             Mutex::Autolock _l(mLock);
1121             ALOGV("readerEntry, mSeekIdx: %d mSeekPos: %lld (%lld/%lld)", mSeekIdx, mSeekPos, mSeekMin, mSeekMax);
1122             ret = avformat_seek_file(mFormatCtx, -1, mSeekMin, mSeekPos, mSeekMax, 0);
1123             if (ret < 0) {
1124                 ALOGE("%s: error while seeking", mFormatCtx->filename);
1125             } else {
1126                 if (mAudioStreamIdx >= 0) {
1127                     packet_queue_flush(&mAudioQ);
1128                     packet_queue_put(&mAudioQ, &mAudioQ.flush_pkt);
1129                 }
1130                 if (mVideoStreamIdx >= 0) {
1131                     packet_queue_flush(&mVideoQ);
1132                     packet_queue_put(&mVideoQ, &mVideoQ.flush_pkt);
1133                 }
1134             }
1135             mSeekIdx = -1;
1136             eof = false;
1137             mCondition.signal();
1138         }
1139
1140         /* if the queue are full, no need to read more */
1141         if (   mAudioQ.size + mVideoQ.size > MAX_QUEUE_SIZE
1142             || (   (mAudioQ   .size  > MIN_AUDIOQ_SIZE || mAudioStreamIdx < 0)
1143                 && (mVideoQ   .nb_packets > MIN_FRAMES || mVideoStreamIdx < 0))) {
1144 #if DEBUG_READ_ENTRY
1145             ALOGV("readerEntry, full(wtf!!!), mVideoQ.size: %d, mVideoQ.nb_packets: %d, mAudioQ.size: %d, mAudioQ.nb_packets: %d",
1146                     mVideoQ.size, mVideoQ.nb_packets, mAudioQ.size, mAudioQ.nb_packets);
1147 #endif
1148             /* wait 10 ms */
1149             mExtractorMutex.lock();
1150             mCondition.waitRelative(mExtractorMutex, milliseconds(10));
1151             mExtractorMutex.unlock();
1152             continue;
1153         }
1154
1155         if (eof) {
1156             if (mVideoStreamIdx >= 0) {
1157                 packet_queue_put_nullpacket(&mVideoQ, mVideoStreamIdx);
1158             }
1159             if (mAudioStreamIdx >= 0) {
1160                 packet_queue_put_nullpacket(&mAudioQ, mAudioStreamIdx);
1161             }
1162             /* wait 10 ms */
1163             mExtractorMutex.lock();
1164             mCondition.waitRelative(mExtractorMutex, milliseconds(10));
1165             eof = false;
1166             mExtractorMutex.unlock();
1167             continue;
1168         }
1169
1170         ret = av_read_frame(mFormatCtx, pkt);
1171
1172         mProbePkts++;
1173         if (ret < 0) {
1174             mEOF = true;
1175             eof = true;
1176             if (mFormatCtx->pb && mFormatCtx->pb->error) {
1177                 ALOGE("mFormatCtx->pb->error: %d", mFormatCtx->pb->error);
1178                 break;
1179             }
1180             /* wait 10 ms */
1181             mExtractorMutex.lock();
1182             mCondition.waitRelative(mExtractorMutex, milliseconds(10));
1183             mExtractorMutex.unlock();
1184             continue;
1185         }
1186
1187         if (pkt->stream_index == mVideoStreamIdx) {
1188              if (mDefersToCreateVideoTrack) {
1189                 AVCodecContext *avctx = mFormatCtx->streams[mVideoStreamIdx]->codec;
1190
1191                 int i = parser_split(avctx, pkt->data, pkt->size);
1192                 if (i > 0 && i < FF_MAX_EXTRADATA_SIZE) {
1193                     if (avctx->extradata)
1194                         av_freep(&avctx->extradata);
1195                     avctx->extradata_size= i;
1196                     avctx->extradata = (uint8_t *)av_malloc(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
1197                     if (!avctx->extradata) {
1198                         //return AVERROR(ENOMEM);
1199                         ret = AVERROR(ENOMEM);
1200                         goto fail;
1201                     }
1202                     // sps + pps(there may be sei in it)
1203                     memcpy(avctx->extradata, pkt->data, avctx->extradata_size);
1204                     memset(avctx->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
1205                 } else {
1206                     av_free_packet(pkt);
1207                     continue;
1208                 }
1209
1210                 stream_component_open(mVideoStreamIdx);
1211                 if (!mDefersToCreateVideoTrack)
1212                     ALOGI("probe packet counter: %d when create video track ok", mProbePkts);
1213                 if (mProbePkts == EXTRACTOR_MAX_PROBE_PACKETS)
1214                     ALOGI("probe packet counter to max: %d, create video track: %d",
1215                         mProbePkts, !mDefersToCreateVideoTrack);
1216             }
1217         } else if (pkt->stream_index == mAudioStreamIdx) {
1218             int ret;
1219             uint8_t *outbuf;
1220             int   outbuf_size;
1221             AVCodecContext *avctx = mFormatCtx->streams[mAudioStreamIdx]->codec;
1222             if (mAudioBsfc && pkt && pkt->data) {
1223                 ret = av_bitstream_filter_filter(mAudioBsfc, avctx, NULL, &outbuf, &outbuf_size,
1224                                    pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY);
1225
1226                 if (ret < 0 ||!outbuf_size) {
1227                     av_free_packet(pkt);
1228                     continue;
1229                 }
1230                 if (outbuf && outbuf != pkt->data) {
1231                     memmove(pkt->data, outbuf, outbuf_size);
1232                     pkt->size = outbuf_size;
1233                 }
1234             }
1235             if (mDefersToCreateAudioTrack) {
1236                 if (avctx->extradata_size <= 0) {
1237                     av_free_packet(pkt);
1238                     continue;
1239                 }
1240                 stream_component_open(mAudioStreamIdx);
1241                 if (!mDefersToCreateAudioTrack)
1242                     ALOGI("probe packet counter: %d when create audio track ok", mProbePkts);
1243                 if (mProbePkts == EXTRACTOR_MAX_PROBE_PACKETS)
1244                     ALOGI("probe packet counter to max: %d, create audio track: %d",
1245                         mProbePkts, !mDefersToCreateAudioTrack);
1246             }
1247         }
1248
1249         if (pkt->stream_index == mAudioStreamIdx) {
1250             packet_queue_put(&mAudioQ, pkt);
1251         } else if (pkt->stream_index == mVideoStreamIdx) {
1252             packet_queue_put(&mVideoQ, pkt);
1253         } else {
1254             av_free_packet(pkt);
1255         }
1256     }
1257
1258     ret = 0;
1259
1260 fail:
1261     ALOGV("FFmpegExtractor exit thread(readerEntry)");
1262 }
1263
1264 ////////////////////////////////////////////////////////////////////////////////
1265
1266 FFmpegSource::FFmpegSource(
1267         const sp<FFmpegExtractor> &extractor, size_t index)
1268     : mExtractor(extractor),
1269       mTrackIndex(index),
1270       mIsAVC(false),
1271       mNal2AnnexB(false),
1272       mStream(mExtractor->mTracks.itemAt(index).mStream),
1273       mQueue(mExtractor->mTracks.itemAt(index).mQueue),
1274       mLastPTS(AV_NOPTS_VALUE),
1275       mTargetTime(AV_NOPTS_VALUE) {
1276     sp<MetaData> meta = mExtractor->mTracks.itemAt(index).mMeta;
1277
1278     {
1279         AVCodecContext *avctx = mStream->codec;
1280
1281         /* Parse codec specific data */
1282         if (avctx->codec_id == AV_CODEC_ID_H264
1283                 && avctx->extradata_size > 0
1284                 && avctx->extradata[0] == 1) {
1285             mIsAVC = true;
1286
1287             uint32_t type;
1288             const void *data;
1289             size_t size;
1290             CHECK(meta->findData(kKeyAVCC, &type, &data, &size));
1291
1292             const uint8_t *ptr = (const uint8_t *)data;
1293
1294             CHECK(size >= 7);
1295             CHECK_EQ((unsigned)ptr[0], 1u);  // configurationVersion == 1
1296
1297             // The number of bytes used to encode the length of a NAL unit.
1298             mNALLengthSize = 1 + (ptr[4] & 3);
1299
1300             ALOGV("the stream is AVC, the length of a NAL unit: %d", mNALLengthSize);
1301
1302             mNal2AnnexB = true;
1303         }
1304     }
1305
1306     mMediaType = mStream->codec->codec_type;
1307     mFirstKeyPktTimestamp = AV_NOPTS_VALUE;
1308 }
1309
1310 FFmpegSource::~FFmpegSource() {
1311     ALOGV("FFmpegSource::~FFmpegSource %s",
1312             av_get_media_type_string(mMediaType));
1313     mExtractor = NULL;
1314 }
1315
1316 status_t FFmpegSource::start(MetaData *params __unused) {
1317     ALOGV("FFmpegSource::start %s",
1318             av_get_media_type_string(mMediaType));
1319     return OK;
1320 }
1321
1322 status_t FFmpegSource::stop() {
1323     ALOGV("FFmpegSource::stop %s",
1324             av_get_media_type_string(mMediaType));
1325     return OK;
1326 }
1327
1328 sp<MetaData> FFmpegSource::getFormat() {
1329     return mExtractor->mTracks.itemAt(mTrackIndex).mMeta;;
1330 }
1331
1332 status_t FFmpegSource::read(
1333         MediaBuffer **buffer, const ReadOptions *options) {
1334     *buffer = NULL;
1335
1336     AVPacket pkt;
1337     bool seeking = false;
1338     bool waitKeyPkt = false;
1339     ReadOptions::SeekMode mode;
1340     int64_t pktTS = AV_NOPTS_VALUE;
1341     int64_t seekTimeUs = AV_NOPTS_VALUE;
1342     int64_t timeUs = AV_NOPTS_VALUE;
1343     int key = 0;
1344     status_t status = OK;
1345
1346     int64_t startTimeUs = mStream->start_time == AV_NOPTS_VALUE ? 0 :
1347         av_rescale_q(mStream->start_time, mStream->time_base, AV_TIME_BASE_Q);
1348
1349     if (options && options->getSeekTo(&seekTimeUs, &mode)) {
1350         int64_t seekPTS = seekTimeUs;
1351         ALOGV("~~~%s seekTimeUs: %lld, seekPTS: %lld, mode: %d", av_get_media_type_string(mMediaType), seekTimeUs, seekPTS, mode);
1352         /* add the stream start time */
1353         if (mStream->start_time != AV_NOPTS_VALUE) {
1354             seekPTS += startTimeUs;
1355         }
1356         ALOGV("~~~%s seekTimeUs[+startTime]: %lld, mode: %d start_time=%lld", av_get_media_type_string(mMediaType), seekPTS, mode, startTimeUs);
1357         seeking = (mExtractor->stream_seek(seekPTS, mMediaType, mode) == SEEK);
1358     }
1359
1360 retry:
1361     if (packet_queue_get(mQueue, &pkt, 1) < 0) {
1362         ALOGD("read %s abort reqeust", av_get_media_type_string(mMediaType));
1363         mExtractor->reachedEOS(mMediaType);
1364         return ERROR_END_OF_STREAM;
1365     }
1366
1367     if (seeking) {
1368         if (pkt.data != mQueue->flush_pkt.data) {
1369             av_free_packet(&pkt);
1370             goto retry;
1371         } else {
1372             seeking = false;
1373 #if WAIT_KEY_PACKET_AFTER_SEEK
1374             waitKeyPkt = true;
1375 #endif
1376         }
1377     }
1378
1379     if (pkt.data == mQueue->flush_pkt.data) {
1380         ALOGV("read %s flush pkt", av_get_media_type_string(mMediaType));
1381         av_free_packet(&pkt);
1382         mFirstKeyPktTimestamp = AV_NOPTS_VALUE;
1383         goto retry;
1384     } else if (pkt.data == NULL && pkt.size == 0) {
1385         ALOGD("read %s eos pkt", av_get_media_type_string(mMediaType));
1386         av_free_packet(&pkt);
1387         mExtractor->reachedEOS(mMediaType);
1388         return ERROR_END_OF_STREAM;
1389     }
1390
1391     key = pkt.flags & AV_PKT_FLAG_KEY ? 1 : 0;
1392     pktTS = pkt.pts == AV_NOPTS_VALUE ? pkt.dts : pkt.pts;
1393
1394     if (waitKeyPkt) {
1395         if (!key) {
1396             ALOGV("drop the non-key packet");
1397             av_free_packet(&pkt);
1398             goto retry;
1399         } else {
1400             ALOGV("~~~~~~ got the key packet");
1401             waitKeyPkt = false;
1402         }
1403     }
1404
1405     if (pktTS != AV_NOPTS_VALUE && mFirstKeyPktTimestamp == AV_NOPTS_VALUE) {
1406         // update the first key timestamp
1407         mFirstKeyPktTimestamp = pktTS;
1408     }
1409
1410     MediaBuffer *mediaBuffer = new MediaBuffer(pkt.size + FF_INPUT_BUFFER_PADDING_SIZE);
1411     mediaBuffer->meta_data()->clear();
1412     mediaBuffer->set_range(0, pkt.size);
1413
1414     //copy data
1415     if (mIsAVC && mNal2AnnexB) {
1416         /* This only works for NAL sizes 3-4 */
1417         CHECK(mNALLengthSize == 3 || mNALLengthSize == 4);
1418
1419         uint8_t *dst = (uint8_t *)mediaBuffer->data();
1420         /* Convert H.264 NAL format to annex b */
1421         status = convertNal2AnnexB(dst, pkt.size, pkt.data, pkt.size, mNALLengthSize);
1422         if (status != OK) {
1423             ALOGE("convertNal2AnnexB failed");
1424             mediaBuffer->release();
1425             mediaBuffer = NULL;
1426             av_free_packet(&pkt);
1427             return ERROR_MALFORMED;
1428         }
1429     } else {
1430         memcpy(mediaBuffer->data(), pkt.data, pkt.size);
1431     }
1432
1433     if (pktTS != AV_NOPTS_VALUE)
1434         timeUs = av_rescale_q(pktTS, mStream->time_base, AV_TIME_BASE_Q) - startTimeUs;
1435     else
1436         timeUs = SF_NOPTS_VALUE; //FIXME AV_NOPTS_VALUE is negative, but stagefright need positive
1437
1438     // predict the next PTS to use for exact-frame seek below
1439     int64_t nextPTS = AV_NOPTS_VALUE;
1440     if (mLastPTS != AV_NOPTS_VALUE && timeUs > mLastPTS) {
1441         nextPTS = timeUs + (timeUs - mLastPTS);
1442         mLastPTS = timeUs;
1443     } else if (mLastPTS == AV_NOPTS_VALUE) {
1444         mLastPTS = timeUs;
1445     }
1446
1447 #if DEBUG_PKT
1448     if (pktTS != AV_NOPTS_VALUE)
1449         ALOGV("read %s pkt, size:%d, key:%d, pktPTS: %lld, pts:%lld, dts:%lld, timeUs[-startTime]:%lld us (%.2f secs) start_time=%lld",
1450             av_get_media_type_string(mMediaType), pkt.size, key, pktTS, pkt.pts, pkt.dts, timeUs, timeUs/1E6, startTimeUs);
1451     else
1452         ALOGV("read %s pkt, size:%d, key:%d, pts:N/A, dts:N/A, timeUs[-startTime]:N/A",
1453             av_get_media_type_string(mMediaType), pkt.size, key);
1454 #endif
1455
1456     mediaBuffer->meta_data()->setInt64(kKeyTime, timeUs);
1457     mediaBuffer->meta_data()->setInt32(kKeyIsSyncFrame, key);
1458
1459     // deal with seek-to-exact-frame, we might be off a bit and Stagefright will assert on us
1460     if (seekTimeUs != AV_NOPTS_VALUE && timeUs < seekTimeUs &&
1461             mode == MediaSource::ReadOptions::SEEK_CLOSEST) {
1462         mTargetTime = seekTimeUs;
1463         mediaBuffer->meta_data()->setInt64(kKeyTargetTime, seekTimeUs);
1464     }
1465
1466     if (mTargetTime != AV_NOPTS_VALUE) {
1467         if (timeUs == mTargetTime) {
1468             mTargetTime = AV_NOPTS_VALUE;
1469         } else if (nextPTS != AV_NOPTS_VALUE && nextPTS > mTargetTime) {
1470             ALOGV("adjust target frame time to %lld", timeUs);
1471             mediaBuffer->meta_data()->setInt64(kKeyTime, mTargetTime);
1472             mTargetTime = AV_NOPTS_VALUE;
1473         }
1474     }
1475
1476     *buffer = mediaBuffer;
1477
1478     av_free_packet(&pkt);
1479
1480     return OK;
1481 }
1482
1483 ////////////////////////////////////////////////////////////////////////////////
1484
1485 typedef struct {
1486     const char *format;
1487     const char *container;
1488 } formatmap;
1489
1490 static formatmap FILE_FORMATS[] = {
1491         {"mpeg",                    MEDIA_MIMETYPE_CONTAINER_MPEG2PS  },
1492         {"mpegts",                  MEDIA_MIMETYPE_CONTAINER_TS       },
1493         {"mov,mp4,m4a,3gp,3g2,mj2", MEDIA_MIMETYPE_CONTAINER_MPEG4    },
1494         {"matroska,webm",           MEDIA_MIMETYPE_CONTAINER_MATROSKA },
1495         {"asf",                     MEDIA_MIMETYPE_CONTAINER_ASF      },
1496         {"rm",                      MEDIA_MIMETYPE_CONTAINER_RM       },
1497         {"flv",                     MEDIA_MIMETYPE_CONTAINER_FLV      },
1498         {"swf",                     MEDIA_MIMETYPE_CONTAINER_FLV      },
1499         {"avi",                     MEDIA_MIMETYPE_CONTAINER_AVI      },
1500         {"ape",                     MEDIA_MIMETYPE_CONTAINER_APE      },
1501         {"dts",                     MEDIA_MIMETYPE_CONTAINER_DTS      },
1502         {"flac",                    MEDIA_MIMETYPE_CONTAINER_FLAC     },
1503         {"ac3",                     MEDIA_MIMETYPE_AUDIO_AC3          },
1504         {"mp3",                     MEDIA_MIMETYPE_AUDIO_MPEG         },
1505         {"wav",                     MEDIA_MIMETYPE_CONTAINER_WAV      },
1506         {"ogg",                     MEDIA_MIMETYPE_CONTAINER_OGG      },
1507         {"vc1",                     MEDIA_MIMETYPE_CONTAINER_VC1      },
1508         {"hevc",                    MEDIA_MIMETYPE_CONTAINER_HEVC     },
1509         {"divx",                    MEDIA_MIMETYPE_CONTAINER_DIVX     },
1510 };
1511
1512 static AVCodecContext* getCodecContext(AVFormatContext *ic, AVMediaType codec_type)
1513 {
1514     unsigned int idx = 0;
1515     AVCodecContext *avctx = NULL;
1516
1517     for (idx = 0; idx < ic->nb_streams; idx++) {
1518         if (ic->streams[idx]->disposition & AV_DISPOSITION_ATTACHED_PIC) {
1519             // FFMPEG converts album art to MJPEG, but we don't want to
1520             // include that in the parsing as MJPEG is not supported by
1521             // Android, which forces the media to be extracted by FFMPEG
1522             // while in fact, Android supports it.
1523             continue;
1524         }
1525
1526         avctx = ic->streams[idx]->codec;
1527         if (avctx->codec_type == codec_type) {
1528             return avctx;
1529         }
1530     }
1531
1532     return NULL;
1533 }
1534
1535 static enum AVCodecID getCodecId(AVFormatContext *ic, AVMediaType codec_type)
1536 {
1537     AVCodecContext *avctx = getCodecContext(ic, codec_type);
1538     return avctx == NULL ? AV_CODEC_ID_NONE : avctx->codec_id;
1539 }
1540
1541 static bool hasAudioCodecOnly(AVFormatContext *ic)
1542 {
1543     enum AVCodecID codec_id = AV_CODEC_ID_NONE;
1544     bool haveVideo = false;
1545     bool haveAudio = false;
1546
1547     if (getCodecId(ic, AVMEDIA_TYPE_VIDEO) != AV_CODEC_ID_NONE) {
1548         haveVideo = true;
1549     }
1550     if (getCodecId(ic, AVMEDIA_TYPE_AUDIO) != AV_CODEC_ID_NONE) {
1551         haveAudio = true;
1552     }
1553
1554     if (!haveVideo && haveAudio) {
1555         return true;
1556     }
1557
1558     return false;
1559 }
1560
1561 //FIXME all codecs: frameworks/av/media/libstagefright/codecs/*
1562 static bool isCodecSupportedByStagefright(enum AVCodecID codec_id)
1563 {
1564     bool supported = false;
1565
1566     switch(codec_id) {
1567     //video
1568     case AV_CODEC_ID_HEVC:
1569     case AV_CODEC_ID_H264:
1570     case AV_CODEC_ID_MPEG4:
1571     case AV_CODEC_ID_H263:
1572     case AV_CODEC_ID_H263P:
1573     case AV_CODEC_ID_H263I:
1574     case AV_CODEC_ID_VP6:
1575     case AV_CODEC_ID_VP8:
1576     case AV_CODEC_ID_VP9:
1577     //audio
1578     case AV_CODEC_ID_AAC:
1579     case AV_CODEC_ID_MP3:
1580     case AV_CODEC_ID_AMR_NB:
1581     case AV_CODEC_ID_AMR_WB:
1582     case AV_CODEC_ID_FLAC:
1583     case AV_CODEC_ID_VORBIS:
1584     case AV_CODEC_ID_PCM_MULAW: //g711
1585     case AV_CODEC_ID_PCM_ALAW:  //g711
1586     case AV_CODEC_ID_GSM_MS:
1587     case AV_CODEC_ID_PCM_U8:
1588     case AV_CODEC_ID_PCM_S16LE:
1589     case AV_CODEC_ID_PCM_S24LE:
1590         supported = true;
1591         break;
1592
1593     default:
1594         break;
1595     }
1596
1597     ALOGD("%ssuppoted codec(%s) by official Stagefright",
1598             (supported ? "" : "un"),
1599             avcodec_get_name(codec_id));
1600
1601     return supported;
1602 }
1603
1604 static void adjustMPEG4Confidence(AVFormatContext *ic, float *confidence)
1605 {
1606     AVDictionary *tags = NULL;
1607     AVDictionaryEntry *tag = NULL;
1608     enum AVCodecID codec_id = AV_CODEC_ID_NONE;
1609
1610     //1. check codec id
1611     codec_id = getCodecId(ic, AVMEDIA_TYPE_VIDEO);
1612     if (codec_id != AV_CODEC_ID_NONE
1613             && codec_id != AV_CODEC_ID_HEVC
1614             && codec_id != AV_CODEC_ID_H264
1615             && codec_id != AV_CODEC_ID_MPEG4
1616             && codec_id != AV_CODEC_ID_H263
1617             && codec_id != AV_CODEC_ID_H263P
1618             && codec_id != AV_CODEC_ID_H263I) {
1619         //the MEDIA_MIMETYPE_CONTAINER_MPEG4 of confidence is 0.4f
1620         ALOGI("[mp4]video codec(%s), confidence should be larger than MPEG4Extractor",
1621                 avcodec_get_name(codec_id));
1622         *confidence = 0.41f;
1623     }
1624
1625     codec_id = getCodecId(ic, AVMEDIA_TYPE_AUDIO);
1626     if (codec_id != AV_CODEC_ID_NONE
1627             && codec_id != AV_CODEC_ID_MP3
1628             && codec_id != AV_CODEC_ID_AAC
1629             && codec_id != AV_CODEC_ID_AMR_NB
1630             && codec_id != AV_CODEC_ID_AMR_WB) {
1631         ALOGI("[mp4]audio codec(%s), confidence should be larger than MPEG4Extractor",
1632                 avcodec_get_name(codec_id));
1633         *confidence = 0.41f;
1634     }
1635
1636     //2. check tag
1637     tags = ic->metadata;
1638     //NOTE: You can use command to show these tags,
1639     //e.g. "ffprobe -show_format 2012.mov"
1640     tag = av_dict_get(tags, "major_brand", NULL, 0);
1641     if (!tag) {
1642         return;
1643     }
1644
1645     ALOGV("major_brand tag is:%s", tag->value);
1646
1647     //when MEDIA_MIMETYPE_CONTAINER_MPEG4
1648     //WTF, MPEG4Extractor.cpp can not extractor mov format
1649     //NOTE: isCompatibleBrand(MPEG4Extractor.cpp)
1650     //  Won't promise that the following file types can be played.
1651     //  Just give these file types a chance.
1652     //  FOURCC('q', 't', ' ', ' '),  // Apple's QuickTime
1653     //So......
1654     if (!strcmp(tag->value, "qt  ")) {
1655         ALOGI("[mp4]format is mov, confidence should be larger than mpeg4");
1656         *confidence = 0.41f;
1657     }
1658 }
1659
1660 static void adjustMPEG2TSConfidence(AVFormatContext *ic, float *confidence)
1661 {
1662     enum AVCodecID codec_id = AV_CODEC_ID_NONE;
1663
1664     codec_id = getCodecId(ic, AVMEDIA_TYPE_VIDEO);
1665     if (codec_id != AV_CODEC_ID_NONE
1666             && codec_id != AV_CODEC_ID_H264
1667             && codec_id != AV_CODEC_ID_MPEG4
1668             && codec_id != AV_CODEC_ID_MPEG1VIDEO
1669             && codec_id != AV_CODEC_ID_MPEG2VIDEO) {
1670         //the MEDIA_MIMETYPE_CONTAINER_MPEG2TS of confidence is 0.1f
1671         ALOGI("[mpeg2ts]video codec(%s), confidence should be larger than MPEG2TSExtractor",
1672                 avcodec_get_name(codec_id));
1673         *confidence = 0.11f;
1674     }
1675
1676     codec_id = getCodecId(ic, AVMEDIA_TYPE_AUDIO);
1677     if (codec_id != AV_CODEC_ID_NONE
1678             && codec_id != AV_CODEC_ID_AAC
1679             && codec_id != AV_CODEC_ID_PCM_S16LE
1680             && codec_id != AV_CODEC_ID_PCM_S24LE
1681             && codec_id != AV_CODEC_ID_MP1
1682             && codec_id != AV_CODEC_ID_MP2
1683             && codec_id != AV_CODEC_ID_MP3) {
1684         ALOGI("[mpeg2ts]audio codec(%s), confidence should be larger than MPEG2TSExtractor",
1685                 avcodec_get_name(codec_id));
1686         *confidence = 0.11f;
1687     }
1688 }
1689
1690 static void adjustMKVConfidence(AVFormatContext *ic, float *confidence)
1691 {
1692     enum AVCodecID codec_id = AV_CODEC_ID_NONE;
1693
1694     codec_id = getCodecId(ic, AVMEDIA_TYPE_VIDEO);
1695     if (codec_id != AV_CODEC_ID_NONE
1696             && codec_id != AV_CODEC_ID_H264
1697             && codec_id != AV_CODEC_ID_MPEG4
1698             && codec_id != AV_CODEC_ID_VP6
1699             && codec_id != AV_CODEC_ID_VP8
1700             && codec_id != AV_CODEC_ID_VP9) {
1701         //the MEDIA_MIMETYPE_CONTAINER_MATROSKA of confidence is 0.6f
1702         ALOGI("[mkv]video codec(%s), confidence should be larger than MatroskaExtractor",
1703                 avcodec_get_name(codec_id));
1704         *confidence = 0.61f;
1705     }
1706
1707     codec_id = getCodecId(ic, AVMEDIA_TYPE_AUDIO);
1708     if (codec_id != AV_CODEC_ID_NONE
1709             && codec_id != AV_CODEC_ID_AAC
1710             && codec_id != AV_CODEC_ID_MP3
1711             && codec_id != AV_CODEC_ID_VORBIS) {
1712         ALOGI("[mkv]audio codec(%s), confidence should be larger than MatroskaExtractor",
1713                 avcodec_get_name(codec_id));
1714         *confidence = 0.61f;
1715     }
1716 }
1717
1718 static void adjustCodecConfidence(AVFormatContext *ic, float *confidence)
1719 {
1720     enum AVCodecID codec_id = AV_CODEC_ID_NONE;
1721
1722     codec_id = getCodecId(ic, AVMEDIA_TYPE_VIDEO);
1723     if (codec_id != AV_CODEC_ID_NONE) {
1724         if (!isCodecSupportedByStagefright(codec_id)) {
1725             *confidence = 0.88f;
1726         }
1727     }
1728
1729     codec_id = getCodecId(ic, AVMEDIA_TYPE_AUDIO);
1730     if (codec_id != AV_CODEC_ID_NONE) {
1731         if (!isCodecSupportedByStagefright(codec_id)) {
1732             *confidence = 0.88f;
1733         }
1734     }
1735
1736     if (getCodecId(ic, AVMEDIA_TYPE_VIDEO) != AV_CODEC_ID_NONE
1737             && getCodecId(ic, AVMEDIA_TYPE_AUDIO) == AV_CODEC_ID_MP3) {
1738         *confidence = 0.22f; //larger than MP3Extractor
1739     }
1740 }
1741
1742 //TODO need more checks
1743 static void adjustConfidenceIfNeeded(const char *mime,
1744         AVFormatContext *ic, float *confidence)
1745 {
1746     //1. check mime
1747     if (!strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_MPEG4)) {
1748         adjustMPEG4Confidence(ic, confidence);
1749     } else if (!strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_MPEG2TS)) {
1750         adjustMPEG2TSConfidence(ic, confidence);
1751     } else if (!strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_MATROSKA)) {
1752         adjustMKVConfidence(ic, confidence);
1753     } else {
1754         //todo here
1755     }
1756
1757     if (*confidence > 0.08) {
1758         return;
1759     }
1760
1761     //2. check codec
1762     adjustCodecConfidence(ic, confidence);
1763 }
1764
1765 static void adjustContainerIfNeeded(const char **mime, AVFormatContext *ic)
1766 {
1767     const char *newMime = *mime;
1768     enum AVCodecID codec_id = AV_CODEC_ID_NONE;
1769
1770     AVCodecContext *avctx = getCodecContext(ic, AVMEDIA_TYPE_VIDEO);
1771     if (avctx != NULL && getDivXVersion(avctx) >= 0) {
1772         newMime = MEDIA_MIMETYPE_VIDEO_DIVX;
1773
1774     } else if (hasAudioCodecOnly(ic)) {
1775         codec_id = getCodecId(ic, AVMEDIA_TYPE_AUDIO);
1776         CHECK(codec_id != AV_CODEC_ID_NONE);
1777         switch (codec_id) {
1778         case AV_CODEC_ID_MP3:
1779             newMime = MEDIA_MIMETYPE_AUDIO_MPEG;
1780             break;
1781         case AV_CODEC_ID_AAC:
1782             newMime = MEDIA_MIMETYPE_AUDIO_AAC;
1783             break;
1784         case AV_CODEC_ID_VORBIS:
1785             newMime = MEDIA_MIMETYPE_AUDIO_VORBIS;
1786             break;
1787         case AV_CODEC_ID_FLAC:
1788             newMime = MEDIA_MIMETYPE_AUDIO_FLAC;
1789             break;
1790         case AV_CODEC_ID_AC3:
1791             newMime = MEDIA_MIMETYPE_AUDIO_AC3;
1792             break;
1793         case AV_CODEC_ID_APE:
1794             newMime = MEDIA_MIMETYPE_AUDIO_APE;
1795             break;
1796         case AV_CODEC_ID_DTS:
1797             newMime = MEDIA_MIMETYPE_AUDIO_DTS;
1798             break;
1799         case AV_CODEC_ID_MP2:
1800             newMime = MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_II;
1801             break;
1802         case AV_CODEC_ID_COOK:
1803             newMime = MEDIA_MIMETYPE_AUDIO_RA;
1804             break;
1805         case AV_CODEC_ID_WMAV1:
1806         case AV_CODEC_ID_WMAV2:
1807         case AV_CODEC_ID_WMAPRO:
1808         case AV_CODEC_ID_WMALOSSLESS:
1809             newMime = MEDIA_MIMETYPE_AUDIO_WMA;
1810             break;
1811         default:
1812             break;
1813         }
1814
1815         if (!strcmp(*mime, MEDIA_MIMETYPE_CONTAINER_FFMPEG)) {
1816             newMime = MEDIA_MIMETYPE_AUDIO_FFMPEG;
1817         }
1818     }
1819
1820     if (strcmp(*mime, newMime)) {
1821         ALOGI("adjust mime(%s -> %s)", *mime, newMime);
1822         *mime = newMime;
1823     }
1824 }
1825
1826 static const char *findMatchingContainer(const char *name)
1827 {
1828     size_t i = 0;
1829 #if SUPPOURT_UNKNOWN_FORMAT
1830     //The FFmpegExtractor support all ffmpeg formats!!!
1831     //Unknown format is defined as MEDIA_MIMETYPE_CONTAINER_FFMPEG
1832     const char *container = MEDIA_MIMETYPE_CONTAINER_FFMPEG;
1833 #else
1834     const char *container = NULL;
1835 #endif
1836
1837     ALOGV("list the formats suppoted by ffmpeg: ");
1838     ALOGV("========================================");
1839     for (i = 0; i < NELEM(FILE_FORMATS); ++i) {
1840         ALOGV("format_names[%02d]: %s", i, FILE_FORMATS[i].format);
1841     }
1842     ALOGV("========================================");
1843
1844     for (i = 0; i < NELEM(FILE_FORMATS); ++i) {
1845         int len = strlen(FILE_FORMATS[i].format);
1846         if (!strncasecmp(name, FILE_FORMATS[i].format, len)) {
1847             container = FILE_FORMATS[i].container;
1848             break;
1849         }
1850     }
1851
1852     return container;
1853 }
1854
1855 static const char *SniffFFMPEGCommon(const char *url, float *confidence, bool fastMPEG4)
1856 {
1857     int err = 0;
1858     size_t i = 0;
1859     size_t nb_streams = 0;
1860     const char *container = NULL;
1861     AVFormatContext *ic = NULL;
1862     AVDictionary **opts = NULL;
1863
1864     status_t status = initFFmpeg();
1865     if (status != OK) {
1866         ALOGE("could not init ffmpeg");
1867         return NULL;
1868     }
1869
1870     ic = avformat_alloc_context();
1871     if (!ic)
1872     {
1873         ALOGE("oom for alloc avformat context");
1874         goto fail;
1875     }
1876
1877     err = avformat_open_input(&ic, url, NULL, NULL);
1878
1879     if (err < 0) {
1880         ALOGE("%s: avformat_open_input failed, err:%s", url, av_err2str(err));
1881         goto fail;
1882     }
1883
1884     if (ic->iformat != NULL && ic->iformat->name != NULL &&
1885         findMatchingContainer(ic->iformat->name) != NULL &&
1886         !strcasecmp(findMatchingContainer(ic->iformat->name),
1887         MEDIA_MIMETYPE_CONTAINER_MPEG4)) {
1888         if (fastMPEG4) {
1889             container = findMatchingContainer(ic->iformat->name);
1890             goto fail;
1891         }
1892     }
1893
1894     opts = setup_find_stream_info_opts(ic, codec_opts);
1895     nb_streams = ic->nb_streams;
1896     err = avformat_find_stream_info(ic, opts);
1897     if (err < 0) {
1898         ALOGE("%s: could not find stream info, err:%s", url, av_err2str(err));
1899         goto fail;
1900     }
1901     for (i = 0; i < nb_streams; i++) {
1902         av_dict_free(&opts[i]);
1903     }
1904     av_freep(&opts);
1905
1906     av_dump_format(ic, 0, url, 0);
1907
1908     ALOGD("FFmpegExtrator, url: %s, format_name: %s, format_long_name: %s",
1909             url, ic->iformat->name, ic->iformat->long_name);
1910
1911     container = findMatchingContainer(ic->iformat->name);
1912     if (container) {
1913         adjustContainerIfNeeded(&container, ic);
1914         adjustConfidenceIfNeeded(container, ic, confidence);
1915     }
1916
1917 fail:
1918     if (ic) {
1919         avformat_close_input(&ic);
1920     }
1921     if (status == OK) {
1922         deInitFFmpeg();
1923     }
1924
1925     return container;
1926 }
1927
1928 static const char *BetterSniffFFMPEG(const sp<DataSource> &source,
1929         float *confidence, sp<AMessage> meta)
1930 {
1931     const char *ret = NULL;
1932     char url[PATH_MAX] = {0};
1933
1934     ALOGI("android-source:%p", source.get());
1935
1936     // pass the addr of smart pointer("source")
1937     snprintf(url, sizeof(url), "android-source:%p", source.get());
1938
1939     ret = SniffFFMPEGCommon(url, confidence, (source->flags() & DataSource::kIsCachingDataSource));
1940     if (ret) {
1941         meta->setString("extended-extractor-url", url);
1942     }
1943
1944     return ret;
1945 }
1946
1947 static const char *LegacySniffFFMPEG(const sp<DataSource> &source,
1948          float *confidence, sp<AMessage> meta)
1949 {
1950     const char *ret = NULL;
1951     char url[PATH_MAX] = {0};
1952
1953     String8 uri = source->getUri();
1954     if (!uri.string()) {
1955         return NULL;
1956     }
1957
1958     ALOGV("source url:%s", uri.string());
1959
1960     // pass the addr of smart pointer("source") + file name
1961     snprintf(url, sizeof(url), "android-source:%p|file:%s", source.get(), uri.string());
1962
1963     ret = SniffFFMPEGCommon(url, confidence, false);
1964     if (ret) {
1965         meta->setString("extended-extractor-url", url);
1966     }
1967
1968     return ret;
1969 }
1970
1971 bool SniffFFMPEG(
1972         const sp<DataSource> &source, String8 *mimeType, float *confidence,
1973         sp<AMessage> *meta) {
1974     ALOGV("SniffFFMPEG");
1975
1976     *meta = new AMessage;
1977     *confidence = 0.08f;  // be the last resort, by default
1978
1979     const char *container = BetterSniffFFMPEG(source, confidence, *meta);
1980     if (!container) {
1981         ALOGW("sniff through BetterSniffFFMPEG failed, try LegacySniffFFMPEG");
1982         container = LegacySniffFFMPEG(source, confidence, *meta);
1983         if (container) {
1984             ALOGV("sniff through LegacySniffFFMPEG success");
1985         }
1986     } else {
1987         ALOGV("sniff through BetterSniffFFMPEG success");
1988     }
1989
1990     if (container == NULL) {
1991         ALOGD("SniffFFMPEG failed to sniff this source");
1992         (*meta)->clear();
1993         *meta = NULL;
1994         return false;
1995     }
1996
1997     ALOGD("ffmpeg detected media content as '%s' with confidence %.2f",
1998             container, *confidence);
1999
2000     /* use MPEG4Extractor(not extended extractor) for HTTP source only */
2001     if (!strcasecmp(container, MEDIA_MIMETYPE_CONTAINER_MPEG4)
2002             && (source->flags() & DataSource::kIsCachingDataSource)) {
2003         ALOGI("support container: %s, but it is caching data source, "
2004                 "Don't use ffmpegextractor", container);
2005         (*meta)->clear();
2006         *meta = NULL;
2007         return false;
2008     }
2009
2010     mimeType->setTo(container);
2011
2012     (*meta)->setString("extended-extractor", "extended-extractor");
2013     (*meta)->setString("extended-extractor-subtype", "ffmpegextractor");
2014     (*meta)->setString("extended-extractor-mime", container);
2015
2016     //debug only
2017     char value[PROPERTY_VALUE_MAX];
2018     property_get("sys.media.parser.ffmpeg", value, "0");
2019     if (atoi(value)) {
2020         ALOGD("[debug] use ffmpeg parser");
2021         *confidence = 0.88f;
2022     }
2023
2024     if (*confidence > 0.08f) {
2025         (*meta)->setString("extended-extractor-use", "ffmpegextractor");
2026     }
2027
2028     return true;
2029 }
2030
2031 MediaExtractor *CreateFFmpegExtractor(const sp<DataSource> &source, const char *mime, const sp<AMessage> &meta) {
2032     MediaExtractor *ret = NULL;
2033     AString notuse;
2034     if (meta.get() && meta->findString("extended-extractor", &notuse) && (
2035             !strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_MPEG)          ||
2036             !strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_AAC)           ||
2037             !strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_VORBIS)        ||
2038             !strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_FLAC)          ||
2039             !strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_AC3)           ||
2040             !strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_APE)           ||
2041             !strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_DTS)           ||
2042             !strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_II) ||
2043             !strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_RA)            ||
2044             !strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_WMA)           ||
2045             !strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_FFMPEG)        ||
2046             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_MPEG4)     ||
2047             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_MOV)       ||
2048             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_MATROSKA)  ||
2049             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_TS)        ||
2050             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_MPEG2PS)   ||
2051             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_AVI)       ||
2052             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_ASF)       ||
2053             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_WEBM)      ||
2054             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_WMV)       ||
2055             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_MPG)       ||
2056             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_FLV)       ||
2057             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_DIVX)      ||
2058             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_RM)        ||
2059             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_WAV)       ||
2060             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_FLAC)      ||
2061             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_APE)       ||
2062             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_DTS)       ||
2063             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_MP2)       ||
2064             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_RA)        ||
2065             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_OGG)       ||
2066             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_VC1)       ||
2067             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_HEVC)      ||
2068             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_WMA)       ||
2069             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_FFMPEG))) {
2070         ret = new FFmpegExtractor(source, meta);
2071     }
2072
2073     ALOGD("%ssupported mime: %s", (ret ? "" : "un"), mime);
2074     return ret;
2075 }
2076
2077 }  // namespace android
2078
2079 extern "C" void getExtractorPlugin(android::MediaExtractor::Plugin *plugin)
2080 {
2081     plugin->sniff = android::SniffFFMPEG;
2082     plugin->create = android::CreateFFmpegExtractor;
2083 }