2 * Copyright 2012 Michael Chen <omxcodec@gmail.com>
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 #define LOG_TAG "FFmpegExtractor"
19 #include <utils/Log.h>
21 #include <limits.h> /* INT_MAX */
23 #include <media/stagefright/foundation/ABitReader.h>
24 #include <media/stagefright/foundation/ABuffer.h>
25 #include <media/stagefright/foundation/ADebug.h>
26 #include <media/stagefright/foundation/AMessage.h>
27 #include <media/stagefright/foundation/hexdump.h>
28 #include <media/stagefright/DataSource.h>
29 #include <media/stagefright/MediaBuffer.h>
30 #include <media/stagefright/MediaDebug.h>
31 #include <media/stagefright/MediaDefs.h>
32 #include <media/stagefright/MediaErrors.h>
33 #include <media/stagefright/MediaSource.h>
34 #include <media/stagefright/MetaData.h>
35 #include <media/stagefright/Utils.h>
36 #include <utils/String8.h>
37 #include <utils/misc.h>
39 #include "include/avc_utils.h"
40 #include "ffmpeg_utils/ffmpeg_utils.h"
41 #include "FFmpegExtractor.h"
43 #define DEBUG_READ_ENTRY 0
44 #define DIABLE_VIDEO 0
45 #define DIABLE_AUDIO 0
46 #define WAIT_KEY_PACKET_AFTER_SEEK 1
47 #define DISABLE_NAL_TO_ANNEXB 0
49 #define MAX_QUEUE_SIZE (15 * 1024 * 1024)
50 #define MIN_AUDIOQ_SIZE (20 * 16 * 1024)
52 #define EXTRACTOR_MAX_PROBE_PACKETS 200
59 static AVPacket flush_pkt;
63 struct FFmpegExtractor::Track : public MediaSource {
64 Track(const sp<FFmpegExtractor> &extractor, sp<MetaData> meta, bool isAVC,
65 AVStream *stream, PacketQueue *queue);
67 virtual status_t start(MetaData *params);
68 virtual status_t stop();
69 virtual sp<MetaData> getFormat();
71 virtual status_t read(
72 MediaBuffer **buffer, const ReadOptions *options);
78 friend struct FFmpegExtractor;
80 sp<FFmpegExtractor> mExtractor;
83 enum AVMediaType mMediaType;
88 size_t mNALLengthSize;
94 DISALLOW_EVIL_CONSTRUCTORS(Track);
97 ////////////////////////////////////////////////////////////////////////////////
99 FFmpegExtractor::FFmpegExtractor(const sp<DataSource> &source)
100 : mDataSource(source),
101 mReaderThreadStarted(false),
102 mInitCheck(NO_INIT) {
103 LOGV("FFmpegExtractor::FFmpegExtractor");
106 const char *url = mDataSource->getNamURI();
108 LOGI("url is error!");
112 if (!strcmp(url, "-")) {
113 av_strlcpy(mFilename, "pipe:", strlen("pipe:") + 1);
115 av_strlcpy(mFilename, url, strlen(url) + 1);
117 LOGI("url: %s, mFilename: %s", url, mFilename);
121 LOGE("failed to init ffmpeg");
125 // start reader here, as we want to extract extradata from bitstream if no extradata
128 while(mProbePkts <= EXTRACTOR_MAX_PROBE_PACKETS && !mEOF &&
129 (mFormatCtx->pb ? !mFormatCtx->pb->error : 1) &&
130 (mDefersToCreateVideoTrack || mDefersToCreateAudioTrack)) {
131 // FIXME, i am so lazy! Should use pthread_cond_wait to wait conditions
135 LOGV("mProbePkts: %d, mEOF: %d, pb->error(if has): %d, mDefersToCreateVideoTrack: %d, mDefersToCreateAudioTrack: %d",
136 mProbePkts, mEOF, mFormatCtx->pb ? mFormatCtx->pb->error : 0, mDefersToCreateVideoTrack, mDefersToCreateAudioTrack);
141 FFmpegExtractor::~FFmpegExtractor() {
142 LOGV("FFmpegExtractor::~FFmpegExtractor");
144 // stop reader here if no track!
150 size_t FFmpegExtractor::countTracks() {
151 return mInitCheck == OK ? mTracks.size() : 0;
154 sp<MediaSource> FFmpegExtractor::getTrack(size_t index) {
155 LOGV("FFmpegExtractor::getTrack[%d]", index);
157 if (mInitCheck != OK) {
161 if (index >= mTracks.size()) {
165 return mTracks.valueAt(index);
168 sp<MetaData> FFmpegExtractor::getTrackMetaData(size_t index, uint32_t flags) {
169 LOGV("FFmpegExtractor::getTrackMetaData[%d]", index);
171 if (mInitCheck != OK) {
175 if (index >= mTracks.size()) {
179 return mTracks.valueAt(index)->getFormat();
182 sp<MetaData> FFmpegExtractor::getMetaData() {
183 LOGV("FFmpegExtractor::getMetaData");
185 if (mInitCheck != OK) {
189 sp<MetaData> meta = new MetaData;
191 meta->setCString(kKeyMIMEType, "video/ffmpeg");
196 uint32_t FFmpegExtractor::flags() const {
197 LOGV("FFmpegExtractor::flags");
199 if (mInitCheck != OK) {
203 uint32_t flags = CAN_PAUSE;
205 if (mFormatCtx->duration != AV_NOPTS_VALUE) {
206 flags |= CAN_SEEK_BACKWARD | CAN_SEEK_FORWARD | CAN_SEEK;
212 void FFmpegExtractor::packet_queue_init(PacketQueue *q)
214 memset(q, 0, sizeof(PacketQueue));
215 q->mutex = SDL_CreateMutex();
216 q->cond = SDL_CreateCond();
217 packet_queue_put(q, &flush_pkt);
220 void FFmpegExtractor::packet_queue_flush(PacketQueue *q)
222 AVPacketList *pkt, *pkt1;
224 SDL_LockMutex(q->mutex);
225 for (pkt = q->first_pkt; pkt != NULL; pkt = pkt1) {
227 av_free_packet(&pkt->pkt);
234 SDL_UnlockMutex(q->mutex);
237 void FFmpegExtractor::packet_queue_end(PacketQueue *q)
239 packet_queue_flush(q);
240 SDL_DestroyMutex(q->mutex);
241 SDL_DestroyCond(q->cond);
244 void FFmpegExtractor::packet_queue_abort(PacketQueue *q)
246 SDL_LockMutex(q->mutex);
248 q->abort_request = 1;
250 SDL_CondSignal(q->cond);
252 SDL_UnlockMutex(q->mutex);
255 int FFmpegExtractor::packet_queue_put(PacketQueue *q, AVPacket *pkt)
259 /* duplicate the packet */
260 if (pkt != &flush_pkt && av_dup_packet(pkt) < 0)
263 pkt1 = (AVPacketList *)av_malloc(sizeof(AVPacketList));
269 SDL_LockMutex(q->mutex);
275 q->last_pkt->next = pkt1;
278 //q->size += pkt1->pkt.size + sizeof(*pkt1);
279 q->size += pkt1->pkt.size;
280 SDL_CondSignal(q->cond);
282 SDL_UnlockMutex(q->mutex);
286 /* packet queue handling */
287 /* return < 0 if aborted, 0 if no packet and > 0 if packet. */
288 int FFmpegExtractor::packet_queue_get(PacketQueue *q, AVPacket *pkt, int block)
293 SDL_LockMutex(q->mutex);
296 if (q->abort_request) {
303 q->first_pkt = pkt1->next;
307 //q->size -= pkt1->pkt.size + sizeof(*pkt1);
308 q->size -= pkt1->pkt.size;
317 SDL_CondWait(q->cond, q->mutex);
320 SDL_UnlockMutex(q->mutex);
324 static int lockmgr(void **mtx, enum AVLockOp op)
328 *mtx = (void *)SDL_CreateMutex();
333 return !!SDL_LockMutex((SDL_mutex *)*mtx);
334 case AV_LOCK_RELEASE:
335 return !!SDL_UnlockMutex((SDL_mutex *)*mtx);
336 case AV_LOCK_DESTROY:
337 SDL_DestroyMutex((SDL_mutex *)*mtx);
343 static void EncodeSize14(uint8_t **_ptr, size_t size) {
344 CHECK_LE(size, 0x3fff);
346 uint8_t *ptr = *_ptr;
348 *ptr++ = 0x80 | (size >> 7);
349 *ptr++ = size & 0x7f;
354 static sp<ABuffer> MakeMPEGVideoESDS(const sp<ABuffer> &csd) {
355 sp<ABuffer> esds = new ABuffer(csd->size() + 25);
357 uint8_t *ptr = esds->data();
359 EncodeSize14(&ptr, 22 + csd->size());
361 *ptr++ = 0x00; // ES_ID
364 *ptr++ = 0x00; // streamDependenceFlag, URL_Flag, OCRstreamFlag
367 EncodeSize14(&ptr, 16 + csd->size());
369 *ptr++ = 0x40; // Audio ISO/IEC 14496-3
371 for (size_t i = 0; i < 12; ++i) {
376 EncodeSize14(&ptr, csd->size());
378 memcpy(ptr, csd->data(), csd->size());
383 // Returns the sample rate based on the sampling frequency index
384 static uint32_t get_sample_rate(const uint8_t sf_index)
386 static const uint32_t sample_rates[] =
388 96000, 88200, 64000, 48000, 44100, 32000,
389 24000, 22050, 16000, 12000, 11025, 8000
392 if (sf_index < sizeof(sample_rates) / sizeof(sample_rates[0])) {
393 return sample_rates[sf_index];
399 int FFmpegExtractor::check_extradata(AVCodecContext *avctx)
402 bool *defersToCreateTrack;
403 AVBitStreamFilterContext **bsfc;
406 if (avctx->codec_id == CODEC_ID_MP3 ||
407 avctx->codec_id == CODEC_ID_H263 ||
408 avctx->codec_id == CODEC_ID_H263P ||
409 avctx->codec_id == CODEC_ID_H263I)
412 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
414 defersToCreateTrack = &mDefersToCreateVideoTrack;
415 } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO){
417 defersToCreateTrack = &mDefersToCreateAudioTrack;
421 switch(avctx->codec_id) {
429 name = "aac_adtstoasc";
437 if (avctx->extradata_size <= 0) {
438 LOGI("No %s extradata found, should to extract it from bitstream",
439 av_get_media_type_string(avctx->codec_type));
440 *defersToCreateTrack = true;
441 //CHECK(name != NULL);
442 if (!*bsfc && name) {
443 *bsfc = av_bitstream_filter_init(name);
445 LOGE("Cannot open the %s BSF!", name);
446 *defersToCreateTrack = false;
449 LOGV("open the %s bsf", name);
460 int FFmpegExtractor::stream_component_open(int stream_index)
462 AVCodecContext *avctx;
465 bool supported = false;
471 LOGI("stream_index: %d", stream_index);
472 if (stream_index < 0 || stream_index >= mFormatCtx->nb_streams)
474 avctx = mFormatCtx->streams[stream_index]->codec;
476 switch(avctx->codec_id) {
484 case CODEC_ID_MPEG2VIDEO:
496 LOGE("unsupport the codec, id: 0x%0x", avctx->codec_id);
499 LOGV("support the codec");
502 ssize_t index = mTracks.indexOfKey(stream_index);
505 LOGE("this track already exists");
509 mFormatCtx->streams[stream_index]->discard = AVDISCARD_DEFAULT;
512 av_get_codec_tag_string(tagbuf, sizeof(tagbuf), avctx->codec_tag);
513 LOGV("Tag %s/0x%08x with codec id '%d'\n", tagbuf, avctx->codec_tag, avctx->codec_id);
515 switch (avctx->codec_type) {
516 case AVMEDIA_TYPE_VIDEO:
517 if (mVideoStreamIdx == -1)
518 mVideoStreamIdx = stream_index;
519 if (mVideoStream == NULL)
520 mVideoStream = mFormatCtx->streams[stream_index];
521 if (!mVideoQInited) {
522 packet_queue_init(&mVideoQ);
523 mVideoQInited = true;
526 ret = check_extradata(avctx);
529 // disable the stream
530 mVideoStreamIdx = -1;
532 packet_queue_end(&mVideoQ);
533 mVideoQInited = false;
534 mFormatCtx->streams[stream_index]->discard = AVDISCARD_ALL;
539 if (avctx->extradata) {
540 LOGV("video stream extradata:");
541 hexdump(avctx->extradata, avctx->extradata_size);
543 LOGV("video stream no extradata, but we can ignore it.");
548 switch(avctx->codec_id) {
552 * http://msdn.microsoft.com/en-us/library/dd757808(v=vs.85).aspx
554 //if (avctx->codec_tag && avctx->codec_tag == AV_RL32("avc1")) {
555 if (avctx->extradata[0] == 1 /* configurationVersion */) {
556 // H.264 bitstream without start codes.
560 if (avctx->width == 0 || avctx->height == 0) {
561 int32_t width, height;
562 sp<ABuffer> seqParamSet = new ABuffer(avctx->extradata_size - 8);
563 memcpy(seqParamSet->data(), avctx->extradata + 8, avctx->extradata_size - 8);
564 FindAVCDimensions(seqParamSet, &width, &height);
565 avctx->width = width;
566 avctx->height = height;
569 meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
570 meta->setData(kKeyAVCC, kTypeAVCC, avctx->extradata, avctx->extradata_size);
572 // H.264 bitstream with start codes.
576 /* set NULL to release meta as we will new a meta in MakeAVCCodecSpecificData() fxn */
580 sp<ABuffer> buffer = new ABuffer(avctx->extradata_size);
581 memcpy(buffer->data(), avctx->extradata, avctx->extradata_size);
582 meta = MakeAVCCodecSpecificData(buffer);
587 meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4);
589 sp<ABuffer> csd = new ABuffer(avctx->extradata_size);
590 memcpy(csd->data(), avctx->extradata, avctx->extradata_size);
591 sp<ABuffer> esds = MakeMPEGVideoESDS(csd);
592 meta->setData(kKeyESDS, kTypeESDS, esds->data(), esds->size());
599 meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263);
601 case CODEC_ID_MPEG2VIDEO:
603 meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG2);
605 sp<ABuffer> csd = new ABuffer(avctx->extradata_size);
606 memcpy(csd->data(), avctx->extradata, avctx->extradata_size);
607 sp<ABuffer> esds = MakeMPEGVideoESDS(csd);
608 meta->setData(kKeyESDS, kTypeESDS, esds->data(), esds->size());
613 meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_WMV12);
614 meta->setData(kKeyESDS, kTypeESDS, avctx->extradata, avctx->extradata_size);
617 CHECK(!"Should not be here. Unsupported codec.");
621 LOGI("width: %d, height: %d, bit_rate: %d", avctx->width, avctx->height, avctx->bit_rate);
623 meta->setInt32(kKeyWidth, avctx->width);
624 meta->setInt32(kKeyHeight, avctx->height);
625 meta->setInt32(kKeyBitRate, avctx->bit_rate);
626 if (mFormatCtx->duration != AV_NOPTS_VALUE)
627 meta->setInt64(kKeyDuration, mFormatCtx->duration);
629 LOGV("create a video track");
631 stream_index, new Track(this, meta, isAVC, mVideoStream, &mVideoQ));
633 mDefersToCreateVideoTrack = false;
636 case AVMEDIA_TYPE_AUDIO:
637 if (mAudioStreamIdx == -1)
638 mAudioStreamIdx = stream_index;
639 if (mAudioStream == NULL)
640 mAudioStream = mFormatCtx->streams[stream_index];
641 if (!mAudioQInited) {
642 packet_queue_init(&mAudioQ);
643 mAudioQInited = true;
646 ret = check_extradata(avctx);
649 // disable the stream
650 mAudioStreamIdx = -1;
652 packet_queue_end(&mAudioQ);
653 mAudioQInited = false;
654 mFormatCtx->streams[stream_index]->discard = AVDISCARD_ALL;
659 if (avctx->extradata) {
660 LOGV("audio stream extradata:");
661 hexdump(avctx->extradata, avctx->extradata_size);
663 LOGV("audio stream no extradata, but we can ignore it.");
666 switch(avctx->codec_id) {
670 meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_MPEG);
671 //meta->setData(kKeyESDS, kTypeESDS, avctx->extradata, avctx->extradata_size);
676 const uint8_t *header;
677 uint8_t profile, sf_index, channel;
679 header = avctx->extradata;
680 CHECK(header != NULL);
682 // AudioSpecificInfo follows
683 // oooo offf fccc c000
684 // o - audioObjectType
685 // f - samplingFreqIndex
687 profile = ((header[0] & 0xf8) >> 3) - 1;
688 sf_index = (header[0] & 0x07) << 1 | (header[1] & 0x80) >> 7;
689 sr = get_sample_rate(sf_index);
691 LOGE("unsupport the sample rate");
694 channel = (header[1] >> 3) & 0xf;
695 LOGV("profile: %d, sf_index: %d, channel: %d", profile, sf_index, channel);
697 meta = MakeAACCodecSpecificData(profile, sf_index, channel);
698 meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AAC);
701 CHECK(!"Should not be here. Unsupported codec.");
705 LOGI("bit_rate: %d, sample_rate: %d, channels: %d", avctx->bit_rate, avctx->sample_rate, avctx->channels);
707 meta->setInt32(kKeySampleRate, avctx->sample_rate);
708 meta->setInt32(kKeyChannelCount, avctx->channels);
709 meta->setInt32(kKeyBitRate, avctx->bit_rate);
710 if (mFormatCtx->duration != AV_NOPTS_VALUE)
711 meta->setInt64(kKeyDuration, mFormatCtx->duration);
713 if (avctx->codec_id != CODEC_ID_MP3) {
714 LOGV("audio meta esds:");
715 CHECK(meta->findData(kKeyESDS, &type, &data, &size));
719 LOGV("create a audio track");
721 stream_index, new Track(this, meta, false, mAudioStream, &mAudioQ));
723 mDefersToCreateAudioTrack = false;
726 case AVMEDIA_TYPE_SUBTITLE:
728 CHECK(!"Should not be here. Unsupported media type.");
731 CHECK(!"Should not be here. Unsupported media type.");
737 void FFmpegExtractor::stream_component_close(int stream_index)
739 AVCodecContext *avctx;
741 if (stream_index < 0 || stream_index >= mFormatCtx->nb_streams)
743 avctx = mFormatCtx->streams[stream_index]->codec;
745 switch (avctx->codec_type) {
746 case AVMEDIA_TYPE_VIDEO:
747 LOGV("packet_queue_abort videoq");
748 packet_queue_abort(&mVideoQ);
749 /* wait until the end */
750 while (!mAbortRequest && !mVideoEOSReceived) {
751 LOGV("wait for video received");
754 LOGV("packet_queue_end videoq");
755 packet_queue_end(&mVideoQ);
757 case AVMEDIA_TYPE_AUDIO:
758 LOGV("packet_queue_abort audioq");
759 packet_queue_abort(&mAudioQ);
760 while (!mAbortRequest && !mAudioEOSReceived) {
761 LOGV("wait for audio received");
764 LOGV("packet_queue_end audioq");
765 packet_queue_end(&mAudioQ);
767 case AVMEDIA_TYPE_SUBTITLE:
773 mFormatCtx->streams[stream_index]->discard = AVDISCARD_ALL;
774 switch (avctx->codec_type) {
775 case AVMEDIA_TYPE_VIDEO:
777 mVideoStreamIdx = -1;
779 av_bitstream_filter_close(mVideoBsfc);
783 case AVMEDIA_TYPE_AUDIO:
785 mAudioStreamIdx = -1;
787 av_bitstream_filter_close(mAudioBsfc);
791 case AVMEDIA_TYPE_SUBTITLE:
798 void FFmpegExtractor::reachedEOS(enum AVMediaType media_type)
800 Mutex::Autolock autoLock(mLock);
802 if (media_type == AVMEDIA_TYPE_VIDEO) {
803 mVideoEOSReceived = true;
804 } else if (media_type == AVMEDIA_TYPE_AUDIO) {
805 mAudioEOSReceived = true;
809 /* seek in the stream */
810 int FFmpegExtractor::stream_seek(int64_t pos, enum AVMediaType media_type)
812 Mutex::Autolock autoLock(mLock);
814 if (mVideoStreamIdx >= 0 &&
815 mAudioStreamIdx >= 0 &&
816 media_type == AVMEDIA_TYPE_AUDIO &&
817 !mVideoEOSReceived) {
822 if (mAudioStreamIdx >= 0)
823 packet_queue_flush(&mAudioQ);
824 if (mVideoStreamIdx >= 0)
825 packet_queue_flush(&mVideoQ);
828 mSeekFlags &= ~AVSEEK_FLAG_BYTE;
835 int FFmpegExtractor::decode_interrupt_cb(void *ctx)
837 FFmpegExtractor *extrator = static_cast<FFmpegExtractor *>(ctx);
838 return extrator->mAbortRequest;
841 void FFmpegExtractor::print_error_ex(const char *filename, int err)
844 const char *errbuf_ptr = errbuf;
846 if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
847 errbuf_ptr = strerror(AVUNERROR(err));
848 LOGI("%s: %s\n", filename, errbuf_ptr);
851 void FFmpegExtractor::setFFmpegDefaultOpts()
865 mSeekByBytes = 0; /* seek by bytes 0=off 1=on -1=auto" */
866 mStartTime = AV_NOPTS_VALUE;
867 mDuration = AV_NOPTS_VALUE;
868 mSeekPos = AV_NOPTS_VALUE;
872 mVideoStreamIdx = -1;
873 mAudioStreamIdx = -1;
876 mVideoQInited = false;
877 mAudioQInited = false;
878 mDefersToCreateVideoTrack = false;
879 mDefersToCreateAudioTrack = false;
892 int FFmpegExtractor::initFFmpeg()
896 int ret = 0, audio_ret = 0, video_ret = 0;
897 int pkt_in_play_range = 0;
898 AVDictionaryEntry *t;
901 int st_index[AVMEDIA_TYPE_NB] = {0};
902 int wanted_stream[AVMEDIA_TYPE_NB] = {0};
903 st_index[AVMEDIA_TYPE_AUDIO] = -1;
904 st_index[AVMEDIA_TYPE_VIDEO] = -1;
905 wanted_stream[AVMEDIA_TYPE_AUDIO] = -1;
906 wanted_stream[AVMEDIA_TYPE_VIDEO] = -1;
908 setFFmpegDefaultOpts();
910 //nam_av_log_set_flags(AV_LOG_SKIP_REPEATED);
911 av_log_set_level(AV_LOG_DEBUG);
912 av_log_set_callback(nam_av_log_callback);
914 /* register all codecs, demux and protocols */
915 avcodec_register_all();
917 avdevice_register_all();
920 avformat_network_init();
924 if (av_lockmgr_register(lockmgr)) {
925 LOGE("could not initialize lock manager!");
928 av_init_packet(&flush_pkt);
929 flush_pkt.data = (uint8_t *)"FLUSH";
932 mFormatCtx = avformat_alloc_context();
933 mFormatCtx->interrupt_callback.callback = decode_interrupt_cb;
934 mFormatCtx->interrupt_callback.opaque = this;
936 LOGV("mFilename: %s", mFilename);
937 err = avformat_open_input(&mFormatCtx, mFilename, NULL, &format_opts);
939 print_error_ex(mFilename, err);
943 if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
944 LOGE("Option %s not found.\n", t->key);
945 //ret = AVERROR_OPTION_NOT_FOUND;
951 mFormatCtx->flags |= AVFMT_FLAG_GENPTS;
953 opts = setup_find_stream_info_opts(mFormatCtx, codec_opts);
954 orig_nb_streams = mFormatCtx->nb_streams;
956 err = avformat_find_stream_info(mFormatCtx, opts);
958 LOGE("%s: could not find codec parameters\n", mFilename);
962 for (i = 0; i < orig_nb_streams; i++)
963 av_dict_free(&opts[i]);
967 mFormatCtx->pb->eof_reached = 0; // FIXME hack, ffplay maybe should not use url_feof() to test for the end
969 if (mSeekByBytes < 0)
970 mSeekByBytes = !!(mFormatCtx->iformat->flags & AVFMT_TS_DISCONT);
972 /* if seeking requested, we execute it */
973 if (mStartTime != AV_NOPTS_VALUE) {
976 timestamp = mStartTime;
977 /* add the stream start time */
978 if (mFormatCtx->start_time != AV_NOPTS_VALUE)
979 timestamp += mFormatCtx->start_time;
980 ret = avformat_seek_file(mFormatCtx, -1, INT64_MIN, timestamp, INT64_MAX, 0);
982 LOGE("%s: could not seek to position %0.3f",
983 mFilename, (double)timestamp / AV_TIME_BASE);
988 for (i = 0; i < mFormatCtx->nb_streams; i++)
989 mFormatCtx->streams[i]->discard = AVDISCARD_ALL;
991 st_index[AVMEDIA_TYPE_VIDEO] =
992 av_find_best_stream(mFormatCtx, AVMEDIA_TYPE_VIDEO,
993 wanted_stream[AVMEDIA_TYPE_VIDEO], -1, NULL, 0);
995 st_index[AVMEDIA_TYPE_AUDIO] =
996 av_find_best_stream(mFormatCtx, AVMEDIA_TYPE_AUDIO,
997 wanted_stream[AVMEDIA_TYPE_AUDIO],
998 st_index[AVMEDIA_TYPE_VIDEO],
1001 av_dump_format(mFormatCtx, 0, mFilename, 0);
1004 if (mFormatCtx->duration != AV_NOPTS_VALUE) {
1005 int hours, mins, secs, us;
1006 secs = mFormatCtx->duration / AV_TIME_BASE;
1007 us = mFormatCtx->duration % AV_TIME_BASE;
1012 LOGI("the duration is %02d:%02d:%02d.%02d", hours, mins, secs, (100 * us) / AV_TIME_BASE);
1015 if (st_index[AVMEDIA_TYPE_AUDIO] >= 0) {
1016 audio_ret = stream_component_open(st_index[AVMEDIA_TYPE_AUDIO]);
1019 if (st_index[AVMEDIA_TYPE_VIDEO] >= 0) {
1020 video_ret = stream_component_open(st_index[AVMEDIA_TYPE_VIDEO]);
1023 if ( audio_ret < 0 && video_ret < 0) {
1024 LOGE("%s: could not open codecs\n", mFilename);
1035 void FFmpegExtractor::deInitFFmpeg()
1038 avformat_close_input(&mFormatCtx);
1041 av_lockmgr_register(NULL);
1043 avformat_network_deinit();
1045 av_log(NULL, AV_LOG_QUIET, "%s", "");
1048 status_t FFmpegExtractor::startReaderThread() {
1049 LOGV("Starting reader thread");
1050 Mutex::Autolock autoLock(mLock);
1052 if (mReaderThreadStarted)
1055 pthread_attr_t attr;
1056 pthread_attr_init(&attr);
1057 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1058 pthread_create(&mReaderThread, &attr, ReaderWrapper, this);
1059 pthread_attr_destroy(&attr);
1060 mReaderThreadStarted = true;
1061 LOGD("Reader thread started");
1066 void FFmpegExtractor::stopReaderThread() {
1067 LOGV("Stopping reader thread");
1068 Mutex::Autolock autoLock(mLock);
1070 if (!mReaderThreadStarted) {
1071 LOGD("Reader thread have been stopped");
1078 pthread_join(mReaderThread, &dummy);
1079 mReaderThreadStarted = false;
1080 LOGD("Reader thread stopped");
1084 void *FFmpegExtractor::ReaderWrapper(void *me) {
1085 ((FFmpegExtractor *)me)->readerEntry();
1090 void FFmpegExtractor::readerEntry() {
1092 AVPacket pkt1, *pkt = &pkt1;
1094 int pkt_in_play_range = 0;
1096 LOGV("FFmpegExtractor::readerEntry");
1098 mVideoEOSReceived = false;
1099 mAudioEOSReceived = false;
1105 if (mPaused != mLastPaused) {
1106 mLastPaused = mPaused;
1108 mReadPauseReturn = av_read_pause(mFormatCtx);
1110 av_read_play(mFormatCtx);
1112 #if CONFIG_RTSP_DEMUXER || CONFIG_MMSH_PROTOCOL
1114 (!strcmp(mFormatCtx->iformat->name, "rtsp") ||
1115 (mFormatCtx->pb && !strncmp(mFilename, "mmsh:", 5)))) {
1116 /* wait 10 ms to avoid trying to get another packet */
1124 LOGV("readerEntry, mSeekReq: %d", mSeekReq);
1125 ret = avformat_seek_file(mFormatCtx, -1, INT64_MIN, mSeekPos, INT64_MAX, mSeekFlags);
1127 LOGE("%s: error while seeking", mFormatCtx->filename);
1129 if (mAudioStreamIdx >= 0) {
1130 packet_queue_flush(&mAudioQ);
1131 packet_queue_put(&mAudioQ, &flush_pkt);
1133 if (mVideoStreamIdx >= 0) {
1134 packet_queue_flush(&mVideoQ);
1135 packet_queue_put(&mVideoQ, &flush_pkt);
1142 /* if the queue are full, no need to read more */
1143 if ( mAudioQ.size + mVideoQ.size > MAX_QUEUE_SIZE
1144 || ( (mAudioQ .size > MIN_AUDIOQ_SIZE || mAudioStreamIdx < 0)
1145 && (mVideoQ .nb_packets > MIN_FRAMES || mVideoStreamIdx < 0))) {
1146 #if DEBUG_READ_ENTRY
1147 LOGV("readerEntry, is full, fuck");
1155 if (mVideoStreamIdx >= 0) {
1156 av_init_packet(pkt);
1159 pkt->stream_index = mVideoStreamIdx;
1160 packet_queue_put(&mVideoQ, pkt);
1162 if (mAudioStreamIdx >= 0) {
1163 av_init_packet(pkt);
1166 pkt->stream_index = mAudioStreamIdx;
1167 packet_queue_put(&mAudioQ, pkt);
1170 #if DEBUG_READ_ENTRY
1171 LOGV("readerEntry, eof = 1, mVideoQ.size: %d, mVideoQ.nb_packets: %d, mAudioQ.size: %d, mAudioQ.nb_packets: %d",
1172 mVideoQ.size, mVideoQ.nb_packets, mAudioQ.size, mAudioQ.nb_packets);
1174 if (mAudioQ.size + mVideoQ.size == 0) {
1175 if (mLoop != 1 && (!mLoop || --mLoop)) {
1176 if (mVideoStreamIdx >= 0) {
1177 stream_seek(mStartTime != AV_NOPTS_VALUE ? mStartTime : 0, AVMEDIA_TYPE_VIDEO);
1178 } else if (mAudioStreamIdx >= 0) {
1179 stream_seek(mStartTime != AV_NOPTS_VALUE ? mStartTime : 0, AVMEDIA_TYPE_AUDIO);
1181 } else if (mAutoExit) {
1190 ret = av_read_frame(mFormatCtx, pkt);
1193 if (ret == AVERROR_EOF || url_feof(mFormatCtx->pb))
1194 if (ret == AVERROR_EOF) {
1195 //LOGV("ret == AVERROR_EOF");
1197 if (url_feof(mFormatCtx->pb)) {
1198 //LOGV("url_feof(mFormatCtx->pb)");
1203 if (mFormatCtx->pb && mFormatCtx->pb->error) {
1204 LOGE("mFormatCtx->pb->error: %d", mFormatCtx->pb->error);
1211 if (pkt->stream_index == mAudioStreamIdx) {
1215 AVCodecContext *avctx = mFormatCtx->streams[mAudioStreamIdx]->codec;
1216 if (mAudioBsfc && pkt && pkt->data) {
1217 ret = av_bitstream_filter_filter(mAudioBsfc, avctx, NULL, &outbuf, &outbuf_size,
1218 pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY);
1220 if (ret < 0 ||!outbuf_size) {
1221 av_free_packet(pkt);
1224 if (outbuf && outbuf != pkt->data) {
1225 memmove(pkt->data, outbuf, outbuf_size);
1226 pkt->size = outbuf_size;
1229 if (mDefersToCreateAudioTrack) {
1230 if (avctx->extradata_size <= 0) {
1231 av_free_packet(pkt);
1234 stream_component_open(mAudioStreamIdx);
1235 if (!mDefersToCreateAudioTrack)
1236 LOGI("probe packet counter: %d when create audio track ok", mProbePkts);
1237 if (mProbePkts == EXTRACTOR_MAX_PROBE_PACKETS)
1238 LOGI("probe packet counter to max: %d, create audio track: %d",
1239 mProbePkts, !mDefersToCreateAudioTrack);
1243 /* check if packet is in play range specified by user, then queue, otherwise discard */
1244 pkt_in_play_range = mDuration == AV_NOPTS_VALUE ||
1245 (pkt->pts - mFormatCtx->streams[pkt->stream_index]->start_time) *
1246 av_q2d(mFormatCtx->streams[pkt->stream_index]->time_base) -
1247 (double)(mStartTime != AV_NOPTS_VALUE ? mStartTime : 0) / 1000000
1248 <= ((double)mDuration / 1000000);
1249 if (pkt->stream_index == mAudioStreamIdx && pkt_in_play_range) {
1250 packet_queue_put(&mAudioQ, pkt);
1251 } else if (pkt->stream_index == mVideoStreamIdx && pkt_in_play_range) {
1252 packet_queue_put(&mVideoQ, pkt);
1254 av_free_packet(pkt);
1257 /* wait until the end */
1258 while (!mAbortRequest) {
1264 LOGI("reader thread goto end...");
1266 /* close each stream */
1267 if (mAudioStreamIdx >= 0)
1268 stream_component_close(mAudioStreamIdx);
1269 if (mVideoStreamIdx >= 0)
1270 stream_component_close(mVideoStreamIdx);
1272 avformat_close_input(&mFormatCtx);
1276 ////////////////////////////////////////////////////////////////////////////////
1278 FFmpegExtractor::Track::Track(
1279 const sp<FFmpegExtractor> &extractor, sp<MetaData> meta, bool isAVC,
1280 AVStream *stream, PacketQueue *queue)
1281 : mExtractor(extractor),
1288 /* H.264 Video Types */
1290 mNal2AnnexB = false;
1296 CHECK(meta->findData(kKeyAVCC, &type, &data, &size));
1298 const uint8_t *ptr = (const uint8_t *)data;
1301 CHECK_EQ((unsigned)ptr[0], 1u); // configurationVersion == 1
1303 // The number of bytes used to encode the length of a NAL unit.
1304 mNALLengthSize = 1 + (ptr[4] & 3);
1306 LOGV("the stream is AVC, the length of a NAL unit: %d", mNALLengthSize);
1312 mMediaType = mStream->codec->codec_type;
1315 FFmpegExtractor::Track::~Track() {
1318 status_t FFmpegExtractor::Track::start(MetaData *params) {
1319 Mutex::Autolock autoLock(mLock);
1320 //mExtractor->startReaderThread();
1324 status_t FFmpegExtractor::Track::stop() {
1325 Mutex::Autolock autoLock(mLock);
1326 mExtractor->stopReaderThread();
1330 sp<MetaData> FFmpegExtractor::Track::getFormat() {
1331 Mutex::Autolock autoLock(mLock);
1336 status_t FFmpegExtractor::Track::read(
1337 MediaBuffer **buffer, const ReadOptions *options) {
1340 Mutex::Autolock autoLock(mLock);
1343 bool seeking = false;
1344 bool waitKeyPkt = false;
1345 ReadOptions::SeekMode mode;
1346 int64_t pktTS = AV_NOPTS_VALUE;
1347 int64_t seekTimeUs = AV_NOPTS_VALUE;
1350 status_t status = OK;
1352 if (options && options->getSeekTo(&seekTimeUs, &mode)) {
1353 LOGV("~~~%s seekTimeUs: %lld, mode: %d", av_get_media_type_string(mMediaType), seekTimeUs, mode);
1354 if (mExtractor->stream_seek(seekTimeUs, mMediaType) == SEEK)
1359 if (mExtractor->packet_queue_get(mQueue, &pkt, 1) < 0) {
1360 mExtractor->reachedEOS(mMediaType);
1361 return ERROR_END_OF_STREAM;
1365 if (pkt.data != flush_pkt.data) {
1366 av_free_packet(&pkt);
1370 #if WAIT_KEY_PACKET_AFTER_SEEK
1376 if (pkt.data == flush_pkt.data) {
1377 LOGV("read %s flush pkt", av_get_media_type_string(mMediaType));
1378 av_free_packet(&pkt);
1380 } else if (pkt.data == NULL && pkt.size == 0) {
1381 LOGV("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;
1387 key = pkt.flags & AV_PKT_FLAG_KEY ? 1 : 0;
1391 LOGV("drop the no key packet");
1392 av_free_packet(&pkt);
1395 LOGV("~~~~~~ got the key packet");
1400 MediaBuffer *mediaBuffer = new MediaBuffer(pkt.size + FF_INPUT_BUFFER_PADDING_SIZE);
1401 mediaBuffer->meta_data()->clear();
1402 mediaBuffer->set_range(0, pkt.size);
1403 #if DISABLE_NAL_TO_ANNEXB
1404 mNal2AnnexB = false;
1406 if (mIsAVC && mNal2AnnexB) {
1407 /* Convert H.264 NAL format to annex b */
1408 if (mNALLengthSize >= 3 && mNALLengthSize <= 4 )
1410 uint8_t *dst = (uint8_t *)mediaBuffer->data();
1412 /* This only works for NAL sizes 3-4 */
1413 size_t len = pkt.size, i;
1414 uint8_t *ptr = pkt.data;
1415 while (len >= mNALLengthSize) {
1416 uint32_t nal_len = 0;
1417 for( i = 0; i < mNALLengthSize; i++ ) {
1418 nal_len = (nal_len << 8) | ptr[i];
1421 dst[mNALLengthSize - 1] = 1;
1422 if (nal_len > INT_MAX || nal_len > (unsigned int)len) {
1423 status = ERROR_MALFORMED;
1426 dst += mNALLengthSize;
1427 ptr += mNALLengthSize;
1428 len -= mNALLengthSize;
1430 memcpy(dst, ptr, nal_len);
1437 status = ERROR_MALFORMED;
1441 LOGV("status != OK");
1442 mediaBuffer->release();
1444 av_free_packet(&pkt);
1445 return ERROR_MALFORMED;
1448 memcpy(mediaBuffer->data(), pkt.data, pkt.size);
1453 if (pkt.pts == AV_NOPTS_VALUE)
1457 // TODO, Stagefright can't handle negative timestamps
1458 // if needed, work around this by offsetting them manually?
1463 timeUs = (int64_t)(pktTS * av_q2d(mStream->time_base) * 1000000);
1466 LOGV("read %s pkt, size: %d, key: %d, pts: %lld, dts: %lld, timeUs: %llu us (%.2f secs)",
1467 av_get_media_type_string(mMediaType), pkt.size, key, pkt.pts, pkt.dts, timeUs, timeUs/1E6);
1471 // TODO, Stagefright can't handle negative timestamps
1472 // if needed, work around this by offsetting them manually?
1477 mediaBuffer->meta_data()->setInt64(kKeyTime, timeUs);
1478 mediaBuffer->meta_data()->setInt32(kKeyIsSyncFrame, key);
1480 *buffer = mediaBuffer;
1482 av_free_packet(&pkt);
1487 ////////////////////////////////////////////////////////////////////////////////
1491 const char *extension;
1492 const char *container;
1495 static extmap FILE_EXTS [] = {
1496 {".mp4", MEDIA_MIMETYPE_CONTAINER_MPEG4},
1497 {".3gp", MEDIA_MIMETYPE_CONTAINER_MPEG4},
1498 {".mp3", MEDIA_MIMETYPE_AUDIO_MPEG},
1499 {".mov", MEDIA_MIMETYPE_CONTAINER_MOV},
1500 {".mkv", MEDIA_MIMETYPE_CONTAINER_MATROSKA},
1501 {".ts", MEDIA_MIMETYPE_CONTAINER_TS},
1502 {".avi", MEDIA_MIMETYPE_CONTAINER_AVI},
1504 {".asf", MEDIA_MIMETYPE_CONTAINER_ASF},
1505 {".wmv", MEDIA_MIMETYPE_CONTAINER_WMV},
1506 {".wma", MEDIA_MIMETYPE_CONTAINER_WMA},
1507 {".mpg", MEDIA_MIMETYPE_CONTAINER_MPG},
1508 {".flv", MEDIA_MIMETYPE_CONTAINER_FLV},
1509 {".divx", MEDIA_MIMETYPE_CONTAINER_DIVX},
1510 {".mp2", MEDIA_MIMETYPE_CONTAINER_MP2},
1511 {".ape", MEDIA_MIMETYPE_CONTAINER_APE},
1512 {".rm ", MEDIA_MIMETYPE_CONTAINER_RM},
1513 {".ra", MEDIA_MIMETYPE_CONTAINER_RA},
1517 // TODO: check mFormatCtx->iformat->name?
1519 const sp<DataSource> &source, String8 *mimeType, float *confidence,
1520 sp<AMessage> *meta) {
1521 LOGV("SniffFFMPEG");
1523 const char *uri, *container = NULL;
1525 //av_find_input_format()??
1526 uri = source->getNamURI();
1531 LOGI("ffmpeg uri: %s", uri);
1533 LOGI("list the file extensions suppoted by ffmpeg: ");
1534 LOGI("========================================");
1535 for (i = 0; i < NELEM(FILE_EXTS); ++i) {
1536 LOGV("file_exts[%02d]: %s", i, FILE_EXTS[i].extension);
1538 LOGI("========================================");
1540 int lenURI = strlen(uri);
1541 for (i = 0; i < NELEM(FILE_EXTS); ++i) {
1542 int len = strlen(FILE_EXTS[i].extension);
1543 int start = lenURI - len;
1545 if (!av_strncasecmp(uri + start, FILE_EXTS[i].extension, len)) {
1546 container = FILE_EXTS[i].container;
1552 if (container == NULL)
1555 LOGV("found container: %s", container);
1557 *confidence = 0.88f; // Slightly larger than other extractor's confidence
1558 mimeType->setTo(container);
1560 /* use MPEG4Extractor(not extended extractor) for HTTP source only */
1561 if (!av_strcasecmp(container, MEDIA_MIMETYPE_CONTAINER_MPEG4)
1562 && (source->flags() & DataSource::kIsCachingDataSource)) {
1566 *meta = new AMessage;
1567 (*meta)->setString("extended-extractor", "extended-extractor");
1568 (*meta)->setString("extended-extractor-subtype", "ffmpegextractor");
1573 } // namespace android