OSDN Git Service

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