OSDN Git Service

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