]> git.sesse.net Git - ffmpeg/blob - libavcodec/mpegpicture.c
Merge commit '5d8bea3bb2357bb304f8f771a4107039037c5549'
[ffmpeg] / libavcodec / mpegpicture.c
1 /*
2  * Mpeg video formats-related picture management functions
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 #include <stdint.h>
22
23 #include "libavutil/avassert.h"
24 #include "libavutil/common.h"
25
26 #include "avcodec.h"
27 #include "motion_est.h"
28 #include "mpegpicture.h"
29 #include "mpegutils.h"
30
31 static int make_tables_writable(Picture *pic)
32 {
33     int ret, i;
34 #define MAKE_WRITABLE(table) \
35 do {\
36     if (pic->table &&\
37        (ret = av_buffer_make_writable(&pic->table)) < 0)\
38     return ret;\
39 } while (0)
40
41     MAKE_WRITABLE(mb_var_buf);
42     MAKE_WRITABLE(mc_mb_var_buf);
43     MAKE_WRITABLE(mb_mean_buf);
44     MAKE_WRITABLE(mbskip_table_buf);
45     MAKE_WRITABLE(qscale_table_buf);
46     MAKE_WRITABLE(mb_type_buf);
47
48     for (i = 0; i < 2; i++) {
49         MAKE_WRITABLE(motion_val_buf[i]);
50         MAKE_WRITABLE(ref_index_buf[i]);
51     }
52
53     return 0;
54 }
55
56 int ff_mpeg_framesize_alloc(AVCodecContext *avctx, MotionEstContext *me,
57                             ScratchpadContext *sc, int linesize)
58 {
59     int alloc_size = FFALIGN(FFABS(linesize) + 64, 32);
60
61     if (avctx->hwaccel || avctx->codec->capabilities & AV_CODEC_CAP_HWACCEL_VDPAU)
62         return 0;
63
64     if (linesize < 24) {
65         av_log(avctx, AV_LOG_ERROR, "Image too small, temporary buffers cannot function\n");
66         return AVERROR_PATCHWELCOME;
67     }
68
69     // edge emu needs blocksize + filter length - 1
70     // (= 17x17 for  halfpel / 21x21 for  h264)
71     // VC1 computes luma and chroma simultaneously and needs 19X19 + 9x9
72     // at uvlinesize. It supports only YUV420 so 24x24 is enough
73     // linesize * interlaced * MBsize
74     // we also use this buffer for encoding in encode_mb_internal() needig an additional 32 lines
75     FF_ALLOCZ_ARRAY_OR_GOTO(avctx, sc->edge_emu_buffer, alloc_size, 4 * 68,
76                       fail);
77
78     FF_ALLOCZ_ARRAY_OR_GOTO(avctx, me->scratchpad, alloc_size, 4 * 16 * 2,
79                       fail)
80     me->temp            = me->scratchpad;
81     sc->rd_scratchpad   = me->scratchpad;
82     sc->b_scratchpad    = me->scratchpad;
83     sc->obmc_scratchpad = me->scratchpad + 16;
84
85     return 0;
86 fail:
87     av_freep(&sc->edge_emu_buffer);
88     return AVERROR(ENOMEM);
89 }
90
91 /**
92  * Allocate a frame buffer
93  */
94 static int alloc_frame_buffer(AVCodecContext *avctx,  Picture *pic,
95                               MotionEstContext *me, ScratchpadContext *sc,
96                               int chroma_x_shift, int chroma_y_shift,
97                               int linesize, int uvlinesize)
98 {
99     int edges_needed = av_codec_is_encoder(avctx->codec);
100     int r, ret;
101
102     pic->tf.f = pic->f;
103     if (avctx->codec_id != AV_CODEC_ID_WMV3IMAGE &&
104         avctx->codec_id != AV_CODEC_ID_VC1IMAGE  &&
105         avctx->codec_id != AV_CODEC_ID_MSS2) {
106         if (edges_needed) {
107             pic->f->width  = avctx->width  + 2 * EDGE_WIDTH;
108             pic->f->height = avctx->height + 2 * EDGE_WIDTH;
109         }
110
111         r = ff_thread_get_buffer(avctx, &pic->tf,
112                                  pic->reference ? AV_GET_BUFFER_FLAG_REF : 0);
113     } else {
114         pic->f->width  = avctx->width;
115         pic->f->height = avctx->height;
116         pic->f->format = avctx->pix_fmt;
117         r = avcodec_default_get_buffer2(avctx, pic->f, 0);
118     }
119
120     if (r < 0 || !pic->f->buf[0]) {
121         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed (%d %p)\n",
122                r, pic->f->data[0]);
123         return -1;
124     }
125
126     if (edges_needed) {
127         int i;
128         for (i = 0; pic->f->data[i]; i++) {
129             int offset = (EDGE_WIDTH >> (i ? chroma_y_shift : 0)) *
130                          pic->f->linesize[i] +
131                          (EDGE_WIDTH >> (i ? chroma_x_shift : 0));
132             pic->f->data[i] += offset;
133         }
134         pic->f->width  = avctx->width;
135         pic->f->height = avctx->height;
136     }
137
138     if (avctx->hwaccel) {
139         assert(!pic->hwaccel_picture_private);
140         if (avctx->hwaccel->frame_priv_data_size) {
141             pic->hwaccel_priv_buf = av_buffer_allocz(avctx->hwaccel->frame_priv_data_size);
142             if (!pic->hwaccel_priv_buf) {
143                 av_log(avctx, AV_LOG_ERROR, "alloc_frame_buffer() failed (hwaccel private data allocation)\n");
144                 return -1;
145             }
146             pic->hwaccel_picture_private = pic->hwaccel_priv_buf->data;
147         }
148     }
149
150     if (linesize && (linesize   != pic->f->linesize[0] ||
151                      uvlinesize != pic->f->linesize[1])) {
152         av_log(avctx, AV_LOG_ERROR,
153                "get_buffer() failed (stride changed)\n");
154         ff_mpeg_unref_picture(avctx, pic);
155         return -1;
156     }
157
158     if (pic->f->linesize[1] != pic->f->linesize[2]) {
159         av_log(avctx, AV_LOG_ERROR,
160                "get_buffer() failed (uv stride mismatch)\n");
161         ff_mpeg_unref_picture(avctx, pic);
162         return -1;
163     }
164
165     if (!sc->edge_emu_buffer &&
166         (ret = ff_mpeg_framesize_alloc(avctx, me, sc,
167                                        pic->f->linesize[0])) < 0) {
168         av_log(avctx, AV_LOG_ERROR,
169                "get_buffer() failed to allocate context scratch buffers.\n");
170         ff_mpeg_unref_picture(avctx, pic);
171         return ret;
172     }
173
174     return 0;
175 }
176
177 static int alloc_picture_tables(AVCodecContext *avctx, Picture *pic, int encoding, int out_format,
178                                 int mb_stride, int mb_width, int mb_height, int b8_stride)
179 {
180     const int big_mb_num    = mb_stride * (mb_height + 1) + 1;
181     const int mb_array_size = mb_stride * mb_height;
182     const int b8_array_size = b8_stride * mb_height * 2;
183     int i;
184
185
186     pic->mbskip_table_buf = av_buffer_allocz(mb_array_size + 2);
187     pic->qscale_table_buf = av_buffer_allocz(big_mb_num + mb_stride);
188     pic->mb_type_buf      = av_buffer_allocz((big_mb_num + mb_stride) *
189                                              sizeof(uint32_t));
190     if (!pic->mbskip_table_buf || !pic->qscale_table_buf || !pic->mb_type_buf)
191         return AVERROR(ENOMEM);
192
193     if (encoding) {
194         pic->mb_var_buf    = av_buffer_allocz(mb_array_size * sizeof(int16_t));
195         pic->mc_mb_var_buf = av_buffer_allocz(mb_array_size * sizeof(int16_t));
196         pic->mb_mean_buf   = av_buffer_allocz(mb_array_size);
197         if (!pic->mb_var_buf || !pic->mc_mb_var_buf || !pic->mb_mean_buf)
198             return AVERROR(ENOMEM);
199     }
200
201     if (out_format == FMT_H263 || encoding || avctx->debug_mv ||
202         (avctx->flags2 & AV_CODEC_FLAG2_EXPORT_MVS)) {
203         int mv_size        = 2 * (b8_array_size + 4) * sizeof(int16_t);
204         int ref_index_size = 4 * mb_array_size;
205
206         for (i = 0; mv_size && i < 2; i++) {
207             pic->motion_val_buf[i] = av_buffer_allocz(mv_size);
208             pic->ref_index_buf[i]  = av_buffer_allocz(ref_index_size);
209             if (!pic->motion_val_buf[i] || !pic->ref_index_buf[i])
210                 return AVERROR(ENOMEM);
211         }
212     }
213
214     pic->alloc_mb_width  = mb_width;
215     pic->alloc_mb_height = mb_height;
216
217     return 0;
218 }
219
220 /**
221  * Allocate a Picture.
222  * The pixels are allocated/set by calling get_buffer() if shared = 0
223  */
224 int ff_alloc_picture(AVCodecContext *avctx, Picture *pic, MotionEstContext *me,
225                      ScratchpadContext *sc, int shared, int encoding,
226                      int chroma_x_shift, int chroma_y_shift, int out_format,
227                      int mb_stride, int mb_width, int mb_height, int b8_stride,
228                      ptrdiff_t *linesize, ptrdiff_t *uvlinesize)
229 {
230     int i, ret;
231
232     if (pic->qscale_table_buf)
233         if (   pic->alloc_mb_width  != mb_width
234             || pic->alloc_mb_height != mb_height)
235             ff_free_picture_tables(pic);
236
237     if (shared) {
238         av_assert0(pic->f->data[0]);
239         pic->shared = 1;
240     } else {
241         av_assert0(!pic->f->buf[0]);
242         if (alloc_frame_buffer(avctx, pic, me, sc,
243                                chroma_x_shift, chroma_y_shift,
244                                *linesize, *uvlinesize) < 0)
245             return -1;
246
247         *linesize   = pic->f->linesize[0];
248         *uvlinesize = pic->f->linesize[1];
249     }
250
251     if (!pic->qscale_table_buf)
252         ret = alloc_picture_tables(avctx, pic, encoding, out_format,
253                                    mb_stride, mb_width, mb_height, b8_stride);
254     else
255         ret = make_tables_writable(pic);
256     if (ret < 0)
257         goto fail;
258
259     if (encoding) {
260         pic->mb_var    = (uint16_t*)pic->mb_var_buf->data;
261         pic->mc_mb_var = (uint16_t*)pic->mc_mb_var_buf->data;
262         pic->mb_mean   = pic->mb_mean_buf->data;
263     }
264
265     pic->mbskip_table = pic->mbskip_table_buf->data;
266     pic->qscale_table = pic->qscale_table_buf->data + 2 * mb_stride + 1;
267     pic->mb_type      = (uint32_t*)pic->mb_type_buf->data + 2 * mb_stride + 1;
268
269     if (pic->motion_val_buf[0]) {
270         for (i = 0; i < 2; i++) {
271             pic->motion_val[i] = (int16_t (*)[2])pic->motion_val_buf[i]->data + 4;
272             pic->ref_index[i]  = pic->ref_index_buf[i]->data;
273         }
274     }
275
276     return 0;
277 fail:
278     av_log(avctx, AV_LOG_ERROR, "Error allocating a picture.\n");
279     ff_mpeg_unref_picture(avctx, pic);
280     ff_free_picture_tables(pic);
281     return AVERROR(ENOMEM);
282 }
283
284 /**
285  * Deallocate a picture.
286  */
287 void ff_mpeg_unref_picture(AVCodecContext *avctx, Picture *pic)
288 {
289     int off = offsetof(Picture, mb_mean) + sizeof(pic->mb_mean);
290
291     pic->tf.f = pic->f;
292     /* WM Image / Screen codecs allocate internal buffers with different
293      * dimensions / colorspaces; ignore user-defined callbacks for these. */
294     if (avctx->codec_id != AV_CODEC_ID_WMV3IMAGE &&
295         avctx->codec_id != AV_CODEC_ID_VC1IMAGE  &&
296         avctx->codec_id != AV_CODEC_ID_MSS2)
297         ff_thread_release_buffer(avctx, &pic->tf);
298     else if (pic->f)
299         av_frame_unref(pic->f);
300
301     av_buffer_unref(&pic->hwaccel_priv_buf);
302
303     if (pic->needs_realloc)
304         ff_free_picture_tables(pic);
305
306     memset((uint8_t*)pic + off, 0, sizeof(*pic) - off);
307 }
308
309 int ff_update_picture_tables(Picture *dst, Picture *src)
310 {
311      int i;
312
313 #define UPDATE_TABLE(table)                                                   \
314 do {                                                                          \
315     if (src->table &&                                                         \
316         (!dst->table || dst->table->buffer != src->table->buffer)) {          \
317         av_buffer_unref(&dst->table);                                         \
318         dst->table = av_buffer_ref(src->table);                               \
319         if (!dst->table) {                                                    \
320             ff_free_picture_tables(dst);                                      \
321             return AVERROR(ENOMEM);                                           \
322         }                                                                     \
323     }                                                                         \
324 } while (0)
325
326     UPDATE_TABLE(mb_var_buf);
327     UPDATE_TABLE(mc_mb_var_buf);
328     UPDATE_TABLE(mb_mean_buf);
329     UPDATE_TABLE(mbskip_table_buf);
330     UPDATE_TABLE(qscale_table_buf);
331     UPDATE_TABLE(mb_type_buf);
332     for (i = 0; i < 2; i++) {
333         UPDATE_TABLE(motion_val_buf[i]);
334         UPDATE_TABLE(ref_index_buf[i]);
335     }
336
337     dst->mb_var        = src->mb_var;
338     dst->mc_mb_var     = src->mc_mb_var;
339     dst->mb_mean       = src->mb_mean;
340     dst->mbskip_table  = src->mbskip_table;
341     dst->qscale_table  = src->qscale_table;
342     dst->mb_type       = src->mb_type;
343     for (i = 0; i < 2; i++) {
344         dst->motion_val[i] = src->motion_val[i];
345         dst->ref_index[i]  = src->ref_index[i];
346     }
347
348     dst->alloc_mb_width  = src->alloc_mb_width;
349     dst->alloc_mb_height = src->alloc_mb_height;
350
351     return 0;
352 }
353
354 int ff_mpeg_ref_picture(AVCodecContext *avctx, Picture *dst, Picture *src)
355 {
356     int ret;
357
358     av_assert0(!dst->f->buf[0]);
359     av_assert0(src->f->buf[0]);
360
361     src->tf.f = src->f;
362     dst->tf.f = dst->f;
363     ret = ff_thread_ref_frame(&dst->tf, &src->tf);
364     if (ret < 0)
365         goto fail;
366
367     ret = ff_update_picture_tables(dst, src);
368     if (ret < 0)
369         goto fail;
370
371     if (src->hwaccel_picture_private) {
372         dst->hwaccel_priv_buf = av_buffer_ref(src->hwaccel_priv_buf);
373         if (!dst->hwaccel_priv_buf)
374             goto fail;
375         dst->hwaccel_picture_private = dst->hwaccel_priv_buf->data;
376     }
377
378     dst->field_picture           = src->field_picture;
379     dst->mb_var_sum              = src->mb_var_sum;
380     dst->mc_mb_var_sum           = src->mc_mb_var_sum;
381     dst->b_frame_score           = src->b_frame_score;
382     dst->needs_realloc           = src->needs_realloc;
383     dst->reference               = src->reference;
384     dst->shared                  = src->shared;
385
386     return 0;
387 fail:
388     ff_mpeg_unref_picture(avctx, dst);
389     return ret;
390 }
391
392 static inline int pic_is_unused(Picture *pic)
393 {
394     if (!pic->f->buf[0])
395         return 1;
396     if (pic->needs_realloc && !(pic->reference & DELAYED_PIC_REF))
397         return 1;
398     return 0;
399 }
400
401 static int find_unused_picture(AVCodecContext *avctx, Picture *picture, int shared)
402 {
403     int i;
404
405     if (shared) {
406         for (i = 0; i < MAX_PICTURE_COUNT; i++) {
407             if (!picture[i].f->buf[0])
408                 return i;
409         }
410     } else {
411         for (i = 0; i < MAX_PICTURE_COUNT; i++) {
412             if (pic_is_unused(&picture[i]))
413                 return i;
414         }
415     }
416
417     av_log(avctx, AV_LOG_FATAL,
418            "Internal error, picture buffer overflow\n");
419     /* We could return -1, but the codec would crash trying to draw into a
420      * non-existing frame anyway. This is safer than waiting for a random crash.
421      * Also the return of this is never useful, an encoder must only allocate
422      * as much as allowed in the specification. This has no relationship to how
423      * much libavcodec could allocate (and MAX_PICTURE_COUNT is always large
424      * enough for such valid streams).
425      * Plus, a decoder has to check stream validity and remove frames if too
426      * many reference frames are around. Waiting for "OOM" is not correct at
427      * all. Similarly, missing reference frames have to be replaced by
428      * interpolated/MC frames, anything else is a bug in the codec ...
429      */
430     abort();
431     return -1;
432 }
433
434 int ff_find_unused_picture(AVCodecContext *avctx, Picture *picture, int shared)
435 {
436     int ret = find_unused_picture(avctx, picture, shared);
437
438     if (ret >= 0 && ret < MAX_PICTURE_COUNT) {
439         if (picture[ret].needs_realloc) {
440             picture[ret].needs_realloc = 0;
441             ff_free_picture_tables(&picture[ret]);
442             ff_mpeg_unref_picture(avctx, &picture[ret]);
443         }
444     }
445     return ret;
446 }
447
448 void ff_free_picture_tables(Picture *pic)
449 {
450     int i;
451
452     pic->alloc_mb_width  =
453     pic->alloc_mb_height = 0;
454
455     av_buffer_unref(&pic->mb_var_buf);
456     av_buffer_unref(&pic->mc_mb_var_buf);
457     av_buffer_unref(&pic->mb_mean_buf);
458     av_buffer_unref(&pic->mbskip_table_buf);
459     av_buffer_unref(&pic->qscale_table_buf);
460     av_buffer_unref(&pic->mb_type_buf);
461
462     for (i = 0; i < 2; i++) {
463         av_buffer_unref(&pic->motion_val_buf[i]);
464         av_buffer_unref(&pic->ref_index_buf[i]);
465     }
466 }