OSDN Git Service

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