OSDN Git Service

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