OSDN Git Service

stagefright-plugins: workaround negative timestamp
[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     // Negative timestamp will cause crash for media_server
1524     // in OMXCodec.cpp CHECK(lastBufferTimeUs >= 0).
1525     // And we should not get negative timestamp
1526     if (timeUs < 0) {
1527         ALOGE("negative timestamp encounter: time: %" PRId64
1528                " startTimeUs: %" PRId64
1529                " packet dts: %" PRId64
1530                " packet pts: %" PRId64
1531                , timeUs, startTimeUs, pkt.dts, pkt.pts);
1532         mediaBuffer->release();
1533         mediaBuffer = NULL;
1534         av_free_packet(&pkt);
1535         return ERROR_MALFORMED;
1536     }
1537
1538     // predict the next PTS to use for exact-frame seek below
1539     int64_t nextPTS = AV_NOPTS_VALUE;
1540     if (mLastPTS != AV_NOPTS_VALUE && timeUs > mLastPTS) {
1541         nextPTS = timeUs + (timeUs - mLastPTS);
1542         mLastPTS = timeUs;
1543     } else if (mLastPTS == AV_NOPTS_VALUE) {
1544         mLastPTS = timeUs;
1545     }
1546
1547 #if DEBUG_PKT
1548     if (pktTS != AV_NOPTS_VALUE)
1549         ALOGV("read %s pkt, size:%d, key:%d, pktPTS: %lld, pts:%lld, dts:%lld, timeUs[-startTime]:%lld us (%.2f secs) start_time=%lld",
1550             av_get_media_type_string(mMediaType), pkt.size, key, pktTS, pkt.pts, pkt.dts, timeUs, timeUs/1E6, startTimeUs);
1551     else
1552         ALOGV("read %s pkt, size:%d, key:%d, pts:N/A, dts:N/A, timeUs[-startTime]:N/A",
1553             av_get_media_type_string(mMediaType), pkt.size, key);
1554 #endif
1555
1556     mediaBuffer->meta_data()->setInt64(kKeyTime, timeUs);
1557     mediaBuffer->meta_data()->setInt32(kKeyIsSyncFrame, key);
1558
1559     // deal with seek-to-exact-frame, we might be off a bit and Stagefright will assert on us
1560     if (seekTimeUs != AV_NOPTS_VALUE && timeUs < seekTimeUs &&
1561             mode == MediaSource::ReadOptions::SEEK_CLOSEST) {
1562         mTargetTime = seekTimeUs;
1563         mediaBuffer->meta_data()->setInt64(kKeyTargetTime, seekTimeUs);
1564     }
1565
1566     if (mTargetTime != AV_NOPTS_VALUE) {
1567         if (timeUs == mTargetTime) {
1568             mTargetTime = AV_NOPTS_VALUE;
1569         } else if (nextPTS != AV_NOPTS_VALUE && nextPTS > mTargetTime) {
1570             ALOGV("adjust target frame time to %lld", timeUs);
1571             mediaBuffer->meta_data()->setInt64(kKeyTime, mTargetTime);
1572             mTargetTime = AV_NOPTS_VALUE;
1573         }
1574     }
1575
1576     *buffer = mediaBuffer;
1577
1578     av_free_packet(&pkt);
1579
1580     return OK;
1581 }
1582
1583 ////////////////////////////////////////////////////////////////////////////////
1584
1585 typedef struct {
1586     const char *format;
1587     const char *container;
1588 } formatmap;
1589
1590 static formatmap FILE_FORMATS[] = {
1591         {"mpeg",                    MEDIA_MIMETYPE_CONTAINER_MPEG2PS  },
1592         {"mpegts",                  MEDIA_MIMETYPE_CONTAINER_TS       },
1593         {"mov,mp4,m4a,3gp,3g2,mj2", MEDIA_MIMETYPE_CONTAINER_MPEG4    },
1594         {"matroska,webm",           MEDIA_MIMETYPE_CONTAINER_MATROSKA },
1595         {"asf",                     MEDIA_MIMETYPE_CONTAINER_ASF      },
1596         {"rm",                      MEDIA_MIMETYPE_CONTAINER_RM       },
1597         {"flv",                     MEDIA_MIMETYPE_CONTAINER_FLV      },
1598         {"swf",                     MEDIA_MIMETYPE_CONTAINER_FLV      },
1599         {"avi",                     MEDIA_MIMETYPE_CONTAINER_AVI      },
1600         {"ape",                     MEDIA_MIMETYPE_CONTAINER_APE      },
1601         {"dts",                     MEDIA_MIMETYPE_CONTAINER_DTS      },
1602         {"flac",                    MEDIA_MIMETYPE_CONTAINER_FLAC     },
1603         {"ac3",                     MEDIA_MIMETYPE_AUDIO_AC3          },
1604         {"mp3",                     MEDIA_MIMETYPE_AUDIO_MPEG         },
1605         {"wav",                     MEDIA_MIMETYPE_CONTAINER_WAV      },
1606         {"ogg",                     MEDIA_MIMETYPE_CONTAINER_OGG      },
1607         {"vc1",                     MEDIA_MIMETYPE_CONTAINER_VC1      },
1608         {"hevc",                    MEDIA_MIMETYPE_CONTAINER_HEVC     },
1609         {"divx",                    MEDIA_MIMETYPE_CONTAINER_DIVX     },
1610 };
1611
1612 static AVCodecContext* getCodecContext(AVFormatContext *ic, AVMediaType codec_type)
1613 {
1614     unsigned int idx = 0;
1615     AVCodecContext *avctx = NULL;
1616
1617     for (idx = 0; idx < ic->nb_streams; idx++) {
1618         if (ic->streams[idx]->disposition & AV_DISPOSITION_ATTACHED_PIC) {
1619             // FFMPEG converts album art to MJPEG, but we don't want to
1620             // include that in the parsing as MJPEG is not supported by
1621             // Android, which forces the media to be extracted by FFMPEG
1622             // while in fact, Android supports it.
1623             continue;
1624         }
1625
1626         avctx = ic->streams[idx]->codec;
1627         if (avctx->codec_tag == MKTAG('j', 'p', 'e', 'g')) {
1628             // Sometimes the disposition isn't set
1629             continue;
1630         }
1631         if (avctx->codec_type == codec_type) {
1632             return avctx;
1633         }
1634     }
1635
1636     return NULL;
1637 }
1638
1639 static enum AVCodecID getCodecId(AVFormatContext *ic, AVMediaType codec_type)
1640 {
1641     AVCodecContext *avctx = getCodecContext(ic, codec_type);
1642     return avctx == NULL ? AV_CODEC_ID_NONE : avctx->codec_id;
1643 }
1644
1645 static bool hasAudioCodecOnly(AVFormatContext *ic)
1646 {
1647     enum AVCodecID codec_id = AV_CODEC_ID_NONE;
1648     bool haveVideo = false;
1649     bool haveAudio = false;
1650
1651     if (getCodecId(ic, AVMEDIA_TYPE_VIDEO) != AV_CODEC_ID_NONE) {
1652         haveVideo = true;
1653     }
1654     if (getCodecId(ic, AVMEDIA_TYPE_AUDIO) != AV_CODEC_ID_NONE) {
1655         haveAudio = true;
1656     }
1657
1658     if (!haveVideo && haveAudio) {
1659         return true;
1660     }
1661
1662     return false;
1663 }
1664
1665 //FIXME all codecs: frameworks/av/media/libstagefright/codecs/*
1666 static bool isCodecSupportedByStagefright(enum AVCodecID codec_id)
1667 {
1668     bool supported = false;
1669
1670     switch(codec_id) {
1671     //video
1672     case AV_CODEC_ID_HEVC:
1673     case AV_CODEC_ID_H264:
1674     case AV_CODEC_ID_MPEG4:
1675     case AV_CODEC_ID_H263:
1676     case AV_CODEC_ID_H263P:
1677     case AV_CODEC_ID_H263I:
1678     case AV_CODEC_ID_VP6:
1679     case AV_CODEC_ID_VP8:
1680     case AV_CODEC_ID_VP9:
1681     //audio
1682     case AV_CODEC_ID_AAC:
1683     case AV_CODEC_ID_MP3:
1684     case AV_CODEC_ID_AMR_NB:
1685     case AV_CODEC_ID_AMR_WB:
1686     case AV_CODEC_ID_VORBIS:
1687     case AV_CODEC_ID_PCM_MULAW: //g711
1688     case AV_CODEC_ID_PCM_ALAW:  //g711
1689     case AV_CODEC_ID_GSM_MS:
1690     case AV_CODEC_ID_PCM_U8:
1691     case AV_CODEC_ID_PCM_S16LE:
1692     case AV_CODEC_ID_PCM_S24LE:
1693         supported = true;
1694         break;
1695
1696     default:
1697         break;
1698     }
1699
1700     ALOGD("%ssuppoted codec(%s) by official Stagefright",
1701             (supported ? "" : "un"),
1702             avcodec_get_name(codec_id));
1703
1704     return supported;
1705 }
1706
1707 static void adjustMPEG4Confidence(AVFormatContext *ic, float *confidence, bool isStreaming)
1708 {
1709     AVDictionary *tags = NULL;
1710     AVDictionaryEntry *tag = NULL;
1711     enum AVCodecID codec_id = AV_CODEC_ID_NONE;
1712     bool is_mov = false;
1713
1714     //1. check codec id
1715     codec_id = getCodecId(ic, AVMEDIA_TYPE_VIDEO);
1716     if (codec_id != AV_CODEC_ID_NONE
1717             && codec_id != AV_CODEC_ID_HEVC
1718             && codec_id != AV_CODEC_ID_H264
1719             && codec_id != AV_CODEC_ID_MPEG4
1720             && codec_id != AV_CODEC_ID_H263
1721             && codec_id != AV_CODEC_ID_H263P
1722             && codec_id != AV_CODEC_ID_H263I) {
1723         //the MEDIA_MIMETYPE_CONTAINER_MPEG4 of confidence is 0.4f
1724         ALOGI("[mp4]video codec(%s), confidence should be larger than MPEG4Extractor",
1725                 avcodec_get_name(codec_id));
1726         *confidence = 0.41f;
1727     }
1728
1729     codec_id = getCodecId(ic, AVMEDIA_TYPE_AUDIO);
1730     if (codec_id != AV_CODEC_ID_NONE
1731             && codec_id != AV_CODEC_ID_MP3
1732             && codec_id != AV_CODEC_ID_AAC
1733             && codec_id != AV_CODEC_ID_AMR_NB
1734             && codec_id != AV_CODEC_ID_AMR_WB) {
1735         ALOGI("[mp4]audio codec(%s), confidence should be larger than MPEG4Extractor",
1736                 avcodec_get_name(codec_id));
1737         *confidence = 0.41f;
1738     }
1739
1740     //2. check tag
1741     tags = ic->metadata;
1742     //NOTE: You can use command to show these tags,
1743     //e.g. "ffprobe -show_format 2012.mov"
1744     tag = av_dict_get(tags, "major_brand", NULL, 0);
1745     if (tag) {
1746         ALOGV("major_brand tag is:%s", tag->value);
1747
1748         //when MEDIA_MIMETYPE_CONTAINER_MPEG4
1749         //WTF, MPEG4Extractor.cpp can not extractor mov format
1750         //NOTE: isCompatibleBrand(MPEG4Extractor.cpp)
1751         //  Won't promise that the following file types can be played.
1752         //  Just give these file types a chance.
1753         //  FOURCC('q', 't', ' ', ' '),  // Apple's QuickTime
1754         //So......
1755         if (!strcmp(tag->value, "qt  ")) {
1756             ALOGI("[mp4]format is mov, confidence should be larger than mpeg4");
1757             *confidence = 0.41f;
1758             is_mov = true;
1759         }
1760     }
1761     if (isStreaming && !is_mov) {
1762         ALOGI("support container: video/mp4, but it is caching data source, "
1763                 "Don't use ffmpegextractor");
1764         *confidence = 0; // MP4 and streaming, use AOSP
1765     }
1766 }
1767
1768 static void adjustMPEG2PSConfidence(AVFormatContext *ic, float *confidence)
1769 {
1770     enum AVCodecID codec_id = AV_CODEC_ID_NONE;
1771
1772     codec_id = getCodecId(ic, AVMEDIA_TYPE_VIDEO);
1773     if (codec_id != AV_CODEC_ID_NONE
1774             && codec_id != AV_CODEC_ID_H264
1775             && codec_id != AV_CODEC_ID_MPEG4
1776             && codec_id != AV_CODEC_ID_MPEG1VIDEO
1777             && codec_id != AV_CODEC_ID_MPEG2VIDEO) {
1778         //the MEDIA_MIMETYPE_CONTAINER_MPEG2TS of confidence is 0.25f
1779         ALOGI("[mpeg2ps]video codec(%s), confidence should be larger than MPEG2PSExtractor",
1780                 avcodec_get_name(codec_id));
1781         *confidence = 0.26f;
1782     }
1783
1784     codec_id = getCodecId(ic, AVMEDIA_TYPE_AUDIO);
1785     if (codec_id != AV_CODEC_ID_NONE
1786             && codec_id != AV_CODEC_ID_AAC
1787             && codec_id != AV_CODEC_ID_PCM_S16LE
1788             && codec_id != AV_CODEC_ID_PCM_S24LE
1789             && codec_id != AV_CODEC_ID_MP1
1790             && codec_id != AV_CODEC_ID_MP2
1791             && codec_id != AV_CODEC_ID_MP3) {
1792         ALOGI("[mpeg2ps]audio codec(%s), confidence should be larger than MPEG2PSExtractor",
1793                 avcodec_get_name(codec_id));
1794         *confidence = 0.26f;
1795     }
1796 }
1797
1798 static void adjustMPEG2TSConfidence(AVFormatContext *ic, float *confidence)
1799 {
1800     enum AVCodecID codec_id = AV_CODEC_ID_NONE;
1801
1802     codec_id = getCodecId(ic, AVMEDIA_TYPE_VIDEO);
1803     if (codec_id != AV_CODEC_ID_NONE
1804             && codec_id != AV_CODEC_ID_H264
1805             && codec_id != AV_CODEC_ID_MPEG4
1806             && codec_id != AV_CODEC_ID_MPEG1VIDEO
1807             && codec_id != AV_CODEC_ID_MPEG2VIDEO) {
1808         //the MEDIA_MIMETYPE_CONTAINER_MPEG2TS of confidence is 0.1f
1809         ALOGI("[mpeg2ts]video codec(%s), confidence should be larger than MPEG2TSExtractor",
1810                 avcodec_get_name(codec_id));
1811         *confidence = 0.11f;
1812     }
1813
1814     codec_id = getCodecId(ic, AVMEDIA_TYPE_AUDIO);
1815     if (codec_id != AV_CODEC_ID_NONE
1816             && codec_id != AV_CODEC_ID_AAC
1817             && codec_id != AV_CODEC_ID_PCM_S16LE
1818             && codec_id != AV_CODEC_ID_PCM_S24LE
1819             && codec_id != AV_CODEC_ID_MP1
1820             && codec_id != AV_CODEC_ID_MP2
1821             && codec_id != AV_CODEC_ID_MP3) {
1822         ALOGI("[mpeg2ts]audio codec(%s), confidence should be larger than MPEG2TSExtractor",
1823                 avcodec_get_name(codec_id));
1824         *confidence = 0.11f;
1825     }
1826 }
1827
1828 static void adjustMKVConfidence(AVFormatContext *ic, float *confidence)
1829 {
1830     enum AVCodecID codec_id = AV_CODEC_ID_NONE;
1831
1832     codec_id = getCodecId(ic, AVMEDIA_TYPE_VIDEO);
1833     if (codec_id != AV_CODEC_ID_NONE
1834             && codec_id != AV_CODEC_ID_H264
1835             && codec_id != AV_CODEC_ID_MPEG4
1836             && codec_id != AV_CODEC_ID_VP6
1837             && codec_id != AV_CODEC_ID_VP8
1838             && codec_id != AV_CODEC_ID_VP9) {
1839         //the MEDIA_MIMETYPE_CONTAINER_MATROSKA of confidence is 0.6f
1840         ALOGI("[mkv]video codec(%s), confidence should be larger than MatroskaExtractor",
1841                 avcodec_get_name(codec_id));
1842         *confidence = 0.61f;
1843     }
1844
1845     codec_id = getCodecId(ic, AVMEDIA_TYPE_AUDIO);
1846     if (codec_id != AV_CODEC_ID_NONE
1847             && codec_id != AV_CODEC_ID_AAC
1848             && codec_id != AV_CODEC_ID_MP3
1849             && codec_id != AV_CODEC_ID_VORBIS) {
1850         ALOGI("[mkv]audio codec(%s), confidence should be larger than MatroskaExtractor",
1851                 avcodec_get_name(codec_id));
1852         *confidence = 0.61f;
1853     }
1854 }
1855
1856 static void adjustCodecConfidence(AVFormatContext *ic, float *confidence)
1857 {
1858     enum AVCodecID codec_id = AV_CODEC_ID_NONE;
1859
1860     codec_id = getCodecId(ic, AVMEDIA_TYPE_VIDEO);
1861     if (codec_id != AV_CODEC_ID_NONE) {
1862         if (!isCodecSupportedByStagefright(codec_id)) {
1863             *confidence = 0.88f;
1864         }
1865     }
1866
1867     codec_id = getCodecId(ic, AVMEDIA_TYPE_AUDIO);
1868     if (codec_id != AV_CODEC_ID_NONE) {
1869         if (!isCodecSupportedByStagefright(codec_id)) {
1870             *confidence = 0.88f;
1871         }
1872     }
1873
1874     if (getCodecId(ic, AVMEDIA_TYPE_VIDEO) != AV_CODEC_ID_NONE
1875             && getCodecId(ic, AVMEDIA_TYPE_AUDIO) == AV_CODEC_ID_MP3) {
1876         *confidence = 0.22f; //larger than MP3Extractor
1877     }
1878 }
1879
1880 //TODO need more checks
1881 static void adjustConfidenceIfNeeded(const char *mime,
1882         AVFormatContext *ic, float *confidence, bool isStreaming)
1883 {
1884     //1. check mime
1885     if (!strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_MPEG4)) {
1886         adjustMPEG4Confidence(ic, confidence, isStreaming);
1887     } else if (!strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_MPEG2TS)) {
1888         adjustMPEG2TSConfidence(ic, confidence);
1889     } else if (!strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_MPEG2PS)) {
1890         adjustMPEG2PSConfidence(ic, confidence);
1891     } else if (!strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_MATROSKA)) {
1892         adjustMKVConfidence(ic, confidence);
1893     } else if (!strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_DIVX)) {
1894         *confidence = 0.4f;
1895     } else {
1896         //todo here
1897     }
1898
1899     //2. check codec
1900     adjustCodecConfidence(ic, confidence);
1901 }
1902
1903 static void adjustContainerIfNeeded(const char **mime, AVFormatContext *ic)
1904 {
1905     const char *newMime = *mime;
1906     enum AVCodecID codec_id = AV_CODEC_ID_NONE;
1907
1908     AVCodecContext *avctx = getCodecContext(ic, AVMEDIA_TYPE_VIDEO);
1909     if (avctx != NULL && getDivXVersion(avctx) >= 0) {
1910         newMime = MEDIA_MIMETYPE_VIDEO_DIVX;
1911
1912     } else if (hasAudioCodecOnly(ic)) {
1913         codec_id = getCodecId(ic, AVMEDIA_TYPE_AUDIO);
1914         CHECK(codec_id != AV_CODEC_ID_NONE);
1915         switch (codec_id) {
1916         case AV_CODEC_ID_MP3:
1917             newMime = MEDIA_MIMETYPE_AUDIO_MPEG;
1918             break;
1919         case AV_CODEC_ID_AAC:
1920             newMime = MEDIA_MIMETYPE_AUDIO_AAC;
1921             break;
1922         case AV_CODEC_ID_VORBIS:
1923             newMime = MEDIA_MIMETYPE_AUDIO_VORBIS;
1924             break;
1925         case AV_CODEC_ID_FLAC:
1926             newMime = MEDIA_MIMETYPE_AUDIO_FLAC;
1927             break;
1928         case AV_CODEC_ID_AC3:
1929             newMime = MEDIA_MIMETYPE_AUDIO_AC3;
1930             break;
1931         case AV_CODEC_ID_APE:
1932             newMime = MEDIA_MIMETYPE_AUDIO_APE;
1933             break;
1934         case AV_CODEC_ID_DTS:
1935             newMime = MEDIA_MIMETYPE_AUDIO_DTS;
1936             break;
1937         case AV_CODEC_ID_MP2:
1938             newMime = MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_II;
1939             break;
1940         case AV_CODEC_ID_COOK:
1941             newMime = MEDIA_MIMETYPE_AUDIO_RA;
1942             break;
1943         case AV_CODEC_ID_WMAV1:
1944         case AV_CODEC_ID_WMAV2:
1945         case AV_CODEC_ID_WMAPRO:
1946         case AV_CODEC_ID_WMALOSSLESS:
1947             newMime = MEDIA_MIMETYPE_AUDIO_WMA;
1948             break;
1949         default:
1950             break;
1951         }
1952
1953         if (!strcmp(*mime, MEDIA_MIMETYPE_CONTAINER_FFMPEG)) {
1954             newMime = MEDIA_MIMETYPE_AUDIO_FFMPEG;
1955         }
1956     }
1957
1958     if (strcmp(*mime, newMime)) {
1959         ALOGI("adjust mime(%s -> %s)", *mime, newMime);
1960         *mime = newMime;
1961     }
1962 }
1963
1964 static const char *findMatchingContainer(const char *name)
1965 {
1966     size_t i = 0;
1967 #if SUPPOURT_UNKNOWN_FORMAT
1968     //The FFmpegExtractor support all ffmpeg formats!!!
1969     //Unknown format is defined as MEDIA_MIMETYPE_CONTAINER_FFMPEG
1970     const char *container = MEDIA_MIMETYPE_CONTAINER_FFMPEG;
1971 #else
1972     const char *container = NULL;
1973 #endif
1974
1975     for (i = 0; i < NELEM(FILE_FORMATS); ++i) {
1976         int len = strlen(FILE_FORMATS[i].format);
1977         if (!strncasecmp(name, FILE_FORMATS[i].format, len)) {
1978             container = FILE_FORMATS[i].container;
1979             break;
1980         }
1981     }
1982
1983     return container;
1984 }
1985
1986 static const char *SniffFFMPEGCommon(const char *url, float *confidence, bool isStreaming)
1987 {
1988     int err = 0;
1989     size_t i = 0;
1990     size_t nb_streams = 0;
1991     int64_t timeNow = 0;
1992     const char *container = NULL;
1993     AVFormatContext *ic = NULL;
1994     AVDictionary *codec_opts = NULL;
1995     AVDictionary **opts = NULL;
1996     bool needProbe = false;
1997
1998     status_t status = initFFmpeg();
1999     if (status != OK) {
2000         ALOGE("could not init ffmpeg");
2001         return NULL;
2002     }
2003
2004     ic = avformat_alloc_context();
2005     if (!ic)
2006     {
2007         ALOGE("oom for alloc avformat context");
2008         goto fail;
2009     }
2010
2011     // Don't download more than a meg
2012     ic->probesize = 1024 * 1024;
2013
2014     timeNow = ALooper::GetNowUs();
2015
2016     err = avformat_open_input(&ic, url, NULL, NULL);
2017
2018     if (err < 0) {
2019         ALOGE("%s: avformat_open_input failed, err:%s", url, av_err2str(err));
2020         goto fail;
2021     }
2022
2023     if (ic->iformat != NULL && ic->iformat->name != NULL) {
2024         container = findMatchingContainer(ic->iformat->name);
2025     }
2026
2027     ALOGV("opened, nb_streams: %d container: %s delay: %.2f ms", ic->nb_streams, container,
2028             ((float)ALooper::GetNowUs() - timeNow) / 1000);
2029
2030     // Only probe if absolutely necessary. For formats with headers, avformat_open_input will
2031     // figure out the components.
2032     for (unsigned int i = 0; i < ic->nb_streams; i++) {
2033         AVStream* stream = ic->streams[i];
2034         if (!stream->codec || !stream->codec->codec_id) {
2035             needProbe = true;
2036             break;
2037         }
2038         ALOGV("found stream %d id %d codec %s", i, stream->codec->codec_id, avcodec_get_name(stream->codec->codec_id));
2039     }
2040
2041     // We must go deeper.
2042     if (!isStreaming && (!ic->nb_streams || needProbe)) {
2043         timeNow = ALooper::GetNowUs();
2044
2045         opts = setup_find_stream_info_opts(ic, codec_opts);
2046         nb_streams = ic->nb_streams;
2047         err = avformat_find_stream_info(ic, opts);
2048         if (err < 0) {
2049             ALOGE("%s: could not find stream info, err:%s", url, av_err2str(err));
2050             goto fail;
2051         }
2052
2053         ALOGV("probed stream info after %.2f ms", ((float)ALooper::GetNowUs() - timeNow) / 1000);
2054
2055         for (i = 0; i < nb_streams; i++) {
2056             av_dict_free(&opts[i]);
2057         }
2058         av_freep(&opts);
2059
2060         av_dump_format(ic, 0, url, 0);
2061     }
2062
2063     ALOGV("url: %s, format_name: %s, format_long_name: %s",
2064             url, ic->iformat->name, ic->iformat->long_name);
2065
2066     container = findMatchingContainer(ic->iformat->name);
2067     if (container) {
2068         adjustContainerIfNeeded(&container, ic);
2069         adjustConfidenceIfNeeded(container, ic, confidence, isStreaming);
2070         if (*confidence == 0)
2071             container = NULL;
2072     }
2073
2074 fail:
2075     if (ic) {
2076         avformat_close_input(&ic);
2077     }
2078     if (status == OK) {
2079         deInitFFmpeg();
2080     }
2081
2082     return container;
2083 }
2084
2085 static const char *BetterSniffFFMPEG(const sp<DataSource> &source,
2086         float *confidence, sp<AMessage> meta)
2087 {
2088     const char *ret = NULL;
2089     char url[PATH_MAX] = {0};
2090
2091     ALOGI("android-source:%p", source.get());
2092
2093     // pass the addr of smart pointer("source")
2094     snprintf(url, sizeof(url), "android-source:%p", source.get());
2095
2096     ret = SniffFFMPEGCommon(url, confidence,
2097             (source->flags() & DataSource::kIsCachingDataSource));
2098     if (ret) {
2099         meta->setString("extended-extractor-url", url);
2100     }
2101
2102     return ret;
2103 }
2104
2105 static const char *LegacySniffFFMPEG(const sp<DataSource> &source,
2106          float *confidence, sp<AMessage> meta)
2107 {
2108     const char *ret = NULL;
2109     char url[PATH_MAX] = {0};
2110
2111     String8 uri = source->getUri();
2112     if (!uri.string()) {
2113         return NULL;
2114     }
2115
2116     if (source->flags() & DataSource::kIsCachingDataSource)
2117        return NULL;
2118
2119     ALOGV("source url:%s", uri.string());
2120
2121     // pass the addr of smart pointer("source") + file name
2122     snprintf(url, sizeof(url), "android-source:%p|file:%s", source.get(), uri.string());
2123
2124     ret = SniffFFMPEGCommon(url, confidence, false);
2125     if (ret) {
2126         meta->setString("extended-extractor-url", url);
2127     }
2128
2129     return ret;
2130 }
2131
2132 bool SniffFFMPEG(
2133         const sp<DataSource> &source, String8 *mimeType, float *confidence,
2134         sp<AMessage> *meta) {
2135
2136     float newConfidence = 0.08f;
2137
2138     ALOGV("SniffFFMPEG (initial confidence: %f, mime: %s)", *confidence,
2139             mimeType == NULL ? "unknown" : *mimeType);
2140
2141     // This is a heavyweight sniffer, don't invoke it if Stagefright knows
2142     // what it is doing already.
2143     if (mimeType != NULL && confidence != NULL) {
2144         if (*confidence > 0.8f) {
2145             return false;
2146         }
2147     }
2148
2149     *meta = new AMessage;
2150
2151     const char *container = BetterSniffFFMPEG(source, &newConfidence, *meta);
2152     if (!container) {
2153         ALOGW("sniff through BetterSniffFFMPEG failed, try LegacySniffFFMPEG");
2154         container = LegacySniffFFMPEG(source, &newConfidence, *meta);
2155         if (container) {
2156             ALOGV("sniff through LegacySniffFFMPEG success");
2157         }
2158     } else {
2159         ALOGV("sniff through BetterSniffFFMPEG success");
2160     }
2161
2162     if (container == NULL) {
2163         ALOGD("SniffFFMPEG failed to sniff this source");
2164         (*meta)->clear();
2165         *meta = NULL;
2166         return false;
2167     }
2168
2169     ALOGD("ffmpeg detected media content as '%s' with confidence %.2f",
2170             container, newConfidence);
2171
2172     mimeType->setTo(container);
2173
2174     (*meta)->setString("extended-extractor", "extended-extractor");
2175     (*meta)->setString("extended-extractor-subtype", "ffmpegextractor");
2176     (*meta)->setString("extended-extractor-mime", container);
2177
2178     //debug only
2179     char value[PROPERTY_VALUE_MAX];
2180     property_get("sys.media.parser.ffmpeg", value, "0");
2181     if (atoi(value)) {
2182         ALOGD("[debug] use ffmpeg parser");
2183         newConfidence = 0.88f;
2184     }
2185
2186     if (newConfidence > *confidence) {
2187         (*meta)->setString("extended-extractor-use", "ffmpegextractor");
2188         *confidence = newConfidence;
2189     }
2190
2191     return true;
2192 }
2193
2194 MediaExtractor *CreateFFmpegExtractor(const sp<DataSource> &source, const char *mime, const sp<AMessage> &meta) {
2195     MediaExtractor *ret = NULL;
2196     AString notuse;
2197     if (meta.get() && meta->findString("extended-extractor", &notuse) && (
2198             !strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_MPEG)          ||
2199             !strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_AAC)           ||
2200             !strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_VORBIS)        ||
2201             !strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_FLAC)          ||
2202             !strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_AC3)           ||
2203             !strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_APE)           ||
2204             !strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_DTS)           ||
2205             !strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_II) ||
2206             !strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_RA)            ||
2207             !strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_WMA)           ||
2208             !strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_FFMPEG)        ||
2209             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_MPEG4)     ||
2210             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_MOV)       ||
2211             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_MATROSKA)  ||
2212             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_TS)        ||
2213             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_MPEG2PS)   ||
2214             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_AVI)       ||
2215             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_ASF)       ||
2216             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_WEBM)      ||
2217             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_WMV)       ||
2218             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_MPG)       ||
2219             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_FLV)       ||
2220             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_DIVX)      ||
2221             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_RM)        ||
2222             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_WAV)       ||
2223             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_FLAC)      ||
2224             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_APE)       ||
2225             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_DTS)       ||
2226             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_MP2)       ||
2227             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_RA)        ||
2228             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_OGG)       ||
2229             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_VC1)       ||
2230             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_HEVC)      ||
2231             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_WMA)       ||
2232             !strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_FFMPEG))) {
2233         ret = new FFmpegExtractor(source, meta);
2234     }
2235
2236     ALOGD("%ssupported mime: %s", (ret ? "" : "un"), mime);
2237     return ret;
2238 }
2239
2240 }  // namespace android
2241
2242 extern "C" void getExtractorPlugin(android::MediaExtractor::Plugin *plugin)
2243 {
2244     plugin->sniff = android::SniffFFMPEG;
2245     plugin->create = android::CreateFFmpegExtractor;
2246 }