OSDN Git Service

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