]> git.sesse.net Git - ffmpeg/blob - libavcodec/libstagefright.cpp
h264: reject unsupported 422 9 bit streams
[ffmpeg] / libavcodec / libstagefright.cpp
1 /*
2  * Interface to the Android Stagefright library for
3  * H/W accelerated H.264 decoding
4  *
5  * Copyright (C) 2011 Mohamed Naufal
6  * Copyright (C) 2011 Martin Storsjö
7  *
8  * This file is part of FFmpeg.
9  *
10  * FFmpeg is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * FFmpeg is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with FFmpeg; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23  */
24
25 #include <binder/ProcessState.h>
26 #include <media/stagefright/MetaData.h>
27 #include <media/stagefright/MediaBufferGroup.h>
28 #include <media/stagefright/MediaDebug.h>
29 #include <media/stagefright/MediaDefs.h>
30 #include <media/stagefright/OMXClient.h>
31 #include <media/stagefright/OMXCodec.h>
32 #include <utils/List.h>
33 #include <new>
34
35 extern "C" {
36 #include "avcodec.h"
37 #include "libavutil/imgutils.h"
38 }
39
40 #define OMX_QCOM_COLOR_FormatYVU420SemiPlanar 0x7FA30C00
41
42 using namespace android;
43
44 struct Frame {
45     status_t status;
46     size_t size;
47     int64_t time;
48     int key;
49     uint8_t *buffer;
50     MediaBuffer* mbuffer;
51     int32_t w, h;
52 };
53
54 class CustomSource;
55
56 struct StagefrightContext {
57     AVCodecContext *avctx;
58     AVBitStreamFilterContext *bsfc;
59     uint8_t* orig_extradata;
60     int orig_extradata_size;
61     sp<MediaSource> *source;
62     List<Frame*> *in_queue, *out_queue;
63     pthread_mutex_t in_mutex, out_mutex;
64     pthread_cond_t condition;
65     pthread_t decode_thread_id;
66
67     Frame *end_frame;
68     bool source_done;
69     volatile sig_atomic_t thread_exited, stop_decode;
70
71     AVFrame ret_frame;
72
73     uint8_t *dummy_buf;
74     int dummy_bufsize;
75
76     OMXClient *client;
77     sp<MediaSource> *decoder;
78     const char *decoder_component;
79 };
80
81 class CustomSource : public MediaSource {
82 public:
83     CustomSource(AVCodecContext *avctx, sp<MetaData> meta) {
84         s = (StagefrightContext*)avctx->priv_data;
85         source_meta = meta;
86         frame_size  = (avctx->width * avctx->height * 3) / 2;
87         buf_group.add_buffer(new MediaBuffer(frame_size));
88     }
89
90     virtual sp<MetaData> getFormat() {
91         return source_meta;
92     }
93
94     virtual status_t start(MetaData *params) {
95         return OK;
96     }
97
98     virtual status_t stop() {
99         return OK;
100     }
101
102     virtual status_t read(MediaBuffer **buffer,
103                           const MediaSource::ReadOptions *options) {
104         Frame *frame;
105         status_t ret;
106
107         pthread_mutex_lock(&s->in_mutex);
108
109         while (s->in_queue->empty())
110             pthread_cond_wait(&s->condition, &s->in_mutex);
111
112         frame = *s->in_queue->begin();
113         ret = frame->status;
114
115         if (ret == OK) {
116             ret = buf_group.acquire_buffer(buffer);
117             if (ret == OK) {
118                 memcpy((*buffer)->data(), frame->buffer, frame->size);
119                 (*buffer)->set_range(0, frame->size);
120                 (*buffer)->meta_data()->clear();
121                 (*buffer)->meta_data()->setInt32(kKeyIsSyncFrame,frame->key);
122                 (*buffer)->meta_data()->setInt64(kKeyTime, frame->time);
123             } else {
124                 av_log(s->avctx, AV_LOG_ERROR, "Failed to acquire MediaBuffer\n");
125             }
126             av_freep(&frame->buffer);
127         }
128
129         s->in_queue->erase(s->in_queue->begin());
130         pthread_mutex_unlock(&s->in_mutex);
131
132         av_freep(&frame);
133         return ret;
134     }
135
136 private:
137     MediaBufferGroup buf_group;
138     sp<MetaData> source_meta;
139     StagefrightContext *s;
140     int frame_size;
141 };
142
143 void* decode_thread(void *arg)
144 {
145     AVCodecContext *avctx = (AVCodecContext*)arg;
146     StagefrightContext *s = (StagefrightContext*)avctx->priv_data;
147     Frame* frame;
148     MediaBuffer *buffer;
149     int decode_done = 0;
150     do {
151         buffer = NULL;
152         frame = (Frame*)av_mallocz(sizeof(Frame));
153         if (!frame) {
154             frame         = s->end_frame;
155             frame->status = AVERROR(ENOMEM);
156             decode_done   = 1;
157             s->end_frame  = NULL;
158         } else {
159             frame->status = (*s->decoder)->read(&buffer);
160             if (frame->status == OK) {
161                 sp<MetaData> outFormat = (*s->decoder)->getFormat();
162                 outFormat->findInt32(kKeyWidth , &frame->w);
163                 outFormat->findInt32(kKeyHeight, &frame->h);
164                 frame->size    = buffer->range_length();
165                 frame->mbuffer = buffer;
166             } else if (frame->status == INFO_FORMAT_CHANGED) {
167                 if (buffer)
168                     buffer->release();
169                 av_free(frame);
170                 continue;
171             } else {
172                 decode_done = 1;
173             }
174         }
175         pthread_mutex_lock(&s->out_mutex);
176         s->out_queue->push_back(frame);
177         pthread_mutex_unlock(&s->out_mutex);
178     } while (!decode_done && !s->stop_decode);
179
180     s->thread_exited = true;
181
182     return 0;
183 }
184
185 static av_cold int Stagefright_init(AVCodecContext *avctx)
186 {
187     StagefrightContext *s = (StagefrightContext*)avctx->priv_data;
188     sp<MetaData> meta, outFormat;
189     int32_t colorFormat = 0;
190     int ret;
191
192     if (!avctx->extradata || !avctx->extradata_size || avctx->extradata[0] != 1)
193         return -1;
194
195     s->avctx = avctx;
196     s->bsfc  = av_bitstream_filter_init("h264_mp4toannexb");
197     if (!s->bsfc) {
198         av_log(avctx, AV_LOG_ERROR, "Cannot open the h264_mp4toannexb BSF!\n");
199         return -1;
200     }
201
202     s->orig_extradata_size = avctx->extradata_size;
203     s->orig_extradata = (uint8_t*) av_mallocz(avctx->extradata_size +
204                                               FF_INPUT_BUFFER_PADDING_SIZE);
205     if (!s->orig_extradata) {
206         ret = AVERROR(ENOMEM);
207         goto fail;
208     }
209     memcpy(s->orig_extradata, avctx->extradata, avctx->extradata_size);
210
211     meta = new MetaData;
212     if (meta == NULL) {
213         ret = AVERROR(ENOMEM);
214         goto fail;
215     }
216     meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
217     meta->setInt32(kKeyWidth, avctx->width);
218     meta->setInt32(kKeyHeight, avctx->height);
219     meta->setData(kKeyAVCC, kTypeAVCC, avctx->extradata, avctx->extradata_size);
220
221     android::ProcessState::self()->startThreadPool();
222
223     s->source    = new sp<MediaSource>();
224     *s->source   = new CustomSource(avctx, meta);
225     s->in_queue  = new List<Frame*>;
226     s->out_queue = new List<Frame*>;
227     s->client    = new OMXClient;
228     s->end_frame = (Frame*)av_mallocz(sizeof(Frame));
229     if (s->source == NULL || !s->in_queue || !s->out_queue || !s->client ||
230         !s->end_frame) {
231         ret = AVERROR(ENOMEM);
232         goto fail;
233     }
234
235     if (s->client->connect() !=  OK) {
236         av_log(avctx, AV_LOG_ERROR, "Cannot connect OMX client\n");
237         ret = -1;
238         goto fail;
239     }
240
241     s->decoder  = new sp<MediaSource>();
242     *s->decoder = OMXCodec::Create(s->client->interface(), meta,
243                                   false, *s->source, NULL,
244                                   OMXCodec::kClientNeedsFramebuffer);
245     if ((*s->decoder)->start() !=  OK) {
246         av_log(avctx, AV_LOG_ERROR, "Cannot start decoder\n");
247         ret = -1;
248         s->client->disconnect();
249         goto fail;
250     }
251
252     outFormat = (*s->decoder)->getFormat();
253     outFormat->findInt32(kKeyColorFormat, &colorFormat);
254     if (colorFormat == OMX_QCOM_COLOR_FormatYVU420SemiPlanar ||
255         colorFormat == OMX_COLOR_FormatYUV420SemiPlanar)
256         avctx->pix_fmt = PIX_FMT_NV21;
257     else
258         avctx->pix_fmt = PIX_FMT_YUV420P;
259
260     outFormat->findCString(kKeyDecoderComponent, &s->decoder_component);
261     if (s->decoder_component)
262         s->decoder_component = av_strdup(s->decoder_component);
263
264     pthread_mutex_init(&s->in_mutex, NULL);
265     pthread_mutex_init(&s->out_mutex, NULL);
266     pthread_cond_init(&s->condition, NULL);
267     pthread_create(&s->decode_thread_id, NULL, &decode_thread, avctx);
268     return 0;
269
270 fail:
271     av_bitstream_filter_close(s->bsfc);
272     av_freep(&s->orig_extradata);
273     av_freep(&s->end_frame);
274     delete s->in_queue;
275     delete s->out_queue;
276     delete s->client;
277     return ret;
278 }
279
280 static int Stagefright_decode_frame(AVCodecContext *avctx, void *data,
281                                     int *data_size, AVPacket *avpkt)
282 {
283     StagefrightContext *s = (StagefrightContext*)avctx->priv_data;
284     Frame *frame;
285     MediaBuffer *mbuffer;
286     status_t status;
287     size_t size;
288     uint8_t *buf;
289     const uint8_t *src_data[3];
290     int w, h;
291     int src_linesize[3];
292     int orig_size = avpkt->size;
293     AVPacket pkt = *avpkt;
294     int ret;
295
296     if (avpkt && avpkt->data) {
297         av_bitstream_filter_filter(s->bsfc, avctx, NULL, &pkt.data, &pkt.size,
298                                    avpkt->data, avpkt->size, avpkt->flags & AV_PKT_FLAG_KEY);
299         avpkt = &pkt;
300     }
301
302     if (!s->source_done) {
303         if(!s->dummy_buf) {
304             s->dummy_buf = (uint8_t*)av_malloc(avpkt->size);
305             if (!s->dummy_buf)
306                 return AVERROR(ENOMEM);
307             s->dummy_bufsize = avpkt->size;
308             memcpy(s->dummy_buf, avpkt->data, avpkt->size);
309         }
310
311         frame = (Frame*)av_mallocz(sizeof(Frame));
312         if (avpkt->data) {
313             frame->status  = OK;
314             frame->size    = orig_size;
315             // Stagefright can't handle negative timestamps -
316             // if needed, work around this by offsetting them manually?
317             if (avpkt->pts >= 0)
318                 frame->time    = avpkt->pts;
319             frame->key     = avpkt->flags & AV_PKT_FLAG_KEY ? 1 : 0;
320             frame->buffer  = (uint8_t*)av_malloc(avpkt->size);
321             if (!frame->buffer) {
322                 av_freep(&frame);
323                 return AVERROR(ENOMEM);
324             }
325             uint8_t *ptr = avpkt->data;
326             // The OMX.SEC decoder fails without this.
327             if (avpkt->size == orig_size + avctx->extradata_size)
328                 ptr += avctx->extradata_size;
329             memcpy(frame->buffer, ptr, orig_size);
330         } else {
331             frame->status  = ERROR_END_OF_STREAM;
332             s->source_done = true;
333         }
334
335         while (true) {
336             if (s->thread_exited) {
337                 s->source_done = true;
338                 break;
339             }
340             pthread_mutex_lock(&s->in_mutex);
341             if (s->in_queue->size() >= 10) {
342                 pthread_mutex_unlock(&s->in_mutex);
343                 usleep(10000);
344                 continue;
345             }
346             s->in_queue->push_back(frame);
347             pthread_cond_signal(&s->condition);
348             pthread_mutex_unlock(&s->in_mutex);
349             break;
350         }
351     }
352     while (true) {
353         pthread_mutex_lock(&s->out_mutex);
354         if (!s->out_queue->empty()) break;
355         pthread_mutex_unlock(&s->out_mutex);
356         if (s->source_done) {
357             usleep(10000);
358             continue;
359         } else {
360             return orig_size;
361         }
362     }
363
364     frame = *s->out_queue->begin();
365     s->out_queue->erase(s->out_queue->begin());
366     pthread_mutex_unlock(&s->out_mutex);
367
368     mbuffer = frame->mbuffer;
369     status  = frame->status;
370     size    = frame->size;
371     w       = frame->w;
372     h       = frame->h;
373     av_freep(&frame);
374
375     if (status == ERROR_END_OF_STREAM)
376         return 0;
377     if (status != OK) {
378         if (status == AVERROR(ENOMEM))
379             return status;
380         av_log(avctx, AV_LOG_ERROR, "Decode failed: %x\n", status);
381         return -1;
382     }
383
384     // The OMX.SEC decoder doesn't signal the modified width/height
385     if (s->decoder_component && !strncmp(s->decoder_component, "OMX.SEC", 7) &&
386         (w & 15 || h & 15)) {
387         if (((w + 15)&~15) * ((h + 15)&~15) * 3/2 == size) {
388             w = (w + 15)&~15;
389             h = (h + 15)&~15;
390         }
391     }
392
393     if (!avctx->width || !avctx->height || avctx->width > w || avctx->height > h) {
394         avctx->width  = w;
395         avctx->height = h;
396     }
397
398     ret = avctx->reget_buffer(avctx, &s->ret_frame);
399     if (ret < 0) {
400         av_log(avctx, AV_LOG_ERROR, "reget buffer() failed\n");
401         goto end;
402     }
403
404     src_linesize[0] = w;
405     if (avctx->pix_fmt == PIX_FMT_YUV420P)
406         src_linesize[1] = src_linesize[2] = w/2;
407     else if (avctx->pix_fmt == PIX_FMT_NV21)
408         src_linesize[1] = w;
409
410     buf = (uint8_t*)mbuffer->data();
411     src_data[0] = buf;
412     src_data[1] = buf + src_linesize[0] * h;
413     src_data[2] = src_data[1] + src_linesize[1] * h/2;
414     av_image_copy(s->ret_frame.data, s->ret_frame.linesize,
415                   src_data, src_linesize,
416                   avctx->pix_fmt, avctx->width, avctx->height);
417
418     *data_size = sizeof(AVFrame);
419     *(AVFrame*)data = s->ret_frame;
420     ret = orig_size;
421 end:
422     mbuffer->release();
423     return ret;
424 }
425
426 static av_cold int Stagefright_close(AVCodecContext *avctx)
427 {
428     StagefrightContext *s = (StagefrightContext*)avctx->priv_data;
429     Frame *frame;
430
431     if (!s->thread_exited) {
432         s->stop_decode = 1;
433
434         // Feed a dummy frame prior to signalling EOF.
435         // This is required to terminate the decoder(OMX.SEC)
436         // when only one frame is read during stream info detection.
437         if (s->dummy_buf && (frame = (Frame*)av_mallocz(sizeof(Frame)))) {
438             frame->status = OK;
439             frame->size   = s->dummy_bufsize;
440             frame->buffer = s->dummy_buf;
441             pthread_mutex_lock(&s->in_mutex);
442             s->in_queue->push_back(frame);
443             pthread_cond_signal(&s->condition);
444             pthread_mutex_unlock(&s->in_mutex);
445             s->dummy_buf = NULL;
446         }
447
448         pthread_mutex_lock(&s->in_mutex);
449         s->end_frame->status = ERROR_END_OF_STREAM;
450         s->in_queue->push_back(s->end_frame);
451         pthread_cond_signal(&s->condition);
452         pthread_mutex_unlock(&s->in_mutex);
453         s->end_frame = NULL;
454     }
455
456     pthread_join(s->decode_thread_id, NULL);
457
458     if (s->ret_frame.data[0])
459         avctx->release_buffer(avctx, &s->ret_frame);
460
461     while (!s->in_queue->empty()) {
462         frame = *s->in_queue->begin();
463         s->in_queue->erase(s->in_queue->begin());
464         if (frame->size)
465             av_freep(&frame->buffer);
466         av_freep(&frame);
467     }
468
469     while (!s->out_queue->empty()) {
470         frame = *s->out_queue->begin();
471         s->out_queue->erase(s->out_queue->begin());
472         if (frame->size)
473             frame->mbuffer->release();
474         av_freep(&frame);
475     }
476
477     (*s->decoder)->stop();
478     s->client->disconnect();
479
480     if (s->decoder_component)
481         av_freep(&s->decoder_component);
482     av_freep(&s->dummy_buf);
483     av_freep(&s->end_frame);
484
485     // Reset the extradata back to the original mp4 format, so that
486     // the next invocation (both when decoding and when called from
487     // av_find_stream_info) get the original mp4 format extradata.
488     av_freep(&avctx->extradata);
489     avctx->extradata = s->orig_extradata;
490     avctx->extradata_size = s->orig_extradata_size;
491
492     delete s->in_queue;
493     delete s->out_queue;
494     delete s->client;
495     delete s->decoder;
496     delete s->source;
497
498     pthread_mutex_destroy(&s->in_mutex);
499     pthread_mutex_destroy(&s->out_mutex);
500     pthread_cond_destroy(&s->condition);
501     av_bitstream_filter_close(s->bsfc);
502     return 0;
503 }
504
505 AVCodec ff_libstagefright_h264_decoder = {
506     "libstagefright_h264",
507     AVMEDIA_TYPE_VIDEO,
508     CODEC_ID_H264,
509     sizeof(StagefrightContext),
510     Stagefright_init,
511     NULL, //encode
512     Stagefright_close,
513     Stagefright_decode_frame,
514     CODEC_CAP_DELAY,
515     NULL, //next
516     NULL, //flush
517     NULL, //supported_framerates
518     NULL, //pixel_formats
519     NULL_IF_CONFIG_SMALL("libstagefright H.264"),
520 };