OSDN Git Service

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