OSDN Git Service

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