OSDN Git Service

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