OSDN Git Service

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