OSDN Git Service

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