OSDN Git Service

change formatmap name from FORMAT_NAMES to FILE_FORMATS
[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 = initStreams();
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     deInitStreams();
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::initStreams()
920 {
921     int err, i;
922     status_t status;
923     int eof = 0;
924     int ret = 0, audio_ret = 0, video_ret = 0;
925     int pkt_in_play_range = 0;
926     AVDictionaryEntry *t;
927     AVDictionary **opts;
928     int orig_nb_streams;
929     int st_index[AVMEDIA_TYPE_NB] = {0};
930     int wanted_stream[AVMEDIA_TYPE_NB] = {0};
931     st_index[AVMEDIA_TYPE_AUDIO]  = -1;
932     st_index[AVMEDIA_TYPE_VIDEO]  = -1;
933     wanted_stream[AVMEDIA_TYPE_AUDIO]  = -1;
934     wanted_stream[AVMEDIA_TYPE_VIDEO]  = -1;
935
936     setFFmpegDefaultOpts();
937
938     status = initFFmpeg();
939     if (status != OK) {
940         ret = -1;
941         goto fail;
942     }
943
944     av_init_packet(&flush_pkt);
945     flush_pkt.data = (uint8_t *)"FLUSH";
946     flush_pkt.size = 0;
947
948     mFormatCtx = avformat_alloc_context();
949     mFormatCtx->interrupt_callback.callback = decode_interrupt_cb;
950     mFormatCtx->interrupt_callback.opaque = this;
951     LOGV("mFilename: %s", mFilename);
952     err = avformat_open_input(&mFormatCtx, mFilename, NULL, &format_opts);
953     if (err < 0) {
954         print_error_ex(mFilename, err);
955         ret = -1;
956         goto fail;
957     }
958     if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
959         LOGE("Option %s not found.\n", t->key);
960         //ret = AVERROR_OPTION_NOT_FOUND;
961         ret = -1;
962         goto fail;
963     }
964
965     if (mGenPTS)
966         mFormatCtx->flags |= AVFMT_FLAG_GENPTS;
967
968     opts = setup_find_stream_info_opts(mFormatCtx, codec_opts);
969     orig_nb_streams = mFormatCtx->nb_streams;
970
971     err = avformat_find_stream_info(mFormatCtx, opts);
972     if (err < 0) {
973         LOGE("%s: could not find codec parameters\n", mFilename);
974         ret = -1;
975         goto fail;
976     }
977     for (i = 0; i < orig_nb_streams; i++)
978         av_dict_free(&opts[i]);
979     av_freep(&opts);
980
981     if (mFormatCtx->pb)
982         mFormatCtx->pb->eof_reached = 0; // FIXME hack, ffplay maybe should not use url_feof() to test for the end
983
984     if (mSeekByBytes < 0)
985         mSeekByBytes = !!(mFormatCtx->iformat->flags & AVFMT_TS_DISCONT);
986
987     /* if seeking requested, we execute it */
988     if (mStartTime != AV_NOPTS_VALUE) {
989         int64_t timestamp;
990
991         timestamp = mStartTime;
992         /* add the stream start time */
993         if (mFormatCtx->start_time != AV_NOPTS_VALUE)
994             timestamp += mFormatCtx->start_time;
995         ret = avformat_seek_file(mFormatCtx, -1, INT64_MIN, timestamp, INT64_MAX, 0);
996         if (ret < 0) {
997             LOGE("%s: could not seek to position %0.3f",
998                     mFilename, (double)timestamp / AV_TIME_BASE);
999             goto fail;
1000         }
1001     }
1002
1003     for (i = 0; i < mFormatCtx->nb_streams; i++)
1004         mFormatCtx->streams[i]->discard = AVDISCARD_ALL;
1005     if (!mVideoDisable)
1006         st_index[AVMEDIA_TYPE_VIDEO] =
1007             av_find_best_stream(mFormatCtx, AVMEDIA_TYPE_VIDEO,
1008                                 wanted_stream[AVMEDIA_TYPE_VIDEO], -1, NULL, 0);
1009     if (!mAudioDisable)
1010         st_index[AVMEDIA_TYPE_AUDIO] =
1011             av_find_best_stream(mFormatCtx, AVMEDIA_TYPE_AUDIO,
1012                                 wanted_stream[AVMEDIA_TYPE_AUDIO],
1013                                 st_index[AVMEDIA_TYPE_VIDEO],
1014                                 NULL, 0);
1015     if (mShowStatus) {
1016         av_dump_format(mFormatCtx, 0, mFilename, 0);
1017     }
1018
1019     if (mFormatCtx->duration != AV_NOPTS_VALUE) {
1020         int hours, mins, secs, us;
1021         secs = mFormatCtx->duration / AV_TIME_BASE;
1022         us = mFormatCtx->duration % AV_TIME_BASE;
1023         mins = secs / 60;
1024         secs %= 60;
1025         hours = mins / 60;
1026         mins %= 60;
1027         LOGI("the duration is %02d:%02d:%02d.%02d", hours, mins, secs, (100 * us) / AV_TIME_BASE);
1028     }
1029
1030     if (st_index[AVMEDIA_TYPE_AUDIO] >= 0) {
1031         audio_ret = stream_component_open(st_index[AVMEDIA_TYPE_AUDIO]);
1032     }
1033
1034     if (st_index[AVMEDIA_TYPE_VIDEO] >= 0) {
1035         video_ret = stream_component_open(st_index[AVMEDIA_TYPE_VIDEO]);
1036     }
1037
1038     if ( audio_ret < 0 && video_ret < 0) {
1039         LOGE("%s: could not open codecs\n", mFilename);
1040         ret = -1;
1041         goto fail;
1042     }
1043
1044     ret = 0;
1045
1046 fail:
1047     return ret;
1048 }
1049
1050 void FFmpegExtractor::deInitStreams()
1051 {
1052     if (mFormatCtx) {
1053         avformat_close_input(&mFormatCtx);
1054     }
1055
1056     deInitFFmpeg();
1057 }
1058
1059 status_t FFmpegExtractor::startReaderThread() {
1060     LOGV("Starting reader thread");
1061     Mutex::Autolock autoLock(mLock);
1062
1063     if (mReaderThreadStarted)
1064         return OK;
1065
1066     pthread_attr_t attr;
1067     pthread_attr_init(&attr);
1068     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1069     pthread_create(&mReaderThread, &attr, ReaderWrapper, this);
1070     pthread_attr_destroy(&attr);
1071     mReaderThreadStarted = true;
1072     LOGD("Reader thread started");
1073
1074     return OK;
1075 }
1076
1077 void FFmpegExtractor::stopReaderThread() {
1078     LOGV("Stopping reader thread");
1079     Mutex::Autolock autoLock(mLock);
1080
1081     if (!mReaderThreadStarted) {
1082         LOGD("Reader thread have been stopped");
1083         return;
1084     }
1085
1086     mAbortRequest = 1;
1087
1088     void *dummy;
1089     pthread_join(mReaderThread, &dummy);
1090     mReaderThreadStarted = false;
1091     LOGD("Reader thread stopped");
1092 }
1093
1094 // static
1095 void *FFmpegExtractor::ReaderWrapper(void *me) {
1096     ((FFmpegExtractor *)me)->readerEntry();
1097
1098     return NULL;
1099 }
1100
1101 void FFmpegExtractor::readerEntry() {
1102     int err, i, ret;
1103     AVPacket pkt1, *pkt = &pkt1;
1104     int eof = 0;
1105     int pkt_in_play_range = 0;
1106
1107     LOGV("FFmpegExtractor::readerEntry");
1108
1109     mVideoEOSReceived = false;
1110     mAudioEOSReceived = false;
1111
1112     for (;;) {
1113         if (mAbortRequest)
1114             break;
1115
1116         if (mPaused != mLastPaused) {
1117             mLastPaused = mPaused;
1118             if (mPaused)
1119                 mReadPauseReturn = av_read_pause(mFormatCtx);
1120             else
1121                 av_read_play(mFormatCtx);
1122         }
1123 #if CONFIG_RTSP_DEMUXER || CONFIG_MMSH_PROTOCOL
1124         if (mPaused &&
1125                 (!strcmp(mFormatCtx->iformat->name, "rtsp") ||
1126                  (mFormatCtx->pb && !strncmp(mFilename, "mmsh:", 5)))) {
1127             /* wait 10 ms to avoid trying to get another packet */
1128             /* XXX: horrible */
1129             SDL_Delay(10);
1130             continue;
1131         }
1132 #endif
1133
1134         if (mSeekReq) {
1135             LOGV("readerEntry, mSeekReq: %d", mSeekReq);
1136             ret = avformat_seek_file(mFormatCtx, -1, INT64_MIN, mSeekPos, INT64_MAX, mSeekFlags);
1137             if (ret < 0) {
1138                 LOGE("%s: error while seeking", mFormatCtx->filename);
1139             } else {
1140                 if (mAudioStreamIdx >= 0) {
1141                     packet_queue_flush(&mAudioQ);
1142                     packet_queue_put(&mAudioQ, &flush_pkt);
1143                 }
1144                 if (mVideoStreamIdx >= 0) {
1145                     packet_queue_flush(&mVideoQ);
1146                     packet_queue_put(&mVideoQ, &flush_pkt);
1147                 }
1148             }
1149             mSeekReq = 0;
1150             eof = 0;
1151         }
1152
1153         /* if the queue are full, no need to read more */
1154         if (   mAudioQ.size + mVideoQ.size > MAX_QUEUE_SIZE
1155             || (   (mAudioQ   .size  > MIN_AUDIOQ_SIZE || mAudioStreamIdx < 0)
1156                 && (mVideoQ   .nb_packets > MIN_FRAMES || mVideoStreamIdx < 0))) {
1157 #if DEBUG_READ_ENTRY
1158             LOGV("readerEntry, is full, fuck");
1159 #endif
1160             /* wait 10 ms */
1161             SDL_Delay(10);
1162             continue;
1163         }
1164
1165         if (eof) {
1166             if (mVideoStreamIdx >= 0) {
1167                 av_init_packet(pkt);
1168                 pkt->data = NULL;
1169                 pkt->size = 0;
1170                 pkt->stream_index = mVideoStreamIdx;
1171                 packet_queue_put(&mVideoQ, pkt);
1172             }
1173             if (mAudioStreamIdx >= 0) {
1174                 av_init_packet(pkt);
1175                 pkt->data = NULL;
1176                 pkt->size = 0;
1177                 pkt->stream_index = mAudioStreamIdx;
1178                 packet_queue_put(&mAudioQ, pkt);
1179             }
1180             SDL_Delay(10);
1181 #if DEBUG_READ_ENTRY
1182             LOGV("readerEntry, eof = 1, mVideoQ.size: %d, mVideoQ.nb_packets: %d, mAudioQ.size: %d, mAudioQ.nb_packets: %d",
1183                     mVideoQ.size, mVideoQ.nb_packets, mAudioQ.size, mAudioQ.nb_packets);
1184 #endif
1185             if (mAudioQ.size + mVideoQ.size  == 0) {
1186                 if (mLoop != 1 && (!mLoop || --mLoop)) {
1187                     if (mVideoStreamIdx >= 0) {
1188                         stream_seek(mStartTime != AV_NOPTS_VALUE ? mStartTime : 0, AVMEDIA_TYPE_VIDEO);
1189                     } else if (mAudioStreamIdx >= 0) {
1190                         stream_seek(mStartTime != AV_NOPTS_VALUE ? mStartTime : 0, AVMEDIA_TYPE_AUDIO);
1191                     }
1192                 } else if (mAutoExit) {
1193                     ret = AVERROR_EOF;
1194                     goto fail;
1195                 }
1196             }
1197             eof=0;
1198             continue;
1199         }
1200
1201         ret = av_read_frame(mFormatCtx, pkt);
1202         mProbePkts++;
1203         if (ret < 0) {
1204             if (ret == AVERROR_EOF || url_feof(mFormatCtx->pb))
1205                 if (ret == AVERROR_EOF) {
1206                     //LOGV("ret == AVERROR_EOF");
1207                 }
1208                 if (url_feof(mFormatCtx->pb)) {
1209                     //LOGV("url_feof(mFormatCtx->pb)");
1210                 }
1211
1212                 eof = 1;
1213                 mEOF = true;
1214             if (mFormatCtx->pb && mFormatCtx->pb->error) {
1215                 LOGE("mFormatCtx->pb->error: %d", mFormatCtx->pb->error);
1216                 break;
1217             }
1218             SDL_Delay(100);
1219             continue;
1220         }
1221
1222         if (pkt->stream_index == mVideoStreamIdx) {
1223              if (mDefersToCreateVideoTrack) {
1224                 AVCodecContext *avctx = mFormatCtx->streams[mVideoStreamIdx]->codec;
1225
1226                 int i = parser_split(avctx, pkt->data, pkt->size);
1227                 if (i > 0 && i < FF_MAX_EXTRADATA_SIZE) {
1228                     if (avctx->extradata)
1229                         av_freep(&avctx->extradata);
1230                     avctx->extradata_size= i;
1231                     avctx->extradata = (uint8_t *)av_malloc(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
1232                     if (!avctx->extradata) {
1233                         //return AVERROR(ENOMEM);
1234                         ret = AVERROR(ENOMEM);
1235                         goto fail;
1236                     }
1237                     // sps + pps(there may be sei in it)
1238                     memcpy(avctx->extradata, pkt->data, avctx->extradata_size);
1239                     memset(avctx->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
1240                 } else {
1241                     av_free_packet(pkt);
1242                     continue;
1243                 }
1244
1245                 stream_component_open(mVideoStreamIdx);
1246                 if (!mDefersToCreateVideoTrack)
1247                     LOGI("probe packet counter: %d when create video track ok", mProbePkts);
1248                 if (mProbePkts == EXTRACTOR_MAX_PROBE_PACKETS)
1249                     LOGI("probe packet counter to max: %d, create video track: %d",
1250                         mProbePkts, !mDefersToCreateVideoTrack);
1251             }
1252         } else if (pkt->stream_index == mAudioStreamIdx) {
1253             int ret;
1254             uint8_t *outbuf;
1255             int   outbuf_size;
1256             AVCodecContext *avctx = mFormatCtx->streams[mAudioStreamIdx]->codec;
1257             if (mAudioBsfc && pkt && pkt->data) {
1258                 ret = av_bitstream_filter_filter(mAudioBsfc, avctx, NULL, &outbuf, &outbuf_size,
1259                                    pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY);
1260
1261                 if (ret < 0 ||!outbuf_size) {
1262                     av_free_packet(pkt);
1263                     continue;
1264                 }
1265                 if (outbuf && outbuf != pkt->data) {
1266                     memmove(pkt->data, outbuf, outbuf_size);
1267                     pkt->size = outbuf_size;
1268                 }
1269             }
1270             if (mDefersToCreateAudioTrack) {
1271                 if (avctx->extradata_size <= 0) {
1272                     av_free_packet(pkt);
1273                     continue;
1274                 }
1275                 stream_component_open(mAudioStreamIdx);
1276                 if (!mDefersToCreateAudioTrack)
1277                     LOGI("probe packet counter: %d when create audio track ok", mProbePkts);
1278                 if (mProbePkts == EXTRACTOR_MAX_PROBE_PACKETS)
1279                     LOGI("probe packet counter to max: %d, create audio track: %d",
1280                         mProbePkts, !mDefersToCreateAudioTrack);
1281             }
1282         }
1283
1284         /* check if packet is in play range specified by user, then queue, otherwise discard */
1285         pkt_in_play_range = mDuration == AV_NOPTS_VALUE ||
1286                 (pkt->pts - mFormatCtx->streams[pkt->stream_index]->start_time) *
1287                 av_q2d(mFormatCtx->streams[pkt->stream_index]->time_base) -
1288                 (double)(mStartTime != AV_NOPTS_VALUE ? mStartTime : 0) / 1000000
1289                 <= ((double)mDuration / 1000000);
1290         if (pkt->stream_index == mAudioStreamIdx && pkt_in_play_range) {
1291             packet_queue_put(&mAudioQ, pkt);
1292         } else if (pkt->stream_index == mVideoStreamIdx && pkt_in_play_range) {
1293             packet_queue_put(&mVideoQ, pkt);
1294         } else {
1295             av_free_packet(pkt);
1296         }
1297     }
1298     /* wait until the end */
1299     while (!mAbortRequest) {
1300         SDL_Delay(100);
1301     }
1302
1303     ret = 0;
1304 fail:
1305     LOGI("reader thread goto end...");
1306
1307     /* close each stream */
1308     if (mAudioStreamIdx >= 0)
1309         stream_component_close(mAudioStreamIdx);
1310     if (mVideoStreamIdx >= 0)
1311         stream_component_close(mVideoStreamIdx);
1312     if (mFormatCtx) {
1313         avformat_close_input(&mFormatCtx);
1314     }
1315 }
1316
1317 ////////////////////////////////////////////////////////////////////////////////
1318
1319 FFmpegExtractor::Track::Track(
1320         const sp<FFmpegExtractor> &extractor, sp<MetaData> meta, bool isAVC,
1321           AVStream *stream, PacketQueue *queue)
1322     : mExtractor(extractor),
1323       mMeta(meta),
1324       mIsAVC(isAVC),
1325       mStream(stream),
1326       mQueue(queue) {
1327     const char *mime;
1328
1329     /* H.264 Video Types */
1330     {
1331         mNal2AnnexB = false;
1332
1333         if (mIsAVC) {
1334             uint32_t type;
1335             const void *data;
1336             size_t size;
1337             CHECK(meta->findData(kKeyAVCC, &type, &data, &size));
1338
1339             const uint8_t *ptr = (const uint8_t *)data;
1340
1341             CHECK(size >= 7);
1342             CHECK_EQ((unsigned)ptr[0], 1u);  // configurationVersion == 1
1343
1344             // The number of bytes used to encode the length of a NAL unit.
1345             mNALLengthSize = 1 + (ptr[4] & 3);
1346
1347             LOGV("the stream is AVC, the length of a NAL unit: %d", mNALLengthSize);
1348
1349             mNal2AnnexB = true;
1350         }
1351     }
1352
1353     mMediaType = mStream->codec->codec_type;
1354 }
1355
1356 FFmpegExtractor::Track::~Track() {
1357 }
1358
1359 status_t FFmpegExtractor::Track::start(MetaData *params) {
1360     Mutex::Autolock autoLock(mLock);
1361     //mExtractor->startReaderThread();
1362     return OK;
1363 }
1364
1365 status_t FFmpegExtractor::Track::stop() {
1366     Mutex::Autolock autoLock(mLock);
1367     mExtractor->stopReaderThread();
1368     return OK;
1369 }
1370
1371 sp<MetaData> FFmpegExtractor::Track::getFormat() {
1372     Mutex::Autolock autoLock(mLock);
1373
1374     return mMeta;
1375 }
1376
1377 status_t FFmpegExtractor::Track::read(
1378         MediaBuffer **buffer, const ReadOptions *options) {
1379     *buffer = NULL;
1380
1381     Mutex::Autolock autoLock(mLock);
1382
1383     AVPacket pkt;
1384     bool seeking = false;
1385     bool waitKeyPkt = false;
1386     ReadOptions::SeekMode mode;
1387     int64_t pktTS = AV_NOPTS_VALUE;
1388     int64_t seekTimeUs = AV_NOPTS_VALUE;
1389     int64_t timeUs;
1390     int key;
1391     status_t status = OK;
1392
1393     if (options && options->getSeekTo(&seekTimeUs, &mode)) {
1394         LOGV("~~~%s seekTimeUs: %lld, mode: %d", av_get_media_type_string(mMediaType), seekTimeUs, mode);
1395         if (mExtractor->stream_seek(seekTimeUs, mMediaType) == SEEK)
1396             seeking = true;
1397     }
1398
1399 retry:
1400     if (mExtractor->packet_queue_get(mQueue, &pkt, 1) < 0) {
1401         mExtractor->reachedEOS(mMediaType);
1402         return ERROR_END_OF_STREAM;
1403     }
1404
1405     if (seeking) {
1406         if (pkt.data != flush_pkt.data) {
1407             av_free_packet(&pkt);
1408             goto retry;
1409         } else {
1410             seeking = false;
1411 #if WAIT_KEY_PACKET_AFTER_SEEK
1412             waitKeyPkt = true;
1413 #endif
1414         }
1415     }
1416
1417     if (pkt.data == flush_pkt.data) {
1418         LOGV("read %s flush pkt", av_get_media_type_string(mMediaType));
1419         av_free_packet(&pkt);
1420         goto retry;
1421     } else if (pkt.data == NULL && pkt.size == 0) {
1422         LOGV("read %s eos pkt", av_get_media_type_string(mMediaType));
1423         av_free_packet(&pkt);
1424         mExtractor->reachedEOS(mMediaType);
1425         return ERROR_END_OF_STREAM;
1426     }
1427
1428     key = pkt.flags & AV_PKT_FLAG_KEY ? 1 : 0;
1429
1430     if (waitKeyPkt) {
1431         if (!key) {
1432             LOGV("drop the no key packet");
1433             av_free_packet(&pkt);
1434             goto retry;
1435         } else {
1436             LOGV("~~~~~~ got the key packet");
1437             waitKeyPkt = false;
1438         }
1439     }
1440      
1441     MediaBuffer *mediaBuffer = new MediaBuffer(pkt.size + FF_INPUT_BUFFER_PADDING_SIZE);
1442     mediaBuffer->meta_data()->clear();
1443     mediaBuffer->set_range(0, pkt.size);
1444 #if DISABLE_NAL_TO_ANNEXB
1445     mNal2AnnexB = false;
1446 #endif
1447     if (mIsAVC && mNal2AnnexB) {
1448         /* Convert H.264 NAL format to annex b */
1449         if (mNALLengthSize >= 3 && mNALLengthSize <= 4 )
1450         {
1451             uint8_t *dst = (uint8_t *)mediaBuffer->data();
1452
1453             /* This only works for NAL sizes 3-4 */
1454             size_t len = pkt.size, i;
1455             uint8_t *ptr = pkt.data;
1456             while (len >= mNALLengthSize) {
1457                 uint32_t nal_len = 0;
1458                 for( i = 0; i < mNALLengthSize; i++ ) {
1459                     nal_len = (nal_len << 8) | ptr[i];
1460                     dst[i] = 0;
1461                 }
1462                 dst[mNALLengthSize - 1] = 1;
1463                 if (nal_len > INT_MAX || nal_len > (unsigned int)len) {
1464                     status = ERROR_MALFORMED;
1465                     break;
1466                 }
1467                 dst += mNALLengthSize;
1468                 ptr += mNALLengthSize;
1469                 len -= mNALLengthSize;
1470
1471                 memcpy(dst, ptr, nal_len);
1472
1473                 dst += nal_len;
1474                 ptr += nal_len;
1475                 len -= nal_len;
1476             }
1477         } else {
1478              status = ERROR_MALFORMED;
1479         }
1480
1481         if (status != OK) {
1482             LOGV("status != OK");
1483             mediaBuffer->release();
1484             mediaBuffer = NULL;
1485             av_free_packet(&pkt);
1486             return ERROR_MALFORMED;
1487         }
1488     } else {
1489         memcpy(mediaBuffer->data(), pkt.data, pkt.size);
1490     }
1491
1492     pktTS = pkt.pts;
1493     // use dts when AVI
1494     if (pkt.pts == AV_NOPTS_VALUE)
1495         pktTS = pkt.dts;
1496
1497 #if 0
1498     // TODO, Stagefright can't handle negative timestamps
1499     // if needed, work around this by offsetting them manually?
1500     if (pktTS < 0)
1501         pktTS = 0;
1502 #endif
1503
1504     timeUs = (int64_t)(pktTS * av_q2d(mStream->time_base) * 1000000);
1505
1506 #if 0
1507     LOGV("read %s pkt, size: %d, key: %d, pts: %lld, dts: %lld, timeUs: %llu us (%.2f secs)",
1508         av_get_media_type_string(mMediaType), pkt.size, key, pkt.pts, pkt.dts, timeUs, timeUs/1E6);
1509 #endif
1510
1511 #if 0
1512     // TODO, Stagefright can't handle negative timestamps
1513     // if needed, work around this by offsetting them manually?
1514     if (timeUs < 0)
1515         timeUs = 0;
1516 #endif
1517
1518     mediaBuffer->meta_data()->setInt64(kKeyTime, timeUs);
1519     mediaBuffer->meta_data()->setInt32(kKeyIsSyncFrame, key);
1520
1521     *buffer = mediaBuffer;
1522
1523     av_free_packet(&pkt);
1524
1525     return OK;
1526 }
1527
1528 ////////////////////////////////////////////////////////////////////////////////
1529
1530 // LegacySniffFFMPEG
1531 typedef struct {
1532     const char *extension;
1533     const char *container;
1534 } extmap;
1535
1536 static extmap FILE_EXTS[] = {
1537         {".mp4", MEDIA_MIMETYPE_CONTAINER_MPEG4},
1538         {".3gp", MEDIA_MIMETYPE_CONTAINER_MPEG4},
1539         {".mp3", MEDIA_MIMETYPE_AUDIO_MPEG},
1540         {".mov", MEDIA_MIMETYPE_CONTAINER_MOV},
1541         {".mkv", MEDIA_MIMETYPE_CONTAINER_MATROSKA},
1542         {".ts",  MEDIA_MIMETYPE_CONTAINER_TS},
1543         {".avi", MEDIA_MIMETYPE_CONTAINER_AVI},
1544 #if 0
1545         {".asf", MEDIA_MIMETYPE_CONTAINER_ASF},
1546         {".wmv", MEDIA_MIMETYPE_CONTAINER_WMV},
1547         {".wma", MEDIA_MIMETYPE_CONTAINER_WMA},
1548         {".mpg", MEDIA_MIMETYPE_CONTAINER_MPG},
1549         {".flv", MEDIA_MIMETYPE_CONTAINER_FLV},
1550         {".divx", MEDIA_MIMETYPE_CONTAINER_DIVX},
1551         {".mp2", MEDIA_MIMETYPE_CONTAINER_MP2},
1552         {".ape", MEDIA_MIMETYPE_CONTAINER_APE},
1553         {".rm ", MEDIA_MIMETYPE_CONTAINER_RM},
1554         {".ra",  MEDIA_MIMETYPE_CONTAINER_RA},
1555 #endif
1556 };
1557
1558 const char *LegacySniffFFMPEG(const char * uri)
1559 {
1560     size_t i;
1561     const char *container = NULL;
1562
1563     LOGI("list the file extensions suppoted by ffmpeg: ");
1564     LOGI("========================================");
1565     for (i = 0; i < NELEM(FILE_EXTS); ++i) {
1566             LOGV("file_exts[%02d]: %s", i, FILE_EXTS[i].extension);
1567     }
1568     LOGI("========================================");
1569
1570     int lenURI = strlen(uri);
1571     for (i = 0; i < NELEM(FILE_EXTS); ++i) {
1572         int len = strlen(FILE_EXTS[i].extension);
1573         int start = lenURI - len;
1574         if (start > 0) {
1575             if (!av_strncasecmp(uri + start, FILE_EXTS[i].extension, len)) {
1576                 container = FILE_EXTS[i].container;
1577                 break;
1578             }
1579         }
1580     }
1581
1582     return container;
1583 }
1584
1585 // BetterSniffFFMPEG
1586 typedef struct {
1587     const char *format;
1588     const char *container;
1589 } formatmap;
1590
1591 static formatmap FILE_FORMATS[] = {
1592         {"mpegts",                  MEDIA_MIMETYPE_CONTAINER_TS},
1593         {"mov,mp4,m4a,3gp,3g2,mj2", MEDIA_MIMETYPE_CONTAINER_MOV},
1594 };
1595
1596 const char *BetterSniffFFMPEG(const char * uri)
1597 {
1598     size_t i;
1599     const char *container = NULL;
1600     AVFormatContext *ic = NULL;
1601
1602     status_t status = initFFmpeg();
1603     if (status != OK) {
1604         LOGE("could not init ffmpeg");
1605         return false;
1606     }
1607
1608     ic = avformat_alloc_context();
1609     avformat_open_input(&ic, uri, NULL, NULL);
1610
1611     av_dump_format(ic, 0, uri, 0);
1612
1613     LOGI("FFmpegExtrator, uri: %s, format: %s", uri, ic->iformat->name);
1614
1615     LOGI("list the format suppoted by ffmpeg: ");
1616     LOGI("========================================");
1617     for (i = 0; i < NELEM(FILE_FORMATS); ++i) {
1618             LOGV("format_names[%02d]: %s", i, FILE_FORMATS[i].format);
1619     }
1620     LOGI("========================================");
1621
1622     for (i = 0; i < NELEM(FILE_FORMATS); ++i) {
1623         int len = strlen(FILE_FORMATS[i].format);
1624         if (!av_strncasecmp(ic->iformat->name, FILE_FORMATS[i].format, len)) {
1625             container = FILE_FORMATS[i].container;
1626             break;
1627         }
1628     }
1629
1630     avformat_close_input(&ic);
1631     av_free(ic);
1632
1633     return container;
1634 }
1635
1636 bool SniffFFMPEG(
1637         const sp<DataSource> &source, String8 *mimeType, float *confidence,
1638         sp<AMessage> *meta) {
1639     LOGV("SniffFFMPEG");
1640     const char *uri, *container = NULL;
1641
1642     uri = source->getNamURI();
1643
1644     if (!uri)
1645         return false;
1646
1647     LOGI("ffmpeg uri: %s", uri);
1648
1649     container = BetterSniffFFMPEG(uri);
1650     if (!container) {
1651         LOGW("sniff through LegacySniffFFMPEG, only check the file extension");
1652         container = LegacySniffFFMPEG(uri);
1653     }
1654
1655     if (container == NULL)
1656         return false;
1657
1658     LOGV("found container: %s", container);
1659
1660     *confidence = 0.88f;  // Slightly larger than other extractor's confidence
1661     mimeType->setTo(container);
1662
1663     /* use MPEG4Extractor(not extended extractor) for HTTP source only */
1664     if (!av_strcasecmp(container, MEDIA_MIMETYPE_CONTAINER_MPEG4)
1665             && (source->flags() & DataSource::kIsCachingDataSource)) {
1666             return true;
1667     }
1668
1669     *meta = new AMessage;
1670     (*meta)->setString("extended-extractor", "extended-extractor");
1671     (*meta)->setString("extended-extractor-subtype", "ffmpegextractor");
1672
1673     return true;
1674 }
1675
1676 }  // namespace android