OSDN Git Service

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