OSDN Git Service

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