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_MP1 ||
408 avctx->codec_id == CODEC_ID_MP2 ||
409 avctx->codec_id == CODEC_ID_H263 ||
410 avctx->codec_id == CODEC_ID_H263P ||
411 avctx->codec_id == CODEC_ID_H263I)
414 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
416 defersToCreateTrack = &mDefersToCreateVideoTrack;
417 } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO){
419 defersToCreateTrack = &mDefersToCreateAudioTrack;
423 switch(avctx->codec_id) {
427 name = "aac_adtstoasc";
433 if (avctx->extradata_size <= 0) {
434 LOGI("No %s extradata found, should to extract it from bitstream",
435 av_get_media_type_string(avctx->codec_type));
436 *defersToCreateTrack = true;
437 //CHECK(name != NULL);
438 if (!*bsfc && name) {
439 *bsfc = av_bitstream_filter_init(name);
441 LOGE("Cannot open the %s BSF!", name);
442 *defersToCreateTrack = false;
445 LOGV("open the %s bsf", name);
456 int FFmpegExtractor::stream_component_open(int stream_index)
458 AVCodecContext *avctx;
461 bool supported = false;
467 LOGI("stream_index: %d", stream_index);
468 if (stream_index < 0 || stream_index >= mFormatCtx->nb_streams)
470 avctx = mFormatCtx->streams[stream_index]->codec;
472 switch(avctx->codec_id) {
482 case CODEC_ID_MPEG2VIDEO:
494 LOGE("unsupport the codec, id: 0x%0x", avctx->codec_id);
497 LOGV("support the codec");
500 ssize_t index = mTracks.indexOfKey(stream_index);
503 LOGE("this track already exists");
507 mFormatCtx->streams[stream_index]->discard = AVDISCARD_DEFAULT;
510 av_get_codec_tag_string(tagbuf, sizeof(tagbuf), avctx->codec_tag);
511 LOGV("Tag %s/0x%08x with codec id '%d'\n", tagbuf, avctx->codec_tag, avctx->codec_id);
513 switch (avctx->codec_type) {
514 case AVMEDIA_TYPE_VIDEO:
515 if (mVideoStreamIdx == -1)
516 mVideoStreamIdx = stream_index;
517 if (mVideoStream == NULL)
518 mVideoStream = mFormatCtx->streams[stream_index];
519 if (!mVideoQInited) {
520 packet_queue_init(&mVideoQ);
521 mVideoQInited = true;
524 ret = check_extradata(avctx);
527 // disable the stream
528 mVideoStreamIdx = -1;
530 packet_queue_end(&mVideoQ);
531 mVideoQInited = false;
532 mFormatCtx->streams[stream_index]->discard = AVDISCARD_ALL;
537 if (avctx->extradata) {
538 LOGV("video stream extradata:");
539 hexdump(avctx->extradata, avctx->extradata_size);
541 LOGV("video stream no extradata, but we can ignore it.");
546 switch(avctx->codec_id) {
550 * http://msdn.microsoft.com/en-us/library/dd757808(v=vs.85).aspx
552 //if (avctx->codec_tag && avctx->codec_tag == AV_RL32("avc1")) {
553 if (avctx->extradata[0] == 1 /* configurationVersion */) {
554 // H.264 bitstream without start codes.
558 if (avctx->width == 0 || avctx->height == 0) {
559 int32_t width, height;
560 sp<ABuffer> seqParamSet = new ABuffer(avctx->extradata_size - 8);
561 memcpy(seqParamSet->data(), avctx->extradata + 8, avctx->extradata_size - 8);
562 FindAVCDimensions(seqParamSet, &width, &height);
563 avctx->width = width;
564 avctx->height = height;
567 meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
568 meta->setData(kKeyAVCC, kTypeAVCC, avctx->extradata, avctx->extradata_size);
570 // H.264 bitstream with start codes.
574 /* set NULL to release meta as we will new a meta in MakeAVCCodecSpecificData() fxn */
578 sp<ABuffer> buffer = new ABuffer(avctx->extradata_size);
579 memcpy(buffer->data(), avctx->extradata, avctx->extradata_size);
580 meta = MakeAVCCodecSpecificData(buffer);
585 meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4);
587 sp<ABuffer> csd = new ABuffer(avctx->extradata_size);
588 memcpy(csd->data(), avctx->extradata, avctx->extradata_size);
589 sp<ABuffer> esds = MakeMPEGVideoESDS(csd);
590 meta->setData(kKeyESDS, kTypeESDS, esds->data(), esds->size());
597 meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263);
599 case CODEC_ID_MPEG2VIDEO:
601 meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG2);
603 sp<ABuffer> csd = new ABuffer(avctx->extradata_size);
604 memcpy(csd->data(), avctx->extradata, avctx->extradata_size);
605 sp<ABuffer> esds = MakeMPEGVideoESDS(csd);
606 meta->setData(kKeyESDS, kTypeESDS, esds->data(), esds->size());
611 meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_WMV12);
612 meta->setData(kKeyESDS, kTypeESDS, avctx->extradata, avctx->extradata_size);
615 CHECK(!"Should not be here. Unsupported codec.");
619 LOGI("width: %d, height: %d, bit_rate: %d", avctx->width, avctx->height, avctx->bit_rate);
621 meta->setInt32(kKeyWidth, avctx->width);
622 meta->setInt32(kKeyHeight, avctx->height);
623 meta->setInt32(kKeyBitRate, avctx->bit_rate);
624 if (mFormatCtx->duration != AV_NOPTS_VALUE)
625 meta->setInt64(kKeyDuration, mFormatCtx->duration);
627 LOGV("create a video track");
629 stream_index, new Track(this, meta, isAVC, mVideoStream, &mVideoQ));
631 mDefersToCreateVideoTrack = false;
634 case AVMEDIA_TYPE_AUDIO:
635 if (mAudioStreamIdx == -1)
636 mAudioStreamIdx = stream_index;
637 if (mAudioStream == NULL)
638 mAudioStream = mFormatCtx->streams[stream_index];
639 if (!mAudioQInited) {
640 packet_queue_init(&mAudioQ);
641 mAudioQInited = true;
644 ret = check_extradata(avctx);
647 // disable the stream
648 mAudioStreamIdx = -1;
650 packet_queue_end(&mAudioQ);
651 mAudioQInited = false;
652 mFormatCtx->streams[stream_index]->discard = AVDISCARD_ALL;
657 if (avctx->extradata) {
658 LOGV("audio stream extradata:");
659 hexdump(avctx->extradata, avctx->extradata_size);
661 LOGV("audio stream no extradata, but we can ignore it.");
664 switch(avctx->codec_id) {
668 meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_I);
669 //meta->setData(kKeyESDS, kTypeESDS, avctx->extradata, avctx->extradata_size);
674 meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_II);
675 //meta->setData(kKeyESDS, kTypeESDS, avctx->extradata, avctx->extradata_size);
680 meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_MPEG);
681 //meta->setData(kKeyESDS, kTypeESDS, avctx->extradata, avctx->extradata_size);
686 const uint8_t *header;
687 uint8_t profile, sf_index, channel;
689 header = avctx->extradata;
690 CHECK(header != NULL);
692 // AudioSpecificInfo follows
693 // oooo offf fccc c000
694 // o - audioObjectType
695 // f - samplingFreqIndex
697 profile = ((header[0] & 0xf8) >> 3) - 1;
698 sf_index = (header[0] & 0x07) << 1 | (header[1] & 0x80) >> 7;
699 sr = get_sample_rate(sf_index);
701 LOGE("unsupport the sample rate");
704 channel = (header[1] >> 3) & 0xf;
705 LOGV("profile: %d, sf_index: %d, channel: %d", profile, sf_index, channel);
707 meta = MakeAACCodecSpecificData(profile, sf_index, channel);
708 meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AAC);
711 CHECK(!"Should not be here. Unsupported codec.");
715 LOGI("bit_rate: %d, sample_rate: %d, channels: %d", avctx->bit_rate, avctx->sample_rate, avctx->channels);
717 meta->setInt32(kKeySampleRate, avctx->sample_rate);
718 meta->setInt32(kKeyChannelCount, avctx->channels);
719 meta->setInt32(kKeyBitRate, avctx->bit_rate);
720 if (mFormatCtx->duration != AV_NOPTS_VALUE)
721 meta->setInt64(kKeyDuration, mFormatCtx->duration);
723 if (avctx->codec_id != CODEC_ID_MP3 &&
724 avctx->codec_id != CODEC_ID_MP1 &&
725 avctx->codec_id != CODEC_ID_MP2) {
726 LOGV("audio meta esds:");
727 CHECK(meta->findData(kKeyESDS, &type, &data, &size));
731 LOGV("create a audio track");
733 stream_index, new Track(this, meta, false, mAudioStream, &mAudioQ));
735 mDefersToCreateAudioTrack = false;
738 case AVMEDIA_TYPE_SUBTITLE:
740 CHECK(!"Should not be here. Unsupported media type.");
743 CHECK(!"Should not be here. Unsupported media type.");
749 void FFmpegExtractor::stream_component_close(int stream_index)
751 AVCodecContext *avctx;
753 if (stream_index < 0 || stream_index >= mFormatCtx->nb_streams)
755 avctx = mFormatCtx->streams[stream_index]->codec;
757 switch (avctx->codec_type) {
758 case AVMEDIA_TYPE_VIDEO:
759 LOGV("packet_queue_abort videoq");
760 packet_queue_abort(&mVideoQ);
761 /* wait until the end */
762 while (!mAbortRequest && !mVideoEOSReceived) {
763 LOGV("wait for video received");
766 LOGV("packet_queue_end videoq");
767 packet_queue_end(&mVideoQ);
769 case AVMEDIA_TYPE_AUDIO:
770 LOGV("packet_queue_abort audioq");
771 packet_queue_abort(&mAudioQ);
772 while (!mAbortRequest && !mAudioEOSReceived) {
773 LOGV("wait for audio received");
776 LOGV("packet_queue_end audioq");
777 packet_queue_end(&mAudioQ);
779 case AVMEDIA_TYPE_SUBTITLE:
785 mFormatCtx->streams[stream_index]->discard = AVDISCARD_ALL;
786 switch (avctx->codec_type) {
787 case AVMEDIA_TYPE_VIDEO:
789 mVideoStreamIdx = -1;
791 av_bitstream_filter_close(mVideoBsfc);
795 case AVMEDIA_TYPE_AUDIO:
797 mAudioStreamIdx = -1;
799 av_bitstream_filter_close(mAudioBsfc);
803 case AVMEDIA_TYPE_SUBTITLE:
810 void FFmpegExtractor::reachedEOS(enum AVMediaType media_type)
812 Mutex::Autolock autoLock(mLock);
814 if (media_type == AVMEDIA_TYPE_VIDEO) {
815 mVideoEOSReceived = true;
816 } else if (media_type == AVMEDIA_TYPE_AUDIO) {
817 mAudioEOSReceived = true;
821 /* seek in the stream */
822 int FFmpegExtractor::stream_seek(int64_t pos, enum AVMediaType media_type)
824 Mutex::Autolock autoLock(mLock);
826 if (mVideoStreamIdx >= 0 &&
827 mAudioStreamIdx >= 0 &&
828 media_type == AVMEDIA_TYPE_AUDIO &&
829 !mVideoEOSReceived) {
834 if (mAudioStreamIdx >= 0)
835 packet_queue_flush(&mAudioQ);
836 if (mVideoStreamIdx >= 0)
837 packet_queue_flush(&mVideoQ);
840 mSeekFlags &= ~AVSEEK_FLAG_BYTE;
847 int FFmpegExtractor::decode_interrupt_cb(void *ctx)
849 FFmpegExtractor *extrator = static_cast<FFmpegExtractor *>(ctx);
850 return extrator->mAbortRequest;
853 void FFmpegExtractor::print_error_ex(const char *filename, int err)
856 const char *errbuf_ptr = errbuf;
858 if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
859 errbuf_ptr = strerror(AVUNERROR(err));
860 LOGI("%s: %s\n", filename, errbuf_ptr);
863 void FFmpegExtractor::setFFmpegDefaultOpts()
877 mSeekByBytes = 0; /* seek by bytes 0=off 1=on -1=auto" */
878 mStartTime = AV_NOPTS_VALUE;
879 mDuration = AV_NOPTS_VALUE;
880 mSeekPos = AV_NOPTS_VALUE;
884 mVideoStreamIdx = -1;
885 mAudioStreamIdx = -1;
888 mVideoQInited = false;
889 mAudioQInited = false;
890 mDefersToCreateVideoTrack = false;
891 mDefersToCreateAudioTrack = false;
904 int FFmpegExtractor::initFFmpeg()
908 int ret = 0, audio_ret = 0, video_ret = 0;
909 int pkt_in_play_range = 0;
910 AVDictionaryEntry *t;
913 int st_index[AVMEDIA_TYPE_NB] = {0};
914 int wanted_stream[AVMEDIA_TYPE_NB] = {0};
915 st_index[AVMEDIA_TYPE_AUDIO] = -1;
916 st_index[AVMEDIA_TYPE_VIDEO] = -1;
917 wanted_stream[AVMEDIA_TYPE_AUDIO] = -1;
918 wanted_stream[AVMEDIA_TYPE_VIDEO] = -1;
920 setFFmpegDefaultOpts();
922 //nam_av_log_set_flags(AV_LOG_SKIP_REPEATED);
923 av_log_set_level(AV_LOG_DEBUG);
924 av_log_set_callback(nam_av_log_callback);
926 /* register all codecs, demux and protocols */
927 avcodec_register_all();
929 avdevice_register_all();
932 avformat_network_init();
936 if (av_lockmgr_register(lockmgr)) {
937 LOGE("could not initialize lock manager!");
940 av_init_packet(&flush_pkt);
941 flush_pkt.data = (uint8_t *)"FLUSH";
944 mFormatCtx = avformat_alloc_context();
945 mFormatCtx->interrupt_callback.callback = decode_interrupt_cb;
946 mFormatCtx->interrupt_callback.opaque = this;
948 LOGV("mFilename: %s", mFilename);
949 err = avformat_open_input(&mFormatCtx, mFilename, NULL, &format_opts);
951 print_error_ex(mFilename, err);
955 if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
956 LOGE("Option %s not found.\n", t->key);
957 //ret = AVERROR_OPTION_NOT_FOUND;
963 mFormatCtx->flags |= AVFMT_FLAG_GENPTS;
965 opts = setup_find_stream_info_opts(mFormatCtx, codec_opts);
966 orig_nb_streams = mFormatCtx->nb_streams;
968 err = avformat_find_stream_info(mFormatCtx, opts);
970 LOGE("%s: could not find codec parameters\n", mFilename);
974 for (i = 0; i < orig_nb_streams; i++)
975 av_dict_free(&opts[i]);
979 mFormatCtx->pb->eof_reached = 0; // FIXME hack, ffplay maybe should not use url_feof() to test for the end
981 if (mSeekByBytes < 0)
982 mSeekByBytes = !!(mFormatCtx->iformat->flags & AVFMT_TS_DISCONT);
984 /* if seeking requested, we execute it */
985 if (mStartTime != AV_NOPTS_VALUE) {
988 timestamp = mStartTime;
989 /* add the stream start time */
990 if (mFormatCtx->start_time != AV_NOPTS_VALUE)
991 timestamp += mFormatCtx->start_time;
992 ret = avformat_seek_file(mFormatCtx, -1, INT64_MIN, timestamp, INT64_MAX, 0);
994 LOGE("%s: could not seek to position %0.3f",
995 mFilename, (double)timestamp / AV_TIME_BASE);
1000 for (i = 0; i < mFormatCtx->nb_streams; i++)
1001 mFormatCtx->streams[i]->discard = AVDISCARD_ALL;
1003 st_index[AVMEDIA_TYPE_VIDEO] =
1004 av_find_best_stream(mFormatCtx, AVMEDIA_TYPE_VIDEO,
1005 wanted_stream[AVMEDIA_TYPE_VIDEO], -1, NULL, 0);
1007 st_index[AVMEDIA_TYPE_AUDIO] =
1008 av_find_best_stream(mFormatCtx, AVMEDIA_TYPE_AUDIO,
1009 wanted_stream[AVMEDIA_TYPE_AUDIO],
1010 st_index[AVMEDIA_TYPE_VIDEO],
1013 av_dump_format(mFormatCtx, 0, mFilename, 0);
1016 if (mFormatCtx->duration != AV_NOPTS_VALUE) {
1017 int hours, mins, secs, us;
1018 secs = mFormatCtx->duration / AV_TIME_BASE;
1019 us = mFormatCtx->duration % AV_TIME_BASE;
1024 LOGI("the duration is %02d:%02d:%02d.%02d", hours, mins, secs, (100 * us) / AV_TIME_BASE);
1027 if (st_index[AVMEDIA_TYPE_AUDIO] >= 0) {
1028 audio_ret = stream_component_open(st_index[AVMEDIA_TYPE_AUDIO]);
1031 if (st_index[AVMEDIA_TYPE_VIDEO] >= 0) {
1032 video_ret = stream_component_open(st_index[AVMEDIA_TYPE_VIDEO]);
1035 if ( audio_ret < 0 && video_ret < 0) {
1036 LOGE("%s: could not open codecs\n", mFilename);
1047 void FFmpegExtractor::deInitFFmpeg()
1050 avformat_close_input(&mFormatCtx);
1053 av_lockmgr_register(NULL);
1055 avformat_network_deinit();
1057 av_log(NULL, AV_LOG_QUIET, "%s", "");
1060 status_t FFmpegExtractor::startReaderThread() {
1061 LOGV("Starting reader thread");
1062 Mutex::Autolock autoLock(mLock);
1064 if (mReaderThreadStarted)
1067 pthread_attr_t attr;
1068 pthread_attr_init(&attr);
1069 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1070 pthread_create(&mReaderThread, &attr, ReaderWrapper, this);
1071 pthread_attr_destroy(&attr);
1072 mReaderThreadStarted = true;
1073 LOGD("Reader thread started");
1078 void FFmpegExtractor::stopReaderThread() {
1079 LOGV("Stopping reader thread");
1080 Mutex::Autolock autoLock(mLock);
1082 if (!mReaderThreadStarted) {
1083 LOGD("Reader thread have been stopped");
1090 pthread_join(mReaderThread, &dummy);
1091 mReaderThreadStarted = false;
1092 LOGD("Reader thread stopped");
1096 void *FFmpegExtractor::ReaderWrapper(void *me) {
1097 ((FFmpegExtractor *)me)->readerEntry();
1102 void FFmpegExtractor::readerEntry() {
1104 AVPacket pkt1, *pkt = &pkt1;
1106 int pkt_in_play_range = 0;
1108 LOGV("FFmpegExtractor::readerEntry");
1110 mVideoEOSReceived = false;
1111 mAudioEOSReceived = false;
1117 if (mPaused != mLastPaused) {
1118 mLastPaused = mPaused;
1120 mReadPauseReturn = av_read_pause(mFormatCtx);
1122 av_read_play(mFormatCtx);
1124 #if CONFIG_RTSP_DEMUXER || CONFIG_MMSH_PROTOCOL
1126 (!strcmp(mFormatCtx->iformat->name, "rtsp") ||
1127 (mFormatCtx->pb && !strncmp(mFilename, "mmsh:", 5)))) {
1128 /* wait 10 ms to avoid trying to get another packet */
1136 LOGV("readerEntry, mSeekReq: %d", mSeekReq);
1137 ret = avformat_seek_file(mFormatCtx, -1, INT64_MIN, mSeekPos, INT64_MAX, mSeekFlags);
1139 LOGE("%s: error while seeking", mFormatCtx->filename);
1141 if (mAudioStreamIdx >= 0) {
1142 packet_queue_flush(&mAudioQ);
1143 packet_queue_put(&mAudioQ, &flush_pkt);
1145 if (mVideoStreamIdx >= 0) {
1146 packet_queue_flush(&mVideoQ);
1147 packet_queue_put(&mVideoQ, &flush_pkt);
1154 /* if the queue are full, no need to read more */
1155 if ( mAudioQ.size + mVideoQ.size > MAX_QUEUE_SIZE
1156 || ( (mAudioQ .size > MIN_AUDIOQ_SIZE || mAudioStreamIdx < 0)
1157 && (mVideoQ .nb_packets > MIN_FRAMES || mVideoStreamIdx < 0))) {
1158 #if DEBUG_READ_ENTRY
1159 LOGV("readerEntry, is full, fuck");
1167 if (mVideoStreamIdx >= 0) {
1168 av_init_packet(pkt);
1171 pkt->stream_index = mVideoStreamIdx;
1172 packet_queue_put(&mVideoQ, pkt);
1174 if (mAudioStreamIdx >= 0) {
1175 av_init_packet(pkt);
1178 pkt->stream_index = mAudioStreamIdx;
1179 packet_queue_put(&mAudioQ, pkt);
1182 #if DEBUG_READ_ENTRY
1183 LOGV("readerEntry, eof = 1, mVideoQ.size: %d, mVideoQ.nb_packets: %d, mAudioQ.size: %d, mAudioQ.nb_packets: %d",
1184 mVideoQ.size, mVideoQ.nb_packets, mAudioQ.size, mAudioQ.nb_packets);
1186 if (mAudioQ.size + mVideoQ.size == 0) {
1187 if (mLoop != 1 && (!mLoop || --mLoop)) {
1188 if (mVideoStreamIdx >= 0) {
1189 stream_seek(mStartTime != AV_NOPTS_VALUE ? mStartTime : 0, AVMEDIA_TYPE_VIDEO);
1190 } else if (mAudioStreamIdx >= 0) {
1191 stream_seek(mStartTime != AV_NOPTS_VALUE ? mStartTime : 0, AVMEDIA_TYPE_AUDIO);
1193 } else if (mAutoExit) {
1202 ret = av_read_frame(mFormatCtx, pkt);
1205 if (ret == AVERROR_EOF || url_feof(mFormatCtx->pb))
1206 if (ret == AVERROR_EOF) {
1207 //LOGV("ret == AVERROR_EOF");
1209 if (url_feof(mFormatCtx->pb)) {
1210 //LOGV("url_feof(mFormatCtx->pb)");
1215 if (mFormatCtx->pb && mFormatCtx->pb->error) {
1216 LOGE("mFormatCtx->pb->error: %d", mFormatCtx->pb->error);
1223 if (pkt->stream_index == mAudioStreamIdx) {
1227 AVCodecContext *avctx = mFormatCtx->streams[mAudioStreamIdx]->codec;
1228 if (mAudioBsfc && pkt && pkt->data) {
1229 ret = av_bitstream_filter_filter(mAudioBsfc, avctx, NULL, &outbuf, &outbuf_size,
1230 pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY);
1232 if (ret < 0 ||!outbuf_size) {
1233 av_free_packet(pkt);
1236 if (outbuf && outbuf != pkt->data) {
1237 memmove(pkt->data, outbuf, outbuf_size);
1238 pkt->size = outbuf_size;
1241 if (mDefersToCreateAudioTrack) {
1242 if (avctx->extradata_size <= 0) {
1243 av_free_packet(pkt);
1246 stream_component_open(mAudioStreamIdx);
1247 if (!mDefersToCreateAudioTrack)
1248 LOGI("probe packet counter: %d when create audio track ok", mProbePkts);
1249 if (mProbePkts == EXTRACTOR_MAX_PROBE_PACKETS)
1250 LOGI("probe packet counter to max: %d, create audio track: %d",
1251 mProbePkts, !mDefersToCreateAudioTrack);
1255 /* check if packet is in play range specified by user, then queue, otherwise discard */
1256 pkt_in_play_range = mDuration == AV_NOPTS_VALUE ||
1257 (pkt->pts - mFormatCtx->streams[pkt->stream_index]->start_time) *
1258 av_q2d(mFormatCtx->streams[pkt->stream_index]->time_base) -
1259 (double)(mStartTime != AV_NOPTS_VALUE ? mStartTime : 0) / 1000000
1260 <= ((double)mDuration / 1000000);
1261 if (pkt->stream_index == mAudioStreamIdx && pkt_in_play_range) {
1262 packet_queue_put(&mAudioQ, pkt);
1263 } else if (pkt->stream_index == mVideoStreamIdx && pkt_in_play_range) {
1264 packet_queue_put(&mVideoQ, pkt);
1266 av_free_packet(pkt);
1269 /* wait until the end */
1270 while (!mAbortRequest) {
1276 LOGI("reader thread goto end...");
1278 /* close each stream */
1279 if (mAudioStreamIdx >= 0)
1280 stream_component_close(mAudioStreamIdx);
1281 if (mVideoStreamIdx >= 0)
1282 stream_component_close(mVideoStreamIdx);
1284 avformat_close_input(&mFormatCtx);
1288 ////////////////////////////////////////////////////////////////////////////////
1290 FFmpegExtractor::Track::Track(
1291 const sp<FFmpegExtractor> &extractor, sp<MetaData> meta, bool isAVC,
1292 AVStream *stream, PacketQueue *queue)
1293 : mExtractor(extractor),
1300 /* H.264 Video Types */
1302 mNal2AnnexB = false;
1308 CHECK(meta->findData(kKeyAVCC, &type, &data, &size));
1310 const uint8_t *ptr = (const uint8_t *)data;
1313 CHECK_EQ((unsigned)ptr[0], 1u); // configurationVersion == 1
1315 // The number of bytes used to encode the length of a NAL unit.
1316 mNALLengthSize = 1 + (ptr[4] & 3);
1318 LOGV("the stream is AVC, the length of a NAL unit: %d", mNALLengthSize);
1324 mMediaType = mStream->codec->codec_type;
1327 FFmpegExtractor::Track::~Track() {
1330 status_t FFmpegExtractor::Track::start(MetaData *params) {
1331 Mutex::Autolock autoLock(mLock);
1332 //mExtractor->startReaderThread();
1336 status_t FFmpegExtractor::Track::stop() {
1337 Mutex::Autolock autoLock(mLock);
1338 mExtractor->stopReaderThread();
1342 sp<MetaData> FFmpegExtractor::Track::getFormat() {
1343 Mutex::Autolock autoLock(mLock);
1348 status_t FFmpegExtractor::Track::read(
1349 MediaBuffer **buffer, const ReadOptions *options) {
1352 Mutex::Autolock autoLock(mLock);
1355 bool seeking = false;
1356 bool waitKeyPkt = false;
1357 ReadOptions::SeekMode mode;
1358 int64_t pktTS = AV_NOPTS_VALUE;
1359 int64_t seekTimeUs = AV_NOPTS_VALUE;
1362 status_t status = OK;
1364 if (options && options->getSeekTo(&seekTimeUs, &mode)) {
1365 LOGV("~~~%s seekTimeUs: %lld, mode: %d", av_get_media_type_string(mMediaType), seekTimeUs, mode);
1366 if (mExtractor->stream_seek(seekTimeUs, mMediaType) == SEEK)
1371 if (mExtractor->packet_queue_get(mQueue, &pkt, 1) < 0) {
1372 mExtractor->reachedEOS(mMediaType);
1373 return ERROR_END_OF_STREAM;
1377 if (pkt.data != flush_pkt.data) {
1378 av_free_packet(&pkt);
1382 #if WAIT_KEY_PACKET_AFTER_SEEK
1388 if (pkt.data == flush_pkt.data) {
1389 LOGV("read %s flush pkt", av_get_media_type_string(mMediaType));
1390 av_free_packet(&pkt);
1392 } else if (pkt.data == NULL && pkt.size == 0) {
1393 LOGV("read %s eos pkt", av_get_media_type_string(mMediaType));
1394 av_free_packet(&pkt);
1395 mExtractor->reachedEOS(mMediaType);
1396 return ERROR_END_OF_STREAM;
1399 key = pkt.flags & AV_PKT_FLAG_KEY ? 1 : 0;
1403 LOGV("drop the no key packet");
1404 av_free_packet(&pkt);
1407 LOGV("~~~~~~ got the key packet");
1412 MediaBuffer *mediaBuffer = new MediaBuffer(pkt.size + FF_INPUT_BUFFER_PADDING_SIZE);
1413 mediaBuffer->meta_data()->clear();
1414 mediaBuffer->set_range(0, pkt.size);
1415 #if DISABLE_NAL_TO_ANNEXB
1416 mNal2AnnexB = false;
1418 if (mIsAVC && mNal2AnnexB) {
1419 /* Convert H.264 NAL format to annex b */
1420 if (mNALLengthSize >= 3 && mNALLengthSize <= 4 )
1422 uint8_t *dst = (uint8_t *)mediaBuffer->data();
1424 /* This only works for NAL sizes 3-4 */
1425 size_t len = pkt.size, i;
1426 uint8_t *ptr = pkt.data;
1427 while (len >= mNALLengthSize) {
1428 uint32_t nal_len = 0;
1429 for( i = 0; i < mNALLengthSize; i++ ) {
1430 nal_len = (nal_len << 8) | ptr[i];
1433 dst[mNALLengthSize - 1] = 1;
1434 if (nal_len > INT_MAX || nal_len > (unsigned int)len) {
1435 status = ERROR_MALFORMED;
1438 dst += mNALLengthSize;
1439 ptr += mNALLengthSize;
1440 len -= mNALLengthSize;
1442 memcpy(dst, ptr, nal_len);
1449 status = ERROR_MALFORMED;
1453 LOGV("status != OK");
1454 mediaBuffer->release();
1456 av_free_packet(&pkt);
1457 return ERROR_MALFORMED;
1460 memcpy(mediaBuffer->data(), pkt.data, pkt.size);
1465 if (pkt.pts == AV_NOPTS_VALUE)
1469 // TODO, Stagefright can't handle negative timestamps
1470 // if needed, work around this by offsetting them manually?
1475 timeUs = (int64_t)(pktTS * av_q2d(mStream->time_base) * 1000000);
1478 LOGV("read %s pkt, size: %d, key: %d, pts: %lld, dts: %lld, timeUs: %llu us (%.2f secs)",
1479 av_get_media_type_string(mMediaType), pkt.size, key, pkt.pts, pkt.dts, timeUs, timeUs/1E6);
1483 // TODO, Stagefright can't handle negative timestamps
1484 // if needed, work around this by offsetting them manually?
1489 mediaBuffer->meta_data()->setInt64(kKeyTime, timeUs);
1490 mediaBuffer->meta_data()->setInt32(kKeyIsSyncFrame, key);
1492 *buffer = mediaBuffer;
1494 av_free_packet(&pkt);
1499 ////////////////////////////////////////////////////////////////////////////////
1503 const char *extension;
1504 const char *container;
1507 static extmap FILE_EXTS [] = {
1508 {".mp4", MEDIA_MIMETYPE_CONTAINER_MPEG4},
1509 {".3gp", MEDIA_MIMETYPE_CONTAINER_MPEG4},
1510 {".mp3", MEDIA_MIMETYPE_AUDIO_MPEG},
1511 {".mov", MEDIA_MIMETYPE_CONTAINER_MOV},
1512 {".mkv", MEDIA_MIMETYPE_CONTAINER_MATROSKA},
1513 {".ts", MEDIA_MIMETYPE_CONTAINER_TS},
1514 {".avi", MEDIA_MIMETYPE_CONTAINER_AVI},
1516 {".asf", MEDIA_MIMETYPE_CONTAINER_ASF},
1517 {".wmv", MEDIA_MIMETYPE_CONTAINER_WMV},
1518 {".wma", MEDIA_MIMETYPE_CONTAINER_WMA},
1519 {".mpg", MEDIA_MIMETYPE_CONTAINER_MPG},
1520 {".flv", MEDIA_MIMETYPE_CONTAINER_FLV},
1521 {".divx", MEDIA_MIMETYPE_CONTAINER_DIVX},
1522 {".mp2", MEDIA_MIMETYPE_CONTAINER_MP2},
1523 {".ape", MEDIA_MIMETYPE_CONTAINER_APE},
1524 {".rm ", MEDIA_MIMETYPE_CONTAINER_RM},
1525 {".ra", MEDIA_MIMETYPE_CONTAINER_RA},
1529 // TODO: check mFormatCtx->iformat->name?
1531 const sp<DataSource> &source, String8 *mimeType, float *confidence,
1532 sp<AMessage> *meta) {
1533 LOGV("SniffFFMPEG");
1535 const char *uri, *container = NULL;
1537 //av_find_input_format()??
1538 uri = source->getNamURI();
1543 LOGI("ffmpeg uri: %s", uri);
1545 LOGI("list the file extensions suppoted by ffmpeg: ");
1546 LOGI("========================================");
1547 for (i = 0; i < NELEM(FILE_EXTS); ++i) {
1548 LOGV("file_exts[%02d]: %s", i, FILE_EXTS[i].extension);
1550 LOGI("========================================");
1552 int lenURI = strlen(uri);
1553 for (i = 0; i < NELEM(FILE_EXTS); ++i) {
1554 int len = strlen(FILE_EXTS[i].extension);
1555 int start = lenURI - len;
1557 if (!av_strncasecmp(uri + start, FILE_EXTS[i].extension, len)) {
1558 container = FILE_EXTS[i].container;
1564 if (container == NULL)
1567 LOGV("found container: %s", container);
1569 *confidence = 0.88f; // Slightly larger than other extractor's confidence
1570 mimeType->setTo(container);
1572 /* use MPEG4Extractor(not extended extractor) for HTTP source only */
1573 if (!av_strcasecmp(container, MEDIA_MIMETYPE_CONTAINER_MPEG4)
1574 && (source->flags() & DataSource::kIsCachingDataSource)) {
1578 *meta = new AMessage;
1579 (*meta)->setString("extended-extractor", "extended-extractor");
1580 (*meta)->setString("extended-extractor-subtype", "ffmpegextractor");
1585 } // namespace android