OSDN Git Service

fix crash when no mp3 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     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
406         bsfc = &mVideoBsfc;
407         defersToCreateTrack = &mDefersToCreateVideoTrack;
408     } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO){
409         bsfc = &mAudioBsfc;
410         defersToCreateTrack = &mDefersToCreateAudioTrack;
411     }
412
413     name = NULL;
414     switch(avctx->codec_id) {
415     case CODEC_ID_H264:
416     case CODEC_ID_MPEG4:
417     case CODEC_ID_H263:
418     case CODEC_ID_H263P:
419     case CODEC_ID_H263I:
420         break;
421     case CODEC_ID_AAC:
422         name = "aac_adtstoasc";
423         break;
424     case CODEC_ID_MP3:
425         break;
426     default:
427         break;
428     }
429
430     if (avctx->extradata_size <= 0) {
431         LOGI("No %s extradata found, should to extract it from bitstream",
432             av_get_media_type_string(avctx->codec_type));
433         *defersToCreateTrack = true;
434          //CHECK(name != NULL);
435         if (!*bsfc && name) {
436             *bsfc = av_bitstream_filter_init(name);
437             if (!*bsfc) {
438                 LOGE("Cannot open the %s BSF!", name);
439                 *defersToCreateTrack = false;
440                 return -1;
441             } else {
442                 LOGV("open the %s bsf", name);
443                 return 0;
444             }
445         } else {
446             return 0;
447         }
448     }
449     return 1;
450 }
451
452
453 int FFmpegExtractor::stream_component_open(int stream_index)
454 {
455     AVCodecContext *avctx;
456     sp<MetaData> meta;
457     bool isAVC = false;
458     bool supported = false;
459     uint32_t type;
460     const void *data;
461     size_t size;
462     int ret;
463
464     LOGI("stream_index: %d", stream_index);
465     if (stream_index < 0 || stream_index >= mFormatCtx->nb_streams)
466         return -1;
467     avctx = mFormatCtx->streams[stream_index]->codec;
468
469     switch(avctx->codec_id) {
470     case CODEC_ID_H264:
471     case CODEC_ID_MPEG4:
472     case CODEC_ID_H263:
473     case CODEC_ID_H263P:
474     case CODEC_ID_H263I:
475     case CODEC_ID_AAC:
476     case CODEC_ID_MP3:
477     case CODEC_ID_MPEG2VIDEO:
478 #if 0
479     case CODEC_ID_VC1:
480 #endif
481         supported = true;
482         break;
483     default:
484         supported = false;
485         break;
486     }
487
488     if (!supported) {
489         LOGE("unsupport the codec");
490         return -1;
491     }
492     LOGV("support the codec");
493
494     unsigned streamType;
495     ssize_t index = mTracks.indexOfKey(stream_index);
496
497     if (index >= 0) {
498         LOGE("this track already exists");
499         return 0;
500     }
501
502     mFormatCtx->streams[stream_index]->discard = AVDISCARD_DEFAULT;
503
504     char tagbuf[32];
505     av_get_codec_tag_string(tagbuf, sizeof(tagbuf), avctx->codec_tag);
506     LOGV("Tag %s/0x%08x with codec id '%d'\n", tagbuf, avctx->codec_tag, avctx->codec_id);
507
508     switch (avctx->codec_type) {
509     case AVMEDIA_TYPE_VIDEO:
510         if (mVideoStreamIdx == -1)
511             mVideoStreamIdx = stream_index;
512         if (mVideoStream == NULL)
513             mVideoStream = mFormatCtx->streams[stream_index];
514         if (!mVideoQInited) {
515             packet_queue_init(&mVideoQ);
516             mVideoQInited = true;
517         }
518
519         ret = check_extradata(avctx);
520         if (ret != 1) {
521             if (ret == -1) {
522                 // disable the stream
523                 mVideoStreamIdx = -1;
524                 mVideoStream = NULL;
525                 packet_queue_end(&mVideoQ);
526                 mVideoQInited =  false;
527                 mFormatCtx->streams[stream_index]->discard = AVDISCARD_ALL;
528             }
529             return ret;
530          }
531
532         LOGV("video extradata:");
533         hexdump(avctx->extradata, avctx->extradata_size);
534
535         meta = new MetaData;
536
537         switch(avctx->codec_id) {
538         case CODEC_ID_H264:
539             /**
540              * H.264 Video Types
541              * http://msdn.microsoft.com/en-us/library/dd757808(v=vs.85).aspx
542              */
543             //if (avctx->codec_tag && avctx->codec_tag == AV_RL32("avc1")) {
544             if (avctx->extradata[0] == 1 /* configurationVersion */) {
545                 // H.264 bitstream without start codes.
546                 isAVC = true;
547                 LOGV("AVC");
548
549                 if (avctx->width == 0 || avctx->height == 0) {
550                     int32_t width, height;
551                     sp<ABuffer> seqParamSet = new ABuffer(avctx->extradata_size - 8);
552                     memcpy(seqParamSet->data(), avctx->extradata + 8, avctx->extradata_size - 8);
553                     FindAVCDimensions(seqParamSet, &width, &height);
554                     avctx->width  = width;
555                     avctx->height = height;
556                 }
557
558                 meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
559                 meta->setData(kKeyAVCC, kTypeAVCC, avctx->extradata, avctx->extradata_size);
560             } else {
561                 // H.264 bitstream with start codes.
562                 isAVC = false;
563                 LOGV("H264");
564
565                 /* set NULL to release meta as we will new a meta in MakeAVCCodecSpecificData() fxn */
566                 meta->clear();
567                 meta = NULL;
568
569                 sp<ABuffer> buffer = new ABuffer(avctx->extradata_size);
570                 memcpy(buffer->data(), avctx->extradata, avctx->extradata_size);
571                 meta = MakeAVCCodecSpecificData(buffer);
572             }
573             break;
574         case CODEC_ID_MPEG4:
575             LOGV("MPEG4");
576             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4);
577             {
578                 sp<ABuffer> csd = new ABuffer(avctx->extradata_size);
579                 memcpy(csd->data(), avctx->extradata, avctx->extradata_size);
580                 sp<ABuffer> esds = MakeMPEGVideoESDS(csd);
581                 meta->setData(kKeyESDS, kTypeESDS, esds->data(), esds->size());
582             }
583             break;
584         case CODEC_ID_H263:
585         case CODEC_ID_H263P:
586         case CODEC_ID_H263I:
587             LOGV("H263");
588             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263);
589             {
590                 sp<ABuffer> csd = new ABuffer(avctx->extradata_size);
591                 memcpy(csd->data(), avctx->extradata, avctx->extradata_size);
592                 sp<ABuffer> esds = MakeMPEGVideoESDS(csd);
593                 meta->setData(kKeyESDS, kTypeESDS, esds->data(), esds->size());
594             }
595             break;
596         case CODEC_ID_MPEG2VIDEO:
597             LOGV("MPEG2VIDEO");
598             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG2);
599             {
600                 sp<ABuffer> csd = new ABuffer(avctx->extradata_size);
601                 memcpy(csd->data(), avctx->extradata, avctx->extradata_size);
602                 sp<ABuffer> esds = MakeMPEGVideoESDS(csd);
603                 meta->setData(kKeyESDS, kTypeESDS, esds->data(), esds->size());
604             }
605             break;
606         case CODEC_ID_VC1:
607             LOGV("VC1");
608             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_WMV12);
609             meta->setData(kKeyESDS, kTypeESDS, avctx->extradata, avctx->extradata_size);
610             break;
611         default:
612             CHECK(!"Should not be here. Unsupported codec.");
613             break;
614         }
615
616         LOGI("width: %d, height: %d, bit_rate: %d", avctx->width, avctx->height, avctx->bit_rate);
617
618         meta->setInt32(kKeyWidth, avctx->width);
619         meta->setInt32(kKeyHeight, avctx->height);
620         meta->setInt32(kKeyBitRate, avctx->bit_rate);
621         if (mFormatCtx->duration != AV_NOPTS_VALUE)
622             meta->setInt64(kKeyDuration, mFormatCtx->duration);
623
624         LOGV("create a video track");
625         index = mTracks.add(
626             stream_index, new Track(this, meta, isAVC, mVideoStream, &mVideoQ));
627
628         mDefersToCreateVideoTrack = false;
629
630         break;
631     case AVMEDIA_TYPE_AUDIO:
632         if (mAudioStreamIdx == -1)
633             mAudioStreamIdx = stream_index;
634         if (mAudioStream == NULL)
635             mAudioStream = mFormatCtx->streams[stream_index];
636         if (!mAudioQInited) {
637             packet_queue_init(&mAudioQ);
638             mAudioQInited = true;
639         }
640
641         ret = check_extradata(avctx);
642         if (ret != 1) {
643             if (ret == -1) {
644                 // disable the stream
645                 mAudioStreamIdx = -1;
646                 mAudioStream = NULL;
647                 packet_queue_end(&mAudioQ);
648                 mAudioQInited =  false;
649                 mFormatCtx->streams[stream_index]->discard = AVDISCARD_ALL;
650             }
651             return ret;
652         }
653
654
655         LOGV("audio extradata:");
656         hexdump(avctx->extradata, avctx->extradata_size);
657
658         switch(avctx->codec_id) {
659         case CODEC_ID_MP3:
660             LOGV("MP3");
661             meta = new MetaData;
662             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_MPEG);
663             //meta->setData(kKeyESDS, kTypeESDS, avctx->extradata, avctx->extradata_size);
664             break;
665         case CODEC_ID_AAC:
666             LOGV("AAC"); 
667             uint32_t sr;
668             const uint8_t *header;
669             uint8_t profile, sf_index, channel;
670
671             header = avctx->extradata;
672             CHECK(header != NULL);
673
674             // AudioSpecificInfo follows
675             // oooo offf fccc c000
676             // o - audioObjectType
677             // f - samplingFreqIndex
678             // c - channelConfig
679             profile = ((header[0] & 0xf8) >> 3) - 1;
680             sf_index = (header[0] & 0x07) << 1 | (header[1] & 0x80) >> 7;
681             sr = get_sample_rate(sf_index);
682             if (sr == 0) {
683                 LOGE("unsupport the sample rate");
684                 return -1;
685             }
686             channel = (header[1] >> 3) & 0xf;
687             LOGV("profile: %d, sf_index: %d, channel: %d", profile, sf_index, channel);
688
689             meta = MakeAACCodecSpecificData(profile, sf_index, channel);
690             meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AAC);
691             break;
692         default:
693             CHECK(!"Should not be here. Unsupported codec.");
694             break;
695         }
696
697         LOGI("bit_rate: %d, sample_rate: %d, channels: %d", avctx->bit_rate, avctx->sample_rate, avctx->channels);
698
699         meta->setInt32(kKeySampleRate, avctx->sample_rate);
700         meta->setInt32(kKeyChannelCount, avctx->channels);
701         meta->setInt32(kKeyBitRate, avctx->bit_rate);
702         if (mFormatCtx->duration != AV_NOPTS_VALUE)
703             meta->setInt64(kKeyDuration, mFormatCtx->duration);
704
705         if (avctx->codec_id != CODEC_ID_MP3) {
706             LOGV("audio meta esds:");
707             CHECK(meta->findData(kKeyESDS, &type, &data, &size));
708             hexdump(data, size);
709         }
710
711         LOGV("create a audio track");
712         index = mTracks.add(
713             stream_index, new Track(this, meta, false, mAudioStream, &mAudioQ));
714
715         mDefersToCreateAudioTrack = false;
716
717         break;
718     case AVMEDIA_TYPE_SUBTITLE:
719         /* Unsupport now */
720         CHECK(!"Should not be here. Unsupported media type.");
721         break;
722     default:
723         CHECK(!"Should not be here. Unsupported media type.");
724         break;
725     }
726     return 0;
727 }
728
729 void FFmpegExtractor::stream_component_close(int stream_index)
730 {
731     AVCodecContext *avctx;
732
733     if (stream_index < 0 || stream_index >= mFormatCtx->nb_streams)
734         return;
735     avctx = mFormatCtx->streams[stream_index]->codec;
736
737     switch (avctx->codec_type) {
738     case AVMEDIA_TYPE_VIDEO:
739         LOGV("packet_queue_abort videoq");
740         packet_queue_abort(&mVideoQ);
741         /* wait until the end */
742         while (!mAbortRequest && !mVideoEOSReceived) {
743             LOGV("wait for video received");
744             SDL_Delay(10);
745         }
746         LOGV("packet_queue_end videoq");
747         packet_queue_end(&mVideoQ);
748         break;
749     case AVMEDIA_TYPE_AUDIO:
750         LOGV("packet_queue_abort audioq");
751         packet_queue_abort(&mAudioQ);
752         while (!mAbortRequest && !mAudioEOSReceived) {
753             LOGV("wait for audio received");
754             SDL_Delay(10);
755         }
756         LOGV("packet_queue_end audioq");
757         packet_queue_end(&mAudioQ);
758         break;
759     case AVMEDIA_TYPE_SUBTITLE:
760         break;
761     default:
762         break;
763     }
764
765     mFormatCtx->streams[stream_index]->discard = AVDISCARD_ALL;
766     switch (avctx->codec_type) {
767     case AVMEDIA_TYPE_VIDEO:
768         mVideoStream    = NULL;
769         mVideoStreamIdx = -1;
770         if (mVideoBsfc) {
771             av_bitstream_filter_close(mVideoBsfc);
772             mVideoBsfc  = NULL;
773         }
774         break;
775     case AVMEDIA_TYPE_AUDIO:
776         mAudioStream    = NULL;
777         mAudioStreamIdx = -1;
778         if (mAudioBsfc) {
779             av_bitstream_filter_close(mAudioBsfc);
780             mAudioBsfc  = NULL;
781         }
782         break;
783     case AVMEDIA_TYPE_SUBTITLE:
784         break;
785     default:
786         break;
787     }
788 }
789
790 void FFmpegExtractor::reachedEOS(enum AVMediaType media_type)
791 {
792     Mutex::Autolock autoLock(mLock);
793
794     if (media_type == AVMEDIA_TYPE_VIDEO) {
795         mVideoEOSReceived = true;
796     } else if (media_type == AVMEDIA_TYPE_AUDIO) {
797         mAudioEOSReceived = true;
798     }
799 }
800
801 /* seek in the stream */
802 int FFmpegExtractor::stream_seek(int64_t pos, enum AVMediaType media_type)
803 {
804     Mutex::Autolock autoLock(mLock);
805
806     if (mVideoStreamIdx >= 0 &&
807         mAudioStreamIdx >= 0 &&
808         media_type == AVMEDIA_TYPE_AUDIO &&
809         !mVideoEOSReceived) {
810        return NO_SEEK;
811     }
812
813     // flush immediately
814     if (mAudioStreamIdx >= 0)
815         packet_queue_flush(&mAudioQ);
816     if (mVideoStreamIdx >= 0)
817         packet_queue_flush(&mVideoQ);
818
819     mSeekPos = pos;
820     mSeekFlags &= ~AVSEEK_FLAG_BYTE;
821     mSeekReq = 1;
822
823     return SEEK;
824 }
825
826 // staitc
827 int FFmpegExtractor::decode_interrupt_cb(void *ctx)
828 {
829     FFmpegExtractor *extrator = static_cast<FFmpegExtractor *>(ctx);
830     return extrator->mAbortRequest;
831 }
832
833 void FFmpegExtractor::print_error_ex(const char *filename, int err)
834 {
835     char errbuf[128];
836     const char *errbuf_ptr = errbuf;
837
838     if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
839         errbuf_ptr = strerror(AVUNERROR(err));
840     LOGI("%s: %s\n", filename, errbuf_ptr);
841 }
842
843 void FFmpegExtractor::setFFmpegDefaultOpts()
844 {
845     mGenPTS       = 0;
846 #if DIABLE_VIDEO
847     mVideoDisable = 1;
848 #else
849     mVideoDisable = 0;
850 #endif
851 #if DIABLE_AUDIO
852     mAudioDisable = 1;
853 #else
854     mAudioDisable = 0;
855 #endif
856     mShowStatus   = 1;
857     mSeekByBytes  = 0; /* seek by bytes 0=off 1=on -1=auto" */
858     mStartTime    = AV_NOPTS_VALUE;
859     mDuration     = AV_NOPTS_VALUE;
860     mSeekPos      = AV_NOPTS_VALUE;
861     mAutoExit     = 1;
862     mLoop         = 1;
863
864     mVideoStreamIdx = -1;
865     mAudioStreamIdx = -1;
866     mVideoStream  = NULL;
867     mAudioStream  = NULL;
868     mVideoQInited = false;
869     mAudioQInited = false;
870     mDefersToCreateVideoTrack = false;
871     mDefersToCreateAudioTrack = false;
872     mVideoBsfc = NULL;
873     mAudioBsfc = NULL;
874
875     mAbortRequest = 0;
876     mPaused       = 0;
877     mLastPaused   = 0;
878     mSeekReq      = 0;
879
880     mProbePkts    = 0;
881     mEOF          = false;
882 }
883
884 int FFmpegExtractor::initFFmpeg()
885 {
886     int err, i;
887     int eof = 0;
888     int ret = 0, audio_ret = 0, video_ret = 0;
889     int pkt_in_play_range = 0;
890     AVDictionaryEntry *t;
891     AVDictionary **opts;
892     int orig_nb_streams;
893     int st_index[AVMEDIA_TYPE_NB] = {0};
894     int wanted_stream[AVMEDIA_TYPE_NB] = {0};
895     st_index[AVMEDIA_TYPE_AUDIO]  = -1;
896     st_index[AVMEDIA_TYPE_VIDEO]  = -1;
897     wanted_stream[AVMEDIA_TYPE_AUDIO]  = -1;
898     wanted_stream[AVMEDIA_TYPE_VIDEO]  = -1;
899
900     setFFmpegDefaultOpts();
901  
902     //nam_av_log_set_flags(AV_LOG_SKIP_REPEATED);
903     av_log_set_level(AV_LOG_DEBUG);
904     av_log_set_callback(nam_av_log_callback);
905
906     /* register all codecs, demux and protocols */
907     avcodec_register_all();
908 #if CONFIG_AVDEVICE
909     avdevice_register_all();
910 #endif
911     av_register_all();
912     avformat_network_init();
913
914     init_opts();
915
916     if (av_lockmgr_register(lockmgr)) {
917         LOGE("could not initialize lock manager!");
918     }
919
920     av_init_packet(&flush_pkt);
921     flush_pkt.data = (uint8_t *)"FLUSH";
922     flush_pkt.size = 0;
923
924     mFormatCtx = avformat_alloc_context();
925     mFormatCtx->interrupt_callback.callback = decode_interrupt_cb;
926     mFormatCtx->interrupt_callback.opaque = this;
927     LOGV("1");
928     LOGV("mFilename: %s", mFilename);
929     err = avformat_open_input(&mFormatCtx, mFilename, NULL, &format_opts);
930     if (err < 0) {
931         print_error_ex(mFilename, err);
932         ret = -1;
933         goto fail;
934     }
935     if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
936         LOGE("Option %s not found.\n", t->key);
937         //ret = AVERROR_OPTION_NOT_FOUND;
938         ret = -1;
939         goto fail;
940     }
941
942     if (mGenPTS)
943         mFormatCtx->flags |= AVFMT_FLAG_GENPTS;
944
945     opts = setup_find_stream_info_opts(mFormatCtx, codec_opts);
946     orig_nb_streams = mFormatCtx->nb_streams;
947
948     err = avformat_find_stream_info(mFormatCtx, opts);
949     if (err < 0) {
950         LOGE("%s: could not find codec parameters\n", mFilename);
951         ret = -1;
952         goto fail;
953     }
954     for (i = 0; i < orig_nb_streams; i++)
955         av_dict_free(&opts[i]);
956     av_freep(&opts);
957
958     if (mFormatCtx->pb)
959         mFormatCtx->pb->eof_reached = 0; // FIXME hack, ffplay maybe should not use url_feof() to test for the end
960
961     if (mSeekByBytes < 0)
962         mSeekByBytes = !!(mFormatCtx->iformat->flags & AVFMT_TS_DISCONT);
963
964     /* if seeking requested, we execute it */
965     if (mStartTime != AV_NOPTS_VALUE) {
966         int64_t timestamp;
967
968         timestamp = mStartTime;
969         /* add the stream start time */
970         if (mFormatCtx->start_time != AV_NOPTS_VALUE)
971             timestamp += mFormatCtx->start_time;
972         ret = avformat_seek_file(mFormatCtx, -1, INT64_MIN, timestamp, INT64_MAX, 0);
973         if (ret < 0) {
974             LOGE("%s: could not seek to position %0.3f",
975                     mFilename, (double)timestamp / AV_TIME_BASE);
976             goto fail;
977         }
978     }
979
980     for (i = 0; i < mFormatCtx->nb_streams; i++)
981         mFormatCtx->streams[i]->discard = AVDISCARD_ALL;
982     if (!mVideoDisable)
983         st_index[AVMEDIA_TYPE_VIDEO] =
984             av_find_best_stream(mFormatCtx, AVMEDIA_TYPE_VIDEO,
985                                 wanted_stream[AVMEDIA_TYPE_VIDEO], -1, NULL, 0);
986     if (!mAudioDisable)
987         st_index[AVMEDIA_TYPE_AUDIO] =
988             av_find_best_stream(mFormatCtx, AVMEDIA_TYPE_AUDIO,
989                                 wanted_stream[AVMEDIA_TYPE_AUDIO],
990                                 st_index[AVMEDIA_TYPE_VIDEO],
991                                 NULL, 0);
992     if (mShowStatus) {
993         av_dump_format(mFormatCtx, 0, mFilename, 0);
994     }
995
996     if (mFormatCtx->duration != AV_NOPTS_VALUE) {
997         int hours, mins, secs, us;
998         secs = mFormatCtx->duration / AV_TIME_BASE;
999         us = mFormatCtx->duration % AV_TIME_BASE;
1000         mins = secs / 60;
1001         secs %= 60;
1002         hours = mins / 60;
1003         mins %= 60;
1004         LOGI("the duration is %02d:%02d:%02d.%02d", hours, mins, secs, (100 * us) / AV_TIME_BASE);
1005     }
1006
1007     if (st_index[AVMEDIA_TYPE_AUDIO] >= 0) {
1008         audio_ret = stream_component_open(st_index[AVMEDIA_TYPE_AUDIO]);
1009     }
1010
1011     if (st_index[AVMEDIA_TYPE_VIDEO] >= 0) {
1012         video_ret = stream_component_open(st_index[AVMEDIA_TYPE_VIDEO]);
1013     }
1014
1015     if ( audio_ret < 0 && video_ret < 0) {
1016         LOGE("%s: could not open codecs\n", mFilename);
1017         ret = -1;
1018         goto fail;
1019     }
1020
1021     ret = 0;
1022
1023 fail:
1024     return ret;
1025 }
1026
1027 void FFmpegExtractor::deInitFFmpeg()
1028 {
1029     if (mFormatCtx) {
1030         avformat_close_input(&mFormatCtx);
1031     }
1032         
1033     av_lockmgr_register(NULL);
1034     uninit_opts();
1035     avformat_network_deinit();
1036
1037     av_log(NULL, AV_LOG_QUIET, "%s", "");
1038 }
1039
1040 status_t FFmpegExtractor::startReaderThread() {
1041     LOGV("Starting reader thread");
1042     Mutex::Autolock autoLock(mLock);
1043
1044     if (mReaderThreadStarted)
1045         return OK;
1046
1047     pthread_attr_t attr;
1048     pthread_attr_init(&attr);
1049     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1050     pthread_create(&mReaderThread, &attr, ReaderWrapper, this);
1051     pthread_attr_destroy(&attr);
1052     mReaderThreadStarted = true;
1053     LOGD("Reader thread started");
1054
1055     return OK;
1056 }
1057
1058 void FFmpegExtractor::stopReaderThread() {
1059     LOGV("Stopping reader thread");
1060     Mutex::Autolock autoLock(mLock);
1061
1062     if (!mReaderThreadStarted) {
1063         LOGD("Reader thread have been stopped");
1064         return;
1065     }
1066
1067     mAbortRequest = 1;
1068
1069     void *dummy;
1070     pthread_join(mReaderThread, &dummy);
1071     mReaderThreadStarted = false;
1072     LOGD("Reader thread stopped");
1073 }
1074
1075 // static
1076 void *FFmpegExtractor::ReaderWrapper(void *me) {
1077     ((FFmpegExtractor *)me)->readerEntry();
1078
1079     return NULL;
1080 }
1081
1082 void FFmpegExtractor::readerEntry() {
1083     int err, i, ret;
1084     AVPacket pkt1, *pkt = &pkt1;
1085     int eof = 0;
1086     int pkt_in_play_range = 0;
1087
1088     LOGV("FFmpegExtractor::readerEntry");
1089
1090     mVideoEOSReceived = false;
1091     mAudioEOSReceived = false;
1092
1093     for (;;) {
1094         if (mAbortRequest)
1095             break;
1096
1097         if (mPaused != mLastPaused) {
1098             mLastPaused = mPaused;
1099             if (mPaused)
1100                 mReadPauseReturn = av_read_pause(mFormatCtx);
1101             else
1102                 av_read_play(mFormatCtx);
1103         }
1104 #if CONFIG_RTSP_DEMUXER || CONFIG_MMSH_PROTOCOL
1105         if (mPaused &&
1106                 (!strcmp(mFormatCtx->iformat->name, "rtsp") ||
1107                  (mFormatCtx->pb && !strncmp(mFilename, "mmsh:", 5)))) {
1108             /* wait 10 ms to avoid trying to get another packet */
1109             /* XXX: horrible */
1110             SDL_Delay(10);
1111             continue;
1112         }
1113 #endif
1114
1115         if (mSeekReq) {
1116             LOGV("readerEntry, mSeekReq: %d", mSeekReq);
1117             ret = avformat_seek_file(mFormatCtx, -1, INT64_MIN, mSeekPos, INT64_MAX, mSeekFlags);
1118             if (ret < 0) {
1119                 LOGE("%s: error while seeking", mFormatCtx->filename);
1120             } else {
1121                 if (mAudioStreamIdx >= 0) {
1122                     packet_queue_flush(&mAudioQ);
1123                     packet_queue_put(&mAudioQ, &flush_pkt);
1124                 }
1125                 if (mVideoStreamIdx >= 0) {
1126                     packet_queue_flush(&mVideoQ);
1127                     packet_queue_put(&mVideoQ, &flush_pkt);
1128                 }
1129             }
1130             mSeekReq = 0;
1131             eof = 0;
1132         }
1133
1134         /* if the queue are full, no need to read more */
1135         if (   mAudioQ.size + mVideoQ.size > MAX_QUEUE_SIZE
1136             || (   (mAudioQ   .size  > MIN_AUDIOQ_SIZE || mAudioStreamIdx < 0)
1137                 && (mVideoQ   .nb_packets > MIN_FRAMES || mVideoStreamIdx < 0))) {
1138 #if DEBUG_READ_ENTRY
1139             LOGV("readerEntry, is full, fuck");
1140 #endif
1141             /* wait 10 ms */
1142             SDL_Delay(10);
1143             continue;
1144         }
1145
1146         if (eof) {
1147             if (mVideoStreamIdx >= 0) {
1148                 av_init_packet(pkt);
1149                 pkt->data = NULL;
1150                 pkt->size = 0;
1151                 pkt->stream_index = mVideoStreamIdx;
1152                 packet_queue_put(&mVideoQ, pkt);
1153             }
1154             if (mAudioStreamIdx >= 0) {
1155                 av_init_packet(pkt);
1156                 pkt->data = NULL;
1157                 pkt->size = 0;
1158                 pkt->stream_index = mAudioStreamIdx;
1159                 packet_queue_put(&mAudioQ, pkt);
1160             }
1161             SDL_Delay(10);
1162 #if DEBUG_READ_ENTRY
1163             LOGV("readerEntry, eof = 1, mVideoQ.size: %d, mVideoQ.nb_packets: %d, mAudioQ.size: %d, mAudioQ.nb_packets: %d",
1164                     mVideoQ.size, mVideoQ.nb_packets, mAudioQ.size, mAudioQ.nb_packets);
1165 #endif
1166             if (mAudioQ.size + mVideoQ.size  == 0) {
1167                 if (mLoop != 1 && (!mLoop || --mLoop)) {
1168                     if (mVideoStreamIdx >= 0) {
1169                         stream_seek(mStartTime != AV_NOPTS_VALUE ? mStartTime : 0, AVMEDIA_TYPE_VIDEO);
1170                     } else if (mAudioStreamIdx >= 0) {
1171                         stream_seek(mStartTime != AV_NOPTS_VALUE ? mStartTime : 0, AVMEDIA_TYPE_AUDIO);
1172                     }
1173                 } else if (mAutoExit) {
1174                     ret = AVERROR_EOF;
1175                     goto fail;
1176                 }
1177             }
1178             eof=0;
1179             continue;
1180         }
1181
1182         ret = av_read_frame(mFormatCtx, pkt);
1183         mProbePkts++;
1184         if (ret < 0) {
1185             if (ret == AVERROR_EOF || url_feof(mFormatCtx->pb))
1186                 if (ret == AVERROR_EOF) {
1187                     //LOGV("ret == AVERROR_EOF");
1188                 }
1189                 if (url_feof(mFormatCtx->pb)) {
1190                     LOGV("url_feof(mFormatCtx->pb)");
1191                 }
1192
1193                 eof = 1;
1194                 mEOF = true;
1195             if (mFormatCtx->pb && mFormatCtx->pb->error) {
1196                 LOGE("mFormatCtx->pb->error: %d", mFormatCtx->pb->error);
1197                 break;
1198             }
1199             SDL_Delay(100);
1200             continue;
1201         }
1202
1203         if (pkt->stream_index == mAudioStreamIdx) {
1204             int ret;
1205             uint8_t *outbuf;
1206             int   outbuf_size;
1207             AVCodecContext *avctx = mFormatCtx->streams[mAudioStreamIdx]->codec;
1208             if (mAudioBsfc && pkt && pkt->data) {
1209                 ret = av_bitstream_filter_filter(mAudioBsfc, avctx, NULL, &outbuf, &outbuf_size,
1210                                    pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY);
1211
1212                 if (ret < 0 ||!outbuf_size) {
1213                     av_free_packet(pkt);
1214                     continue;
1215                 }
1216                 if (outbuf && outbuf != pkt->data) {
1217                     memmove(pkt->data, outbuf, outbuf_size);
1218                     pkt->size = outbuf_size;
1219                 }
1220             }
1221             if (mDefersToCreateAudioTrack) {
1222                 if (avctx->extradata_size <= 0) {
1223                     av_free_packet(pkt);
1224                     continue;
1225                 }
1226                 stream_component_open(mAudioStreamIdx);
1227                 if (!mDefersToCreateAudioTrack)
1228                     LOGI("probe packet counter: %d when create audio track ok", mProbePkts);
1229                 if (mProbePkts == EXTRACTOR_MAX_PROBE_PACKETS)
1230                     LOGI("probe packet counter to max: %d, create audio track: %d",
1231                         mProbePkts, !mDefersToCreateAudioTrack);
1232             }
1233         }
1234
1235         /* check if packet is in play range specified by user, then queue, otherwise discard */
1236         pkt_in_play_range = mDuration == AV_NOPTS_VALUE ||
1237                 (pkt->pts - mFormatCtx->streams[pkt->stream_index]->start_time) *
1238                 av_q2d(mFormatCtx->streams[pkt->stream_index]->time_base) -
1239                 (double)(mStartTime != AV_NOPTS_VALUE ? mStartTime : 0) / 1000000
1240                 <= ((double)mDuration / 1000000);
1241         if (pkt->stream_index == mAudioStreamIdx && pkt_in_play_range) {
1242             packet_queue_put(&mAudioQ, pkt);
1243         } else if (pkt->stream_index == mVideoStreamIdx && pkt_in_play_range) {
1244             packet_queue_put(&mVideoQ, pkt);
1245         } else {
1246             av_free_packet(pkt);
1247         }
1248     }
1249     /* wait until the end */
1250     while (!mAbortRequest) {
1251         SDL_Delay(100);
1252     }
1253
1254     ret = 0;
1255 fail:
1256     LOGI("reader thread goto end...");
1257
1258     /* close each stream */
1259     if (mAudioStreamIdx >= 0)
1260         stream_component_close(mAudioStreamIdx);
1261     if (mVideoStreamIdx >= 0)
1262         stream_component_close(mVideoStreamIdx);
1263     if (mFormatCtx) {
1264         avformat_close_input(&mFormatCtx);
1265     }
1266 }
1267
1268 ////////////////////////////////////////////////////////////////////////////////
1269
1270 FFmpegExtractor::Track::Track(
1271         const sp<FFmpegExtractor> &extractor, sp<MetaData> meta, bool isAVC,
1272           AVStream *stream, PacketQueue *queue)
1273     : mExtractor(extractor),
1274       mMeta(meta),
1275       mIsAVC(isAVC),
1276       mStream(stream),
1277       mQueue(queue) {
1278     const char *mime;
1279
1280     /* H.264 Video Types */
1281     {
1282         mNal2AnnexB = false;
1283
1284         if (mIsAVC) {
1285             uint32_t type;
1286             const void *data;
1287             size_t size;
1288             CHECK(meta->findData(kKeyAVCC, &type, &data, &size));
1289
1290             const uint8_t *ptr = (const uint8_t *)data;
1291
1292             CHECK(size >= 7);
1293             CHECK_EQ((unsigned)ptr[0], 1u);  // configurationVersion == 1
1294
1295             // The number of bytes used to encode the length of a NAL unit.
1296             mNALLengthSize = 1 + (ptr[4] & 3);
1297
1298             LOGV("the stream is AVC, the length of a NAL unit: %d", mNALLengthSize);
1299
1300             mNal2AnnexB = true;
1301         }
1302     }
1303
1304     mMediaType = mStream->codec->codec_type;
1305 }
1306
1307 FFmpegExtractor::Track::~Track() {
1308 }
1309
1310 status_t FFmpegExtractor::Track::start(MetaData *params) {
1311     Mutex::Autolock autoLock(mLock);
1312     //mExtractor->startReaderThread();
1313     return OK;
1314 }
1315
1316 status_t FFmpegExtractor::Track::stop() {
1317     Mutex::Autolock autoLock(mLock);
1318     mExtractor->stopReaderThread();
1319     return OK;
1320 }
1321
1322 sp<MetaData> FFmpegExtractor::Track::getFormat() {
1323     Mutex::Autolock autoLock(mLock);
1324
1325     return mMeta;
1326 }
1327
1328 status_t FFmpegExtractor::Track::read(
1329         MediaBuffer **buffer, const ReadOptions *options) {
1330     *buffer = NULL;
1331
1332     Mutex::Autolock autoLock(mLock);
1333
1334     AVPacket pkt;
1335     bool seeking = false;
1336     bool waitKeyPkt = false;
1337     ReadOptions::SeekMode mode;
1338     int64_t pktTS = AV_NOPTS_VALUE;
1339     int64_t seekTimeUs = AV_NOPTS_VALUE;
1340     int64_t timeUs;
1341     int key;
1342     status_t status = OK;
1343
1344     if (options && options->getSeekTo(&seekTimeUs, &mode)) {
1345         LOGV("~~~%s seekTimeUs: %lld, mode: %d", av_get_media_type_string(mMediaType), seekTimeUs, mode);
1346         if (mExtractor->stream_seek(seekTimeUs, mMediaType) == SEEK)
1347             seeking = true;
1348     }
1349
1350 retry:
1351     if (mExtractor->packet_queue_get(mQueue, &pkt, 1) < 0) {
1352         mExtractor->reachedEOS(mMediaType);
1353         return ERROR_END_OF_STREAM;
1354     }
1355
1356     if (seeking) {
1357         if (pkt.data != flush_pkt.data) {
1358             av_free_packet(&pkt);
1359             goto retry;
1360         } else {
1361             seeking = false;
1362 #if WAIT_KEY_PACKET_AFTER_SEEK
1363             waitKeyPkt = true;
1364 #endif
1365         }
1366     }
1367
1368     if (pkt.data == flush_pkt.data) {
1369         LOGV("read %s flush pkt", av_get_media_type_string(mMediaType));
1370         av_free_packet(&pkt);
1371         goto retry;
1372     } else if (pkt.data == NULL && pkt.size == 0) {
1373         LOGV("read %s eos pkt", av_get_media_type_string(mMediaType));
1374         av_free_packet(&pkt);
1375         mExtractor->reachedEOS(mMediaType);
1376         return ERROR_END_OF_STREAM;
1377     }
1378
1379     key = pkt.flags & AV_PKT_FLAG_KEY ? 1 : 0;
1380
1381     if (waitKeyPkt) {
1382         if (!key) {
1383             LOGV("drop the no key packet");
1384             av_free_packet(&pkt);
1385             goto retry;
1386         } else {
1387             LOGV("~~~~~~ got the key packet");
1388             waitKeyPkt = false;
1389         }
1390     }
1391      
1392     MediaBuffer *mediaBuffer = new MediaBuffer(pkt.size + FF_INPUT_BUFFER_PADDING_SIZE);
1393     mediaBuffer->meta_data()->clear();
1394     mediaBuffer->set_range(0, pkt.size);
1395 #if DISABLE_NAL_TO_ANNEXB
1396     mNal2AnnexB = false;
1397 #endif
1398     if (mIsAVC && mNal2AnnexB) {
1399         /* Convert H.264 NAL format to annex b */
1400         if (mNALLengthSize >= 3 && mNALLengthSize <= 4 )
1401         {
1402             uint8_t *dst = (uint8_t *)mediaBuffer->data();
1403
1404             /* This only works for NAL sizes 3-4 */
1405             size_t len = pkt.size, i;
1406             uint8_t *ptr = pkt.data;
1407             while (len >= mNALLengthSize) {
1408                 uint32_t nal_len = 0;
1409                 for( i = 0; i < mNALLengthSize; i++ ) {
1410                     nal_len = (nal_len << 8) | ptr[i];
1411                     dst[i] = 0;
1412                 }
1413                 dst[mNALLengthSize - 1] = 1;
1414                 if (nal_len > INT_MAX || nal_len > (unsigned int)len) {
1415                     status = ERROR_MALFORMED;
1416                     break;
1417                 }
1418                 dst += mNALLengthSize;
1419                 ptr += mNALLengthSize;
1420                 len -= mNALLengthSize;
1421
1422                 memcpy(dst, ptr, nal_len);
1423
1424                 dst += nal_len;
1425                 ptr += nal_len;
1426                 len -= nal_len;
1427             }
1428         } else {
1429              status = ERROR_MALFORMED;
1430         }
1431
1432         if (status != OK) {
1433             LOGV("status != OK");
1434             mediaBuffer->release();
1435             mediaBuffer = NULL;
1436             av_free_packet(&pkt);
1437             return ERROR_MALFORMED;
1438         }
1439     } else {
1440         memcpy(mediaBuffer->data(), pkt.data, pkt.size);
1441     }
1442
1443     pktTS = pkt.pts;
1444     // use dts when AVI
1445     if (pkt.pts == AV_NOPTS_VALUE)
1446         pktTS = pkt.dts;
1447
1448 #if 0
1449     // TODO, Stagefright can't handle negative timestamps
1450     // if needed, work around this by offsetting them manually?
1451     if (pktTS < 0)
1452         pktTS = 0;
1453 #endif
1454
1455     timeUs = (int64_t)(pktTS * av_q2d(mStream->time_base) * 1000000);
1456
1457 #if 0
1458     LOGV("read %s pkt, size: %d, key: %d, pts: %lld, dts: %lld, timeUs: %llu us (%.2f secs)",
1459         av_get_media_type_string(mMediaType), pkt.size, key, pkt.pts, pkt.dts, timeUs, timeUs/1E6);
1460 #endif
1461
1462 #if 0
1463     // TODO, Stagefright can't handle negative timestamps
1464     // if needed, work around this by offsetting them manually?
1465     if (timeUs < 0)
1466         timeUs = 0;
1467 #endif
1468
1469     mediaBuffer->meta_data()->setInt64(kKeyTime, timeUs);
1470     mediaBuffer->meta_data()->setInt32(kKeyIsSyncFrame, key);
1471
1472     *buffer = mediaBuffer;
1473
1474     av_free_packet(&pkt);
1475
1476     return OK;
1477 }
1478
1479 ////////////////////////////////////////////////////////////////////////////////
1480
1481 // TODO: Temp hack
1482 typedef struct {
1483     const char *extension;
1484     const char *container;
1485 } extmap;
1486
1487 static extmap FILE_EXTS [] =  {
1488         {".mp4", MEDIA_MIMETYPE_CONTAINER_MPEG4},
1489         {".3gp", MEDIA_MIMETYPE_CONTAINER_MPEG4},
1490         {".mp3", MEDIA_MIMETYPE_AUDIO_MPEG},
1491         {".mov", MEDIA_MIMETYPE_CONTAINER_MOV},
1492         {".mkv", MEDIA_MIMETYPE_CONTAINER_MATROSKA},
1493         {".ts",  MEDIA_MIMETYPE_CONTAINER_TS},
1494         {".avi", MEDIA_MIMETYPE_CONTAINER_AVI},
1495 #if 0
1496         {".asf", MEDIA_MIMETYPE_CONTAINER_ASF},
1497         {".wmv", MEDIA_MIMETYPE_CONTAINER_WMV},
1498         {".wma", MEDIA_MIMETYPE_CONTAINER_WMA},
1499         {".mpg", MEDIA_MIMETYPE_CONTAINER_MPG},
1500         {".flv", MEDIA_MIMETYPE_CONTAINER_FLV},
1501         {".divx", MEDIA_MIMETYPE_CONTAINER_DIVX},
1502         {".mp2", MEDIA_MIMETYPE_CONTAINER_MP2},
1503         {".ape", MEDIA_MIMETYPE_CONTAINER_APE},
1504         {".rm ", MEDIA_MIMETYPE_CONTAINER_RM},
1505         {".ra",  MEDIA_MIMETYPE_CONTAINER_RA},
1506 #endif
1507 };
1508
1509 bool SniffFFMPEG(
1510         const sp<DataSource> &source, String8 *mimeType, float *confidence,
1511         sp<AMessage> *meta) {
1512     LOGV("SniffFFMPEG");
1513     size_t i;
1514     const char *uri, *container = NULL;
1515
1516     //av_find_input_format()??
1517     uri = source->getNamURI();
1518
1519     if (!uri)
1520         return false;
1521
1522     LOGI("ffmpeg uri: %s", uri);
1523
1524     LOGI("list the file extensions suppoted by ffmpeg: ");
1525     LOGI("========================================");
1526     for (i = 0; i < NELEM(FILE_EXTS); ++i) {
1527             LOGV("file_exts[%02d]: %s", i, FILE_EXTS[i].extension);
1528     }
1529     LOGI("========================================");
1530
1531     int lenURI = strlen(uri);
1532     for (i = 0; i < NELEM(FILE_EXTS); ++i) {
1533         int len = strlen(FILE_EXTS[i].extension);
1534         int start = lenURI - len;
1535         if (start > 0) {
1536             if (!av_strncasecmp(uri + start, FILE_EXTS[i].extension, len)) {
1537                 container = FILE_EXTS[i].container;
1538                 break;
1539             }
1540         }
1541     }
1542
1543     if (container == NULL)
1544         return false;
1545
1546     LOGV("found container: %s", container);
1547
1548     *confidence = 0.88f;  // Slightly larger than other extractor's confidence
1549     mimeType->setTo(container);
1550
1551     /* use MPEG4Extractor(not extended extractor) for HTTP source only */
1552     if (!av_strcasecmp(container, MEDIA_MIMETYPE_CONTAINER_MPEG4)
1553             && (source->flags() & DataSource::kIsCachingDataSource)) {
1554             return true;
1555     }
1556
1557     *meta = new AMessage;
1558     (*meta)->setString("extended-extractor", "extended-extractor");
1559     (*meta)->setString("extended-extractor-subtype", "ffmpegextractor");
1560
1561     return true;
1562 }
1563
1564 }  // namespace android