OSDN Git Service

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