OSDN Git Service

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