OSDN Git Service

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