OSDN Git Service

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