OSDN Git Service

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