OSDN Git Service

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