OSDN Git Service

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