OSDN Git Service

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