]> git.sesse.net Git - ffmpeg/blob - libavcodec/decode.c
decode: restructure the core decoding code
[ffmpeg] / libavcodec / decode.c
1 /*
2  * generic decoding-related code
3  *
4  * This file is part of Libav.
5  *
6  * Libav 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  * Libav 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 Libav; 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 #include <string.h>
23
24 #include "config.h"
25
26 #include "libavutil/avassert.h"
27 #include "libavutil/avstring.h"
28 #include "libavutil/common.h"
29 #include "libavutil/frame.h"
30 #include "libavutil/hwcontext.h"
31 #include "libavutil/imgutils.h"
32
33 #include "avcodec.h"
34 #include "bytestream.h"
35 #include "decode.h"
36 #include "internal.h"
37 #include "thread.h"
38
39 static int apply_param_change(AVCodecContext *avctx, AVPacket *avpkt)
40 {
41     int size = 0, ret;
42     const uint8_t *data;
43     uint32_t flags;
44
45     data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
46     if (!data)
47         return 0;
48
49     if (!(avctx->codec->capabilities & AV_CODEC_CAP_PARAM_CHANGE)) {
50         av_log(avctx, AV_LOG_ERROR, "This decoder does not support parameter "
51                "changes, but PARAM_CHANGE side data was sent to it.\n");
52         ret = AVERROR(EINVAL);
53         goto fail2;
54     }
55
56     if (size < 4)
57         goto fail;
58
59     flags = bytestream_get_le32(&data);
60     size -= 4;
61
62     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
63         if (size < 4)
64             goto fail;
65         avctx->channels = bytestream_get_le32(&data);
66         size -= 4;
67     }
68     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
69         if (size < 8)
70             goto fail;
71         avctx->channel_layout = bytestream_get_le64(&data);
72         size -= 8;
73     }
74     if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
75         if (size < 4)
76             goto fail;
77         avctx->sample_rate = bytestream_get_le32(&data);
78         size -= 4;
79     }
80     if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
81         if (size < 8)
82             goto fail;
83         avctx->width  = bytestream_get_le32(&data);
84         avctx->height = bytestream_get_le32(&data);
85         size -= 8;
86         ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
87         if (ret < 0)
88             goto fail2;
89     }
90
91     return 0;
92 fail:
93     av_log(avctx, AV_LOG_ERROR, "PARAM_CHANGE side data too small.\n");
94     ret = AVERROR_INVALIDDATA;
95 fail2:
96     if (ret < 0) {
97         av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n");
98         if (avctx->err_recognition & AV_EF_EXPLODE)
99             return ret;
100     }
101     return 0;
102 }
103
104 static int extract_packet_props(AVCodecInternal *avci, const AVPacket *pkt)
105 {
106     av_packet_unref(avci->last_pkt_props);
107     if (pkt)
108         return av_packet_copy_props(avci->last_pkt_props, pkt);
109     return 0;
110 }
111
112 static int unrefcount_frame(AVCodecInternal *avci, AVFrame *frame)
113 {
114     int ret;
115
116     /* move the original frame to our backup */
117     av_frame_unref(avci->to_free);
118     av_frame_move_ref(avci->to_free, frame);
119
120     /* now copy everything except the AVBufferRefs back
121      * note that we make a COPY of the side data, so calling av_frame_free() on
122      * the caller's frame will work properly */
123     ret = av_frame_copy_props(frame, avci->to_free);
124     if (ret < 0)
125         return ret;
126
127     memcpy(frame->data,     avci->to_free->data,     sizeof(frame->data));
128     memcpy(frame->linesize, avci->to_free->linesize, sizeof(frame->linesize));
129     if (avci->to_free->extended_data != avci->to_free->data) {
130         int planes = av_get_channel_layout_nb_channels(avci->to_free->channel_layout);
131         int size   = planes * sizeof(*frame->extended_data);
132
133         if (!size) {
134             av_frame_unref(frame);
135             return AVERROR_BUG;
136         }
137
138         frame->extended_data = av_malloc(size);
139         if (!frame->extended_data) {
140             av_frame_unref(frame);
141             return AVERROR(ENOMEM);
142         }
143         memcpy(frame->extended_data, avci->to_free->extended_data,
144                size);
145     } else
146         frame->extended_data = frame->data;
147
148     frame->format         = avci->to_free->format;
149     frame->width          = avci->to_free->width;
150     frame->height         = avci->to_free->height;
151     frame->channel_layout = avci->to_free->channel_layout;
152     frame->nb_samples     = avci->to_free->nb_samples;
153
154     return 0;
155 }
156
157 int ff_decode_get_packet(AVCodecContext *avctx, AVPacket *pkt)
158 {
159     AVCodecInternal *avci = avctx->internal;
160     int ret;
161
162     if (avci->draining)
163         return AVERROR_EOF;
164
165     if (!avci->buffer_pkt->data && !avci->buffer_pkt->side_data_elems)
166         return AVERROR(EAGAIN);
167
168     av_packet_move_ref(pkt, avci->buffer_pkt);
169
170     ret = extract_packet_props(avctx->internal, pkt);
171     if (ret < 0)
172         goto finish;
173
174     ret = apply_param_change(avctx, pkt);
175     if (ret < 0)
176         goto finish;
177
178     if (avctx->codec->receive_frame)
179         avci->compat_decode_consumed += pkt->size;
180
181     return 0;
182 finish:
183     av_packet_unref(pkt);
184     return ret;
185 }
186
187 /*
188  * The core of the receive_frame_wrapper for the decoders implementing
189  * the simple API. Certain decoders might consume partial packets without
190  * returning any output, so this function needs to be called in a loop until it
191  * returns EAGAIN.
192  **/
193 static int decode_simple_internal(AVCodecContext *avctx, AVFrame *frame)
194 {
195     AVCodecInternal   *avci = avctx->internal;
196     DecodeSimpleContext *ds = &avci->ds;
197     AVPacket           *pkt = ds->in_pkt;
198     int got_frame;
199     int ret;
200
201     if (!pkt->data && !avci->draining) {
202         av_packet_unref(pkt);
203         ret = ff_decode_get_packet(avctx, pkt);
204         if (ret < 0 && ret != AVERROR_EOF)
205             return ret;
206     }
207
208     // Some codecs (at least wma lossless) will crash when feeding drain packets
209     // after EOF was signaled.
210     if (avci->draining_done)
211         return AVERROR_EOF;
212
213     if (!pkt->data &&
214         !(avctx->codec->capabilities & AV_CODEC_CAP_DELAY ||
215           avctx->active_thread_type & FF_THREAD_FRAME))
216         return AVERROR_EOF;
217
218     got_frame = 0;
219
220     if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME) {
221         ret = ff_thread_decode_frame(avctx, frame, &got_frame, pkt);
222     } else {
223         ret = avctx->codec->decode(avctx, frame, &got_frame, pkt);
224
225         if (!(avctx->codec->caps_internal & FF_CODEC_CAP_SETS_PKT_DTS))
226             frame->pkt_dts = pkt->dts;
227         /* get_buffer is supposed to set frame parameters */
228         if (!(avctx->codec->capabilities & AV_CODEC_CAP_DR1)) {
229             frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
230             frame->width               = avctx->width;
231             frame->height              = avctx->height;
232             frame->format              = avctx->codec->type == AVMEDIA_TYPE_VIDEO ?
233                                          avctx->pix_fmt : avctx->sample_fmt;
234         }
235     }
236
237     emms_c();
238
239     if (!got_frame)
240         av_frame_unref(frame);
241
242     if (ret >= 0 && avctx->codec->type == AVMEDIA_TYPE_VIDEO)
243         ret = pkt->size;
244
245 #if FF_API_AVCTX_TIMEBASE
246     if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
247         avctx->time_base = av_inv_q(avctx->framerate);
248 #endif
249
250     if (avctx->internal->draining && !got_frame)
251         avci->draining_done = 1;
252
253     avci->compat_decode_consumed += ret;
254
255     if (ret >= pkt->size || ret < 0) {
256         av_packet_unref(pkt);
257     } else {
258         int consumed = ret;
259
260         pkt->data                += consumed;
261         pkt->size                -= consumed;
262         pkt->pts                  = AV_NOPTS_VALUE;
263         pkt->dts                  = AV_NOPTS_VALUE;
264         avci->last_pkt_props->pts = AV_NOPTS_VALUE;
265         avci->last_pkt_props->dts = AV_NOPTS_VALUE;
266     }
267
268     if (got_frame)
269         av_assert0(frame->buf[0]);
270
271     return ret < 0 ? ret : 0;
272 }
273
274 static int decode_simple_receive_frame(AVCodecContext *avctx, AVFrame *frame)
275 {
276     int ret;
277
278     while (!frame->buf[0]) {
279         ret = decode_simple_internal(avctx, frame);
280         if (ret < 0)
281             return ret;
282     }
283
284     return 0;
285 }
286
287 static int decode_receive_frame_internal(AVCodecContext *avctx, AVFrame *frame)
288 {
289     AVCodecInternal *avci = avctx->internal;
290     int ret;
291
292     av_assert0(!frame->buf[0]);
293
294     if (avctx->codec->receive_frame)
295         ret = avctx->codec->receive_frame(avctx, frame);
296     else
297         ret = decode_simple_receive_frame(avctx, frame);
298
299     if (ret == AVERROR_EOF)
300         avci->draining_done = 1;
301
302     return ret;
303 }
304
305 int attribute_align_arg avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)
306 {
307     AVCodecInternal *avci = avctx->internal;
308     int ret = 0;
309
310     if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
311         return AVERROR(EINVAL);
312
313     if (avctx->internal->draining)
314         return AVERROR_EOF;
315
316     if (avci->buffer_pkt->data || avci->buffer_pkt->side_data_elems)
317         return AVERROR(EAGAIN);
318
319     if (!avpkt || !avpkt->size) {
320         avctx->internal->draining = 1;
321     } else {
322         ret = av_packet_ref(avci->buffer_pkt, avpkt);
323         if (ret < 0)
324             return ret;
325     }
326
327     if (!avci->buffer_frame->buf[0]) {
328         ret = decode_receive_frame_internal(avctx, avci->buffer_frame);
329         if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
330             return ret;
331     }
332
333     return 0;
334 }
335
336 int attribute_align_arg avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
337 {
338     AVCodecInternal *avci = avctx->internal;
339     int ret;
340
341     av_frame_unref(frame);
342
343     if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
344         return AVERROR(EINVAL);
345
346     if (avci->buffer_frame->buf[0]) {
347         av_frame_move_ref(frame, avci->buffer_frame);
348     } else {
349         ret = decode_receive_frame_internal(avctx, frame);
350         if (ret < 0)
351             return ret;
352     }
353
354     avctx->frame_number++;
355
356     return 0;
357 }
358
359 static int compat_decode(AVCodecContext *avctx, AVFrame *frame,
360                          int *got_frame, AVPacket *pkt)
361 {
362     AVCodecInternal *avci = avctx->internal;
363     int ret;
364
365     av_assert0(avci->compat_decode_consumed == 0);
366
367     *got_frame = 0;
368     avci->compat_decode = 1;
369
370     if (avci->compat_decode_partial_size > 0 &&
371         avci->compat_decode_partial_size != pkt->size) {
372         av_log(avctx, AV_LOG_ERROR,
373                "Got unexpected packet size after a partial decode\n");
374         ret = AVERROR(EINVAL);
375         goto finish;
376     }
377
378     if (!avci->compat_decode_partial_size) {
379         ret = avcodec_send_packet(avctx, pkt);
380         if (ret == AVERROR_EOF)
381             ret = 0;
382         else if (ret == AVERROR(EAGAIN)) {
383             /* we fully drain all the output in each decode call, so this should not
384              * ever happen */
385             ret = AVERROR_BUG;
386             goto finish;
387         } else if (ret < 0)
388             goto finish;
389     }
390
391     while (ret >= 0) {
392         ret = avcodec_receive_frame(avctx, frame);
393         if (ret < 0) {
394             if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
395                 ret = 0;
396             goto finish;
397         }
398
399         if (frame != avci->compat_decode_frame) {
400             if (!avctx->refcounted_frames) {
401                 ret = unrefcount_frame(avci, frame);
402                 if (ret < 0)
403                     goto finish;
404             }
405
406             *got_frame = 1;
407             frame = avci->compat_decode_frame;
408         } else {
409             if (!avci->compat_decode_warned) {
410                 av_log(avctx, AV_LOG_WARNING, "The deprecated avcodec_decode_* "
411                        "API cannot return all the frames for this decoder. "
412                        "Some frames will be dropped. Update your code to the "
413                        "new decoding API to fix this.\n");
414                 avci->compat_decode_warned = 1;
415             }
416         }
417
418         if (avci->draining || avci->compat_decode_consumed < pkt->size)
419             break;
420     }
421
422 finish:
423     if (ret == 0)
424         ret = FFMIN(avci->compat_decode_consumed, pkt->size);
425     avci->compat_decode_consumed = 0;
426     avci->compat_decode_partial_size = (ret >= 0) ? pkt->size - ret : 0;
427
428     return ret;
429 }
430
431 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
432                                               int *got_picture_ptr,
433                                               AVPacket *avpkt)
434 {
435     return compat_decode(avctx, picture, got_picture_ptr, avpkt);
436 }
437
438 int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
439                                               AVFrame *frame,
440                                               int *got_frame_ptr,
441                                               AVPacket *avpkt)
442 {
443     return compat_decode(avctx, frame, got_frame_ptr, avpkt);
444 }
445
446 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
447                              int *got_sub_ptr,
448                              AVPacket *avpkt)
449 {
450     int ret;
451
452     ret = extract_packet_props(avctx->internal, avpkt);
453     if (ret < 0)
454         return ret;
455
456     *got_sub_ptr = 0;
457     ret = avctx->codec->decode(avctx, sub, got_sub_ptr, avpkt);
458     if (*got_sub_ptr)
459         avctx->frame_number++;
460     return ret;
461 }
462
463 static int is_hwaccel_pix_fmt(enum AVPixelFormat pix_fmt)
464 {
465     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
466     return desc->flags & AV_PIX_FMT_FLAG_HWACCEL;
467 }
468
469 enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
470 {
471     while (*fmt != AV_PIX_FMT_NONE && is_hwaccel_pix_fmt(*fmt))
472         ++fmt;
473     return fmt[0];
474 }
475
476 static AVHWAccel *find_hwaccel(enum AVCodecID codec_id,
477                                enum AVPixelFormat pix_fmt)
478 {
479     AVHWAccel *hwaccel = NULL;
480
481     while ((hwaccel = av_hwaccel_next(hwaccel)))
482         if (hwaccel->id == codec_id
483             && hwaccel->pix_fmt == pix_fmt)
484             return hwaccel;
485     return NULL;
486 }
487
488 static int setup_hwaccel(AVCodecContext *avctx,
489                          const enum AVPixelFormat fmt,
490                          const char *name)
491 {
492     AVHWAccel *hwa = find_hwaccel(avctx->codec_id, fmt);
493     int ret        = 0;
494
495     if (!hwa) {
496         av_log(avctx, AV_LOG_ERROR,
497                "Could not find an AVHWAccel for the pixel format: %s",
498                name);
499         return AVERROR(ENOENT);
500     }
501
502     if (hwa->priv_data_size) {
503         avctx->internal->hwaccel_priv_data = av_mallocz(hwa->priv_data_size);
504         if (!avctx->internal->hwaccel_priv_data)
505             return AVERROR(ENOMEM);
506     }
507
508     if (hwa->init) {
509         ret = hwa->init(avctx);
510         if (ret < 0) {
511             av_freep(&avctx->internal->hwaccel_priv_data);
512             return ret;
513         }
514     }
515
516     avctx->hwaccel = hwa;
517
518     return 0;
519 }
520
521 int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
522 {
523     const AVPixFmtDescriptor *desc;
524     enum AVPixelFormat *choices;
525     enum AVPixelFormat ret;
526     unsigned n = 0;
527
528     while (fmt[n] != AV_PIX_FMT_NONE)
529         ++n;
530
531     av_assert0(n >= 1);
532     avctx->sw_pix_fmt = fmt[n - 1];
533     av_assert2(!is_hwaccel_pix_fmt(avctx->sw_pix_fmt));
534
535     choices = av_malloc_array(n + 1, sizeof(*choices));
536     if (!choices)
537         return AV_PIX_FMT_NONE;
538
539     memcpy(choices, fmt, (n + 1) * sizeof(*choices));
540
541     for (;;) {
542         if (avctx->hwaccel && avctx->hwaccel->uninit)
543             avctx->hwaccel->uninit(avctx);
544         av_freep(&avctx->internal->hwaccel_priv_data);
545         avctx->hwaccel = NULL;
546
547         av_buffer_unref(&avctx->hw_frames_ctx);
548
549         ret = avctx->get_format(avctx, choices);
550
551         desc = av_pix_fmt_desc_get(ret);
552         if (!desc) {
553             ret = AV_PIX_FMT_NONE;
554             break;
555         }
556
557         if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
558             break;
559
560         if (avctx->hw_frames_ctx) {
561             AVHWFramesContext *hw_frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
562             if (hw_frames_ctx->format != ret) {
563                 av_log(avctx, AV_LOG_ERROR, "Format returned from get_buffer() "
564                        "does not match the format of provided AVHWFramesContext\n");
565                 ret = AV_PIX_FMT_NONE;
566                 break;
567             }
568         }
569
570         if (!setup_hwaccel(avctx, ret, desc->name))
571             break;
572
573         /* Remove failed hwaccel from choices */
574         for (n = 0; choices[n] != ret; n++)
575             av_assert0(choices[n] != AV_PIX_FMT_NONE);
576
577         do
578             choices[n] = choices[n + 1];
579         while (choices[n++] != AV_PIX_FMT_NONE);
580     }
581
582     av_freep(&choices);
583     return ret;
584 }
585
586 static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame)
587 {
588     FramePool *pool = avctx->internal->pool;
589     int i, ret;
590
591     switch (avctx->codec_type) {
592     case AVMEDIA_TYPE_VIDEO: {
593         uint8_t *data[4];
594         int linesize[4];
595         int size[4] = { 0 };
596         int w = frame->width;
597         int h = frame->height;
598         int tmpsize, unaligned;
599
600         if (pool->format == frame->format &&
601             pool->width == frame->width && pool->height == frame->height)
602             return 0;
603
604         avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align);
605
606         do {
607             // NOTE: do not align linesizes individually, this breaks e.g. assumptions
608             // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
609             av_image_fill_linesizes(linesize, avctx->pix_fmt, w);
610             // increase alignment of w for next try (rhs gives the lowest bit set in w)
611             w += w & ~(w - 1);
612
613             unaligned = 0;
614             for (i = 0; i < 4; i++)
615                 unaligned |= linesize[i] % pool->stride_align[i];
616         } while (unaligned);
617
618         tmpsize = av_image_fill_pointers(data, avctx->pix_fmt, h,
619                                          NULL, linesize);
620         if (tmpsize < 0)
621             return -1;
622
623         for (i = 0; i < 3 && data[i + 1]; i++)
624             size[i] = data[i + 1] - data[i];
625         size[i] = tmpsize - (data[i] - data[0]);
626
627         for (i = 0; i < 4; i++) {
628             av_buffer_pool_uninit(&pool->pools[i]);
629             pool->linesize[i] = linesize[i];
630             if (size[i]) {
631                 pool->pools[i] = av_buffer_pool_init(size[i] + 16, NULL);
632                 if (!pool->pools[i]) {
633                     ret = AVERROR(ENOMEM);
634                     goto fail;
635                 }
636             }
637         }
638         pool->format = frame->format;
639         pool->width  = frame->width;
640         pool->height = frame->height;
641
642         break;
643         }
644     case AVMEDIA_TYPE_AUDIO: {
645         int ch     = av_get_channel_layout_nb_channels(frame->channel_layout);
646         int planar = av_sample_fmt_is_planar(frame->format);
647         int planes = planar ? ch : 1;
648
649         if (pool->format == frame->format && pool->planes == planes &&
650             pool->channels == ch && frame->nb_samples == pool->samples)
651             return 0;
652
653         av_buffer_pool_uninit(&pool->pools[0]);
654         ret = av_samples_get_buffer_size(&pool->linesize[0], ch,
655                                          frame->nb_samples, frame->format, 0);
656         if (ret < 0)
657             goto fail;
658
659         pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL);
660         if (!pool->pools[0]) {
661             ret = AVERROR(ENOMEM);
662             goto fail;
663         }
664
665         pool->format     = frame->format;
666         pool->planes     = planes;
667         pool->channels   = ch;
668         pool->samples = frame->nb_samples;
669         break;
670         }
671     default: av_assert0(0);
672     }
673     return 0;
674 fail:
675     for (i = 0; i < 4; i++)
676         av_buffer_pool_uninit(&pool->pools[i]);
677     pool->format = -1;
678     pool->planes = pool->channels = pool->samples = 0;
679     pool->width  = pool->height = 0;
680     return ret;
681 }
682
683 static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
684 {
685     FramePool *pool = avctx->internal->pool;
686     int planes = pool->planes;
687     int i;
688
689     frame->linesize[0] = pool->linesize[0];
690
691     if (planes > AV_NUM_DATA_POINTERS) {
692         frame->extended_data = av_mallocz(planes * sizeof(*frame->extended_data));
693         frame->nb_extended_buf = planes - AV_NUM_DATA_POINTERS;
694         frame->extended_buf  = av_mallocz(frame->nb_extended_buf *
695                                           sizeof(*frame->extended_buf));
696         if (!frame->extended_data || !frame->extended_buf) {
697             av_freep(&frame->extended_data);
698             av_freep(&frame->extended_buf);
699             return AVERROR(ENOMEM);
700         }
701     } else
702         frame->extended_data = frame->data;
703
704     for (i = 0; i < FFMIN(planes, AV_NUM_DATA_POINTERS); i++) {
705         frame->buf[i] = av_buffer_pool_get(pool->pools[0]);
706         if (!frame->buf[i])
707             goto fail;
708         frame->extended_data[i] = frame->data[i] = frame->buf[i]->data;
709     }
710     for (i = 0; i < frame->nb_extended_buf; i++) {
711         frame->extended_buf[i] = av_buffer_pool_get(pool->pools[0]);
712         if (!frame->extended_buf[i])
713             goto fail;
714         frame->extended_data[i + AV_NUM_DATA_POINTERS] = frame->extended_buf[i]->data;
715     }
716
717     if (avctx->debug & FF_DEBUG_BUFFERS)
718         av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p", frame);
719
720     return 0;
721 fail:
722     av_frame_unref(frame);
723     return AVERROR(ENOMEM);
724 }
725
726 static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
727 {
728     FramePool *pool = s->internal->pool;
729     int i;
730
731     if (pic->data[0]) {
732         av_log(s, AV_LOG_ERROR, "pic->data[0]!=NULL in avcodec_default_get_buffer\n");
733         return -1;
734     }
735
736     memset(pic->data, 0, sizeof(pic->data));
737     pic->extended_data = pic->data;
738
739     for (i = 0; i < 4 && pool->pools[i]; i++) {
740         pic->linesize[i] = pool->linesize[i];
741
742         pic->buf[i] = av_buffer_pool_get(pool->pools[i]);
743         if (!pic->buf[i])
744             goto fail;
745
746         pic->data[i] = pic->buf[i]->data;
747     }
748     for (; i < AV_NUM_DATA_POINTERS; i++) {
749         pic->data[i] = NULL;
750         pic->linesize[i] = 0;
751     }
752     if (pic->data[1] && !pic->data[2])
753         avpriv_set_systematic_pal2((uint32_t *)pic->data[1], s->pix_fmt);
754
755     if (s->debug & FF_DEBUG_BUFFERS)
756         av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p\n", pic);
757
758     return 0;
759 fail:
760     av_frame_unref(pic);
761     return AVERROR(ENOMEM);
762 }
763
764 int avcodec_default_get_buffer2(AVCodecContext *avctx, AVFrame *frame, int flags)
765 {
766     int ret;
767
768     if (avctx->hw_frames_ctx)
769         return av_hwframe_get_buffer(avctx->hw_frames_ctx, frame, 0);
770
771     if ((ret = update_frame_pool(avctx, frame)) < 0)
772         return ret;
773
774     switch (avctx->codec_type) {
775     case AVMEDIA_TYPE_VIDEO:
776         return video_get_buffer(avctx, frame);
777     case AVMEDIA_TYPE_AUDIO:
778         return audio_get_buffer(avctx, frame);
779     default:
780         return -1;
781     }
782 }
783
784 int ff_decode_frame_props(AVCodecContext *avctx, AVFrame *frame)
785 {
786     AVPacket *pkt = avctx->internal->last_pkt_props;
787     int i;
788     struct {
789         enum AVPacketSideDataType packet;
790         enum AVFrameSideDataType frame;
791     } sd[] = {
792         { AV_PKT_DATA_REPLAYGAIN ,   AV_FRAME_DATA_REPLAYGAIN },
793         { AV_PKT_DATA_DISPLAYMATRIX, AV_FRAME_DATA_DISPLAYMATRIX },
794         { AV_PKT_DATA_SPHERICAL,     AV_FRAME_DATA_SPHERICAL },
795         { AV_PKT_DATA_STEREO3D,      AV_FRAME_DATA_STEREO3D },
796         { AV_PKT_DATA_AUDIO_SERVICE_TYPE, AV_FRAME_DATA_AUDIO_SERVICE_TYPE },
797     };
798
799     frame->color_primaries = avctx->color_primaries;
800     frame->color_trc       = avctx->color_trc;
801     frame->colorspace      = avctx->colorspace;
802     frame->color_range     = avctx->color_range;
803     frame->chroma_location = avctx->chroma_sample_location;
804
805     frame->reordered_opaque = avctx->reordered_opaque;
806
807 #if FF_API_PKT_PTS
808 FF_DISABLE_DEPRECATION_WARNINGS
809     frame->pkt_pts = pkt->pts;
810 FF_ENABLE_DEPRECATION_WARNINGS
811 #endif
812     frame->pts     = pkt->pts;
813
814     for (i = 0; i < FF_ARRAY_ELEMS(sd); i++) {
815         int size;
816         uint8_t *packet_sd = av_packet_get_side_data(pkt, sd[i].packet, &size);
817         if (packet_sd) {
818             AVFrameSideData *frame_sd = av_frame_new_side_data(frame,
819                                                                sd[i].frame,
820                                                                size);
821             if (!frame_sd)
822                 return AVERROR(ENOMEM);
823
824             memcpy(frame_sd->data, packet_sd, size);
825         }
826     }
827
828     return 0;
829 }
830
831 int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
832 {
833     const AVHWAccel *hwaccel = avctx->hwaccel;
834     int override_dimensions = 1;
835     int ret;
836
837     switch (avctx->codec_type) {
838     case AVMEDIA_TYPE_VIDEO:
839         if (frame->width <= 0 || frame->height <= 0) {
840             frame->width  = FFMAX(avctx->width, avctx->coded_width);
841             frame->height = FFMAX(avctx->height, avctx->coded_height);
842             override_dimensions = 0;
843         }
844         if (frame->format < 0)
845             frame->format              = avctx->pix_fmt;
846         if (!frame->sample_aspect_ratio.num)
847             frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
848
849         if (av_image_check_sar(frame->width, frame->height,
850                                frame->sample_aspect_ratio) < 0) {
851             av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
852                    frame->sample_aspect_ratio.num,
853                    frame->sample_aspect_ratio.den);
854             frame->sample_aspect_ratio = (AVRational){ 0, 1 };
855         }
856
857         if ((ret = av_image_check_size(avctx->width, avctx->height, 0, avctx)) < 0)
858             return ret;
859         break;
860     case AVMEDIA_TYPE_AUDIO:
861         if (!frame->sample_rate)
862             frame->sample_rate    = avctx->sample_rate;
863         if (frame->format < 0)
864             frame->format         = avctx->sample_fmt;
865         if (!frame->channel_layout) {
866             if (avctx->channel_layout) {
867                  if (av_get_channel_layout_nb_channels(avctx->channel_layout) !=
868                      avctx->channels) {
869                      av_log(avctx, AV_LOG_ERROR, "Inconsistent channel "
870                             "configuration.\n");
871                      return AVERROR(EINVAL);
872                  }
873
874                 frame->channel_layout = avctx->channel_layout;
875             } else {
876                 if (avctx->channels > FF_SANE_NB_CHANNELS) {
877                     av_log(avctx, AV_LOG_ERROR, "Too many channels: %d.\n",
878                            avctx->channels);
879                     return AVERROR(ENOSYS);
880                 }
881
882                 frame->channel_layout = av_get_default_channel_layout(avctx->channels);
883                 if (!frame->channel_layout)
884                     frame->channel_layout = (1ULL << avctx->channels) - 1;
885             }
886         }
887         break;
888     default: return AVERROR(EINVAL);
889     }
890
891     ret = ff_decode_frame_props(avctx, frame);
892     if (ret < 0)
893         return ret;
894
895     if (hwaccel) {
896         if (hwaccel->alloc_frame) {
897             ret = hwaccel->alloc_frame(avctx, frame);
898             goto end;
899         }
900     } else
901         avctx->sw_pix_fmt = avctx->pix_fmt;
902
903     ret = avctx->get_buffer2(avctx, frame, flags);
904
905 end:
906     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO && !override_dimensions) {
907         frame->width  = avctx->width;
908         frame->height = avctx->height;
909     }
910
911     return ret;
912 }
913
914 int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame)
915 {
916     AVFrame *tmp;
917     int ret;
918
919     av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
920
921     if (!frame->data[0])
922         return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
923
924     if (av_frame_is_writable(frame))
925         return ff_decode_frame_props(avctx, frame);
926
927     tmp = av_frame_alloc();
928     if (!tmp)
929         return AVERROR(ENOMEM);
930
931     av_frame_move_ref(tmp, frame);
932
933     ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
934     if (ret < 0) {
935         av_frame_free(&tmp);
936         return ret;
937     }
938
939     av_frame_copy(frame, tmp);
940     av_frame_free(&tmp);
941
942     return 0;
943 }
944
945 void avcodec_flush_buffers(AVCodecContext *avctx)
946 {
947     avctx->internal->draining      = 0;
948     avctx->internal->draining_done = 0;
949     av_frame_unref(avctx->internal->buffer_frame);
950     av_frame_unref(avctx->internal->compat_decode_frame);
951     av_packet_unref(avctx->internal->buffer_pkt);
952     avctx->internal->buffer_pkt_valid = 0;
953
954     av_packet_unref(avctx->internal->ds.in_pkt);
955
956     if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
957         ff_thread_flush(avctx);
958     else if (avctx->codec->flush)
959         avctx->codec->flush(avctx);
960
961     if (!avctx->refcounted_frames)
962         av_frame_unref(avctx->internal->to_free);
963 }