OSDN Git Service

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