OSDN Git Service

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