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 <media/stagefright/foundation/ABitReader.h>
22 #include <media/stagefright/foundation/ABuffer.h>
23 #include <media/stagefright/foundation/ADebug.h>
24 #include <media/stagefright/foundation/AMessage.h>
25 #include <media/stagefright/foundation/hexdump.h>
26 #include <media/stagefright/DataSource.h>
27 #include <media/stagefright/MediaBuffer.h>
28 #include <media/stagefright/MediaDebug.h>
29 #include <media/stagefright/MediaDefs.h>
30 #include <media/stagefright/MediaErrors.h>
31 #include <media/stagefright/MediaSource.h>
32 #include <media/stagefright/MetaData.h>
33 #include <media/stagefright/Utils.h>
34 #include <utils/String8.h>
35 #include <utils/misc.h>
37 #include "include/avc_utils.h"
38 #include "ffmpeg_utils/ffmpeg_utils.h"
39 #include "include/FFmpegExtractor.h"
41 #define DEBUG_READ_ENTRY 0
42 #define DIABLE_VIDEO 0
43 #define DIABLE_AUDIO 0
44 #define WAIT_KEY_PACKET_AFTER_SEEK 1
46 #define MAX_QUEUE_SIZE (15 * 1024 * 1024)
47 #define MIN_AUDIOQ_SIZE (20 * 16 * 1024)
49 #define MAX_PROBE_PACKETS 200
60 struct FFmpegExtractor::Track : public MediaSource {
61 Track(const sp<FFmpegExtractor> &extractor, sp<MetaData> meta, bool isAVC,
62 AVStream *stream, PacketQueue *queue);
64 virtual status_t start(MetaData *params);
65 virtual status_t stop();
66 virtual sp<MetaData> getFormat();
68 virtual status_t read(
69 MediaBuffer **buffer, const ReadOptions *options);
75 friend struct FFmpegExtractor;
77 sp<FFmpegExtractor> mExtractor;
80 enum AVMediaType mMediaType;
85 size_t mNALLengthSize;
91 DISALLOW_EVIL_CONSTRUCTORS(Track);
94 ////////////////////////////////////////////////////////////////////////////////
96 FFmpegExtractor::FFmpegExtractor(const sp<DataSource> &source)
97 : mDataSource(source),
98 mReaderThreadStarted(false),
100 LOGV("FFmpegExtractor::FFmpegExtractor");
103 const char *url = mDataSource->getNamURI();
105 LOGI("url is error!");
109 if (!strcmp(url, "-")) {
110 av_strlcpy(mFilename, "pipe:", strlen("pipe:") + 1);
112 av_strlcpy(mFilename, url, strlen(url) + 1);
114 LOGI("url: %s, mFilename: %s", url, mFilename);
118 LOGE("failed to init ffmpeg");
122 // start reader here, as we want to extract extradata from bitstream if no extradata
125 while(mProbePkts <= MAX_PROBE_PACKETS && !mEOF &&
126 (mFormatCtx->pb ? !mFormatCtx->pb->error : 1) &&
127 (mDefersToCreateVideoTrack || mDefersToCreateAudioTrack)) {
128 // FIXME, i am so lazy! Should use pthread_cond_wait to wait conditions
132 LOGV("mProbePkts: %d, mEOF: %d, pb->error(if has): %d, mDefersToCreateVideoTrack: %d, mDefersToCreateAudioTrack: %d",
133 mProbePkts, mEOF, mFormatCtx->pb ? mFormatCtx->pb->error : 0, mDefersToCreateVideoTrack, mDefersToCreateAudioTrack);
138 FFmpegExtractor::~FFmpegExtractor() {
139 LOGV("FFmpegExtractor::~FFmpegExtractor");
141 // stop reader here if no track!
147 size_t FFmpegExtractor::countTracks() {
148 return mInitCheck == OK ? mTracks.size() : 0;
151 sp<MediaSource> FFmpegExtractor::getTrack(size_t index) {
152 LOGV("FFmpegExtractor::getTrack[%d]", index);
154 if (mInitCheck != OK) {
158 if (index >= mTracks.size()) {
162 return mTracks.valueAt(index);
165 sp<MetaData> FFmpegExtractor::getTrackMetaData(size_t index, uint32_t flags) {
166 LOGV("FFmpegExtractor::getTrackMetaData[%d]", index);
168 if (mInitCheck != OK) {
172 if (index >= mTracks.size()) {
176 return mTracks.valueAt(index)->getFormat();
179 sp<MetaData> FFmpegExtractor::getMetaData() {
180 LOGV("FFmpegExtractor::getMetaData");
182 if (mInitCheck != OK) {
186 sp<MetaData> meta = new MetaData;
188 meta->setCString(kKeyMIMEType, "video/ffmpeg");
193 uint32_t FFmpegExtractor::flags() const {
194 LOGV("FFmpegExtractor::flags");
196 if (mInitCheck != OK) {
200 uint32_t flags = CAN_PAUSE;
202 if (mFormatCtx->duration != AV_NOPTS_VALUE) {
203 flags |= CAN_SEEK_BACKWARD | CAN_SEEK_FORWARD | CAN_SEEK;
209 void FFmpegExtractor::packet_queue_init(PacketQueue *q)
211 memset(q, 0, sizeof(PacketQueue));
212 q->mutex = SDL_CreateMutex();
213 q->cond = SDL_CreateCond();
214 packet_queue_put(q, &flush_pkt);
217 void FFmpegExtractor::packet_queue_flush(PacketQueue *q)
219 AVPacketList *pkt, *pkt1;
221 SDL_LockMutex(q->mutex);
222 for (pkt = q->first_pkt; pkt != NULL; pkt = pkt1) {
224 av_free_packet(&pkt->pkt);
231 SDL_UnlockMutex(q->mutex);
234 void FFmpegExtractor::packet_queue_end(PacketQueue *q)
236 packet_queue_flush(q);
237 SDL_DestroyMutex(q->mutex);
238 SDL_DestroyCond(q->cond);
241 void FFmpegExtractor::packet_queue_abort(PacketQueue *q)
243 SDL_LockMutex(q->mutex);
245 q->abort_request = 1;
247 SDL_CondSignal(q->cond);
249 SDL_UnlockMutex(q->mutex);
252 int FFmpegExtractor::packet_queue_put(PacketQueue *q, AVPacket *pkt)
256 /* duplicate the packet */
257 if (pkt != &flush_pkt && av_dup_packet(pkt) < 0)
260 pkt1 = (AVPacketList *)av_malloc(sizeof(AVPacketList));
266 SDL_LockMutex(q->mutex);
272 q->last_pkt->next = pkt1;
275 //q->size += pkt1->pkt.size + sizeof(*pkt1);
276 q->size += pkt1->pkt.size;
277 SDL_CondSignal(q->cond);
279 SDL_UnlockMutex(q->mutex);
283 /* packet queue handling */
284 /* return < 0 if aborted, 0 if no packet and > 0 if packet. */
285 int FFmpegExtractor::packet_queue_get(PacketQueue *q, AVPacket *pkt, int block)
290 SDL_LockMutex(q->mutex);
293 if (q->abort_request) {
300 q->first_pkt = pkt1->next;
304 //q->size -= pkt1->pkt.size + sizeof(*pkt1);
305 q->size -= pkt1->pkt.size;
314 SDL_CondWait(q->cond, q->mutex);
317 SDL_UnlockMutex(q->mutex);
321 static int lockmgr(void **mtx, enum AVLockOp op)
325 *mtx = (void *)SDL_CreateMutex();
330 return !!SDL_LockMutex((SDL_mutex *)*mtx);
331 case AV_LOCK_RELEASE:
332 return !!SDL_UnlockMutex((SDL_mutex *)*mtx);
333 case AV_LOCK_DESTROY:
334 SDL_DestroyMutex((SDL_mutex *)*mtx);
340 static void EncodeSize14(uint8_t **_ptr, size_t size) {
341 CHECK_LE(size, 0x3fff);
343 uint8_t *ptr = *_ptr;
345 *ptr++ = 0x80 | (size >> 7);
346 *ptr++ = size & 0x7f;
351 static sp<ABuffer> MakeMPEGVideoESDS(const sp<ABuffer> &csd) {
352 sp<ABuffer> esds = new ABuffer(csd->size() + 25);
354 uint8_t *ptr = esds->data();
356 EncodeSize14(&ptr, 22 + csd->size());
358 *ptr++ = 0x00; // ES_ID
361 *ptr++ = 0x00; // streamDependenceFlag, URL_Flag, OCRstreamFlag
364 EncodeSize14(&ptr, 16 + csd->size());
366 *ptr++ = 0x40; // Audio ISO/IEC 14496-3
368 for (size_t i = 0; i < 12; ++i) {
373 EncodeSize14(&ptr, csd->size());
375 memcpy(ptr, csd->data(), csd->size());
380 // Returns the sample rate based on the sampling frequency index
381 static uint32_t get_sample_rate(const uint8_t sf_index)
383 static const uint32_t sample_rates[] =
385 96000, 88200, 64000, 48000, 44100, 32000,
386 24000, 22050, 16000, 12000, 11025, 8000
389 if (sf_index < sizeof(sample_rates) / sizeof(sample_rates[0])) {
390 return sample_rates[sf_index];
396 int FFmpegExtractor::check_extradata(AVCodecContext *avctx)
399 bool *defersToCreateTrack;
400 AVBitStreamFilterContext **bsfc;
402 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
404 defersToCreateTrack = &mDefersToCreateVideoTrack;
405 } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO){
407 defersToCreateTrack = &mDefersToCreateAudioTrack;
411 switch(avctx->codec_id) {
419 name = "aac_adtstoasc";
427 if (avctx->extradata_size <= 0) {
428 LOGI("No %s extradata found, should to extract it from bitstream",
429 av_get_media_type_string(avctx->codec_type));
430 *defersToCreateTrack = true;
433 *bsfc = av_bitstream_filter_init(name);
435 LOGE("Cannot open the %s BSF!", name);
436 *defersToCreateTrack = false;
439 LOGV("open the %s bsf", name);
450 int FFmpegExtractor::stream_component_open(int stream_index)
452 AVCodecContext *avctx;
455 bool supported = false;
461 LOGI("stream_index: %d", stream_index);
462 if (stream_index < 0 || stream_index >= mFormatCtx->nb_streams)
464 avctx = mFormatCtx->streams[stream_index]->codec;
466 switch(avctx->codec_id) {
475 case CODEC_ID_MPEG2VIDEO:
486 LOGE("unsupport the codec");
489 LOGV("support the codec");
492 ssize_t index = mTracks.indexOfKey(stream_index);
495 LOGE("this track already exists");
499 mFormatCtx->streams[stream_index]->discard = AVDISCARD_DEFAULT;
502 av_get_codec_tag_string(tagbuf, sizeof(tagbuf), avctx->codec_tag);
503 LOGV("Tag %s/0x%08x with codec id '%d'\n", tagbuf, avctx->codec_tag, avctx->codec_id);
505 switch (avctx->codec_type) {
506 case AVMEDIA_TYPE_VIDEO:
507 if (mVideoStreamIdx == -1)
508 mVideoStreamIdx = stream_index;
509 if (mVideoStream == NULL)
510 mVideoStream = mFormatCtx->streams[stream_index];
511 if (!mVideoQInited) {
512 packet_queue_init(&mVideoQ);
513 mVideoQInited = true;
516 ret = check_extradata(avctx);
519 // disable the stream
520 mVideoStreamIdx = -1;
522 packet_queue_end(&mVideoQ);
523 mVideoQInited = false;
524 mFormatCtx->streams[stream_index]->discard = AVDISCARD_ALL;
529 LOGV("video extradata:");
530 hexdump(avctx->extradata, avctx->extradata_size);
534 switch(avctx->codec_id) {
538 * http://msdn.microsoft.com/en-us/library/dd757808(v=vs.85).aspx
540 //if (avctx->codec_tag && avctx->codec_tag == AV_RL32("avc1")) {
541 if (avctx->extradata[0] == 1 /* configurationVersion */) {
542 // H.264 bitstream without start codes.
546 if (avctx->width == 0 || avctx->height == 0) {
547 int32_t width, height;
548 sp<ABuffer> seqParamSet = new ABuffer(avctx->extradata_size - 8);
549 memcpy(seqParamSet->data(), avctx->extradata + 8, avctx->extradata_size - 8);
550 FindAVCDimensions(seqParamSet, &width, &height);
551 avctx->width = width;
552 avctx->height = height;
555 meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
556 meta->setData(kKeyAVCC, kTypeAVCC, avctx->extradata, avctx->extradata_size);
558 // H.264 bitstream with start codes.
562 /* set NULL to release meta as we will new a meta in MakeAVCCodecSpecificData() fxn */
566 sp<ABuffer> buffer = new ABuffer(avctx->extradata_size);
567 memcpy(buffer->data(), avctx->extradata, avctx->extradata_size);
568 meta = MakeAVCCodecSpecificData(buffer);
573 meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4);
575 sp<ABuffer> csd = new ABuffer(avctx->extradata_size);
576 memcpy(csd->data(), avctx->extradata, avctx->extradata_size);
577 sp<ABuffer> esds = MakeMPEGVideoESDS(csd);
578 meta->setData(kKeyESDS, kTypeESDS, esds->data(), esds->size());
585 meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263);
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());
593 case CODEC_ID_MPEG2VIDEO:
595 meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG2);
596 meta->setData(kKeyESDS, kTypeESDS, avctx->extradata, avctx->extradata_size);
600 meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_WMV12);
601 meta->setData(kKeyESDS, kTypeESDS, avctx->extradata, avctx->extradata_size);
604 CHECK(!"Should not be here. Unsupported codec.");
608 LOGI("width: %d, height: %d, bit_rate: %d", avctx->width, avctx->height, avctx->bit_rate);
610 meta->setInt32(kKeyWidth, avctx->width);
611 meta->setInt32(kKeyHeight, avctx->height);
612 meta->setInt32(kKeyBitRate, avctx->bit_rate);
613 if (mFormatCtx->duration != AV_NOPTS_VALUE)
614 meta->setInt64(kKeyDuration, mFormatCtx->duration);
616 LOGV("create a video track");
618 stream_index, new Track(this, meta, isAVC, mVideoStream, &mVideoQ));
620 mDefersToCreateVideoTrack = false;
623 case AVMEDIA_TYPE_AUDIO:
624 if (mAudioStreamIdx == -1)
625 mAudioStreamIdx = stream_index;
626 if (mAudioStream == NULL)
627 mAudioStream = mFormatCtx->streams[stream_index];
628 if (!mAudioQInited) {
629 packet_queue_init(&mAudioQ);
630 mAudioQInited = true;
633 ret = check_extradata(avctx);
636 // disable the stream
637 mAudioStreamIdx = -1;
639 packet_queue_end(&mAudioQ);
640 mAudioQInited = false;
641 mFormatCtx->streams[stream_index]->discard = AVDISCARD_ALL;
647 LOGV("audio extradata:");
648 hexdump(avctx->extradata, avctx->extradata_size);
650 switch(avctx->codec_id) {
654 meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_MPEG);
655 //meta->setData(kKeyESDS, kTypeESDS, avctx->extradata, avctx->extradata_size);
660 const uint8_t *header;
661 uint8_t profile, sf_index, channel;
663 header = avctx->extradata;
664 CHECK(header != NULL);
666 // AudioSpecificInfo follows
667 // oooo offf fccc c000
668 // o - audioObjectType
669 // f - samplingFreqIndex
671 profile = ((header[0] & 0xf8) >> 3) - 1;
672 sf_index = (header[0] & 0x07) << 1 | (header[1] & 0x80) >> 7;
673 sr = get_sample_rate(sf_index);
675 LOGE("unsupport the sample rate");
678 channel = (header[1] >> 3) & 0xf;
679 LOGV("profile: %d, sf_index: %d, channel: %d", profile, sf_index, channel);
681 meta = MakeAACCodecSpecificData(profile, sf_index, channel);
682 meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AAC);
685 CHECK(!"Should not be here. Unsupported codec.");
689 LOGI("bit_rate: %d, sample_rate: %d, channels: %d", avctx->bit_rate, avctx->sample_rate, avctx->channels);
691 meta->setInt32(kKeySampleRate, avctx->sample_rate);
692 meta->setInt32(kKeyChannelCount, avctx->channels);
693 meta->setInt32(kKeyBitRate, avctx->bit_rate);
694 if (mFormatCtx->duration != AV_NOPTS_VALUE)
695 meta->setInt64(kKeyDuration, mFormatCtx->duration);
697 if (avctx->codec_id != CODEC_ID_MP3) {
698 LOGV("audio meta esds:");
699 CHECK(meta->findData(kKeyESDS, &type, &data, &size));
703 LOGV("create a audio track");
705 stream_index, new Track(this, meta, false, mAudioStream, &mAudioQ));
707 mDefersToCreateAudioTrack = false;
710 case AVMEDIA_TYPE_SUBTITLE:
712 CHECK(!"Should not be here. Unsupported media type.");
715 CHECK(!"Should not be here. Unsupported media type.");
721 void FFmpegExtractor::stream_component_close(int stream_index)
723 AVCodecContext *avctx;
725 if (stream_index < 0 || stream_index >= mFormatCtx->nb_streams)
727 avctx = mFormatCtx->streams[stream_index]->codec;
729 switch (avctx->codec_type) {
730 case AVMEDIA_TYPE_VIDEO:
731 LOGV("packet_queue_abort videoq");
732 packet_queue_abort(&mVideoQ);
733 /* wait until the end */
734 while (!mAbortRequest && !mVideoEOSReceived) {
735 LOGV("wait for video received");
738 LOGV("packet_queue_end videoq");
739 packet_queue_end(&mVideoQ);
741 case AVMEDIA_TYPE_AUDIO:
742 LOGV("packet_queue_abort audioq");
743 packet_queue_abort(&mAudioQ);
744 while (!mAbortRequest && !mAudioEOSReceived) {
745 LOGV("wait for audio received");
748 LOGV("packet_queue_end audioq");
749 packet_queue_end(&mAudioQ);
751 case AVMEDIA_TYPE_SUBTITLE:
757 mFormatCtx->streams[stream_index]->discard = AVDISCARD_ALL;
758 switch (avctx->codec_type) {
759 case AVMEDIA_TYPE_VIDEO:
761 mVideoStreamIdx = -1;
763 av_bitstream_filter_close(mVideoBsfc);
767 case AVMEDIA_TYPE_AUDIO:
769 mAudioStreamIdx = -1;
771 av_bitstream_filter_close(mAudioBsfc);
775 case AVMEDIA_TYPE_SUBTITLE:
782 void FFmpegExtractor::reachedEOS(enum AVMediaType media_type)
784 Mutex::Autolock autoLock(mLock);
786 if (media_type == AVMEDIA_TYPE_VIDEO) {
787 mVideoEOSReceived = true;
788 } else if (media_type == AVMEDIA_TYPE_AUDIO) {
789 mAudioEOSReceived = true;
793 /* seek in the stream */
794 int FFmpegExtractor::stream_seek(int64_t pos, enum AVMediaType media_type)
796 Mutex::Autolock autoLock(mLock);
798 if (mVideoStreamIdx >= 0 &&
799 mAudioStreamIdx >= 0 &&
800 media_type == AVMEDIA_TYPE_AUDIO &&
801 !mVideoEOSReceived) {
806 if (mAudioStreamIdx >= 0)
807 packet_queue_flush(&mAudioQ);
808 if (mVideoStreamIdx >= 0)
809 packet_queue_flush(&mVideoQ);
812 mSeekFlags &= ~AVSEEK_FLAG_BYTE;
819 int FFmpegExtractor::decode_interrupt_cb(void *ctx)
821 FFmpegExtractor *extrator = static_cast<FFmpegExtractor *>(ctx);
822 return extrator->mAbortRequest;
825 void FFmpegExtractor::print_error_ex(const char *filename, int err)
828 const char *errbuf_ptr = errbuf;
830 if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
831 errbuf_ptr = strerror(AVUNERROR(err));
832 LOGI("%s: %s\n", filename, errbuf_ptr);
835 void FFmpegExtractor::setFFmpegDefaultOpts()
849 mSeekByBytes = 0; /* seek by bytes 0=off 1=on -1=auto" */
850 mStartTime = AV_NOPTS_VALUE;
851 mDuration = AV_NOPTS_VALUE;
852 mSeekPos = AV_NOPTS_VALUE;
856 mVideoStreamIdx = -1;
857 mAudioStreamIdx = -1;
860 mVideoQInited = false;
861 mAudioQInited = false;
862 mDefersToCreateVideoTrack = false;
863 mDefersToCreateAudioTrack = false;
876 int FFmpegExtractor::initFFmpeg()
880 int ret = 0, audio_ret = 0, video_ret = 0;
881 int pkt_in_play_range = 0;
882 AVDictionaryEntry *t;
885 int st_index[AVMEDIA_TYPE_NB] = {0};
886 int wanted_stream[AVMEDIA_TYPE_NB] = {0};
887 st_index[AVMEDIA_TYPE_AUDIO] = -1;
888 st_index[AVMEDIA_TYPE_VIDEO] = -1;
889 wanted_stream[AVMEDIA_TYPE_AUDIO] = -1;
890 wanted_stream[AVMEDIA_TYPE_VIDEO] = -1;
892 setFFmpegDefaultOpts();
894 nam_av_log_set_flags(AV_LOG_SKIP_REPEATED);
895 av_log_set_level(AV_LOG_DEBUG);
896 av_log_set_callback(nam_av_log_callback);
898 /* register all codecs, demux and protocols */
899 avcodec_register_all();
901 avdevice_register_all();
904 avformat_network_init();
908 if (av_lockmgr_register(lockmgr)) {
909 LOGE("could not initialize lock manager!");
912 av_init_packet(&flush_pkt);
913 flush_pkt.data = (uint8_t *)"FLUSH";
916 mFormatCtx = avformat_alloc_context();
917 mFormatCtx->interrupt_callback.callback = decode_interrupt_cb;
918 mFormatCtx->interrupt_callback.opaque = this;
920 LOGV("mFilename: %s", mFilename);
921 err = avformat_open_input(&mFormatCtx, mFilename, NULL, &format_opts);
923 print_error_ex(mFilename, err);
927 if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
928 LOGE("Option %s not found.\n", t->key);
929 //ret = AVERROR_OPTION_NOT_FOUND;
935 mFormatCtx->flags |= AVFMT_FLAG_GENPTS;
937 opts = setup_find_stream_info_opts(mFormatCtx, codec_opts);
938 orig_nb_streams = mFormatCtx->nb_streams;
940 err = avformat_find_stream_info(mFormatCtx, opts);
942 LOGE("%s: could not find codec parameters\n", mFilename);
946 for (i = 0; i < orig_nb_streams; i++)
947 av_dict_free(&opts[i]);
951 mFormatCtx->pb->eof_reached = 0; // FIXME hack, ffplay maybe should not use url_feof() to test for the end
953 if (mSeekByBytes < 0)
954 mSeekByBytes = !!(mFormatCtx->iformat->flags & AVFMT_TS_DISCONT);
956 /* if seeking requested, we execute it */
957 if (mStartTime != AV_NOPTS_VALUE) {
960 timestamp = mStartTime;
961 /* add the stream start time */
962 if (mFormatCtx->start_time != AV_NOPTS_VALUE)
963 timestamp += mFormatCtx->start_time;
964 ret = avformat_seek_file(mFormatCtx, -1, INT64_MIN, timestamp, INT64_MAX, 0);
966 LOGE("%s: could not seek to position %0.3f",
967 mFilename, (double)timestamp / AV_TIME_BASE);
972 for (i = 0; i < mFormatCtx->nb_streams; i++)
973 mFormatCtx->streams[i]->discard = AVDISCARD_ALL;
975 st_index[AVMEDIA_TYPE_VIDEO] =
976 av_find_best_stream(mFormatCtx, AVMEDIA_TYPE_VIDEO,
977 wanted_stream[AVMEDIA_TYPE_VIDEO], -1, NULL, 0);
979 st_index[AVMEDIA_TYPE_AUDIO] =
980 av_find_best_stream(mFormatCtx, AVMEDIA_TYPE_AUDIO,
981 wanted_stream[AVMEDIA_TYPE_AUDIO],
982 st_index[AVMEDIA_TYPE_VIDEO],
985 av_dump_format(mFormatCtx, 0, mFilename, 0);
988 if (mFormatCtx->duration != AV_NOPTS_VALUE) {
989 int hours, mins, secs, us;
990 secs = mFormatCtx->duration / AV_TIME_BASE;
991 us = mFormatCtx->duration % AV_TIME_BASE;
996 LOGI("the duration is %02d:%02d:%02d.%02d", hours, mins, secs, (100 * us) / AV_TIME_BASE);
999 if (st_index[AVMEDIA_TYPE_AUDIO] >= 0) {
1000 audio_ret = stream_component_open(st_index[AVMEDIA_TYPE_AUDIO]);
1003 if (st_index[AVMEDIA_TYPE_VIDEO] >= 0) {
1004 video_ret = stream_component_open(st_index[AVMEDIA_TYPE_VIDEO]);
1007 if ( audio_ret < 0 && video_ret < 0) {
1008 LOGE("%s: could not open codecs\n", mFilename);
1019 void FFmpegExtractor::deInitFFmpeg()
1022 avformat_close_input(&mFormatCtx);
1025 av_lockmgr_register(NULL);
1027 avformat_network_deinit();
1029 av_log(NULL, AV_LOG_QUIET, "%s", "");
1032 status_t FFmpegExtractor::startReaderThread() {
1033 LOGV("Starting reader thread");
1034 Mutex::Autolock autoLock(mLock);
1036 if (mReaderThreadStarted)
1039 pthread_attr_t attr;
1040 pthread_attr_init(&attr);
1041 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1042 pthread_create(&mReaderThread, &attr, ReaderWrapper, this);
1043 pthread_attr_destroy(&attr);
1044 mReaderThreadStarted = true;
1045 LOGD("Reader thread started");
1050 void FFmpegExtractor::stopReaderThread() {
1051 LOGV("Stopping reader thread");
1052 Mutex::Autolock autoLock(mLock);
1054 if (!mReaderThreadStarted)
1060 pthread_join(mReaderThread, &dummy);
1061 mReaderThreadStarted = false;
1062 LOGD("Reader thread stopped");
1066 void *FFmpegExtractor::ReaderWrapper(void *me) {
1067 ((FFmpegExtractor *)me)->readerEntry();
1072 void FFmpegExtractor::readerEntry() {
1074 AVPacket pkt1, *pkt = &pkt1;
1076 int pkt_in_play_range = 0;
1078 LOGV("FFmpegExtractor::readerEntry");
1080 mVideoEOSReceived = false;
1081 mAudioEOSReceived = false;
1087 if (mPaused != mLastPaused) {
1088 mLastPaused = mPaused;
1090 mReadPauseReturn = av_read_pause(mFormatCtx);
1092 av_read_play(mFormatCtx);
1094 #if CONFIG_RTSP_DEMUXER || CONFIG_MMSH_PROTOCOL
1096 (!strcmp(mFormatCtx->iformat->name, "rtsp") ||
1097 (mFormatCtx->pb && !strncmp(mFilename, "mmsh:", 5)))) {
1098 /* wait 10 ms to avoid trying to get another packet */
1106 LOGV("readerEntry, mSeekReq: %d", mSeekReq);
1107 ret = avformat_seek_file(mFormatCtx, -1, INT64_MIN, mSeekPos, INT64_MAX, mSeekFlags);
1109 LOGE("%s: error while seeking", mFormatCtx->filename);
1111 if (mAudioStreamIdx >= 0) {
1112 packet_queue_flush(&mAudioQ);
1113 packet_queue_put(&mAudioQ, &flush_pkt);
1115 if (mVideoStreamIdx >= 0) {
1116 packet_queue_flush(&mVideoQ);
1117 packet_queue_put(&mVideoQ, &flush_pkt);
1124 /* if the queue are full, no need to read more */
1125 if ( mAudioQ.size + mVideoQ.size > MAX_QUEUE_SIZE
1126 || ( (mAudioQ .size > MIN_AUDIOQ_SIZE || mAudioStreamIdx < 0)
1127 && (mVideoQ .nb_packets > MIN_FRAMES || mVideoStreamIdx < 0))) {
1128 #if DEBUG_READ_ENTRY
1129 LOGV("readerEntry, is full, fuck");
1137 if (mVideoStreamIdx >= 0) {
1138 av_init_packet(pkt);
1141 pkt->stream_index = mVideoStreamIdx;
1142 packet_queue_put(&mVideoQ, pkt);
1144 if (mAudioStreamIdx >= 0) {
1145 av_init_packet(pkt);
1148 pkt->stream_index = mAudioStreamIdx;
1149 packet_queue_put(&mAudioQ, pkt);
1152 #if DEBUG_READ_ENTRY
1153 LOGV("readerEntry, eof = 1, mVideoQ.size: %d, mVideoQ.nb_packets: %d, mAudioQ.size: %d, mAudioQ.nb_packets: %d",
1154 mVideoQ.size, mVideoQ.nb_packets, mAudioQ.size, mAudioQ.nb_packets);
1156 if (mAudioQ.size + mVideoQ.size == 0) {
1157 if (mLoop != 1 && (!mLoop || --mLoop)) {
1158 if (mVideoStreamIdx >= 0) {
1159 stream_seek(mStartTime != AV_NOPTS_VALUE ? mStartTime : 0, AVMEDIA_TYPE_VIDEO);
1160 } else if (mAudioStreamIdx >= 0) {
1161 stream_seek(mStartTime != AV_NOPTS_VALUE ? mStartTime : 0, AVMEDIA_TYPE_AUDIO);
1163 } else if (mAutoExit) {
1172 ret = av_read_frame(mFormatCtx, pkt);
1175 if (ret == AVERROR_EOF || url_feof(mFormatCtx->pb))
1176 if (ret == AVERROR_EOF)
1177 LOGV("ret == AVERROR_EOF");
1178 if (url_feof(mFormatCtx->pb))
1179 LOGV("url_feof(mFormatCtx->pb)");
1183 if (mFormatCtx->pb && mFormatCtx->pb->error) {
1184 LOGE("mFormatCtx->pb->error: %d", mFormatCtx->pb->error);
1191 if (pkt->stream_index == mAudioStreamIdx) {
1195 AVCodecContext *avctx = mFormatCtx->streams[mAudioStreamIdx]->codec;
1196 if (mAudioBsfc && pkt && pkt->data) {
1197 ret = av_bitstream_filter_filter(mAudioBsfc, avctx, NULL, &outbuf, &outbuf_size,
1198 pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY);
1200 if (ret < 0 ||!outbuf_size) {
1201 av_free_packet(pkt);
1204 if (outbuf && outbuf != pkt->data) {
1205 memmove(pkt->data, outbuf, outbuf_size);
1206 pkt->size = outbuf_size;
1209 if (mDefersToCreateAudioTrack) {
1210 if (avctx->extradata_size <= 0) {
1211 av_free_packet(pkt);
1214 stream_component_open(mAudioStreamIdx);
1215 if (!mDefersToCreateAudioTrack)
1216 LOGI("probe packet counter: %d when create audio track ok", mProbePkts);
1217 if (mProbePkts == MAX_PROBE_PACKETS)
1218 LOGI("probe packet counter to max: %d, create audio track: %d",
1219 mProbePkts, !mDefersToCreateAudioTrack);
1223 /* check if packet is in play range specified by user, then queue, otherwise discard */
1224 pkt_in_play_range = mDuration == AV_NOPTS_VALUE ||
1225 (pkt->pts - mFormatCtx->streams[pkt->stream_index]->start_time) *
1226 av_q2d(mFormatCtx->streams[pkt->stream_index]->time_base) -
1227 (double)(mStartTime != AV_NOPTS_VALUE ? mStartTime : 0) / 1000000
1228 <= ((double)mDuration / 1000000);
1229 if (pkt->stream_index == mAudioStreamIdx && pkt_in_play_range) {
1230 packet_queue_put(&mAudioQ, pkt);
1231 } else if (pkt->stream_index == mVideoStreamIdx && pkt_in_play_range) {
1232 packet_queue_put(&mVideoQ, pkt);
1234 av_free_packet(pkt);
1237 /* wait until the end */
1238 while (!mAbortRequest) {
1244 LOGI("reader thread goto end...");
1246 /* close each stream */
1247 if (mAudioStreamIdx >= 0)
1248 stream_component_close(mAudioStreamIdx);
1249 if (mVideoStreamIdx >= 0)
1250 stream_component_close(mVideoStreamIdx);
1252 avformat_close_input(&mFormatCtx);
1256 ////////////////////////////////////////////////////////////////////////////////
1258 FFmpegExtractor::Track::Track(
1259 const sp<FFmpegExtractor> &extractor, sp<MetaData> meta, bool isAVC,
1260 AVStream *stream, PacketQueue *queue)
1261 : mExtractor(extractor),
1268 /* H.264 Video Types */
1270 mNal2AnnexB = false;
1276 CHECK(meta->findData(kKeyAVCC, &type, &data, &size));
1278 const uint8_t *ptr = (const uint8_t *)data;
1281 CHECK_EQ((unsigned)ptr[0], 1u); // configurationVersion == 1
1283 // The number of bytes used to encode the length of a NAL unit.
1284 mNALLengthSize = 1 + (ptr[4] & 3);
1286 LOGV("the stream is AVC, the length of a NAL unit: %d", mNALLengthSize);
1292 mMediaType = mStream->codec->codec_type;
1295 FFmpegExtractor::Track::~Track() {
1298 status_t FFmpegExtractor::Track::start(MetaData *params) {
1299 Mutex::Autolock autoLock(mLock);
1300 //mExtractor->startReaderThread();
1304 status_t FFmpegExtractor::Track::stop() {
1305 Mutex::Autolock autoLock(mLock);
1306 mExtractor->stopReaderThread();
1310 sp<MetaData> FFmpegExtractor::Track::getFormat() {
1311 Mutex::Autolock autoLock(mLock);
1316 status_t FFmpegExtractor::Track::read(
1317 MediaBuffer **buffer, const ReadOptions *options) {
1320 Mutex::Autolock autoLock(mLock);
1323 bool seeking = false;
1324 bool waitKeyPkt = false;
1325 ReadOptions::SeekMode mode;
1326 int64_t pktTS = AV_NOPTS_VALUE;
1327 int64_t seekTimeUs = AV_NOPTS_VALUE;
1330 status_t status = OK;
1332 if (options && options->getSeekTo(&seekTimeUs, &mode)) {
1333 LOGV("~~~%s seekTimeUs: %lld, mode: %d", av_get_media_type_string(mMediaType), seekTimeUs, mode);
1334 if (mExtractor->stream_seek(seekTimeUs, mMediaType) == SEEK)
1339 if (mExtractor->packet_queue_get(mQueue, &pkt, 1) < 0) {
1340 mExtractor->reachedEOS(mMediaType);
1341 return ERROR_END_OF_STREAM;
1345 if (pkt.data != flush_pkt.data) {
1346 av_free_packet(&pkt);
1350 #if WAIT_KEY_PACKET_AFTER_SEEK
1356 if (pkt.data == flush_pkt.data) {
1357 LOGV("read %s flush pkt", av_get_media_type_string(mMediaType));
1358 av_free_packet(&pkt);
1360 } else if (pkt.data == NULL && pkt.size == 0) {
1361 LOGV("read %s eos pkt", av_get_media_type_string(mMediaType));
1362 av_free_packet(&pkt);
1363 mExtractor->reachedEOS(mMediaType);
1364 return ERROR_END_OF_STREAM;
1367 key = pkt.flags & AV_PKT_FLAG_KEY ? 1 : 0;
1371 LOGV("drop the no key packet");
1372 av_free_packet(&pkt);
1375 LOGV("~~~~~~ got the key packet");
1380 MediaBuffer *mediaBuffer = new MediaBuffer(pkt.size + FF_INPUT_BUFFER_PADDING_SIZE);
1381 mediaBuffer->meta_data()->clear();
1382 mediaBuffer->set_range(0, pkt.size);
1384 if (mIsAVC && mNal2AnnexB) {
1385 /* Convert H.264 NAL format to annex b */
1386 if (mNALLengthSize >= 3 && mNALLengthSize <= 4 )
1388 uint8_t *dst = (uint8_t *)mediaBuffer->data();
1390 /* This only works for NAL sizes 3-4 */
1391 size_t len = pkt.size, i;
1392 uint8_t *ptr = pkt.data;
1393 while (len >= mNALLengthSize) {
1394 uint32_t nal_len = 0;
1395 for( i = 0; i < mNALLengthSize; i++ ) {
1396 nal_len = (nal_len << 8) | ptr[i];
1399 dst[mNALLengthSize - 1] = 1;
1400 if (nal_len > INT_MAX || nal_len > (unsigned int)len) {
1401 status = ERROR_MALFORMED;
1404 dst += mNALLengthSize;
1405 ptr += mNALLengthSize;
1406 len -= mNALLengthSize;
1408 memcpy(dst, ptr, nal_len);
1415 status = ERROR_MALFORMED;
1419 LOGV("status != OK");
1420 mediaBuffer->release();
1422 av_free_packet(&pkt);
1423 return ERROR_MALFORMED;
1426 memcpy(mediaBuffer->data(), pkt.data, pkt.size);
1431 if (pkt.pts == AV_NOPTS_VALUE)
1435 // TODO, Stagefright can't handle negative timestamps
1436 // if needed, work around this by offsetting them manually?
1441 timeUs = (int64_t)(pktTS * av_q2d(mStream->time_base) * 1000000);
1444 LOGV("read %s pkt, size: %d, key: %d, pts: %lld, dts: %lld, timeUs: %llu us (%.2f secs)",
1445 av_get_media_type_string(mMediaType), pkt.size, key, pkt.pts, pkt.dts, timeUs, timeUs/1E6);
1449 // TODO, Stagefright can't handle negative timestamps
1450 // if needed, work around this by offsetting them manually?
1455 mediaBuffer->meta_data()->setInt64(kKeyTime, timeUs);
1456 mediaBuffer->meta_data()->setInt32(kKeyIsSyncFrame, key);
1458 *buffer = mediaBuffer;
1460 av_free_packet(&pkt);
1465 ////////////////////////////////////////////////////////////////////////////////
1469 const char *extension;
1470 const char *container;
1473 static extmap FILE_EXTS [] = {
1474 {".mp4", MEDIA_MIMETYPE_CONTAINER_MPEG4},
1475 {".3gp", MEDIA_MIMETYPE_CONTAINER_MPEG4},
1476 {".mp3", MEDIA_MIMETYPE_AUDIO_MPEG},
1477 {".mov", MEDIA_MIMETYPE_CONTAINER_MOV},
1478 {".mkv", MEDIA_MIMETYPE_CONTAINER_MATROSKA},
1479 {".ts", MEDIA_MIMETYPE_CONTAINER_TS},
1480 {".avi", MEDIA_MIMETYPE_CONTAINER_AVI},
1482 {".asf", MEDIA_MIMETYPE_CONTAINER_ASF},
1483 {".wmv", MEDIA_MIMETYPE_CONTAINER_WMV},
1484 {".wma", MEDIA_MIMETYPE_CONTAINER_WMA},
1485 {".mpg", MEDIA_MIMETYPE_CONTAINER_MPG},
1486 {".flv", MEDIA_MIMETYPE_CONTAINER_FLV},
1487 {".divx", MEDIA_MIMETYPE_CONTAINER_DIVX},
1488 {".mp2", MEDIA_MIMETYPE_CONTAINER_MP2},
1489 {".ape", MEDIA_MIMETYPE_CONTAINER_APE},
1490 {".rm ", MEDIA_MIMETYPE_CONTAINER_RM},
1491 {".ra", MEDIA_MIMETYPE_CONTAINER_RA},
1496 const sp<DataSource> &source, String8 *mimeType, float *confidence,
1497 sp<AMessage> *meta) {
1498 LOGV("SniffFFMPEG");
1500 const char *uri, *container = NULL;
1502 //av_find_input_format()??
1503 uri = source->getNamURI();
1508 LOGI("ffmpeg uri: %s", uri);
1510 LOGI("list the file extensions suppoted by ffmpeg: ");
1511 LOGI("========================================");
1512 for (i = 0; i < NELEM(FILE_EXTS); ++i) {
1513 LOGV("file_exts[%02d]: %s", i, FILE_EXTS[i].extension);
1515 LOGI("========================================");
1517 int lenURI = strlen(uri);
1518 for (i = 0; i < NELEM(FILE_EXTS); ++i) {
1519 int len = strlen(FILE_EXTS[i].extension);
1520 int start = lenURI - len;
1522 if (!av_strncasecmp(uri + start, FILE_EXTS[i].extension, len)) {
1523 container = FILE_EXTS[i].container;
1529 if (container == NULL)
1532 LOGV("found container: %s", container);
1534 *confidence = 0.88f; // Slightly larger than other extractor's confidence
1535 mimeType->setTo(container);
1537 /* use MPEG4Extractor(not extended extractor) for HTTP source only */
1538 if (!av_strcasecmp(container, MEDIA_MIMETYPE_CONTAINER_MPEG4)
1539 && (source->flags() & DataSource::kIsCachingDataSource)) {
1543 *meta = new AMessage;
1544 (*meta)->setString("extended-extractor", "extended-extractor");
1545 (*meta)->setString("extended-extractor-subtype", "ffmpegextractor");
1550 } // namespace android