OSDN Git Service

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