OSDN Git Service

fix debug info about WMV3
[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         supported = true;
484         break;
485     default:
486         supported = false;
487         break;
488     }
489
490     if (!supported) {
491         LOGE("unsupport the codec, id: 0x%0x", avctx->codec_id);
492         return -1;
493     }
494     LOGV("support the codec");
495
496     unsigned streamType;
497     ssize_t index = mTracks.indexOfKey(stream_index);
498
499     if (index >= 0) {
500         LOGE("this track already exists");
501         return 0;
502     }
503
504     mFormatCtx->streams[stream_index]->discard = AVDISCARD_DEFAULT;
505
506     char tagbuf[32];
507     av_get_codec_tag_string(tagbuf, sizeof(tagbuf), avctx->codec_tag);
508     LOGV("Tag %s/0x%08x with codec id '%d'\n", tagbuf, avctx->codec_tag, avctx->codec_id);
509
510     switch (avctx->codec_type) {
511     case AVMEDIA_TYPE_VIDEO:
512         if (mVideoStreamIdx == -1)
513             mVideoStreamIdx = stream_index;
514         if (mVideoStream == NULL)
515             mVideoStream = mFormatCtx->streams[stream_index];
516         if (!mVideoQInited) {
517             packet_queue_init(&mVideoQ);
518             mVideoQInited = true;
519         }
520
521         ret = check_extradata(avctx);
522         if (ret != 1) {
523             if (ret == -1) {
524                 // disable the stream
525                 mVideoStreamIdx = -1;
526                 mVideoStream = NULL;
527                 packet_queue_end(&mVideoQ);
528                 mVideoQInited =  false;
529                 mFormatCtx->streams[stream_index]->discard = AVDISCARD_ALL;
530             }
531             return ret;
532          }
533
534         if (avctx->extradata) {
535             LOGV("video stream extradata:");
536             hexdump(avctx->extradata, avctx->extradata_size);
537         } else {
538             LOGV("video stream no extradata, but we can ignore it.");
539         }
540
541         meta = new MetaData;
542
543         switch(avctx->codec_id) {
544         case CODEC_ID_H264:
545             /**
546              * H.264 Video Types
547              * http://msdn.microsoft.com/en-us/library/dd757808(v=vs.85).aspx
548              */
549             //if (avctx->codec_tag && avctx->codec_tag == AV_RL32("avc1")) {
550             if (avctx->extradata[0] == 1 /* configurationVersion */) {
551                 // H.264 bitstream without start codes.
552                 isAVC = true;
553                 LOGV("AVC");
554
555                 if (avctx->width == 0 || avctx->height == 0) {
556                     int32_t width, height;
557                     sp<ABuffer> seqParamSet = new ABuffer(avctx->extradata_size - 8);
558                     memcpy(seqParamSet->data(), avctx->extradata + 8, avctx->extradata_size - 8);
559                     FindAVCDimensions(seqParamSet, &width, &height);
560                     avctx->width  = width;
561                     avctx->height = height;
562                 }
563
564                 meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
565                 meta->setData(kKeyAVCC, kTypeAVCC, avctx->extradata, avctx->extradata_size);
566             } else {
567                 // H.264 bitstream with start codes.
568                 isAVC = false;
569                 LOGV("H264");
570
571                 /* set NULL to release meta as we will new a meta in MakeAVCCodecSpecificData() fxn */
572                 meta->clear();
573                 meta = NULL;
574
575                 sp<ABuffer> buffer = new ABuffer(avctx->extradata_size);
576                 memcpy(buffer->data(), avctx->extradata, avctx->extradata_size);
577                 meta = MakeAVCCodecSpecificData(buffer);
578             }
579             break;
580         case CODEC_ID_MPEG4:
581             LOGV("MPEG4");
582             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4);
583             {
584                 sp<ABuffer> csd = new ABuffer(avctx->extradata_size);
585                 memcpy(csd->data(), avctx->extradata, avctx->extradata_size);
586                 sp<ABuffer> esds = MakeMPEGVideoESDS(csd);
587                 meta->setData(kKeyESDS, kTypeESDS, esds->data(), esds->size());
588             }
589             break;
590         case CODEC_ID_H263:
591         case CODEC_ID_H263P:
592         case CODEC_ID_H263I:
593             LOGV("H263");
594             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263);
595             break;
596         case CODEC_ID_MPEG2VIDEO:
597             LOGV("MPEG2VIDEO");
598             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG2);
599             {
600                 sp<ABuffer> csd = new ABuffer(avctx->extradata_size);
601                 memcpy(csd->data(), avctx->extradata, avctx->extradata_size);
602                 sp<ABuffer> esds = MakeMPEGVideoESDS(csd);
603                 meta->setData(kKeyESDS, kTypeESDS, esds->data(), esds->size());
604             }
605             break;
606         case CODEC_ID_VC1:
607             LOGV("VC1");
608             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_WMV);
609             meta->setData(kKeyRawCodecSpecificData, 0, avctx->extradata, avctx->extradata_size);
610             //meta->setInt32(kKeyWMVVersion, kTypeVC1); // TODO
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         default:
630             CHECK(!"Should not be here. Unsupported codec.");
631             break;
632         }
633
634         LOGI("width: %d, height: %d, bit_rate: %d", avctx->width, avctx->height, avctx->bit_rate);
635
636         meta->setInt32(kKeyWidth, avctx->width);
637         meta->setInt32(kKeyHeight, avctx->height);
638         if (avctx->bit_rate > 0)
639             meta->setInt32(kKeyBitRate, avctx->bit_rate);
640         if (mFormatCtx->duration != AV_NOPTS_VALUE)
641             meta->setInt64(kKeyDuration, mFormatCtx->duration);
642
643         LOGV("create a video track");
644         index = mTracks.add(
645             stream_index, new Track(this, meta, isAVC, mVideoStream, &mVideoQ));
646
647         mDefersToCreateVideoTrack = false;
648
649         break;
650     case AVMEDIA_TYPE_AUDIO:
651         if (mAudioStreamIdx == -1)
652             mAudioStreamIdx = stream_index;
653         if (mAudioStream == NULL)
654             mAudioStream = mFormatCtx->streams[stream_index];
655         if (!mAudioQInited) {
656             packet_queue_init(&mAudioQ);
657             mAudioQInited = true;
658         }
659
660         ret = check_extradata(avctx);
661         if (ret != 1) {
662             if (ret == -1) {
663                 // disable the stream
664                 mAudioStreamIdx = -1;
665                 mAudioStream = NULL;
666                 packet_queue_end(&mAudioQ);
667                 mAudioQInited =  false;
668                 mFormatCtx->streams[stream_index]->discard = AVDISCARD_ALL;
669             }
670             return ret;
671         }
672
673         if (avctx->extradata) {
674             LOGV("audio stream extradata:");
675             hexdump(avctx->extradata, avctx->extradata_size);
676         } else {
677             LOGV("audio stream no extradata, but we can ignore it.");
678         }
679
680         switch(avctx->codec_id) {
681         case CODEC_ID_MP1:
682             LOGV("MP1");
683             meta = new MetaData;
684             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_I);
685             break;
686         case CODEC_ID_MP2:
687             LOGV("MP2");
688             meta = new MetaData;
689             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_II);
690             break;
691         case CODEC_ID_MP3:
692             LOGV("MP3");
693             meta = new MetaData;
694             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_MPEG);
695             break;
696         case CODEC_ID_AC3:
697             LOGV("AC3");
698             meta = new MetaData;
699             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AC3);
700             break;
701         case CODEC_ID_AAC:
702             LOGV("AAC"); 
703             uint32_t sr;
704             const uint8_t *header;
705             uint8_t profile, sf_index, channel;
706
707             header = avctx->extradata;
708             CHECK(header != NULL);
709
710             // AudioSpecificInfo follows
711             // oooo offf fccc c000
712             // o - audioObjectType
713             // f - samplingFreqIndex
714             // c - channelConfig
715             profile = ((header[0] & 0xf8) >> 3) - 1;
716             sf_index = (header[0] & 0x07) << 1 | (header[1] & 0x80) >> 7;
717             sr = get_sample_rate(sf_index);
718             if (sr == 0) {
719                 LOGE("unsupport the sample rate");
720                 return -1;
721             }
722             channel = (header[1] >> 3) & 0xf;
723             LOGV("profile: %d, sf_index: %d, channel: %d", profile, sf_index, channel);
724
725             meta = MakeAACCodecSpecificData(profile, sf_index, channel);
726             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AAC);
727             break;
728         case CODEC_ID_WMAV1:  // TODO, version?
729             LOGV("WMAV1");
730             meta = new MetaData;
731             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_WMA);
732             meta->setData(kKeyRawCodecSpecificData, 0, avctx->extradata, avctx->extradata_size);
733             break;
734         case CODEC_ID_WMAV2:
735             LOGV("WMAV2");
736             meta = new MetaData;
737             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_WMA);
738             meta->setData(kKeyRawCodecSpecificData, 0, avctx->extradata, avctx->extradata_size);
739             meta->setInt32(kKeyWMAVersion, kTypeWMA);
740             break;
741         case CODEC_ID_WMAPRO:
742             LOGV("WMAPRO");
743             meta = new MetaData;
744             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_WMA);
745             meta->setData(kKeyRawCodecSpecificData, 0, avctx->extradata, avctx->extradata_size);
746             meta->setInt32(kKeyWMAVersion, kTypeWMAPro);
747             break;
748         case CODEC_ID_WMALOSSLESS:
749             LOGV("WMALOSSLESS");
750             meta = new MetaData;
751             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_WMA);
752             meta->setData(kKeyRawCodecSpecificData, 0, avctx->extradata, avctx->extradata_size);
753             meta->setInt32(kKeyWMAVersion, kTypeWMALossLess);
754             break;
755         default:
756             CHECK(!"Should not be here. Unsupported codec.");
757             break;
758         }
759
760         LOGI("bit_rate: %d, sample_rate: %d, channels: %d", avctx->bit_rate, avctx->sample_rate, avctx->channels);
761
762         meta->setInt32(kKeySampleRate, avctx->sample_rate);
763         meta->setInt32(kKeyChannelCount, avctx->channels);
764         meta->setInt32(kKeyBitRate, avctx->bit_rate);
765         if (mFormatCtx->duration != AV_NOPTS_VALUE)
766             meta->setInt64(kKeyDuration, mFormatCtx->duration);
767
768         LOGV("create a audio track");
769         index = mTracks.add(
770             stream_index, new Track(this, meta, false, mAudioStream, &mAudioQ));
771
772         mDefersToCreateAudioTrack = false;
773
774         break;
775     case AVMEDIA_TYPE_SUBTITLE:
776         /* Unsupport now */
777         CHECK(!"Should not be here. Unsupported media type.");
778         break;
779     default:
780         CHECK(!"Should not be here. Unsupported media type.");
781         break;
782     }
783     return 0;
784 }
785
786 void FFmpegExtractor::stream_component_close(int stream_index)
787 {
788     AVCodecContext *avctx;
789
790     if (stream_index < 0 || stream_index >= mFormatCtx->nb_streams)
791         return;
792     avctx = mFormatCtx->streams[stream_index]->codec;
793
794     switch (avctx->codec_type) {
795     case AVMEDIA_TYPE_VIDEO:
796         LOGV("packet_queue_abort videoq");
797         packet_queue_abort(&mVideoQ);
798         /* wait until the end */
799         while (!mAbortRequest && !mVideoEOSReceived) {
800             LOGV("wait for video received");
801             NamDelay(10);
802         }
803         LOGV("packet_queue_end videoq");
804         packet_queue_end(&mVideoQ);
805         break;
806     case AVMEDIA_TYPE_AUDIO:
807         LOGV("packet_queue_abort audioq");
808         packet_queue_abort(&mAudioQ);
809         while (!mAbortRequest && !mAudioEOSReceived) {
810             LOGV("wait for audio received");
811             NamDelay(10);
812         }
813         LOGV("packet_queue_end audioq");
814         packet_queue_end(&mAudioQ);
815         break;
816     case AVMEDIA_TYPE_SUBTITLE:
817         break;
818     default:
819         break;
820     }
821
822     mFormatCtx->streams[stream_index]->discard = AVDISCARD_ALL;
823     switch (avctx->codec_type) {
824     case AVMEDIA_TYPE_VIDEO:
825         mVideoStream    = NULL;
826         mVideoStreamIdx = -1;
827         if (mVideoBsfc) {
828             av_bitstream_filter_close(mVideoBsfc);
829             mVideoBsfc  = NULL;
830         }
831         break;
832     case AVMEDIA_TYPE_AUDIO:
833         mAudioStream    = NULL;
834         mAudioStreamIdx = -1;
835         if (mAudioBsfc) {
836             av_bitstream_filter_close(mAudioBsfc);
837             mAudioBsfc  = NULL;
838         }
839         break;
840     case AVMEDIA_TYPE_SUBTITLE:
841         break;
842     default:
843         break;
844     }
845 }
846
847 void FFmpegExtractor::reachedEOS(enum AVMediaType media_type)
848 {
849     Mutex::Autolock autoLock(mLock);
850
851     if (media_type == AVMEDIA_TYPE_VIDEO) {
852         mVideoEOSReceived = true;
853     } else if (media_type == AVMEDIA_TYPE_AUDIO) {
854         mAudioEOSReceived = true;
855     }
856 }
857
858 /* seek in the stream */
859 int FFmpegExtractor::stream_seek(int64_t pos, enum AVMediaType media_type)
860 {
861     Mutex::Autolock autoLock(mLock);
862
863     if (mVideoStreamIdx >= 0 &&
864         mAudioStreamIdx >= 0 &&
865         media_type == AVMEDIA_TYPE_AUDIO &&
866         !mVideoEOSReceived) {
867        return NO_SEEK;
868     }
869
870     // flush immediately
871     if (mAudioStreamIdx >= 0)
872         packet_queue_flush(&mAudioQ);
873     if (mVideoStreamIdx >= 0)
874         packet_queue_flush(&mVideoQ);
875
876     mSeekPos = pos;
877     mSeekFlags &= ~AVSEEK_FLAG_BYTE;
878     mSeekReq = 1;
879
880     return SEEK;
881 }
882
883 // staitc
884 int FFmpegExtractor::decode_interrupt_cb(void *ctx)
885 {
886     FFmpegExtractor *extrator = static_cast<FFmpegExtractor *>(ctx);
887     return extrator->mAbortRequest;
888 }
889
890 void FFmpegExtractor::print_error_ex(const char *filename, int err)
891 {
892     char errbuf[128];
893     const char *errbuf_ptr = errbuf;
894
895     if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
896         errbuf_ptr = strerror(AVUNERROR(err));
897     LOGI("%s: %s\n", filename, errbuf_ptr);
898 }
899
900 void FFmpegExtractor::setFFmpegDefaultOpts()
901 {
902     mGenPTS       = 0;
903 #if DIABLE_VIDEO
904     mVideoDisable = 1;
905 #else
906     mVideoDisable = 0;
907 #endif
908 #if DIABLE_AUDIO
909     mAudioDisable = 1;
910 #else
911     mAudioDisable = 0;
912 #endif
913     mShowStatus   = 1;
914     mSeekByBytes  = 0; /* seek by bytes 0=off 1=on -1=auto" */
915     mStartTime    = AV_NOPTS_VALUE;
916     mDuration     = AV_NOPTS_VALUE;
917     mSeekPos      = AV_NOPTS_VALUE;
918     mAutoExit     = 1;
919     mLoop         = 1;
920
921     mVideoStreamIdx = -1;
922     mAudioStreamIdx = -1;
923     mVideoStream  = NULL;
924     mAudioStream  = NULL;
925     mVideoQInited = false;
926     mAudioQInited = false;
927     mDefersToCreateVideoTrack = false;
928     mDefersToCreateAudioTrack = false;
929     mVideoBsfc = NULL;
930     mAudioBsfc = NULL;
931
932     mAbortRequest = 0;
933     mPaused       = 0;
934     mLastPaused   = 0;
935     mSeekReq      = 0;
936
937     mProbePkts    = 0;
938     mEOF          = false;
939 }
940
941 int FFmpegExtractor::initStreams()
942 {
943     int err, i;
944     status_t status;
945     int eof = 0;
946     int ret = 0, audio_ret = 0, video_ret = 0;
947     int pkt_in_play_range = 0;
948     AVDictionaryEntry *t;
949     AVDictionary **opts;
950     int orig_nb_streams;
951     int st_index[AVMEDIA_TYPE_NB] = {0};
952     int wanted_stream[AVMEDIA_TYPE_NB] = {0};
953     st_index[AVMEDIA_TYPE_AUDIO]  = -1;
954     st_index[AVMEDIA_TYPE_VIDEO]  = -1;
955     wanted_stream[AVMEDIA_TYPE_AUDIO]  = -1;
956     wanted_stream[AVMEDIA_TYPE_VIDEO]  = -1;
957
958     setFFmpegDefaultOpts();
959
960     status = initFFmpeg();
961     if (status != OK) {
962         ret = -1;
963         goto fail;
964     }
965
966     av_init_packet(&flush_pkt);
967     flush_pkt.data = (uint8_t *)"FLUSH";
968     flush_pkt.size = 0;
969
970     mFormatCtx = avformat_alloc_context();
971     mFormatCtx->interrupt_callback.callback = decode_interrupt_cb;
972     mFormatCtx->interrupt_callback.opaque = this;
973     LOGV("mFilename: %s", mFilename);
974     err = avformat_open_input(&mFormatCtx, mFilename, NULL, &format_opts);
975     if (err < 0) {
976         print_error_ex(mFilename, err);
977         ret = -1;
978         goto fail;
979     }
980     if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
981         LOGE("Option %s not found.\n", t->key);
982         //ret = AVERROR_OPTION_NOT_FOUND;
983         ret = -1;
984         goto fail;
985     }
986
987     if (mGenPTS)
988         mFormatCtx->flags |= AVFMT_FLAG_GENPTS;
989
990     opts = setup_find_stream_info_opts(mFormatCtx, codec_opts);
991     orig_nb_streams = mFormatCtx->nb_streams;
992
993     err = avformat_find_stream_info(mFormatCtx, opts);
994     if (err < 0) {
995         LOGE("%s: could not find codec parameters\n", mFilename);
996         ret = -1;
997         goto fail;
998     }
999     for (i = 0; i < orig_nb_streams; i++)
1000         av_dict_free(&opts[i]);
1001     av_freep(&opts);
1002
1003     if (mFormatCtx->pb)
1004         mFormatCtx->pb->eof_reached = 0; // FIXME hack, ffplay maybe should not use url_feof() to test for the end
1005
1006     if (mSeekByBytes < 0)
1007         mSeekByBytes = !!(mFormatCtx->iformat->flags & AVFMT_TS_DISCONT);
1008
1009     /* if seeking requested, we execute it */
1010     if (mStartTime != AV_NOPTS_VALUE) {
1011         int64_t timestamp;
1012
1013         timestamp = mStartTime;
1014         /* add the stream start time */
1015         if (mFormatCtx->start_time != AV_NOPTS_VALUE)
1016             timestamp += mFormatCtx->start_time;
1017         ret = avformat_seek_file(mFormatCtx, -1, INT64_MIN, timestamp, INT64_MAX, 0);
1018         if (ret < 0) {
1019             LOGE("%s: could not seek to position %0.3f",
1020                     mFilename, (double)timestamp / AV_TIME_BASE);
1021             goto fail;
1022         }
1023     }
1024
1025     for (i = 0; i < mFormatCtx->nb_streams; i++)
1026         mFormatCtx->streams[i]->discard = AVDISCARD_ALL;
1027     if (!mVideoDisable)
1028         st_index[AVMEDIA_TYPE_VIDEO] =
1029             av_find_best_stream(mFormatCtx, AVMEDIA_TYPE_VIDEO,
1030                                 wanted_stream[AVMEDIA_TYPE_VIDEO], -1, NULL, 0);
1031     if (!mAudioDisable)
1032         st_index[AVMEDIA_TYPE_AUDIO] =
1033             av_find_best_stream(mFormatCtx, AVMEDIA_TYPE_AUDIO,
1034                                 wanted_stream[AVMEDIA_TYPE_AUDIO],
1035                                 st_index[AVMEDIA_TYPE_VIDEO],
1036                                 NULL, 0);
1037     if (mShowStatus) {
1038         av_dump_format(mFormatCtx, 0, mFilename, 0);
1039     }
1040
1041     if (mFormatCtx->duration != AV_NOPTS_VALUE) {
1042         int hours, mins, secs, us;
1043         secs = mFormatCtx->duration / AV_TIME_BASE;
1044         us = mFormatCtx->duration % AV_TIME_BASE;
1045         mins = secs / 60;
1046         secs %= 60;
1047         hours = mins / 60;
1048         mins %= 60;
1049         LOGI("the duration is %02d:%02d:%02d.%02d", hours, mins, secs, (100 * us) / AV_TIME_BASE);
1050     }
1051
1052     if (st_index[AVMEDIA_TYPE_AUDIO] >= 0) {
1053         audio_ret = stream_component_open(st_index[AVMEDIA_TYPE_AUDIO]);
1054     }
1055
1056     if (st_index[AVMEDIA_TYPE_VIDEO] >= 0) {
1057         video_ret = stream_component_open(st_index[AVMEDIA_TYPE_VIDEO]);
1058     }
1059
1060     if ( audio_ret < 0 && video_ret < 0) {
1061         LOGE("%s: could not open codecs\n", mFilename);
1062         ret = -1;
1063         goto fail;
1064     }
1065
1066     ret = 0;
1067
1068 fail:
1069     return ret;
1070 }
1071
1072 void FFmpegExtractor::deInitStreams()
1073 {
1074     if (mFormatCtx) {
1075         avformat_close_input(&mFormatCtx);
1076     }
1077
1078     deInitFFmpeg();
1079 }
1080
1081 status_t FFmpegExtractor::startReaderThread() {
1082     LOGV("Starting reader thread");
1083     Mutex::Autolock autoLock(mLock);
1084
1085     if (mReaderThreadStarted)
1086         return OK;
1087
1088     pthread_attr_t attr;
1089     pthread_attr_init(&attr);
1090     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1091     pthread_create(&mReaderThread, &attr, ReaderWrapper, this);
1092     pthread_attr_destroy(&attr);
1093     mReaderThreadStarted = true;
1094     LOGD("Reader thread started");
1095
1096     return OK;
1097 }
1098
1099 void FFmpegExtractor::stopReaderThread() {
1100     LOGV("Stopping reader thread");
1101     Mutex::Autolock autoLock(mLock);
1102
1103     if (!mReaderThreadStarted) {
1104         LOGD("Reader thread have been stopped");
1105         return;
1106     }
1107
1108     mAbortRequest = 1;
1109
1110     void *dummy;
1111     pthread_join(mReaderThread, &dummy);
1112     mReaderThreadStarted = false;
1113     LOGD("Reader thread stopped");
1114 }
1115
1116 // static
1117 void *FFmpegExtractor::ReaderWrapper(void *me) {
1118     ((FFmpegExtractor *)me)->readerEntry();
1119
1120     return NULL;
1121 }
1122
1123 void FFmpegExtractor::readerEntry() {
1124     int err, i, ret;
1125     AVPacket pkt1, *pkt = &pkt1;
1126     int eof = 0;
1127     int pkt_in_play_range = 0;
1128
1129     LOGV("FFmpegExtractor::readerEntry");
1130
1131     mVideoEOSReceived = false;
1132     mAudioEOSReceived = false;
1133
1134     for (;;) {
1135         if (mAbortRequest)
1136             break;
1137
1138         if (mPaused != mLastPaused) {
1139             mLastPaused = mPaused;
1140             if (mPaused)
1141                 mReadPauseReturn = av_read_pause(mFormatCtx);
1142             else
1143                 av_read_play(mFormatCtx);
1144         }
1145 #if CONFIG_RTSP_DEMUXER || CONFIG_MMSH_PROTOCOL
1146         if (mPaused &&
1147                 (!strcmp(mFormatCtx->iformat->name, "rtsp") ||
1148                  (mFormatCtx->pb && !strncmp(mFilename, "mmsh:", 5)))) {
1149             /* wait 10 ms to avoid trying to get another packet */
1150             /* XXX: horrible */
1151             NamDelay(10);
1152             continue;
1153         }
1154 #endif
1155
1156         if (mSeekReq) {
1157             LOGV("readerEntry, mSeekReq: %d", mSeekReq);
1158             ret = avformat_seek_file(mFormatCtx, -1, INT64_MIN, mSeekPos, INT64_MAX, mSeekFlags);
1159             if (ret < 0) {
1160                 LOGE("%s: error while seeking", mFormatCtx->filename);
1161             } else {
1162                 if (mAudioStreamIdx >= 0) {
1163                     packet_queue_flush(&mAudioQ);
1164                     packet_queue_put(&mAudioQ, &flush_pkt);
1165                 }
1166                 if (mVideoStreamIdx >= 0) {
1167                     packet_queue_flush(&mVideoQ);
1168                     packet_queue_put(&mVideoQ, &flush_pkt);
1169                 }
1170             }
1171             mSeekReq = 0;
1172             eof = 0;
1173         }
1174
1175         /* if the queue are full, no need to read more */
1176         if (   mAudioQ.size + mVideoQ.size > MAX_QUEUE_SIZE
1177             || (   (mAudioQ   .size  > MIN_AUDIOQ_SIZE || mAudioStreamIdx < 0)
1178                 && (mVideoQ   .nb_packets > MIN_FRAMES || mVideoStreamIdx < 0))) {
1179 #if DEBUG_READ_ENTRY
1180             LOGV("readerEntry, is full, fuck");
1181 #endif
1182             /* wait 10 ms */
1183             NamDelay(10);
1184             continue;
1185         }
1186
1187         if (eof) {
1188             if (mVideoStreamIdx >= 0) {
1189                 av_init_packet(pkt);
1190                 pkt->data = NULL;
1191                 pkt->size = 0;
1192                 pkt->stream_index = mVideoStreamIdx;
1193                 packet_queue_put(&mVideoQ, pkt);
1194             }
1195             if (mAudioStreamIdx >= 0) {
1196                 av_init_packet(pkt);
1197                 pkt->data = NULL;
1198                 pkt->size = 0;
1199                 pkt->stream_index = mAudioStreamIdx;
1200                 packet_queue_put(&mAudioQ, pkt);
1201             }
1202             NamDelay(10);
1203 #if DEBUG_READ_ENTRY
1204             LOGV("readerEntry, eof = 1, mVideoQ.size: %d, mVideoQ.nb_packets: %d, mAudioQ.size: %d, mAudioQ.nb_packets: %d",
1205                     mVideoQ.size, mVideoQ.nb_packets, mAudioQ.size, mAudioQ.nb_packets);
1206 #endif
1207             if (mAudioQ.size + mVideoQ.size  == 0) {
1208                 if (mLoop != 1 && (!mLoop || --mLoop)) {
1209                     if (mVideoStreamIdx >= 0) {
1210                         stream_seek(mStartTime != AV_NOPTS_VALUE ? mStartTime : 0, AVMEDIA_TYPE_VIDEO);
1211                     } else if (mAudioStreamIdx >= 0) {
1212                         stream_seek(mStartTime != AV_NOPTS_VALUE ? mStartTime : 0, AVMEDIA_TYPE_AUDIO);
1213                     }
1214                 } else if (mAutoExit) {
1215                     ret = AVERROR_EOF;
1216                     goto fail;
1217                 }
1218             }
1219             eof=0;
1220             continue;
1221         }
1222
1223         ret = av_read_frame(mFormatCtx, pkt);
1224         mProbePkts++;
1225         if (ret < 0) {
1226             if (ret == AVERROR_EOF || url_feof(mFormatCtx->pb))
1227                 if (ret == AVERROR_EOF) {
1228                     //LOGV("ret == AVERROR_EOF");
1229                 }
1230                 if (url_feof(mFormatCtx->pb)) {
1231                     //LOGV("url_feof(mFormatCtx->pb)");
1232                 }
1233
1234                 eof = 1;
1235                 mEOF = true;
1236             if (mFormatCtx->pb && mFormatCtx->pb->error) {
1237                 LOGE("mFormatCtx->pb->error: %d", mFormatCtx->pb->error);
1238                 break;
1239             }
1240             NamDelay(100);
1241             continue;
1242         }
1243
1244         if (pkt->stream_index == mVideoStreamIdx) {
1245              if (mDefersToCreateVideoTrack) {
1246                 AVCodecContext *avctx = mFormatCtx->streams[mVideoStreamIdx]->codec;
1247
1248                 int i = parser_split(avctx, pkt->data, pkt->size);
1249                 if (i > 0 && i < FF_MAX_EXTRADATA_SIZE) {
1250                     if (avctx->extradata)
1251                         av_freep(&avctx->extradata);
1252                     avctx->extradata_size= i;
1253                     avctx->extradata = (uint8_t *)av_malloc(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
1254                     if (!avctx->extradata) {
1255                         //return AVERROR(ENOMEM);
1256                         ret = AVERROR(ENOMEM);
1257                         goto fail;
1258                     }
1259                     // sps + pps(there may be sei in it)
1260                     memcpy(avctx->extradata, pkt->data, avctx->extradata_size);
1261                     memset(avctx->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
1262                 } else {
1263                     av_free_packet(pkt);
1264                     continue;
1265                 }
1266
1267                 stream_component_open(mVideoStreamIdx);
1268                 if (!mDefersToCreateVideoTrack)
1269                     LOGI("probe packet counter: %d when create video track ok", mProbePkts);
1270                 if (mProbePkts == EXTRACTOR_MAX_PROBE_PACKETS)
1271                     LOGI("probe packet counter to max: %d, create video track: %d",
1272                         mProbePkts, !mDefersToCreateVideoTrack);
1273             }
1274         } else if (pkt->stream_index == mAudioStreamIdx) {
1275             int ret;
1276             uint8_t *outbuf;
1277             int   outbuf_size;
1278             AVCodecContext *avctx = mFormatCtx->streams[mAudioStreamIdx]->codec;
1279             if (mAudioBsfc && pkt && pkt->data) {
1280                 ret = av_bitstream_filter_filter(mAudioBsfc, avctx, NULL, &outbuf, &outbuf_size,
1281                                    pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY);
1282
1283                 if (ret < 0 ||!outbuf_size) {
1284                     av_free_packet(pkt);
1285                     continue;
1286                 }
1287                 if (outbuf && outbuf != pkt->data) {
1288                     memmove(pkt->data, outbuf, outbuf_size);
1289                     pkt->size = outbuf_size;
1290                 }
1291             }
1292             if (mDefersToCreateAudioTrack) {
1293                 if (avctx->extradata_size <= 0) {
1294                     av_free_packet(pkt);
1295                     continue;
1296                 }
1297                 stream_component_open(mAudioStreamIdx);
1298                 if (!mDefersToCreateAudioTrack)
1299                     LOGI("probe packet counter: %d when create audio track ok", mProbePkts);
1300                 if (mProbePkts == EXTRACTOR_MAX_PROBE_PACKETS)
1301                     LOGI("probe packet counter to max: %d, create audio track: %d",
1302                         mProbePkts, !mDefersToCreateAudioTrack);
1303             }
1304         }
1305
1306         /* check if packet is in play range specified by user, then queue, otherwise discard */
1307         pkt_in_play_range = mDuration == AV_NOPTS_VALUE ||
1308                 (pkt->pts - mFormatCtx->streams[pkt->stream_index]->start_time) *
1309                 av_q2d(mFormatCtx->streams[pkt->stream_index]->time_base) -
1310                 (double)(mStartTime != AV_NOPTS_VALUE ? mStartTime : 0) / 1000000
1311                 <= ((double)mDuration / 1000000);
1312         if (pkt->stream_index == mAudioStreamIdx && pkt_in_play_range) {
1313             packet_queue_put(&mAudioQ, pkt);
1314         } else if (pkt->stream_index == mVideoStreamIdx && pkt_in_play_range) {
1315             packet_queue_put(&mVideoQ, pkt);
1316         } else {
1317             av_free_packet(pkt);
1318         }
1319     }
1320     /* wait until the end */
1321     while (!mAbortRequest) {
1322         NamDelay(100);
1323     }
1324
1325     ret = 0;
1326 fail:
1327     LOGI("reader thread goto end...");
1328
1329     /* close each stream */
1330     if (mAudioStreamIdx >= 0)
1331         stream_component_close(mAudioStreamIdx);
1332     if (mVideoStreamIdx >= 0)
1333         stream_component_close(mVideoStreamIdx);
1334     if (mFormatCtx) {
1335         avformat_close_input(&mFormatCtx);
1336     }
1337 }
1338
1339 ////////////////////////////////////////////////////////////////////////////////
1340
1341 FFmpegExtractor::Track::Track(
1342         const sp<FFmpegExtractor> &extractor, sp<MetaData> meta, bool isAVC,
1343           AVStream *stream, PacketQueue *queue)
1344     : mExtractor(extractor),
1345       mMeta(meta),
1346       mIsAVC(isAVC),
1347       mStream(stream),
1348       mQueue(queue) {
1349     const char *mime;
1350
1351     /* H.264 Video Types */
1352     {
1353         mNal2AnnexB = false;
1354
1355         if (mIsAVC) {
1356             uint32_t type;
1357             const void *data;
1358             size_t size;
1359             CHECK(meta->findData(kKeyAVCC, &type, &data, &size));
1360
1361             const uint8_t *ptr = (const uint8_t *)data;
1362
1363             CHECK(size >= 7);
1364             CHECK_EQ((unsigned)ptr[0], 1u);  // configurationVersion == 1
1365
1366             // The number of bytes used to encode the length of a NAL unit.
1367             mNALLengthSize = 1 + (ptr[4] & 3);
1368
1369             LOGV("the stream is AVC, the length of a NAL unit: %d", mNALLengthSize);
1370
1371             mNal2AnnexB = true;
1372         }
1373     }
1374
1375     mMediaType = mStream->codec->codec_type;
1376 }
1377
1378 FFmpegExtractor::Track::~Track() {
1379 }
1380
1381 status_t FFmpegExtractor::Track::start(MetaData *params) {
1382     Mutex::Autolock autoLock(mLock);
1383     //mExtractor->startReaderThread();
1384     return OK;
1385 }
1386
1387 status_t FFmpegExtractor::Track::stop() {
1388     Mutex::Autolock autoLock(mLock);
1389     mExtractor->stopReaderThread();
1390     return OK;
1391 }
1392
1393 sp<MetaData> FFmpegExtractor::Track::getFormat() {
1394     Mutex::Autolock autoLock(mLock);
1395
1396     return mMeta;
1397 }
1398
1399 status_t FFmpegExtractor::Track::read(
1400         MediaBuffer **buffer, const ReadOptions *options) {
1401     *buffer = NULL;
1402
1403     Mutex::Autolock autoLock(mLock);
1404
1405     AVPacket pkt;
1406     bool seeking = false;
1407     bool waitKeyPkt = false;
1408     ReadOptions::SeekMode mode;
1409     int64_t pktTS = AV_NOPTS_VALUE;
1410     int64_t seekTimeUs = AV_NOPTS_VALUE;
1411     int64_t timeUs;
1412     int key;
1413     status_t status = OK;
1414
1415     if (options && options->getSeekTo(&seekTimeUs, &mode)) {
1416         LOGV("~~~%s seekTimeUs: %lld, mode: %d", av_get_media_type_string(mMediaType), seekTimeUs, mode);
1417         if (mExtractor->stream_seek(seekTimeUs, mMediaType) == SEEK)
1418             seeking = true;
1419     }
1420
1421 retry:
1422     if (mExtractor->packet_queue_get(mQueue, &pkt, 1) < 0) {
1423         mExtractor->reachedEOS(mMediaType);
1424         return ERROR_END_OF_STREAM;
1425     }
1426
1427     if (seeking) {
1428         if (pkt.data != flush_pkt.data) {
1429             av_free_packet(&pkt);
1430             goto retry;
1431         } else {
1432             seeking = false;
1433 #if WAIT_KEY_PACKET_AFTER_SEEK
1434             waitKeyPkt = true;
1435 #endif
1436         }
1437     }
1438
1439     if (pkt.data == flush_pkt.data) {
1440         LOGV("read %s flush pkt", av_get_media_type_string(mMediaType));
1441         av_free_packet(&pkt);
1442         goto retry;
1443     } else if (pkt.data == NULL && pkt.size == 0) {
1444         LOGV("read %s eos pkt", av_get_media_type_string(mMediaType));
1445         av_free_packet(&pkt);
1446         mExtractor->reachedEOS(mMediaType);
1447         return ERROR_END_OF_STREAM;
1448     }
1449
1450     key = pkt.flags & AV_PKT_FLAG_KEY ? 1 : 0;
1451
1452     if (waitKeyPkt) {
1453         if (!key) {
1454             LOGV("drop the no key packet");
1455             av_free_packet(&pkt);
1456             goto retry;
1457         } else {
1458             LOGV("~~~~~~ got the key packet");
1459             waitKeyPkt = false;
1460         }
1461     }
1462      
1463     MediaBuffer *mediaBuffer = new MediaBuffer(pkt.size + FF_INPUT_BUFFER_PADDING_SIZE);
1464     mediaBuffer->meta_data()->clear();
1465     mediaBuffer->set_range(0, pkt.size);
1466 #if DISABLE_NAL_TO_ANNEXB
1467     mNal2AnnexB = false;
1468 #endif
1469     if (mIsAVC && mNal2AnnexB) {
1470         /* Convert H.264 NAL format to annex b */
1471         if (mNALLengthSize >= 3 && mNALLengthSize <= 4 )
1472         {
1473             uint8_t *dst = (uint8_t *)mediaBuffer->data();
1474
1475             /* This only works for NAL sizes 3-4 */
1476             size_t len = pkt.size, i;
1477             uint8_t *ptr = pkt.data;
1478             while (len >= mNALLengthSize) {
1479                 uint32_t nal_len = 0;
1480                 for( i = 0; i < mNALLengthSize; i++ ) {
1481                     nal_len = (nal_len << 8) | ptr[i];
1482                     dst[i] = 0;
1483                 }
1484                 dst[mNALLengthSize - 1] = 1;
1485                 if (nal_len > INT_MAX || nal_len > (unsigned int)len) {
1486                     status = ERROR_MALFORMED;
1487                     break;
1488                 }
1489                 dst += mNALLengthSize;
1490                 ptr += mNALLengthSize;
1491                 len -= mNALLengthSize;
1492
1493                 memcpy(dst, ptr, nal_len);
1494
1495                 dst += nal_len;
1496                 ptr += nal_len;
1497                 len -= nal_len;
1498             }
1499         } else {
1500              status = ERROR_MALFORMED;
1501         }
1502
1503         if (status != OK) {
1504             LOGV("status != OK");
1505             mediaBuffer->release();
1506             mediaBuffer = NULL;
1507             av_free_packet(&pkt);
1508             return ERROR_MALFORMED;
1509         }
1510     } else {
1511         memcpy(mediaBuffer->data(), pkt.data, pkt.size);
1512     }
1513
1514     pktTS = pkt.pts;
1515     // use dts when AVI
1516     if (pkt.pts == AV_NOPTS_VALUE)
1517         pktTS = pkt.dts;
1518
1519 #if 0
1520     // TODO, Stagefright can't handle negative timestamps
1521     // if needed, work around this by offsetting them manually?
1522     if (pktTS < 0)
1523         pktTS = 0;
1524 #endif
1525
1526     timeUs = (int64_t)(pktTS * av_q2d(mStream->time_base) * 1000000);
1527
1528 #if 0
1529     LOGV("read %s pkt, size: %d, key: %d, pts: %lld, dts: %lld, timeUs: %llu us (%.2f secs)",
1530         av_get_media_type_string(mMediaType), pkt.size, key, pkt.pts, pkt.dts, timeUs, timeUs/1E6);
1531 #endif
1532
1533 #if 0
1534     // TODO, Stagefright can't handle negative timestamps
1535     // if needed, work around this by offsetting them manually?
1536     if (timeUs < 0)
1537         timeUs = 0;
1538 #endif
1539
1540     mediaBuffer->meta_data()->setInt64(kKeyTime, timeUs);
1541     mediaBuffer->meta_data()->setInt32(kKeyIsSyncFrame, key);
1542
1543     *buffer = mediaBuffer;
1544
1545     av_free_packet(&pkt);
1546
1547     return OK;
1548 }
1549
1550 ////////////////////////////////////////////////////////////////////////////////
1551
1552 // LegacySniffFFMPEG
1553 typedef struct {
1554     const char *extension;
1555     const char *container;
1556 } extmap;
1557
1558 static extmap FILE_EXTS[] = {
1559         {".mp4", MEDIA_MIMETYPE_CONTAINER_MPEG4},
1560         {".3gp", MEDIA_MIMETYPE_CONTAINER_MPEG4},
1561         {".mp3", MEDIA_MIMETYPE_AUDIO_MPEG},
1562         {".mov", MEDIA_MIMETYPE_CONTAINER_MOV},
1563         {".mkv", MEDIA_MIMETYPE_CONTAINER_MATROSKA},
1564         {".ts",  MEDIA_MIMETYPE_CONTAINER_TS},
1565         {".avi", MEDIA_MIMETYPE_CONTAINER_AVI},
1566         {".asf", MEDIA_MIMETYPE_CONTAINER_ASF},
1567 #if 0
1568         {".wmv", MEDIA_MIMETYPE_CONTAINER_WMV},
1569         {".wma", MEDIA_MIMETYPE_CONTAINER_WMA},
1570         {".mpg", MEDIA_MIMETYPE_CONTAINER_MPG},
1571         {".flv", MEDIA_MIMETYPE_CONTAINER_FLV},
1572         {".divx", MEDIA_MIMETYPE_CONTAINER_DIVX},
1573         {".mp2", MEDIA_MIMETYPE_CONTAINER_MP2},
1574         {".ape", MEDIA_MIMETYPE_CONTAINER_APE},
1575         {".rm ", MEDIA_MIMETYPE_CONTAINER_RM},
1576         {".ra",  MEDIA_MIMETYPE_CONTAINER_RA},
1577 #endif
1578 };
1579
1580 const char *LegacySniffFFMPEG(const char * uri)
1581 {
1582     size_t i;
1583     const char *container = NULL;
1584
1585     LOGI("list the file extensions suppoted by ffmpeg: ");
1586     LOGI("========================================");
1587     for (i = 0; i < NELEM(FILE_EXTS); ++i) {
1588             LOGV("file_exts[%02d]: %s", i, FILE_EXTS[i].extension);
1589     }
1590     LOGI("========================================");
1591
1592     int lenURI = strlen(uri);
1593     for (i = 0; i < NELEM(FILE_EXTS); ++i) {
1594         int len = strlen(FILE_EXTS[i].extension);
1595         int start = lenURI - len;
1596         if (start > 0) {
1597             if (!av_strncasecmp(uri + start, FILE_EXTS[i].extension, len)) {
1598                 container = FILE_EXTS[i].container;
1599                 break;
1600             }
1601         }
1602     }
1603
1604     return container;
1605 }
1606
1607 // BetterSniffFFMPEG
1608 typedef struct {
1609     const char *format;
1610     const char *container;
1611 } formatmap;
1612
1613 static formatmap FILE_FORMATS[] = {
1614         {"mpegts",                  MEDIA_MIMETYPE_CONTAINER_TS},
1615         {"mov,mp4,m4a,3gp,3g2,mj2", MEDIA_MIMETYPE_CONTAINER_MOV},
1616         {"asf",                     MEDIA_MIMETYPE_CONTAINER_ASF},
1617 };
1618
1619 const char *BetterSniffFFMPEG(const char * uri)
1620 {
1621     size_t i;
1622     const char *container = NULL;
1623     AVFormatContext *ic = NULL;
1624
1625     status_t status = initFFmpeg();
1626     if (status != OK) {
1627         LOGE("could not init ffmpeg");
1628         return false;
1629     }
1630
1631     ic = avformat_alloc_context();
1632     avformat_open_input(&ic, uri, NULL, NULL);
1633
1634     av_dump_format(ic, 0, uri, 0);
1635
1636     LOGI("FFmpegExtrator, uri: %s, format_name: %s, format_long_name: %s", uri, ic->iformat->name, ic->iformat->long_name);
1637
1638     LOGI("list the format suppoted by ffmpeg: ");
1639     LOGI("========================================");
1640     for (i = 0; i < NELEM(FILE_FORMATS); ++i) {
1641             LOGV("format_names[%02d]: %s", i, FILE_FORMATS[i].format);
1642     }
1643     LOGI("========================================");
1644
1645     for (i = 0; i < NELEM(FILE_FORMATS); ++i) {
1646         int len = strlen(FILE_FORMATS[i].format);
1647         if (!av_strncasecmp(ic->iformat->name, FILE_FORMATS[i].format, len)) {
1648             container = FILE_FORMATS[i].container;
1649             break;
1650         }
1651     }
1652
1653     avformat_close_input(&ic);
1654     av_free(ic);
1655
1656     return container;
1657 }
1658
1659 bool SniffFFMPEG(
1660         const sp<DataSource> &source, String8 *mimeType, float *confidence,
1661         sp<AMessage> *meta) {
1662     LOGV("SniffFFMPEG");
1663     const char *uri, *container = NULL;
1664
1665     uri = source->getNamURI();
1666
1667     if (!uri)
1668         return false;
1669
1670     LOGI("ffmpeg uri: %s", uri);
1671
1672     container = BetterSniffFFMPEG(uri);
1673     if (!container) {
1674         LOGW("sniff through LegacySniffFFMPEG, only check the file extension");
1675         container = LegacySniffFFMPEG(uri);
1676     }
1677
1678     if (container == NULL)
1679         return false;
1680
1681     LOGV("found container: %s", container);
1682
1683     *confidence = 0.88f;  // Slightly larger than other extractor's confidence
1684     mimeType->setTo(container);
1685
1686     /* use MPEG4Extractor(not extended extractor) for HTTP source only */
1687     if (!av_strcasecmp(container, MEDIA_MIMETYPE_CONTAINER_MPEG4)
1688             && (source->flags() & DataSource::kIsCachingDataSource)) {
1689             return true;
1690     }
1691
1692     *meta = new AMessage;
1693     (*meta)->setString("extended-extractor", "extended-extractor");
1694     (*meta)->setString("extended-extractor-subtype", "ffmpegextractor");
1695
1696     return true;
1697 }
1698
1699 }  // namespace android