OSDN Git Service

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