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;
405 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
407 defersToCreateTrack = &mDefersToCreateVideoTrack;
408 } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO){
410 defersToCreateTrack = &mDefersToCreateAudioTrack;
414 switch(avctx->codec_id) {
422 name = "aac_adtstoasc";
430 if (avctx->extradata_size <= 0) {
431 LOGI("No %s extradata found, should to extract it from bitstream",
432 av_get_media_type_string(avctx->codec_type));
433 *defersToCreateTrack = true;
434 //CHECK(name != NULL);
435 if (!*bsfc && name) {
436 *bsfc = av_bitstream_filter_init(name);
438 LOGE("Cannot open the %s BSF!", name);
439 *defersToCreateTrack = false;
442 LOGV("open the %s bsf", name);
453 int FFmpegExtractor::stream_component_open(int stream_index)
455 AVCodecContext *avctx;
458 bool supported = false;
464 LOGI("stream_index: %d", stream_index);
465 if (stream_index < 0 || stream_index >= mFormatCtx->nb_streams)
467 avctx = mFormatCtx->streams[stream_index]->codec;
469 switch(avctx->codec_id) {
477 case CODEC_ID_MPEG2VIDEO:
489 LOGE("unsupport the codec");
492 LOGV("support the codec");
495 ssize_t index = mTracks.indexOfKey(stream_index);
498 LOGE("this track already exists");
502 mFormatCtx->streams[stream_index]->discard = AVDISCARD_DEFAULT;
505 av_get_codec_tag_string(tagbuf, sizeof(tagbuf), avctx->codec_tag);
506 LOGV("Tag %s/0x%08x with codec id '%d'\n", tagbuf, avctx->codec_tag, avctx->codec_id);
508 switch (avctx->codec_type) {
509 case AVMEDIA_TYPE_VIDEO:
510 if (mVideoStreamIdx == -1)
511 mVideoStreamIdx = stream_index;
512 if (mVideoStream == NULL)
513 mVideoStream = mFormatCtx->streams[stream_index];
514 if (!mVideoQInited) {
515 packet_queue_init(&mVideoQ);
516 mVideoQInited = true;
519 ret = check_extradata(avctx);
522 // disable the stream
523 mVideoStreamIdx = -1;
525 packet_queue_end(&mVideoQ);
526 mVideoQInited = false;
527 mFormatCtx->streams[stream_index]->discard = AVDISCARD_ALL;
532 LOGV("video extradata:");
533 hexdump(avctx->extradata, avctx->extradata_size);
537 switch(avctx->codec_id) {
541 * http://msdn.microsoft.com/en-us/library/dd757808(v=vs.85).aspx
543 //if (avctx->codec_tag && avctx->codec_tag == AV_RL32("avc1")) {
544 if (avctx->extradata[0] == 1 /* configurationVersion */) {
545 // H.264 bitstream without start codes.
549 if (avctx->width == 0 || avctx->height == 0) {
550 int32_t width, height;
551 sp<ABuffer> seqParamSet = new ABuffer(avctx->extradata_size - 8);
552 memcpy(seqParamSet->data(), avctx->extradata + 8, avctx->extradata_size - 8);
553 FindAVCDimensions(seqParamSet, &width, &height);
554 avctx->width = width;
555 avctx->height = height;
558 meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
559 meta->setData(kKeyAVCC, kTypeAVCC, avctx->extradata, avctx->extradata_size);
561 // H.264 bitstream with start codes.
565 /* set NULL to release meta as we will new a meta in MakeAVCCodecSpecificData() fxn */
569 sp<ABuffer> buffer = new ABuffer(avctx->extradata_size);
570 memcpy(buffer->data(), avctx->extradata, avctx->extradata_size);
571 meta = MakeAVCCodecSpecificData(buffer);
576 meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4);
578 sp<ABuffer> csd = new ABuffer(avctx->extradata_size);
579 memcpy(csd->data(), avctx->extradata, avctx->extradata_size);
580 sp<ABuffer> esds = MakeMPEGVideoESDS(csd);
581 meta->setData(kKeyESDS, kTypeESDS, esds->data(), esds->size());
588 meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263);
590 sp<ABuffer> csd = new ABuffer(avctx->extradata_size);
591 memcpy(csd->data(), avctx->extradata, avctx->extradata_size);
592 sp<ABuffer> esds = MakeMPEGVideoESDS(csd);
593 meta->setData(kKeyESDS, kTypeESDS, esds->data(), esds->size());
596 case CODEC_ID_MPEG2VIDEO:
598 meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG2);
600 sp<ABuffer> csd = new ABuffer(avctx->extradata_size);
601 memcpy(csd->data(), avctx->extradata, avctx->extradata_size);
602 sp<ABuffer> esds = MakeMPEGVideoESDS(csd);
603 meta->setData(kKeyESDS, kTypeESDS, esds->data(), esds->size());
608 meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_WMV12);
609 meta->setData(kKeyESDS, kTypeESDS, avctx->extradata, avctx->extradata_size);
612 CHECK(!"Should not be here. Unsupported codec.");
616 LOGI("width: %d, height: %d, bit_rate: %d", avctx->width, avctx->height, avctx->bit_rate);
618 meta->setInt32(kKeyWidth, avctx->width);
619 meta->setInt32(kKeyHeight, avctx->height);
620 meta->setInt32(kKeyBitRate, avctx->bit_rate);
621 if (mFormatCtx->duration != AV_NOPTS_VALUE)
622 meta->setInt64(kKeyDuration, mFormatCtx->duration);
624 LOGV("create a video track");
626 stream_index, new Track(this, meta, isAVC, mVideoStream, &mVideoQ));
628 mDefersToCreateVideoTrack = false;
631 case AVMEDIA_TYPE_AUDIO:
632 if (mAudioStreamIdx == -1)
633 mAudioStreamIdx = stream_index;
634 if (mAudioStream == NULL)
635 mAudioStream = mFormatCtx->streams[stream_index];
636 if (!mAudioQInited) {
637 packet_queue_init(&mAudioQ);
638 mAudioQInited = true;
641 ret = check_extradata(avctx);
644 // disable the stream
645 mAudioStreamIdx = -1;
647 packet_queue_end(&mAudioQ);
648 mAudioQInited = false;
649 mFormatCtx->streams[stream_index]->discard = AVDISCARD_ALL;
655 LOGV("audio extradata:");
656 hexdump(avctx->extradata, avctx->extradata_size);
658 switch(avctx->codec_id) {
662 meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_MPEG);
663 //meta->setData(kKeyESDS, kTypeESDS, avctx->extradata, avctx->extradata_size);
668 const uint8_t *header;
669 uint8_t profile, sf_index, channel;
671 header = avctx->extradata;
672 CHECK(header != NULL);
674 // AudioSpecificInfo follows
675 // oooo offf fccc c000
676 // o - audioObjectType
677 // f - samplingFreqIndex
679 profile = ((header[0] & 0xf8) >> 3) - 1;
680 sf_index = (header[0] & 0x07) << 1 | (header[1] & 0x80) >> 7;
681 sr = get_sample_rate(sf_index);
683 LOGE("unsupport the sample rate");
686 channel = (header[1] >> 3) & 0xf;
687 LOGV("profile: %d, sf_index: %d, channel: %d", profile, sf_index, channel);
689 meta = MakeAACCodecSpecificData(profile, sf_index, channel);
690 meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AAC);
693 CHECK(!"Should not be here. Unsupported codec.");
697 LOGI("bit_rate: %d, sample_rate: %d, channels: %d", avctx->bit_rate, avctx->sample_rate, avctx->channels);
699 meta->setInt32(kKeySampleRate, avctx->sample_rate);
700 meta->setInt32(kKeyChannelCount, avctx->channels);
701 meta->setInt32(kKeyBitRate, avctx->bit_rate);
702 if (mFormatCtx->duration != AV_NOPTS_VALUE)
703 meta->setInt64(kKeyDuration, mFormatCtx->duration);
705 if (avctx->codec_id != CODEC_ID_MP3) {
706 LOGV("audio meta esds:");
707 CHECK(meta->findData(kKeyESDS, &type, &data, &size));
711 LOGV("create a audio track");
713 stream_index, new Track(this, meta, false, mAudioStream, &mAudioQ));
715 mDefersToCreateAudioTrack = false;
718 case AVMEDIA_TYPE_SUBTITLE:
720 CHECK(!"Should not be here. Unsupported media type.");
723 CHECK(!"Should not be here. Unsupported media type.");
729 void FFmpegExtractor::stream_component_close(int stream_index)
731 AVCodecContext *avctx;
733 if (stream_index < 0 || stream_index >= mFormatCtx->nb_streams)
735 avctx = mFormatCtx->streams[stream_index]->codec;
737 switch (avctx->codec_type) {
738 case AVMEDIA_TYPE_VIDEO:
739 LOGV("packet_queue_abort videoq");
740 packet_queue_abort(&mVideoQ);
741 /* wait until the end */
742 while (!mAbortRequest && !mVideoEOSReceived) {
743 LOGV("wait for video received");
746 LOGV("packet_queue_end videoq");
747 packet_queue_end(&mVideoQ);
749 case AVMEDIA_TYPE_AUDIO:
750 LOGV("packet_queue_abort audioq");
751 packet_queue_abort(&mAudioQ);
752 while (!mAbortRequest && !mAudioEOSReceived) {
753 LOGV("wait for audio received");
756 LOGV("packet_queue_end audioq");
757 packet_queue_end(&mAudioQ);
759 case AVMEDIA_TYPE_SUBTITLE:
765 mFormatCtx->streams[stream_index]->discard = AVDISCARD_ALL;
766 switch (avctx->codec_type) {
767 case AVMEDIA_TYPE_VIDEO:
769 mVideoStreamIdx = -1;
771 av_bitstream_filter_close(mVideoBsfc);
775 case AVMEDIA_TYPE_AUDIO:
777 mAudioStreamIdx = -1;
779 av_bitstream_filter_close(mAudioBsfc);
783 case AVMEDIA_TYPE_SUBTITLE:
790 void FFmpegExtractor::reachedEOS(enum AVMediaType media_type)
792 Mutex::Autolock autoLock(mLock);
794 if (media_type == AVMEDIA_TYPE_VIDEO) {
795 mVideoEOSReceived = true;
796 } else if (media_type == AVMEDIA_TYPE_AUDIO) {
797 mAudioEOSReceived = true;
801 /* seek in the stream */
802 int FFmpegExtractor::stream_seek(int64_t pos, enum AVMediaType media_type)
804 Mutex::Autolock autoLock(mLock);
806 if (mVideoStreamIdx >= 0 &&
807 mAudioStreamIdx >= 0 &&
808 media_type == AVMEDIA_TYPE_AUDIO &&
809 !mVideoEOSReceived) {
814 if (mAudioStreamIdx >= 0)
815 packet_queue_flush(&mAudioQ);
816 if (mVideoStreamIdx >= 0)
817 packet_queue_flush(&mVideoQ);
820 mSeekFlags &= ~AVSEEK_FLAG_BYTE;
827 int FFmpegExtractor::decode_interrupt_cb(void *ctx)
829 FFmpegExtractor *extrator = static_cast<FFmpegExtractor *>(ctx);
830 return extrator->mAbortRequest;
833 void FFmpegExtractor::print_error_ex(const char *filename, int err)
836 const char *errbuf_ptr = errbuf;
838 if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
839 errbuf_ptr = strerror(AVUNERROR(err));
840 LOGI("%s: %s\n", filename, errbuf_ptr);
843 void FFmpegExtractor::setFFmpegDefaultOpts()
857 mSeekByBytes = 0; /* seek by bytes 0=off 1=on -1=auto" */
858 mStartTime = AV_NOPTS_VALUE;
859 mDuration = AV_NOPTS_VALUE;
860 mSeekPos = AV_NOPTS_VALUE;
864 mVideoStreamIdx = -1;
865 mAudioStreamIdx = -1;
868 mVideoQInited = false;
869 mAudioQInited = false;
870 mDefersToCreateVideoTrack = false;
871 mDefersToCreateAudioTrack = false;
884 int FFmpegExtractor::initFFmpeg()
888 int ret = 0, audio_ret = 0, video_ret = 0;
889 int pkt_in_play_range = 0;
890 AVDictionaryEntry *t;
893 int st_index[AVMEDIA_TYPE_NB] = {0};
894 int wanted_stream[AVMEDIA_TYPE_NB] = {0};
895 st_index[AVMEDIA_TYPE_AUDIO] = -1;
896 st_index[AVMEDIA_TYPE_VIDEO] = -1;
897 wanted_stream[AVMEDIA_TYPE_AUDIO] = -1;
898 wanted_stream[AVMEDIA_TYPE_VIDEO] = -1;
900 setFFmpegDefaultOpts();
902 //nam_av_log_set_flags(AV_LOG_SKIP_REPEATED);
903 av_log_set_level(AV_LOG_DEBUG);
904 av_log_set_callback(nam_av_log_callback);
906 /* register all codecs, demux and protocols */
907 avcodec_register_all();
909 avdevice_register_all();
912 avformat_network_init();
916 if (av_lockmgr_register(lockmgr)) {
917 LOGE("could not initialize lock manager!");
920 av_init_packet(&flush_pkt);
921 flush_pkt.data = (uint8_t *)"FLUSH";
924 mFormatCtx = avformat_alloc_context();
925 mFormatCtx->interrupt_callback.callback = decode_interrupt_cb;
926 mFormatCtx->interrupt_callback.opaque = this;
928 LOGV("mFilename: %s", mFilename);
929 err = avformat_open_input(&mFormatCtx, mFilename, NULL, &format_opts);
931 print_error_ex(mFilename, err);
935 if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
936 LOGE("Option %s not found.\n", t->key);
937 //ret = AVERROR_OPTION_NOT_FOUND;
943 mFormatCtx->flags |= AVFMT_FLAG_GENPTS;
945 opts = setup_find_stream_info_opts(mFormatCtx, codec_opts);
946 orig_nb_streams = mFormatCtx->nb_streams;
948 err = avformat_find_stream_info(mFormatCtx, opts);
950 LOGE("%s: could not find codec parameters\n", mFilename);
954 for (i = 0; i < orig_nb_streams; i++)
955 av_dict_free(&opts[i]);
959 mFormatCtx->pb->eof_reached = 0; // FIXME hack, ffplay maybe should not use url_feof() to test for the end
961 if (mSeekByBytes < 0)
962 mSeekByBytes = !!(mFormatCtx->iformat->flags & AVFMT_TS_DISCONT);
964 /* if seeking requested, we execute it */
965 if (mStartTime != AV_NOPTS_VALUE) {
968 timestamp = mStartTime;
969 /* add the stream start time */
970 if (mFormatCtx->start_time != AV_NOPTS_VALUE)
971 timestamp += mFormatCtx->start_time;
972 ret = avformat_seek_file(mFormatCtx, -1, INT64_MIN, timestamp, INT64_MAX, 0);
974 LOGE("%s: could not seek to position %0.3f",
975 mFilename, (double)timestamp / AV_TIME_BASE);
980 for (i = 0; i < mFormatCtx->nb_streams; i++)
981 mFormatCtx->streams[i]->discard = AVDISCARD_ALL;
983 st_index[AVMEDIA_TYPE_VIDEO] =
984 av_find_best_stream(mFormatCtx, AVMEDIA_TYPE_VIDEO,
985 wanted_stream[AVMEDIA_TYPE_VIDEO], -1, NULL, 0);
987 st_index[AVMEDIA_TYPE_AUDIO] =
988 av_find_best_stream(mFormatCtx, AVMEDIA_TYPE_AUDIO,
989 wanted_stream[AVMEDIA_TYPE_AUDIO],
990 st_index[AVMEDIA_TYPE_VIDEO],
993 av_dump_format(mFormatCtx, 0, mFilename, 0);
996 if (mFormatCtx->duration != AV_NOPTS_VALUE) {
997 int hours, mins, secs, us;
998 secs = mFormatCtx->duration / AV_TIME_BASE;
999 us = mFormatCtx->duration % AV_TIME_BASE;
1004 LOGI("the duration is %02d:%02d:%02d.%02d", hours, mins, secs, (100 * us) / AV_TIME_BASE);
1007 if (st_index[AVMEDIA_TYPE_AUDIO] >= 0) {
1008 audio_ret = stream_component_open(st_index[AVMEDIA_TYPE_AUDIO]);
1011 if (st_index[AVMEDIA_TYPE_VIDEO] >= 0) {
1012 video_ret = stream_component_open(st_index[AVMEDIA_TYPE_VIDEO]);
1015 if ( audio_ret < 0 && video_ret < 0) {
1016 LOGE("%s: could not open codecs\n", mFilename);
1027 void FFmpegExtractor::deInitFFmpeg()
1030 avformat_close_input(&mFormatCtx);
1033 av_lockmgr_register(NULL);
1035 avformat_network_deinit();
1037 av_log(NULL, AV_LOG_QUIET, "%s", "");
1040 status_t FFmpegExtractor::startReaderThread() {
1041 LOGV("Starting reader thread");
1042 Mutex::Autolock autoLock(mLock);
1044 if (mReaderThreadStarted)
1047 pthread_attr_t attr;
1048 pthread_attr_init(&attr);
1049 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1050 pthread_create(&mReaderThread, &attr, ReaderWrapper, this);
1051 pthread_attr_destroy(&attr);
1052 mReaderThreadStarted = true;
1053 LOGD("Reader thread started");
1058 void FFmpegExtractor::stopReaderThread() {
1059 LOGV("Stopping reader thread");
1060 Mutex::Autolock autoLock(mLock);
1062 if (!mReaderThreadStarted) {
1063 LOGD("Reader thread have been stopped");
1070 pthread_join(mReaderThread, &dummy);
1071 mReaderThreadStarted = false;
1072 LOGD("Reader thread stopped");
1076 void *FFmpegExtractor::ReaderWrapper(void *me) {
1077 ((FFmpegExtractor *)me)->readerEntry();
1082 void FFmpegExtractor::readerEntry() {
1084 AVPacket pkt1, *pkt = &pkt1;
1086 int pkt_in_play_range = 0;
1088 LOGV("FFmpegExtractor::readerEntry");
1090 mVideoEOSReceived = false;
1091 mAudioEOSReceived = false;
1097 if (mPaused != mLastPaused) {
1098 mLastPaused = mPaused;
1100 mReadPauseReturn = av_read_pause(mFormatCtx);
1102 av_read_play(mFormatCtx);
1104 #if CONFIG_RTSP_DEMUXER || CONFIG_MMSH_PROTOCOL
1106 (!strcmp(mFormatCtx->iformat->name, "rtsp") ||
1107 (mFormatCtx->pb && !strncmp(mFilename, "mmsh:", 5)))) {
1108 /* wait 10 ms to avoid trying to get another packet */
1116 LOGV("readerEntry, mSeekReq: %d", mSeekReq);
1117 ret = avformat_seek_file(mFormatCtx, -1, INT64_MIN, mSeekPos, INT64_MAX, mSeekFlags);
1119 LOGE("%s: error while seeking", mFormatCtx->filename);
1121 if (mAudioStreamIdx >= 0) {
1122 packet_queue_flush(&mAudioQ);
1123 packet_queue_put(&mAudioQ, &flush_pkt);
1125 if (mVideoStreamIdx >= 0) {
1126 packet_queue_flush(&mVideoQ);
1127 packet_queue_put(&mVideoQ, &flush_pkt);
1134 /* if the queue are full, no need to read more */
1135 if ( mAudioQ.size + mVideoQ.size > MAX_QUEUE_SIZE
1136 || ( (mAudioQ .size > MIN_AUDIOQ_SIZE || mAudioStreamIdx < 0)
1137 && (mVideoQ .nb_packets > MIN_FRAMES || mVideoStreamIdx < 0))) {
1138 #if DEBUG_READ_ENTRY
1139 LOGV("readerEntry, is full, fuck");
1147 if (mVideoStreamIdx >= 0) {
1148 av_init_packet(pkt);
1151 pkt->stream_index = mVideoStreamIdx;
1152 packet_queue_put(&mVideoQ, pkt);
1154 if (mAudioStreamIdx >= 0) {
1155 av_init_packet(pkt);
1158 pkt->stream_index = mAudioStreamIdx;
1159 packet_queue_put(&mAudioQ, pkt);
1162 #if DEBUG_READ_ENTRY
1163 LOGV("readerEntry, eof = 1, mVideoQ.size: %d, mVideoQ.nb_packets: %d, mAudioQ.size: %d, mAudioQ.nb_packets: %d",
1164 mVideoQ.size, mVideoQ.nb_packets, mAudioQ.size, mAudioQ.nb_packets);
1166 if (mAudioQ.size + mVideoQ.size == 0) {
1167 if (mLoop != 1 && (!mLoop || --mLoop)) {
1168 if (mVideoStreamIdx >= 0) {
1169 stream_seek(mStartTime != AV_NOPTS_VALUE ? mStartTime : 0, AVMEDIA_TYPE_VIDEO);
1170 } else if (mAudioStreamIdx >= 0) {
1171 stream_seek(mStartTime != AV_NOPTS_VALUE ? mStartTime : 0, AVMEDIA_TYPE_AUDIO);
1173 } else if (mAutoExit) {
1182 ret = av_read_frame(mFormatCtx, pkt);
1185 if (ret == AVERROR_EOF || url_feof(mFormatCtx->pb))
1186 if (ret == AVERROR_EOF) {
1187 //LOGV("ret == AVERROR_EOF");
1189 if (url_feof(mFormatCtx->pb)) {
1190 LOGV("url_feof(mFormatCtx->pb)");
1195 if (mFormatCtx->pb && mFormatCtx->pb->error) {
1196 LOGE("mFormatCtx->pb->error: %d", mFormatCtx->pb->error);
1203 if (pkt->stream_index == mAudioStreamIdx) {
1207 AVCodecContext *avctx = mFormatCtx->streams[mAudioStreamIdx]->codec;
1208 if (mAudioBsfc && pkt && pkt->data) {
1209 ret = av_bitstream_filter_filter(mAudioBsfc, avctx, NULL, &outbuf, &outbuf_size,
1210 pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY);
1212 if (ret < 0 ||!outbuf_size) {
1213 av_free_packet(pkt);
1216 if (outbuf && outbuf != pkt->data) {
1217 memmove(pkt->data, outbuf, outbuf_size);
1218 pkt->size = outbuf_size;
1221 if (mDefersToCreateAudioTrack) {
1222 if (avctx->extradata_size <= 0) {
1223 av_free_packet(pkt);
1226 stream_component_open(mAudioStreamIdx);
1227 if (!mDefersToCreateAudioTrack)
1228 LOGI("probe packet counter: %d when create audio track ok", mProbePkts);
1229 if (mProbePkts == EXTRACTOR_MAX_PROBE_PACKETS)
1230 LOGI("probe packet counter to max: %d, create audio track: %d",
1231 mProbePkts, !mDefersToCreateAudioTrack);
1235 /* check if packet is in play range specified by user, then queue, otherwise discard */
1236 pkt_in_play_range = mDuration == AV_NOPTS_VALUE ||
1237 (pkt->pts - mFormatCtx->streams[pkt->stream_index]->start_time) *
1238 av_q2d(mFormatCtx->streams[pkt->stream_index]->time_base) -
1239 (double)(mStartTime != AV_NOPTS_VALUE ? mStartTime : 0) / 1000000
1240 <= ((double)mDuration / 1000000);
1241 if (pkt->stream_index == mAudioStreamIdx && pkt_in_play_range) {
1242 packet_queue_put(&mAudioQ, pkt);
1243 } else if (pkt->stream_index == mVideoStreamIdx && pkt_in_play_range) {
1244 packet_queue_put(&mVideoQ, pkt);
1246 av_free_packet(pkt);
1249 /* wait until the end */
1250 while (!mAbortRequest) {
1256 LOGI("reader thread goto end...");
1258 /* close each stream */
1259 if (mAudioStreamIdx >= 0)
1260 stream_component_close(mAudioStreamIdx);
1261 if (mVideoStreamIdx >= 0)
1262 stream_component_close(mVideoStreamIdx);
1264 avformat_close_input(&mFormatCtx);
1268 ////////////////////////////////////////////////////////////////////////////////
1270 FFmpegExtractor::Track::Track(
1271 const sp<FFmpegExtractor> &extractor, sp<MetaData> meta, bool isAVC,
1272 AVStream *stream, PacketQueue *queue)
1273 : mExtractor(extractor),
1280 /* H.264 Video Types */
1282 mNal2AnnexB = false;
1288 CHECK(meta->findData(kKeyAVCC, &type, &data, &size));
1290 const uint8_t *ptr = (const uint8_t *)data;
1293 CHECK_EQ((unsigned)ptr[0], 1u); // configurationVersion == 1
1295 // The number of bytes used to encode the length of a NAL unit.
1296 mNALLengthSize = 1 + (ptr[4] & 3);
1298 LOGV("the stream is AVC, the length of a NAL unit: %d", mNALLengthSize);
1304 mMediaType = mStream->codec->codec_type;
1307 FFmpegExtractor::Track::~Track() {
1310 status_t FFmpegExtractor::Track::start(MetaData *params) {
1311 Mutex::Autolock autoLock(mLock);
1312 //mExtractor->startReaderThread();
1316 status_t FFmpegExtractor::Track::stop() {
1317 Mutex::Autolock autoLock(mLock);
1318 mExtractor->stopReaderThread();
1322 sp<MetaData> FFmpegExtractor::Track::getFormat() {
1323 Mutex::Autolock autoLock(mLock);
1328 status_t FFmpegExtractor::Track::read(
1329 MediaBuffer **buffer, const ReadOptions *options) {
1332 Mutex::Autolock autoLock(mLock);
1335 bool seeking = false;
1336 bool waitKeyPkt = false;
1337 ReadOptions::SeekMode mode;
1338 int64_t pktTS = AV_NOPTS_VALUE;
1339 int64_t seekTimeUs = AV_NOPTS_VALUE;
1342 status_t status = OK;
1344 if (options && options->getSeekTo(&seekTimeUs, &mode)) {
1345 LOGV("~~~%s seekTimeUs: %lld, mode: %d", av_get_media_type_string(mMediaType), seekTimeUs, mode);
1346 if (mExtractor->stream_seek(seekTimeUs, mMediaType) == SEEK)
1351 if (mExtractor->packet_queue_get(mQueue, &pkt, 1) < 0) {
1352 mExtractor->reachedEOS(mMediaType);
1353 return ERROR_END_OF_STREAM;
1357 if (pkt.data != flush_pkt.data) {
1358 av_free_packet(&pkt);
1362 #if WAIT_KEY_PACKET_AFTER_SEEK
1368 if (pkt.data == flush_pkt.data) {
1369 LOGV("read %s flush pkt", av_get_media_type_string(mMediaType));
1370 av_free_packet(&pkt);
1372 } else if (pkt.data == NULL && pkt.size == 0) {
1373 LOGV("read %s eos pkt", av_get_media_type_string(mMediaType));
1374 av_free_packet(&pkt);
1375 mExtractor->reachedEOS(mMediaType);
1376 return ERROR_END_OF_STREAM;
1379 key = pkt.flags & AV_PKT_FLAG_KEY ? 1 : 0;
1383 LOGV("drop the no key packet");
1384 av_free_packet(&pkt);
1387 LOGV("~~~~~~ got the key packet");
1392 MediaBuffer *mediaBuffer = new MediaBuffer(pkt.size + FF_INPUT_BUFFER_PADDING_SIZE);
1393 mediaBuffer->meta_data()->clear();
1394 mediaBuffer->set_range(0, pkt.size);
1395 #if DISABLE_NAL_TO_ANNEXB
1396 mNal2AnnexB = false;
1398 if (mIsAVC && mNal2AnnexB) {
1399 /* Convert H.264 NAL format to annex b */
1400 if (mNALLengthSize >= 3 && mNALLengthSize <= 4 )
1402 uint8_t *dst = (uint8_t *)mediaBuffer->data();
1404 /* This only works for NAL sizes 3-4 */
1405 size_t len = pkt.size, i;
1406 uint8_t *ptr = pkt.data;
1407 while (len >= mNALLengthSize) {
1408 uint32_t nal_len = 0;
1409 for( i = 0; i < mNALLengthSize; i++ ) {
1410 nal_len = (nal_len << 8) | ptr[i];
1413 dst[mNALLengthSize - 1] = 1;
1414 if (nal_len > INT_MAX || nal_len > (unsigned int)len) {
1415 status = ERROR_MALFORMED;
1418 dst += mNALLengthSize;
1419 ptr += mNALLengthSize;
1420 len -= mNALLengthSize;
1422 memcpy(dst, ptr, nal_len);
1429 status = ERROR_MALFORMED;
1433 LOGV("status != OK");
1434 mediaBuffer->release();
1436 av_free_packet(&pkt);
1437 return ERROR_MALFORMED;
1440 memcpy(mediaBuffer->data(), pkt.data, pkt.size);
1445 if (pkt.pts == AV_NOPTS_VALUE)
1449 // TODO, Stagefright can't handle negative timestamps
1450 // if needed, work around this by offsetting them manually?
1455 timeUs = (int64_t)(pktTS * av_q2d(mStream->time_base) * 1000000);
1458 LOGV("read %s pkt, size: %d, key: %d, pts: %lld, dts: %lld, timeUs: %llu us (%.2f secs)",
1459 av_get_media_type_string(mMediaType), pkt.size, key, pkt.pts, pkt.dts, timeUs, timeUs/1E6);
1463 // TODO, Stagefright can't handle negative timestamps
1464 // if needed, work around this by offsetting them manually?
1469 mediaBuffer->meta_data()->setInt64(kKeyTime, timeUs);
1470 mediaBuffer->meta_data()->setInt32(kKeyIsSyncFrame, key);
1472 *buffer = mediaBuffer;
1474 av_free_packet(&pkt);
1479 ////////////////////////////////////////////////////////////////////////////////
1483 const char *extension;
1484 const char *container;
1487 static extmap FILE_EXTS [] = {
1488 {".mp4", MEDIA_MIMETYPE_CONTAINER_MPEG4},
1489 {".3gp", MEDIA_MIMETYPE_CONTAINER_MPEG4},
1490 {".mp3", MEDIA_MIMETYPE_AUDIO_MPEG},
1491 {".mov", MEDIA_MIMETYPE_CONTAINER_MOV},
1492 {".mkv", MEDIA_MIMETYPE_CONTAINER_MATROSKA},
1493 {".ts", MEDIA_MIMETYPE_CONTAINER_TS},
1494 {".avi", MEDIA_MIMETYPE_CONTAINER_AVI},
1496 {".asf", MEDIA_MIMETYPE_CONTAINER_ASF},
1497 {".wmv", MEDIA_MIMETYPE_CONTAINER_WMV},
1498 {".wma", MEDIA_MIMETYPE_CONTAINER_WMA},
1499 {".mpg", MEDIA_MIMETYPE_CONTAINER_MPG},
1500 {".flv", MEDIA_MIMETYPE_CONTAINER_FLV},
1501 {".divx", MEDIA_MIMETYPE_CONTAINER_DIVX},
1502 {".mp2", MEDIA_MIMETYPE_CONTAINER_MP2},
1503 {".ape", MEDIA_MIMETYPE_CONTAINER_APE},
1504 {".rm ", MEDIA_MIMETYPE_CONTAINER_RM},
1505 {".ra", MEDIA_MIMETYPE_CONTAINER_RA},
1509 // TODO: check mFormatCtx->iformat->name?
1511 const sp<DataSource> &source, String8 *mimeType, float *confidence,
1512 sp<AMessage> *meta) {
1513 LOGV("SniffFFMPEG");
1515 const char *uri, *container = NULL;
1517 //av_find_input_format()??
1518 uri = source->getNamURI();
1523 LOGI("ffmpeg uri: %s", uri);
1525 LOGI("list the file extensions suppoted by ffmpeg: ");
1526 LOGI("========================================");
1527 for (i = 0; i < NELEM(FILE_EXTS); ++i) {
1528 LOGV("file_exts[%02d]: %s", i, FILE_EXTS[i].extension);
1530 LOGI("========================================");
1532 int lenURI = strlen(uri);
1533 for (i = 0; i < NELEM(FILE_EXTS); ++i) {
1534 int len = strlen(FILE_EXTS[i].extension);
1535 int start = lenURI - len;
1537 if (!av_strncasecmp(uri + start, FILE_EXTS[i].extension, len)) {
1538 container = FILE_EXTS[i].container;
1544 if (container == NULL)
1547 LOGV("found container: %s", container);
1549 *confidence = 0.88f; // Slightly larger than other extractor's confidence
1550 mimeType->setTo(container);
1552 /* use MPEG4Extractor(not extended extractor) for HTTP source only */
1553 if (!av_strcasecmp(container, MEDIA_MIMETYPE_CONTAINER_MPEG4)
1554 && (source->flags() & DataSource::kIsCachingDataSource)) {
1558 *meta = new AMessage;
1559 (*meta)->setString("extended-extractor", "extended-extractor");
1560 (*meta)->setString("extended-extractor-subtype", "ffmpegextractor");
1565 } // namespace android