OSDN Git Service

add support for real-video40(RMVB)
[android-x86/external-stagefright-plugins.git] / libstagefright / FFmpegExtractor / FFmpegExtractor.cpp
1 /*
2  * Copyright 2012 Michael Chen <omxcodec@gmail.com>
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #define LOG_NDEBUG 0
18 #define LOG_TAG "FFmpegExtractor"
19 #include <utils/Log.h>
20
21 #include <limits.h> /* INT_MAX */
22
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>
38
39 #include "include/avc_utils.h"
40 #include "utils/common_utils.h"
41 #include "utils/ffmpeg_utils.h"
42 #include "FFmpegExtractor.h"
43
44 #define DEBUG_READ_ENTRY 0
45 #define DIABLE_VIDEO     0
46 #define DIABLE_AUDIO     0
47 #define WAIT_KEY_PACKET_AFTER_SEEK 1
48 #define DISABLE_NAL_TO_ANNEXB 0
49
50 #define MAX_QUEUE_SIZE (15 * 1024 * 1024)
51 #define MIN_AUDIOQ_SIZE (20 * 16 * 1024)
52 #define MIN_FRAMES 5
53 #define EXTRACTOR_MAX_PROBE_PACKETS 200
54
55 #define FF_MAX_EXTRADATA_SIZE ((1 << 28) - FF_INPUT_BUFFER_PADDING_SIZE)
56
57 enum {
58     NO_SEEK = 0,
59     SEEK,
60 };
61
62 static AVPacket flush_pkt;
63
64 namespace android {
65
66 struct FFmpegExtractor::Track : public MediaSource {
67     Track(const sp<FFmpegExtractor> &extractor, sp<MetaData> meta, bool isAVC,
68           AVStream *stream, PacketQueue *queue);
69
70     virtual status_t start(MetaData *params);
71     virtual status_t stop();
72     virtual sp<MetaData> getFormat();
73
74     virtual status_t read(
75             MediaBuffer **buffer, const ReadOptions *options);
76
77 protected:
78     virtual ~Track();
79
80 private:
81     friend struct FFmpegExtractor;
82
83     sp<FFmpegExtractor> mExtractor;
84     sp<MetaData> mMeta;
85
86     enum AVMediaType mMediaType;
87
88     mutable Mutex mLock;
89
90     bool mIsAVC;
91     size_t mNALLengthSize;
92     bool mNal2AnnexB;
93
94     AVStream *mStream;
95     PacketQueue *mQueue;
96
97     DISALLOW_EVIL_CONSTRUCTORS(Track);
98 };
99
100 ////////////////////////////////////////////////////////////////////////////////
101
102 FFmpegExtractor::FFmpegExtractor(const sp<DataSource> &source)
103     : mDataSource(source),
104       mReaderThreadStarted(false),
105       mInitCheck(NO_INIT) {
106     LOGV("FFmpegExtractor::FFmpegExtractor");
107
108     int err;
109     const char *url = mDataSource->getNamURI();
110     if (url == NULL) {
111         LOGI("url is error!");
112         return;
113     }
114     // is it right?
115     if (!strcmp(url, "-")) {
116         av_strlcpy(mFilename, "pipe:", strlen("pipe:") + 1);
117     } else {
118         av_strlcpy(mFilename, url, strlen(url) + 1);
119     }
120     LOGI("url: %s, mFilename: %s", url, mFilename);
121
122     err = initStreams();
123     if (err < 0) {
124         LOGE("failed to init ffmpeg");
125         return;
126     }
127
128     // start reader here, as we want to extract extradata from bitstream if no extradata
129     startReaderThread();
130
131     while(mProbePkts <= EXTRACTOR_MAX_PROBE_PACKETS && !mEOF &&
132         (mFormatCtx->pb ? !mFormatCtx->pb->error : 1) &&
133         (mDefersToCreateVideoTrack || mDefersToCreateAudioTrack)) {
134         // FIXME, i am so lazy! Should use pthread_cond_wait to wait conditions
135         NamDelay(5);
136     }
137
138     LOGV("mProbePkts: %d, mEOF: %d, pb->error(if has): %d, mDefersToCreateVideoTrack: %d, mDefersToCreateAudioTrack: %d",
139         mProbePkts, mEOF, mFormatCtx->pb ? mFormatCtx->pb->error : 0, mDefersToCreateVideoTrack, mDefersToCreateAudioTrack);
140
141     mInitCheck = OK;
142 }
143
144 FFmpegExtractor::~FFmpegExtractor() {
145     LOGV("FFmpegExtractor::~FFmpegExtractor");
146
147     // stop reader here if no track!
148     stopReaderThread();
149
150     deInitStreams();
151 }
152
153 size_t FFmpegExtractor::countTracks() {
154     return mInitCheck == OK ? mTracks.size() : 0;
155 }
156
157 sp<MediaSource> FFmpegExtractor::getTrack(size_t index) {
158     LOGV("FFmpegExtractor::getTrack[%d]", index);
159
160     if (mInitCheck != OK) {
161         return NULL;
162     }
163
164     if (index >= mTracks.size()) {
165         return NULL;
166     }
167
168     return mTracks.valueAt(index);
169 }
170
171 sp<MetaData> FFmpegExtractor::getTrackMetaData(size_t index, uint32_t flags) {
172     LOGV("FFmpegExtractor::getTrackMetaData[%d]", index);
173
174     if (mInitCheck != OK) {
175         return NULL;
176     }
177
178     if (index >= mTracks.size()) {
179         return NULL;
180     }
181
182     return mTracks.valueAt(index)->getFormat();
183 }
184
185 sp<MetaData> FFmpegExtractor::getMetaData() {
186     LOGV("FFmpegExtractor::getMetaData");
187
188     if (mInitCheck != OK) {
189         return NULL;
190     }
191
192     sp<MetaData> meta = new MetaData;
193     // TODO
194     meta->setCString(kKeyMIMEType, "video/ffmpeg");
195
196     return meta;
197 }
198
199 uint32_t FFmpegExtractor::flags() const {
200     LOGV("FFmpegExtractor::flags");
201
202     if (mInitCheck != OK) {
203         return NULL;
204     }
205
206     uint32_t flags = CAN_PAUSE;
207
208     if (mFormatCtx->duration != AV_NOPTS_VALUE) {
209         flags |= CAN_SEEK_BACKWARD | CAN_SEEK_FORWARD | CAN_SEEK;
210     }
211
212     return flags;
213 }
214
215 void FFmpegExtractor::packet_queue_init(PacketQueue *q)
216 {
217     memset(q, 0, sizeof(PacketQueue));
218     pthread_mutex_init(&q->mutex, NULL);
219     pthread_cond_init(&q->cond, NULL);
220     packet_queue_put(q, &flush_pkt);
221 }
222
223 void FFmpegExtractor::packet_queue_flush(PacketQueue *q)
224 {
225     AVPacketList *pkt, *pkt1;
226
227     pthread_mutex_lock(&q->mutex);
228     for (pkt = q->first_pkt; pkt != NULL; pkt = pkt1) {
229         pkt1 = pkt->next;
230         av_free_packet(&pkt->pkt);
231         av_freep(&pkt);
232     }
233     q->last_pkt = NULL;
234     q->first_pkt = NULL;
235     q->nb_packets = 0;
236     q->size = 0;
237     pthread_mutex_unlock(&q->mutex);
238 }
239
240 void FFmpegExtractor::packet_queue_end(PacketQueue *q)
241 {
242     packet_queue_flush(q);
243 }
244
245 void FFmpegExtractor::packet_queue_abort(PacketQueue *q)
246 {
247     pthread_mutex_lock(&q->mutex);
248
249     q->abort_request = 1;
250
251     pthread_cond_signal(&q->cond);
252
253     pthread_mutex_unlock(&q->mutex);
254 }
255
256 int FFmpegExtractor::packet_queue_put(PacketQueue *q, AVPacket *pkt)
257 {
258     AVPacketList *pkt1;
259
260     /* duplicate the packet */
261     if (pkt != &flush_pkt && av_dup_packet(pkt) < 0)
262         return -1;
263
264     pkt1 = (AVPacketList *)av_malloc(sizeof(AVPacketList));
265     if (!pkt1)
266         return -1;
267     pkt1->pkt = *pkt;
268     pkt1->next = NULL;
269
270     pthread_mutex_lock(&q->mutex);
271
272     if (!q->last_pkt)
273
274         q->first_pkt = pkt1;
275     else
276         q->last_pkt->next = pkt1;
277     q->last_pkt = pkt1;
278     q->nb_packets++;
279     //q->size += pkt1->pkt.size + sizeof(*pkt1);
280     q->size += pkt1->pkt.size;
281     pthread_cond_signal(&q->cond);
282
283     pthread_mutex_unlock(&q->mutex);
284     return 0;
285 }
286
287 /* packet queue handling */
288 /* return < 0 if aborted, 0 if no packet and > 0 if packet.  */
289 int FFmpegExtractor::packet_queue_get(PacketQueue *q, AVPacket *pkt, int block)
290 {
291     AVPacketList *pkt1;
292     int ret;
293
294     pthread_mutex_lock(&q->mutex);
295
296     for (;;) {
297         if (q->abort_request) {
298             ret = -1;
299             break;
300         }
301
302         pkt1 = q->first_pkt;
303         if (pkt1) {
304             q->first_pkt = pkt1->next;
305             if (!q->first_pkt)
306                 q->last_pkt = NULL;
307             q->nb_packets--;
308             //q->size -= pkt1->pkt.size + sizeof(*pkt1);
309             q->size -= pkt1->pkt.size;
310             *pkt = pkt1->pkt;
311             av_free(pkt1);
312             ret = 1;
313             break;
314         } else if (!block) {
315             ret = 0;
316             break;
317         } else {
318             pthread_cond_wait(&q->cond, &q->mutex);
319         }
320     }
321     pthread_mutex_unlock(&q->mutex);
322     return ret;
323 }
324
325 static void EncodeSize14(uint8_t **_ptr, size_t size) {
326     CHECK_LE(size, 0x3fff);
327
328     uint8_t *ptr = *_ptr;
329
330     *ptr++ = 0x80 | (size >> 7);
331     *ptr++ = size & 0x7f;
332
333     *_ptr = ptr;
334 }
335
336 static sp<ABuffer> MakeMPEGVideoESDS(const sp<ABuffer> &csd) {
337     sp<ABuffer> esds = new ABuffer(csd->size() + 25);
338
339     uint8_t *ptr = esds->data();
340     *ptr++ = 0x03;
341     EncodeSize14(&ptr, 22 + csd->size());
342
343     *ptr++ = 0x00;  // ES_ID
344     *ptr++ = 0x00;
345
346     *ptr++ = 0x00;  // streamDependenceFlag, URL_Flag, OCRstreamFlag
347
348     *ptr++ = 0x04;
349     EncodeSize14(&ptr, 16 + csd->size());
350
351     *ptr++ = 0x40;  // Audio ISO/IEC 14496-3
352
353     for (size_t i = 0; i < 12; ++i) {
354         *ptr++ = 0x00;
355     }
356
357     *ptr++ = 0x05;
358     EncodeSize14(&ptr, csd->size());
359
360     memcpy(ptr, csd->data(), csd->size());
361
362     return esds;
363 }
364
365 // Returns the sample rate based on the sampling frequency index
366 static uint32_t get_sample_rate(const uint8_t sf_index)
367 {
368     static const uint32_t sample_rates[] =
369     {
370         96000, 88200, 64000, 48000, 44100, 32000,
371         24000, 22050, 16000, 12000, 11025, 8000
372     };
373
374     if (sf_index < sizeof(sample_rates) / sizeof(sample_rates[0])) {
375         return sample_rates[sf_index];
376     }
377
378     return 0;
379 }
380
381 int FFmpegExtractor::check_extradata(AVCodecContext *avctx)
382 {
383     const char *name;
384     bool *defersToCreateTrack;
385     AVBitStreamFilterContext **bsfc;
386
387     // init
388     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
389         bsfc = &mVideoBsfc;
390         defersToCreateTrack = &mDefersToCreateVideoTrack;
391     } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO){
392         bsfc = &mAudioBsfc;
393         defersToCreateTrack = &mDefersToCreateAudioTrack;
394     }
395
396     // ignore extradata
397     if (avctx->codec_id == CODEC_ID_MP3 ||
398             avctx->codec_id == CODEC_ID_MP1  ||
399             avctx->codec_id == CODEC_ID_MP2  ||
400             avctx->codec_id == CODEC_ID_AC3  ||
401             avctx->codec_id == CODEC_ID_H263  ||
402             avctx->codec_id == CODEC_ID_H263P ||
403             avctx->codec_id == CODEC_ID_H263I ||
404             avctx->codec_id == CODEC_ID_WMV1)
405         return 1;
406
407     // is extradata compatible with android?
408     if (avctx->codec_id != CODEC_ID_AAC) {
409         int is_compatible = is_extradata_compatible_with_android(avctx);
410         if (!is_compatible) {
411             LOGI("%s extradata is not compatible with android, should to extract it from bitstream",
412                     av_get_media_type_string(avctx->codec_type));
413             *defersToCreateTrack = true;
414             *bsfc = NULL; // H264 don't need bsfc, only AAC?
415             return 0;
416         }
417         return 1;
418     }
419
420     if (avctx->codec_id == CODEC_ID_AAC) {
421         name = "aac_adtstoasc";
422     }
423
424     if (avctx->extradata_size <= 0) {
425         LOGI("No %s extradata found, should to extract it from bitstream",
426                 av_get_media_type_string(avctx->codec_type));
427         *defersToCreateTrack = true;
428          //CHECK(name != NULL);
429         if (!*bsfc && name) {
430             *bsfc = av_bitstream_filter_init(name);
431             if (!*bsfc) {
432                 LOGE("Cannot open the %s BSF!", name);
433                 *defersToCreateTrack = false;
434                 return -1;
435             } else {
436                 LOGV("open the %s bsf", name);
437                 return 0;
438             }
439         } else {
440             return 0;
441         }
442     }
443     return 1;
444 }
445
446
447 int FFmpegExtractor::stream_component_open(int stream_index)
448 {
449     AVCodecContext *avctx;
450     sp<MetaData> meta;
451     bool isAVC = false;
452     bool supported = false;
453     uint32_t type;
454     const void *data;
455     size_t size;
456     int ret;
457
458     LOGI("stream_index: %d", stream_index);
459     if (stream_index < 0 || stream_index >= mFormatCtx->nb_streams)
460         return -1;
461     avctx = mFormatCtx->streams[stream_index]->codec;
462
463     switch(avctx->codec_id) {
464     case CODEC_ID_H264:
465     case CODEC_ID_MPEG4:
466     case CODEC_ID_H263:
467     case CODEC_ID_H263P:
468     case CODEC_ID_H263I:
469     case CODEC_ID_AAC:
470     case CODEC_ID_AC3:
471     case CODEC_ID_MP1:
472     case CODEC_ID_MP2:
473     case CODEC_ID_MP3:
474     case CODEC_ID_MPEG2VIDEO:
475     case CODEC_ID_WMV1:
476     case CODEC_ID_WMV2:
477     case CODEC_ID_WMV3:
478     case CODEC_ID_VC1:
479     case CODEC_ID_WMAV1:
480     case CODEC_ID_WMAV2:
481     case CODEC_ID_WMAPRO:
482     case CODEC_ID_WMALOSSLESS:
483     case CODEC_ID_RV40:
484         supported = true;
485         break;
486     default:
487         supported = false;
488         break;
489     }
490
491     if (!supported) {
492         LOGE("unsupport the codec, id: 0x%0x", avctx->codec_id);
493         return -1;
494     }
495     LOGV("support the codec");
496
497     unsigned streamType;
498     ssize_t index = mTracks.indexOfKey(stream_index);
499
500     if (index >= 0) {
501         LOGE("this track already exists");
502         return 0;
503     }
504
505     mFormatCtx->streams[stream_index]->discard = AVDISCARD_DEFAULT;
506
507     char tagbuf[32];
508     av_get_codec_tag_string(tagbuf, sizeof(tagbuf), avctx->codec_tag);
509     LOGV("Tag %s/0x%08x with codec id '%d'\n", tagbuf, avctx->codec_tag, avctx->codec_id);
510
511     switch (avctx->codec_type) {
512     case AVMEDIA_TYPE_VIDEO:
513         if (mVideoStreamIdx == -1)
514             mVideoStreamIdx = stream_index;
515         if (mVideoStream == NULL)
516             mVideoStream = mFormatCtx->streams[stream_index];
517         if (!mVideoQInited) {
518             packet_queue_init(&mVideoQ);
519             mVideoQInited = true;
520         }
521
522         ret = check_extradata(avctx);
523         if (ret != 1) {
524             if (ret == -1) {
525                 // disable the stream
526                 mVideoStreamIdx = -1;
527                 mVideoStream = NULL;
528                 packet_queue_end(&mVideoQ);
529                 mVideoQInited =  false;
530                 mFormatCtx->streams[stream_index]->discard = AVDISCARD_ALL;
531             }
532             return ret;
533          }
534
535         if (avctx->extradata) {
536             LOGV("video stream extradata:");
537             hexdump(avctx->extradata, avctx->extradata_size);
538         } else {
539             LOGV("video stream no extradata, but we can ignore it.");
540         }
541
542         meta = new MetaData;
543
544         switch(avctx->codec_id) {
545         case CODEC_ID_H264:
546             /**
547              * H.264 Video Types
548              * http://msdn.microsoft.com/en-us/library/dd757808(v=vs.85).aspx
549              */
550             //if (avctx->codec_tag && avctx->codec_tag == AV_RL32("avc1")) {
551             if (avctx->extradata[0] == 1 /* configurationVersion */) {
552                 // H.264 bitstream without start codes.
553                 isAVC = true;
554                 LOGV("AVC");
555
556                 if (avctx->width == 0 || avctx->height == 0) {
557                     int32_t width, height;
558                     sp<ABuffer> seqParamSet = new ABuffer(avctx->extradata_size - 8);
559                     memcpy(seqParamSet->data(), avctx->extradata + 8, avctx->extradata_size - 8);
560                     FindAVCDimensions(seqParamSet, &width, &height);
561                     avctx->width  = width;
562                     avctx->height = height;
563                 }
564
565                 meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
566                 meta->setData(kKeyAVCC, kTypeAVCC, avctx->extradata, avctx->extradata_size);
567             } else {
568                 // H.264 bitstream with start codes.
569                 isAVC = false;
570                 LOGV("H264");
571
572                 /* set NULL to release meta as we will new a meta in MakeAVCCodecSpecificData() fxn */
573                 meta->clear();
574                 meta = NULL;
575
576                 sp<ABuffer> buffer = new ABuffer(avctx->extradata_size);
577                 memcpy(buffer->data(), avctx->extradata, avctx->extradata_size);
578                 meta = MakeAVCCodecSpecificData(buffer);
579             }
580             break;
581         case CODEC_ID_MPEG4:
582             LOGV("MPEG4");
583             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4);
584             {
585                 sp<ABuffer> csd = new ABuffer(avctx->extradata_size);
586                 memcpy(csd->data(), avctx->extradata, avctx->extradata_size);
587                 sp<ABuffer> esds = MakeMPEGVideoESDS(csd);
588                 meta->setData(kKeyESDS, kTypeESDS, esds->data(), esds->size());
589             }
590             break;
591         case CODEC_ID_H263:
592         case CODEC_ID_H263P:
593         case CODEC_ID_H263I:
594             LOGV("H263");
595             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263);
596             break;
597         case CODEC_ID_MPEG2VIDEO:
598             LOGV("MPEG2VIDEO");
599             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG2);
600             {
601                 sp<ABuffer> csd = new ABuffer(avctx->extradata_size);
602                 memcpy(csd->data(), avctx->extradata, avctx->extradata_size);
603                 sp<ABuffer> esds = MakeMPEGVideoESDS(csd);
604                 meta->setData(kKeyESDS, kTypeESDS, esds->data(), esds->size());
605             }
606             break;
607         case CODEC_ID_VC1:
608             LOGV("VC1");
609             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_VC1);
610             meta->setData(kKeyRawCodecSpecificData, 0, avctx->extradata, avctx->extradata_size);
611             break;
612         case CODEC_ID_WMV1:
613             LOGV("WMV1");
614             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_WMV);
615             meta->setInt32(kKeyWMVVersion, kTypeWMVVer_7);
616             break;
617         case CODEC_ID_WMV2:
618             LOGV("WMV2");
619             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_WMV);
620             meta->setData(kKeyRawCodecSpecificData, 0, avctx->extradata, avctx->extradata_size);
621             meta->setInt32(kKeyWMVVersion, kTypeWMVVer_8);
622             break;
623         case CODEC_ID_WMV3:
624             LOGV("WMV3");
625             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_WMV);
626             meta->setData(kKeyRawCodecSpecificData, 0, avctx->extradata, avctx->extradata_size);
627             meta->setInt32(kKeyWMVVersion, kTypeWMVVer_9);
628             break;
629         case CODEC_ID_RV40:
630             LOGV("RV40");
631             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_RV);
632             meta->setData(kKeyRawCodecSpecificData, 0, avctx->extradata, avctx->extradata_size);
633             break;
634         default:
635             CHECK(!"Should not be here. Unsupported codec.");
636             break;
637         }
638
639         LOGI("width: %d, height: %d, bit_rate: %d", avctx->width, avctx->height, avctx->bit_rate);
640
641         meta->setInt32(kKeyWidth, avctx->width);
642         meta->setInt32(kKeyHeight, avctx->height);
643         if (avctx->bit_rate > 0)
644             meta->setInt32(kKeyBitRate, avctx->bit_rate);
645         if (mFormatCtx->duration != AV_NOPTS_VALUE)
646             meta->setInt64(kKeyDuration, mFormatCtx->duration);
647
648         LOGV("create a video track");
649         index = mTracks.add(
650             stream_index, new Track(this, meta, isAVC, mVideoStream, &mVideoQ));
651
652         mDefersToCreateVideoTrack = false;
653
654         break;
655     case AVMEDIA_TYPE_AUDIO:
656         if (mAudioStreamIdx == -1)
657             mAudioStreamIdx = stream_index;
658         if (mAudioStream == NULL)
659             mAudioStream = mFormatCtx->streams[stream_index];
660         if (!mAudioQInited) {
661             packet_queue_init(&mAudioQ);
662             mAudioQInited = true;
663         }
664
665         ret = check_extradata(avctx);
666         if (ret != 1) {
667             if (ret == -1) {
668                 // disable the stream
669                 mAudioStreamIdx = -1;
670                 mAudioStream = NULL;
671                 packet_queue_end(&mAudioQ);
672                 mAudioQInited =  false;
673                 mFormatCtx->streams[stream_index]->discard = AVDISCARD_ALL;
674             }
675             return ret;
676         }
677
678         if (avctx->extradata) {
679             LOGV("audio stream extradata:");
680             hexdump(avctx->extradata, avctx->extradata_size);
681         } else {
682             LOGV("audio stream no extradata, but we can ignore it.");
683         }
684
685         switch(avctx->codec_id) {
686         case CODEC_ID_MP1:
687             LOGV("MP1");
688             meta = new MetaData;
689             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_I);
690             break;
691         case CODEC_ID_MP2:
692             LOGV("MP2");
693             meta = new MetaData;
694             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_II);
695             break;
696         case CODEC_ID_MP3:
697             LOGV("MP3");
698             meta = new MetaData;
699             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_MPEG);
700             break;
701         case CODEC_ID_AC3:
702             LOGV("AC3");
703             meta = new MetaData;
704             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AC3);
705             break;
706         case CODEC_ID_AAC:
707             LOGV("AAC"); 
708             uint32_t sr;
709             const uint8_t *header;
710             uint8_t profile, sf_index, channel;
711
712             header = avctx->extradata;
713             CHECK(header != NULL);
714
715             // AudioSpecificInfo follows
716             // oooo offf fccc c000
717             // o - audioObjectType
718             // f - samplingFreqIndex
719             // c - channelConfig
720             profile = ((header[0] & 0xf8) >> 3) - 1;
721             sf_index = (header[0] & 0x07) << 1 | (header[1] & 0x80) >> 7;
722             sr = get_sample_rate(sf_index);
723             if (sr == 0) {
724                 LOGE("unsupport the sample rate");
725                 return -1;
726             }
727             channel = (header[1] >> 3) & 0xf;
728             LOGV("profile: %d, sf_index: %d, channel: %d", profile, sf_index, channel);
729
730             meta = MakeAACCodecSpecificData(profile, sf_index, channel);
731             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AAC);
732             break;
733         case CODEC_ID_WMAV1:  // TODO, version?
734             LOGV("WMAV1");
735             meta = new MetaData;
736             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_WMA);
737             meta->setData(kKeyRawCodecSpecificData, 0, avctx->extradata, avctx->extradata_size);
738             break;
739         case CODEC_ID_WMAV2:
740             LOGV("WMAV2");
741             meta = new MetaData;
742             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_WMA);
743             meta->setData(kKeyRawCodecSpecificData, 0, avctx->extradata, avctx->extradata_size);
744             meta->setInt32(kKeyWMAVersion, kTypeWMA);
745             break;
746         case CODEC_ID_WMAPRO:
747             LOGV("WMAPRO");
748             meta = new MetaData;
749             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_WMA);
750             meta->setData(kKeyRawCodecSpecificData, 0, avctx->extradata, avctx->extradata_size);
751             meta->setInt32(kKeyWMAVersion, kTypeWMAPro);
752             break;
753         case CODEC_ID_WMALOSSLESS:
754             LOGV("WMALOSSLESS");
755             meta = new MetaData;
756             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_WMA);
757             meta->setData(kKeyRawCodecSpecificData, 0, avctx->extradata, avctx->extradata_size);
758             meta->setInt32(kKeyWMAVersion, kTypeWMALossLess);
759             break;
760         default:
761             CHECK(!"Should not be here. Unsupported codec.");
762             break;
763         }
764
765         LOGI("bit_rate: %d, sample_rate: %d, channels: %d", avctx->bit_rate, avctx->sample_rate, avctx->channels);
766
767         meta->setInt32(kKeySampleRate, avctx->sample_rate);
768         meta->setInt32(kKeyChannelCount, avctx->channels);
769         meta->setInt32(kKeyBitRate, avctx->bit_rate);
770         if (mFormatCtx->duration != AV_NOPTS_VALUE)
771             meta->setInt64(kKeyDuration, mFormatCtx->duration);
772
773         LOGV("create a audio track");
774         index = mTracks.add(
775             stream_index, new Track(this, meta, false, mAudioStream, &mAudioQ));
776
777         mDefersToCreateAudioTrack = false;
778
779         break;
780     case AVMEDIA_TYPE_SUBTITLE:
781         /* Unsupport now */
782         CHECK(!"Should not be here. Unsupported media type.");
783         break;
784     default:
785         CHECK(!"Should not be here. Unsupported media type.");
786         break;
787     }
788     return 0;
789 }
790
791 void FFmpegExtractor::stream_component_close(int stream_index)
792 {
793     AVCodecContext *avctx;
794
795     if (stream_index < 0 || stream_index >= mFormatCtx->nb_streams)
796         return;
797     avctx = mFormatCtx->streams[stream_index]->codec;
798
799     switch (avctx->codec_type) {
800     case AVMEDIA_TYPE_VIDEO:
801         LOGV("packet_queue_abort videoq");
802         packet_queue_abort(&mVideoQ);
803         /* wait until the end */
804         while (!mAbortRequest && !mVideoEOSReceived) {
805             LOGV("wait for video received");
806             NamDelay(10);
807         }
808         LOGV("packet_queue_end videoq");
809         packet_queue_end(&mVideoQ);
810         break;
811     case AVMEDIA_TYPE_AUDIO:
812         LOGV("packet_queue_abort audioq");
813         packet_queue_abort(&mAudioQ);
814         while (!mAbortRequest && !mAudioEOSReceived) {
815             LOGV("wait for audio received");
816             NamDelay(10);
817         }
818         LOGV("packet_queue_end audioq");
819         packet_queue_end(&mAudioQ);
820         break;
821     case AVMEDIA_TYPE_SUBTITLE:
822         break;
823     default:
824         break;
825     }
826
827     mFormatCtx->streams[stream_index]->discard = AVDISCARD_ALL;
828     switch (avctx->codec_type) {
829     case AVMEDIA_TYPE_VIDEO:
830         mVideoStream    = NULL;
831         mVideoStreamIdx = -1;
832         if (mVideoBsfc) {
833             av_bitstream_filter_close(mVideoBsfc);
834             mVideoBsfc  = NULL;
835         }
836         break;
837     case AVMEDIA_TYPE_AUDIO:
838         mAudioStream    = NULL;
839         mAudioStreamIdx = -1;
840         if (mAudioBsfc) {
841             av_bitstream_filter_close(mAudioBsfc);
842             mAudioBsfc  = NULL;
843         }
844         break;
845     case AVMEDIA_TYPE_SUBTITLE:
846         break;
847     default:
848         break;
849     }
850 }
851
852 void FFmpegExtractor::reachedEOS(enum AVMediaType media_type)
853 {
854     Mutex::Autolock autoLock(mLock);
855
856     if (media_type == AVMEDIA_TYPE_VIDEO) {
857         mVideoEOSReceived = true;
858     } else if (media_type == AVMEDIA_TYPE_AUDIO) {
859         mAudioEOSReceived = true;
860     }
861 }
862
863 /* seek in the stream */
864 int FFmpegExtractor::stream_seek(int64_t pos, enum AVMediaType media_type)
865 {
866     Mutex::Autolock autoLock(mLock);
867
868     if (mVideoStreamIdx >= 0 &&
869         mAudioStreamIdx >= 0 &&
870         media_type == AVMEDIA_TYPE_AUDIO &&
871         !mVideoEOSReceived) {
872        return NO_SEEK;
873     }
874
875     // flush immediately
876     if (mAudioStreamIdx >= 0)
877         packet_queue_flush(&mAudioQ);
878     if (mVideoStreamIdx >= 0)
879         packet_queue_flush(&mVideoQ);
880
881     mSeekPos = pos;
882     mSeekFlags &= ~AVSEEK_FLAG_BYTE;
883     mSeekReq = 1;
884
885     return SEEK;
886 }
887
888 // staitc
889 int FFmpegExtractor::decode_interrupt_cb(void *ctx)
890 {
891     FFmpegExtractor *extrator = static_cast<FFmpegExtractor *>(ctx);
892     return extrator->mAbortRequest;
893 }
894
895 void FFmpegExtractor::print_error_ex(const char *filename, int err)
896 {
897     char errbuf[128];
898     const char *errbuf_ptr = errbuf;
899
900     if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
901         errbuf_ptr = strerror(AVUNERROR(err));
902     LOGI("%s: %s\n", filename, errbuf_ptr);
903 }
904
905 void FFmpegExtractor::setFFmpegDefaultOpts()
906 {
907     mGenPTS       = 0;
908 #if DIABLE_VIDEO
909     mVideoDisable = 1;
910 #else
911     mVideoDisable = 0;
912 #endif
913 #if DIABLE_AUDIO
914     mAudioDisable = 1;
915 #else
916     mAudioDisable = 0;
917 #endif
918     mShowStatus   = 1;
919     mSeekByBytes  = 0; /* seek by bytes 0=off 1=on -1=auto" */
920     mStartTime    = AV_NOPTS_VALUE;
921     mDuration     = AV_NOPTS_VALUE;
922     mSeekPos      = AV_NOPTS_VALUE;
923     mAutoExit     = 1;
924     mLoop         = 1;
925
926     mVideoStreamIdx = -1;
927     mAudioStreamIdx = -1;
928     mVideoStream  = NULL;
929     mAudioStream  = NULL;
930     mVideoQInited = false;
931     mAudioQInited = false;
932     mDefersToCreateVideoTrack = false;
933     mDefersToCreateAudioTrack = false;
934     mVideoBsfc = NULL;
935     mAudioBsfc = NULL;
936
937     mAbortRequest = 0;
938     mPaused       = 0;
939     mLastPaused   = 0;
940     mSeekReq      = 0;
941
942     mProbePkts    = 0;
943     mEOF          = false;
944 }
945
946 int FFmpegExtractor::initStreams()
947 {
948     int err, i;
949     status_t status;
950     int eof = 0;
951     int ret = 0, audio_ret = 0, video_ret = 0;
952     int pkt_in_play_range = 0;
953     AVDictionaryEntry *t;
954     AVDictionary **opts;
955     int orig_nb_streams;
956     int st_index[AVMEDIA_TYPE_NB] = {0};
957     int wanted_stream[AVMEDIA_TYPE_NB] = {0};
958     st_index[AVMEDIA_TYPE_AUDIO]  = -1;
959     st_index[AVMEDIA_TYPE_VIDEO]  = -1;
960     wanted_stream[AVMEDIA_TYPE_AUDIO]  = -1;
961     wanted_stream[AVMEDIA_TYPE_VIDEO]  = -1;
962
963     setFFmpegDefaultOpts();
964
965     status = initFFmpeg();
966     if (status != OK) {
967         ret = -1;
968         goto fail;
969     }
970
971     av_init_packet(&flush_pkt);
972     flush_pkt.data = (uint8_t *)"FLUSH";
973     flush_pkt.size = 0;
974
975     mFormatCtx = avformat_alloc_context();
976     mFormatCtx->interrupt_callback.callback = decode_interrupt_cb;
977     mFormatCtx->interrupt_callback.opaque = this;
978     LOGV("mFilename: %s", mFilename);
979     err = avformat_open_input(&mFormatCtx, mFilename, NULL, &format_opts);
980     if (err < 0) {
981         print_error_ex(mFilename, err);
982         ret = -1;
983         goto fail;
984     }
985     if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
986         LOGE("Option %s not found.\n", t->key);
987         //ret = AVERROR_OPTION_NOT_FOUND;
988         ret = -1;
989         goto fail;
990     }
991
992     if (mGenPTS)
993         mFormatCtx->flags |= AVFMT_FLAG_GENPTS;
994
995     opts = setup_find_stream_info_opts(mFormatCtx, codec_opts);
996     orig_nb_streams = mFormatCtx->nb_streams;
997
998     err = avformat_find_stream_info(mFormatCtx, opts);
999     if (err < 0) {
1000         LOGE("%s: could not find codec parameters\n", mFilename);
1001         ret = -1;
1002         goto fail;
1003     }
1004     for (i = 0; i < orig_nb_streams; i++)
1005         av_dict_free(&opts[i]);
1006     av_freep(&opts);
1007
1008     if (mFormatCtx->pb)
1009         mFormatCtx->pb->eof_reached = 0; // FIXME hack, ffplay maybe should not use url_feof() to test for the end
1010
1011     if (mSeekByBytes < 0)
1012         mSeekByBytes = !!(mFormatCtx->iformat->flags & AVFMT_TS_DISCONT);
1013
1014     /* if seeking requested, we execute it */
1015     if (mStartTime != AV_NOPTS_VALUE) {
1016         int64_t timestamp;
1017
1018         timestamp = mStartTime;
1019         /* add the stream start time */
1020         if (mFormatCtx->start_time != AV_NOPTS_VALUE)
1021             timestamp += mFormatCtx->start_time;
1022         ret = avformat_seek_file(mFormatCtx, -1, INT64_MIN, timestamp, INT64_MAX, 0);
1023         if (ret < 0) {
1024             LOGE("%s: could not seek to position %0.3f",
1025                     mFilename, (double)timestamp / AV_TIME_BASE);
1026             goto fail;
1027         }
1028     }
1029
1030     for (i = 0; i < mFormatCtx->nb_streams; i++)
1031         mFormatCtx->streams[i]->discard = AVDISCARD_ALL;
1032     if (!mVideoDisable)
1033         st_index[AVMEDIA_TYPE_VIDEO] =
1034             av_find_best_stream(mFormatCtx, AVMEDIA_TYPE_VIDEO,
1035                                 wanted_stream[AVMEDIA_TYPE_VIDEO], -1, NULL, 0);
1036     if (!mAudioDisable)
1037         st_index[AVMEDIA_TYPE_AUDIO] =
1038             av_find_best_stream(mFormatCtx, AVMEDIA_TYPE_AUDIO,
1039                                 wanted_stream[AVMEDIA_TYPE_AUDIO],
1040                                 st_index[AVMEDIA_TYPE_VIDEO],
1041                                 NULL, 0);
1042     if (mShowStatus) {
1043         av_dump_format(mFormatCtx, 0, mFilename, 0);
1044     }
1045
1046     if (mFormatCtx->duration != AV_NOPTS_VALUE) {
1047         int hours, mins, secs, us;
1048         secs = mFormatCtx->duration / AV_TIME_BASE;
1049         us = mFormatCtx->duration % AV_TIME_BASE;
1050         mins = secs / 60;
1051         secs %= 60;
1052         hours = mins / 60;
1053         mins %= 60;
1054         LOGI("the duration is %02d:%02d:%02d.%02d", hours, mins, secs, (100 * us) / AV_TIME_BASE);
1055     }
1056
1057     if (st_index[AVMEDIA_TYPE_AUDIO] >= 0) {
1058         audio_ret = stream_component_open(st_index[AVMEDIA_TYPE_AUDIO]);
1059     }
1060
1061     if (st_index[AVMEDIA_TYPE_VIDEO] >= 0) {
1062         video_ret = stream_component_open(st_index[AVMEDIA_TYPE_VIDEO]);
1063     }
1064
1065     if ( audio_ret < 0 && video_ret < 0) {
1066         LOGE("%s: could not open codecs\n", mFilename);
1067         ret = -1;
1068         goto fail;
1069     }
1070
1071     ret = 0;
1072
1073 fail:
1074     return ret;
1075 }
1076
1077 void FFmpegExtractor::deInitStreams()
1078 {
1079     if (mFormatCtx) {
1080         avformat_close_input(&mFormatCtx);
1081     }
1082
1083     deInitFFmpeg();
1084 }
1085
1086 status_t FFmpegExtractor::startReaderThread() {
1087     LOGV("Starting reader thread");
1088     Mutex::Autolock autoLock(mLock);
1089
1090     if (mReaderThreadStarted)
1091         return OK;
1092
1093     pthread_attr_t attr;
1094     pthread_attr_init(&attr);
1095     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1096     pthread_create(&mReaderThread, &attr, ReaderWrapper, this);
1097     pthread_attr_destroy(&attr);
1098     mReaderThreadStarted = true;
1099     LOGD("Reader thread started");
1100
1101     return OK;
1102 }
1103
1104 void FFmpegExtractor::stopReaderThread() {
1105     LOGV("Stopping reader thread");
1106     Mutex::Autolock autoLock(mLock);
1107
1108     if (!mReaderThreadStarted) {
1109         LOGD("Reader thread have been stopped");
1110         return;
1111     }
1112
1113     mAbortRequest = 1;
1114
1115     void *dummy;
1116     pthread_join(mReaderThread, &dummy);
1117     mReaderThreadStarted = false;
1118     LOGD("Reader thread stopped");
1119 }
1120
1121 // static
1122 void *FFmpegExtractor::ReaderWrapper(void *me) {
1123     ((FFmpegExtractor *)me)->readerEntry();
1124
1125     return NULL;
1126 }
1127
1128 void FFmpegExtractor::readerEntry() {
1129     int err, i, ret;
1130     AVPacket pkt1, *pkt = &pkt1;
1131     int eof = 0;
1132     int pkt_in_play_range = 0;
1133
1134     LOGV("FFmpegExtractor::readerEntry");
1135
1136     mVideoEOSReceived = false;
1137     mAudioEOSReceived = false;
1138
1139     for (;;) {
1140         if (mAbortRequest)
1141             break;
1142
1143         if (mPaused != mLastPaused) {
1144             mLastPaused = mPaused;
1145             if (mPaused)
1146                 mReadPauseReturn = av_read_pause(mFormatCtx);
1147             else
1148                 av_read_play(mFormatCtx);
1149         }
1150 #if CONFIG_RTSP_DEMUXER || CONFIG_MMSH_PROTOCOL
1151         if (mPaused &&
1152                 (!strcmp(mFormatCtx->iformat->name, "rtsp") ||
1153                  (mFormatCtx->pb && !strncmp(mFilename, "mmsh:", 5)))) {
1154             /* wait 10 ms to avoid trying to get another packet */
1155             /* XXX: horrible */
1156             NamDelay(10);
1157             continue;
1158         }
1159 #endif
1160
1161         if (mSeekReq) {
1162             LOGV("readerEntry, mSeekReq: %d", mSeekReq);
1163             ret = avformat_seek_file(mFormatCtx, -1, INT64_MIN, mSeekPos, INT64_MAX, mSeekFlags);
1164             if (ret < 0) {
1165                 LOGE("%s: error while seeking", mFormatCtx->filename);
1166             } else {
1167                 if (mAudioStreamIdx >= 0) {
1168                     packet_queue_flush(&mAudioQ);
1169                     packet_queue_put(&mAudioQ, &flush_pkt);
1170                 }
1171                 if (mVideoStreamIdx >= 0) {
1172                     packet_queue_flush(&mVideoQ);
1173                     packet_queue_put(&mVideoQ, &flush_pkt);
1174                 }
1175             }
1176             mSeekReq = 0;
1177             eof = 0;
1178         }
1179
1180         /* if the queue are full, no need to read more */
1181         if (   mAudioQ.size + mVideoQ.size > MAX_QUEUE_SIZE
1182             || (   (mAudioQ   .size  > MIN_AUDIOQ_SIZE || mAudioStreamIdx < 0)
1183                 && (mVideoQ   .nb_packets > MIN_FRAMES || mVideoStreamIdx < 0))) {
1184 #if DEBUG_READ_ENTRY
1185             LOGV("readerEntry, is full, fuck");
1186 #endif
1187             /* wait 10 ms */
1188             NamDelay(10);
1189             continue;
1190         }
1191
1192         if (eof) {
1193             if (mVideoStreamIdx >= 0) {
1194                 av_init_packet(pkt);
1195                 pkt->data = NULL;
1196                 pkt->size = 0;
1197                 pkt->stream_index = mVideoStreamIdx;
1198                 packet_queue_put(&mVideoQ, pkt);
1199             }
1200             if (mAudioStreamIdx >= 0) {
1201                 av_init_packet(pkt);
1202                 pkt->data = NULL;
1203                 pkt->size = 0;
1204                 pkt->stream_index = mAudioStreamIdx;
1205                 packet_queue_put(&mAudioQ, pkt);
1206             }
1207             NamDelay(10);
1208 #if DEBUG_READ_ENTRY
1209             LOGV("readerEntry, eof = 1, mVideoQ.size: %d, mVideoQ.nb_packets: %d, mAudioQ.size: %d, mAudioQ.nb_packets: %d",
1210                     mVideoQ.size, mVideoQ.nb_packets, mAudioQ.size, mAudioQ.nb_packets);
1211 #endif
1212             if (mAudioQ.size + mVideoQ.size  == 0) {
1213                 if (mLoop != 1 && (!mLoop || --mLoop)) {
1214                     if (mVideoStreamIdx >= 0) {
1215                         stream_seek(mStartTime != AV_NOPTS_VALUE ? mStartTime : 0, AVMEDIA_TYPE_VIDEO);
1216                     } else if (mAudioStreamIdx >= 0) {
1217                         stream_seek(mStartTime != AV_NOPTS_VALUE ? mStartTime : 0, AVMEDIA_TYPE_AUDIO);
1218                     }
1219                 } else if (mAutoExit) {
1220                     ret = AVERROR_EOF;
1221                     goto fail;
1222                 }
1223             }
1224             eof=0;
1225             continue;
1226         }
1227
1228         ret = av_read_frame(mFormatCtx, pkt);
1229         mProbePkts++;
1230         if (ret < 0) {
1231             if (ret == AVERROR_EOF || url_feof(mFormatCtx->pb))
1232                 if (ret == AVERROR_EOF) {
1233                     //LOGV("ret == AVERROR_EOF");
1234                 }
1235                 if (url_feof(mFormatCtx->pb)) {
1236                     //LOGV("url_feof(mFormatCtx->pb)");
1237                 }
1238
1239                 eof = 1;
1240                 mEOF = true;
1241             if (mFormatCtx->pb && mFormatCtx->pb->error) {
1242                 LOGE("mFormatCtx->pb->error: %d", mFormatCtx->pb->error);
1243                 break;
1244             }
1245             NamDelay(100);
1246             continue;
1247         }
1248
1249         if (pkt->stream_index == mVideoStreamIdx) {
1250              if (mDefersToCreateVideoTrack) {
1251                 AVCodecContext *avctx = mFormatCtx->streams[mVideoStreamIdx]->codec;
1252
1253                 int i = parser_split(avctx, pkt->data, pkt->size);
1254                 if (i > 0 && i < FF_MAX_EXTRADATA_SIZE) {
1255                     if (avctx->extradata)
1256                         av_freep(&avctx->extradata);
1257                     avctx->extradata_size= i;
1258                     avctx->extradata = (uint8_t *)av_malloc(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
1259                     if (!avctx->extradata) {
1260                         //return AVERROR(ENOMEM);
1261                         ret = AVERROR(ENOMEM);
1262                         goto fail;
1263                     }
1264                     // sps + pps(there may be sei in it)
1265                     memcpy(avctx->extradata, pkt->data, avctx->extradata_size);
1266                     memset(avctx->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
1267                 } else {
1268                     av_free_packet(pkt);
1269                     continue;
1270                 }
1271
1272                 stream_component_open(mVideoStreamIdx);
1273                 if (!mDefersToCreateVideoTrack)
1274                     LOGI("probe packet counter: %d when create video track ok", mProbePkts);
1275                 if (mProbePkts == EXTRACTOR_MAX_PROBE_PACKETS)
1276                     LOGI("probe packet counter to max: %d, create video track: %d",
1277                         mProbePkts, !mDefersToCreateVideoTrack);
1278             }
1279         } else if (pkt->stream_index == mAudioStreamIdx) {
1280             int ret;
1281             uint8_t *outbuf;
1282             int   outbuf_size;
1283             AVCodecContext *avctx = mFormatCtx->streams[mAudioStreamIdx]->codec;
1284             if (mAudioBsfc && pkt && pkt->data) {
1285                 ret = av_bitstream_filter_filter(mAudioBsfc, avctx, NULL, &outbuf, &outbuf_size,
1286                                    pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY);
1287
1288                 if (ret < 0 ||!outbuf_size) {
1289                     av_free_packet(pkt);
1290                     continue;
1291                 }
1292                 if (outbuf && outbuf != pkt->data) {
1293                     memmove(pkt->data, outbuf, outbuf_size);
1294                     pkt->size = outbuf_size;
1295                 }
1296             }
1297             if (mDefersToCreateAudioTrack) {
1298                 if (avctx->extradata_size <= 0) {
1299                     av_free_packet(pkt);
1300                     continue;
1301                 }
1302                 stream_component_open(mAudioStreamIdx);
1303                 if (!mDefersToCreateAudioTrack)
1304                     LOGI("probe packet counter: %d when create audio track ok", mProbePkts);
1305                 if (mProbePkts == EXTRACTOR_MAX_PROBE_PACKETS)
1306                     LOGI("probe packet counter to max: %d, create audio track: %d",
1307                         mProbePkts, !mDefersToCreateAudioTrack);
1308             }
1309         }
1310
1311         /* check if packet is in play range specified by user, then queue, otherwise discard */
1312         pkt_in_play_range = mDuration == AV_NOPTS_VALUE ||
1313                 (pkt->pts - mFormatCtx->streams[pkt->stream_index]->start_time) *
1314                 av_q2d(mFormatCtx->streams[pkt->stream_index]->time_base) -
1315                 (double)(mStartTime != AV_NOPTS_VALUE ? mStartTime : 0) / 1000000
1316                 <= ((double)mDuration / 1000000);
1317         if (pkt->stream_index == mAudioStreamIdx && pkt_in_play_range) {
1318             packet_queue_put(&mAudioQ, pkt);
1319         } else if (pkt->stream_index == mVideoStreamIdx && pkt_in_play_range) {
1320             packet_queue_put(&mVideoQ, pkt);
1321         } else {
1322             av_free_packet(pkt);
1323         }
1324     }
1325     /* wait until the end */
1326     while (!mAbortRequest) {
1327         NamDelay(100);
1328     }
1329
1330     ret = 0;
1331 fail:
1332     LOGI("reader thread goto end...");
1333
1334     /* close each stream */
1335     if (mAudioStreamIdx >= 0)
1336         stream_component_close(mAudioStreamIdx);
1337     if (mVideoStreamIdx >= 0)
1338         stream_component_close(mVideoStreamIdx);
1339     if (mFormatCtx) {
1340         avformat_close_input(&mFormatCtx);
1341     }
1342 }
1343
1344 ////////////////////////////////////////////////////////////////////////////////
1345
1346 FFmpegExtractor::Track::Track(
1347         const sp<FFmpegExtractor> &extractor, sp<MetaData> meta, bool isAVC,
1348           AVStream *stream, PacketQueue *queue)
1349     : mExtractor(extractor),
1350       mMeta(meta),
1351       mIsAVC(isAVC),
1352       mStream(stream),
1353       mQueue(queue) {
1354     const char *mime;
1355
1356     /* H.264 Video Types */
1357     {
1358         mNal2AnnexB = false;
1359
1360         if (mIsAVC) {
1361             uint32_t type;
1362             const void *data;
1363             size_t size;
1364             CHECK(meta->findData(kKeyAVCC, &type, &data, &size));
1365
1366             const uint8_t *ptr = (const uint8_t *)data;
1367
1368             CHECK(size >= 7);
1369             CHECK_EQ((unsigned)ptr[0], 1u);  // configurationVersion == 1
1370
1371             // The number of bytes used to encode the length of a NAL unit.
1372             mNALLengthSize = 1 + (ptr[4] & 3);
1373
1374             LOGV("the stream is AVC, the length of a NAL unit: %d", mNALLengthSize);
1375
1376             mNal2AnnexB = true;
1377         }
1378     }
1379
1380     mMediaType = mStream->codec->codec_type;
1381 }
1382
1383 FFmpegExtractor::Track::~Track() {
1384 }
1385
1386 status_t FFmpegExtractor::Track::start(MetaData *params) {
1387     Mutex::Autolock autoLock(mLock);
1388     //mExtractor->startReaderThread();
1389     return OK;
1390 }
1391
1392 status_t FFmpegExtractor::Track::stop() {
1393     Mutex::Autolock autoLock(mLock);
1394     mExtractor->stopReaderThread();
1395     return OK;
1396 }
1397
1398 sp<MetaData> FFmpegExtractor::Track::getFormat() {
1399     Mutex::Autolock autoLock(mLock);
1400
1401     return mMeta;
1402 }
1403
1404 status_t FFmpegExtractor::Track::read(
1405         MediaBuffer **buffer, const ReadOptions *options) {
1406     *buffer = NULL;
1407
1408     Mutex::Autolock autoLock(mLock);
1409
1410     AVPacket pkt;
1411     bool seeking = false;
1412     bool waitKeyPkt = false;
1413     ReadOptions::SeekMode mode;
1414     int64_t pktTS = AV_NOPTS_VALUE;
1415     int64_t seekTimeUs = AV_NOPTS_VALUE;
1416     int64_t timeUs;
1417     int key;
1418     status_t status = OK;
1419
1420     if (options && options->getSeekTo(&seekTimeUs, &mode)) {
1421         LOGV("~~~%s seekTimeUs: %lld, mode: %d", av_get_media_type_string(mMediaType), seekTimeUs, mode);
1422         if (mExtractor->stream_seek(seekTimeUs, mMediaType) == SEEK)
1423             seeking = true;
1424     }
1425
1426 retry:
1427     if (mExtractor->packet_queue_get(mQueue, &pkt, 1) < 0) {
1428         mExtractor->reachedEOS(mMediaType);
1429         return ERROR_END_OF_STREAM;
1430     }
1431
1432     if (seeking) {
1433         if (pkt.data != flush_pkt.data) {
1434             av_free_packet(&pkt);
1435             goto retry;
1436         } else {
1437             seeking = false;
1438 #if WAIT_KEY_PACKET_AFTER_SEEK
1439             waitKeyPkt = true;
1440 #endif
1441         }
1442     }
1443
1444     if (pkt.data == flush_pkt.data) {
1445         LOGV("read %s flush pkt", av_get_media_type_string(mMediaType));
1446         av_free_packet(&pkt);
1447         goto retry;
1448     } else if (pkt.data == NULL && pkt.size == 0) {
1449         LOGV("read %s eos pkt", av_get_media_type_string(mMediaType));
1450         av_free_packet(&pkt);
1451         mExtractor->reachedEOS(mMediaType);
1452         return ERROR_END_OF_STREAM;
1453     }
1454
1455     key = pkt.flags & AV_PKT_FLAG_KEY ? 1 : 0;
1456
1457     if (waitKeyPkt) {
1458         if (!key) {
1459             LOGV("drop the no key packet");
1460             av_free_packet(&pkt);
1461             goto retry;
1462         } else {
1463             LOGV("~~~~~~ got the key packet");
1464             waitKeyPkt = false;
1465         }
1466     }
1467      
1468     MediaBuffer *mediaBuffer = new MediaBuffer(pkt.size + FF_INPUT_BUFFER_PADDING_SIZE);
1469     mediaBuffer->meta_data()->clear();
1470     mediaBuffer->set_range(0, pkt.size);
1471 #if DISABLE_NAL_TO_ANNEXB
1472     mNal2AnnexB = false;
1473 #endif
1474     if (mIsAVC && mNal2AnnexB) {
1475         /* Convert H.264 NAL format to annex b */
1476         if (mNALLengthSize >= 3 && mNALLengthSize <= 4 )
1477         {
1478             uint8_t *dst = (uint8_t *)mediaBuffer->data();
1479
1480             /* This only works for NAL sizes 3-4 */
1481             size_t len = pkt.size, i;
1482             uint8_t *ptr = pkt.data;
1483             while (len >= mNALLengthSize) {
1484                 uint32_t nal_len = 0;
1485                 for( i = 0; i < mNALLengthSize; i++ ) {
1486                     nal_len = (nal_len << 8) | ptr[i];
1487                     dst[i] = 0;
1488                 }
1489                 dst[mNALLengthSize - 1] = 1;
1490                 if (nal_len > INT_MAX || nal_len > (unsigned int)len) {
1491                     status = ERROR_MALFORMED;
1492                     break;
1493                 }
1494                 dst += mNALLengthSize;
1495                 ptr += mNALLengthSize;
1496                 len -= mNALLengthSize;
1497
1498                 memcpy(dst, ptr, nal_len);
1499
1500                 dst += nal_len;
1501                 ptr += nal_len;
1502                 len -= nal_len;
1503             }
1504         } else {
1505              status = ERROR_MALFORMED;
1506         }
1507
1508         if (status != OK) {
1509             LOGV("status != OK");
1510             mediaBuffer->release();
1511             mediaBuffer = NULL;
1512             av_free_packet(&pkt);
1513             return ERROR_MALFORMED;
1514         }
1515     } else {
1516         memcpy(mediaBuffer->data(), pkt.data, pkt.size);
1517     }
1518
1519     pktTS = pkt.pts;
1520     // use dts when AVI
1521     if (pkt.pts == AV_NOPTS_VALUE)
1522         pktTS = pkt.dts;
1523
1524 #if 0
1525     // TODO, Stagefright can't handle negative timestamps
1526     // if needed, work around this by offsetting them manually?
1527     if (pktTS < 0)
1528         pktTS = 0;
1529 #endif
1530
1531     timeUs = (int64_t)(pktTS * av_q2d(mStream->time_base) * 1000000);
1532
1533 #if 0
1534     LOGV("read %s pkt, size: %d, key: %d, pts: %lld, dts: %lld, timeUs: %llu us (%.2f secs)",
1535         av_get_media_type_string(mMediaType), pkt.size, key, pkt.pts, pkt.dts, timeUs, timeUs/1E6);
1536 #endif
1537
1538 #if 0
1539     // TODO, Stagefright can't handle negative timestamps
1540     // if needed, work around this by offsetting them manually?
1541     if (timeUs < 0)
1542         timeUs = 0;
1543 #endif
1544
1545     mediaBuffer->meta_data()->setInt64(kKeyTime, timeUs);
1546     mediaBuffer->meta_data()->setInt32(kKeyIsSyncFrame, key);
1547
1548     *buffer = mediaBuffer;
1549
1550     av_free_packet(&pkt);
1551
1552     return OK;
1553 }
1554
1555 ////////////////////////////////////////////////////////////////////////////////
1556
1557 // LegacySniffFFMPEG
1558 typedef struct {
1559     const char *extension;
1560     const char *container;
1561 } extmap;
1562
1563 static extmap FILE_EXTS[] = {
1564         {".mp4", MEDIA_MIMETYPE_CONTAINER_MPEG4},
1565         {".3gp", MEDIA_MIMETYPE_CONTAINER_MPEG4},
1566         {".mp3", MEDIA_MIMETYPE_AUDIO_MPEG},
1567         {".mov", MEDIA_MIMETYPE_CONTAINER_MOV},
1568         {".mkv", MEDIA_MIMETYPE_CONTAINER_MATROSKA},
1569         {".ts",  MEDIA_MIMETYPE_CONTAINER_TS},
1570         {".avi", MEDIA_MIMETYPE_CONTAINER_AVI},
1571         {".asf", MEDIA_MIMETYPE_CONTAINER_ASF},
1572         {".rm ", MEDIA_MIMETYPE_CONTAINER_RM},
1573 #if 0
1574         {".wmv", MEDIA_MIMETYPE_CONTAINER_WMV},
1575         {".wma", MEDIA_MIMETYPE_CONTAINER_WMA},
1576         {".mpg", MEDIA_MIMETYPE_CONTAINER_MPG},
1577         {".flv", MEDIA_MIMETYPE_CONTAINER_FLV},
1578         {".divx", MEDIA_MIMETYPE_CONTAINER_DIVX},
1579         {".mp2", MEDIA_MIMETYPE_CONTAINER_MP2},
1580         {".ape", MEDIA_MIMETYPE_CONTAINER_APE},
1581         {".ra",  MEDIA_MIMETYPE_CONTAINER_RA},
1582 #endif
1583 };
1584
1585 const char *LegacySniffFFMPEG(const char * uri)
1586 {
1587     size_t i;
1588     const char *container = NULL;
1589
1590     LOGI("list the file extensions suppoted by ffmpeg: ");
1591     LOGI("========================================");
1592     for (i = 0; i < NELEM(FILE_EXTS); ++i) {
1593             LOGV("file_exts[%02d]: %s", i, FILE_EXTS[i].extension);
1594     }
1595     LOGI("========================================");
1596
1597     int lenURI = strlen(uri);
1598     for (i = 0; i < NELEM(FILE_EXTS); ++i) {
1599         int len = strlen(FILE_EXTS[i].extension);
1600         int start = lenURI - len;
1601         if (start > 0) {
1602             if (!av_strncasecmp(uri + start, FILE_EXTS[i].extension, len)) {
1603                 container = FILE_EXTS[i].container;
1604                 break;
1605             }
1606         }
1607     }
1608
1609     return container;
1610 }
1611
1612 // BetterSniffFFMPEG
1613 typedef struct {
1614     const char *format;
1615     const char *container;
1616 } formatmap;
1617
1618 static formatmap FILE_FORMATS[] = {
1619         {"mpegts",                  MEDIA_MIMETYPE_CONTAINER_TS},
1620         {"mov,mp4,m4a,3gp,3g2,mj2", MEDIA_MIMETYPE_CONTAINER_MOV},
1621         {"asf",                     MEDIA_MIMETYPE_CONTAINER_ASF},
1622         {"rm",                      MEDIA_MIMETYPE_CONTAINER_RM},
1623 };
1624
1625 const char *BetterSniffFFMPEG(const char * uri)
1626 {
1627     size_t i;
1628     const char *container = NULL;
1629     AVFormatContext *ic = NULL;
1630
1631     status_t status = initFFmpeg();
1632     if (status != OK) {
1633         LOGE("could not init ffmpeg");
1634         return false;
1635     }
1636
1637     ic = avformat_alloc_context();
1638     avformat_open_input(&ic, uri, NULL, NULL);
1639
1640     av_dump_format(ic, 0, uri, 0);
1641
1642     LOGI("FFmpegExtrator, uri: %s, format_name: %s, format_long_name: %s", uri, ic->iformat->name, ic->iformat->long_name);
1643
1644     LOGI("list the format suppoted by ffmpeg: ");
1645     LOGI("========================================");
1646     for (i = 0; i < NELEM(FILE_FORMATS); ++i) {
1647             LOGV("format_names[%02d]: %s", i, FILE_FORMATS[i].format);
1648     }
1649     LOGI("========================================");
1650
1651     for (i = 0; i < NELEM(FILE_FORMATS); ++i) {
1652         int len = strlen(FILE_FORMATS[i].format);
1653         if (!av_strncasecmp(ic->iformat->name, FILE_FORMATS[i].format, len)) {
1654             container = FILE_FORMATS[i].container;
1655             break;
1656         }
1657     }
1658
1659     avformat_close_input(&ic);
1660     av_free(ic);
1661
1662     return container;
1663 }
1664
1665 bool SniffFFMPEG(
1666         const sp<DataSource> &source, String8 *mimeType, float *confidence,
1667         sp<AMessage> *meta) {
1668     LOGV("SniffFFMPEG");
1669     const char *uri, *container = NULL;
1670
1671     uri = source->getNamURI();
1672
1673     if (!uri)
1674         return false;
1675
1676     LOGI("ffmpeg uri: %s", uri);
1677
1678     container = BetterSniffFFMPEG(uri);
1679     if (!container) {
1680         LOGW("sniff through LegacySniffFFMPEG, only check the file extension");
1681         container = LegacySniffFFMPEG(uri);
1682     }
1683
1684     if (container == NULL)
1685         return false;
1686
1687     LOGV("found container: %s", container);
1688
1689     *confidence = 0.88f;  // Slightly larger than other extractor's confidence
1690     mimeType->setTo(container);
1691
1692     /* use MPEG4Extractor(not extended extractor) for HTTP source only */
1693     if (!av_strcasecmp(container, MEDIA_MIMETYPE_CONTAINER_MPEG4)
1694             && (source->flags() & DataSource::kIsCachingDataSource)) {
1695             return true;
1696     }
1697
1698     *meta = new AMessage;
1699     (*meta)->setString("extended-extractor", "extended-extractor");
1700     (*meta)->setString("extended-extractor-subtype", "ffmpegextractor");
1701
1702     return true;
1703 }
1704
1705 }  // namespace android