]> git.sesse.net Git - ffmpeg/blob - libavcodec/decode.c
mpeg12dec: move setting first_field to mpeg_field_start()
[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 static int bsfs_init(AVCodecContext *avctx)
158 {
159     AVCodecInternal *avci = avctx->internal;
160     DecodeFilterContext *s = &avci->filter;
161     const char *bsfs_str;
162     int ret;
163
164     if (s->nb_bsfs)
165         return 0;
166
167     bsfs_str = avctx->codec->bsfs ? avctx->codec->bsfs : "null";
168     while (bsfs_str && *bsfs_str) {
169         AVBSFContext **tmp;
170         const AVBitStreamFilter *filter;
171         char *bsf;
172
173         bsf = av_get_token(&bsfs_str, ",");
174         if (!bsf) {
175             ret = AVERROR(ENOMEM);
176             goto fail;
177         }
178
179         filter = av_bsf_get_by_name(bsf);
180         if (!filter) {
181             av_log(avctx, AV_LOG_ERROR, "A non-existing bitstream filter %s "
182                    "requested by a decoder. This is a bug, please report it.\n",
183                    bsf);
184             ret = AVERROR_BUG;
185             av_freep(&bsf);
186             goto fail;
187         }
188         av_freep(&bsf);
189
190         tmp = av_realloc_array(s->bsfs, s->nb_bsfs + 1, sizeof(*s->bsfs));
191         if (!tmp) {
192             ret = AVERROR(ENOMEM);
193             goto fail;
194         }
195         s->bsfs = tmp;
196         s->nb_bsfs++;
197
198         ret = av_bsf_alloc(filter, &s->bsfs[s->nb_bsfs - 1]);
199         if (ret < 0)
200             goto fail;
201
202         if (s->nb_bsfs == 1) {
203             /* We do not currently have an API for passing the input timebase into decoders,
204              * but no filters used here should actually need it.
205              * So we make up some plausible-looking number (the MPEG 90kHz timebase) */
206             s->bsfs[s->nb_bsfs - 1]->time_base_in = (AVRational){ 1, 90000 };
207             ret = avcodec_parameters_from_context(s->bsfs[s->nb_bsfs - 1]->par_in,
208                                                   avctx);
209         } else {
210             s->bsfs[s->nb_bsfs - 1]->time_base_in = s->bsfs[s->nb_bsfs - 2]->time_base_out;
211             ret = avcodec_parameters_copy(s->bsfs[s->nb_bsfs - 1]->par_in,
212                                           s->bsfs[s->nb_bsfs - 2]->par_out);
213         }
214         if (ret < 0)
215             goto fail;
216
217         ret = av_bsf_init(s->bsfs[s->nb_bsfs - 1]);
218         if (ret < 0)
219             goto fail;
220     }
221
222     return 0;
223 fail:
224     ff_decode_bsfs_uninit(avctx);
225     return ret;
226 }
227
228 /* try to get one output packet from the filter chain */
229 static int bsfs_poll(AVCodecContext *avctx, AVPacket *pkt)
230 {
231     DecodeFilterContext *s = &avctx->internal->filter;
232     int idx, ret;
233
234     /* start with the last filter in the chain */
235     idx = s->nb_bsfs - 1;
236     while (idx >= 0) {
237         /* request a packet from the currently selected filter */
238         ret = av_bsf_receive_packet(s->bsfs[idx], pkt);
239         if (ret == AVERROR(EAGAIN)) {
240             /* no packets available, try the next filter up the chain */
241             ret = 0;
242             idx--;
243             continue;
244         } else if (ret < 0 && ret != AVERROR_EOF) {
245             return ret;
246         }
247
248         /* got a packet or EOF -- pass it to the caller or to the next filter
249          * down the chain */
250         if (idx == s->nb_bsfs - 1) {
251             return ret;
252         } else {
253             idx++;
254             ret = av_bsf_send_packet(s->bsfs[idx], ret < 0 ? NULL : pkt);
255             if (ret < 0) {
256                 av_log(avctx, AV_LOG_ERROR,
257                        "Error pre-processing a packet before decoding\n");
258                 av_packet_unref(pkt);
259                 return ret;
260             }
261         }
262     }
263
264     return AVERROR(EAGAIN);
265 }
266
267 int ff_decode_get_packet(AVCodecContext *avctx, AVPacket *pkt)
268 {
269     AVCodecInternal *avci = avctx->internal;
270     int ret;
271
272     if (avci->draining)
273         return AVERROR_EOF;
274
275     ret = bsfs_poll(avctx, pkt);
276     if (ret == AVERROR_EOF)
277         avci->draining = 1;
278     if (ret < 0)
279         return ret;
280
281     ret = extract_packet_props(avctx->internal, pkt);
282     if (ret < 0)
283         goto finish;
284
285     ret = apply_param_change(avctx, pkt);
286     if (ret < 0)
287         goto finish;
288
289     if (avctx->codec->receive_frame)
290         avci->compat_decode_consumed += pkt->size;
291
292     return 0;
293 finish:
294     av_packet_unref(pkt);
295     return ret;
296 }
297
298 /*
299  * The core of the receive_frame_wrapper for the decoders implementing
300  * the simple API. Certain decoders might consume partial packets without
301  * returning any output, so this function needs to be called in a loop until it
302  * returns EAGAIN.
303  **/
304 static int decode_simple_internal(AVCodecContext *avctx, AVFrame *frame)
305 {
306     AVCodecInternal   *avci = avctx->internal;
307     DecodeSimpleContext *ds = &avci->ds;
308     AVPacket           *pkt = ds->in_pkt;
309     int got_frame;
310     int ret;
311
312     if (!pkt->data && !avci->draining) {
313         av_packet_unref(pkt);
314         ret = ff_decode_get_packet(avctx, pkt);
315         if (ret < 0 && ret != AVERROR_EOF)
316             return ret;
317     }
318
319     // Some codecs (at least wma lossless) will crash when feeding drain packets
320     // after EOF was signaled.
321     if (avci->draining_done)
322         return AVERROR_EOF;
323
324     if (!pkt->data &&
325         !(avctx->codec->capabilities & AV_CODEC_CAP_DELAY ||
326           avctx->active_thread_type & FF_THREAD_FRAME))
327         return AVERROR_EOF;
328
329     got_frame = 0;
330
331     if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME) {
332         ret = ff_thread_decode_frame(avctx, frame, &got_frame, pkt);
333     } else {
334         ret = avctx->codec->decode(avctx, frame, &got_frame, pkt);
335
336         if (!(avctx->codec->caps_internal & FF_CODEC_CAP_SETS_PKT_DTS))
337             frame->pkt_dts = pkt->dts;
338         /* get_buffer is supposed to set frame parameters */
339         if (!(avctx->codec->capabilities & AV_CODEC_CAP_DR1)) {
340             frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
341             frame->width               = avctx->width;
342             frame->height              = avctx->height;
343             frame->format              = avctx->codec->type == AVMEDIA_TYPE_VIDEO ?
344                                          avctx->pix_fmt : avctx->sample_fmt;
345         }
346     }
347
348     emms_c();
349
350     if (!got_frame)
351         av_frame_unref(frame);
352
353     if (ret >= 0 && avctx->codec->type == AVMEDIA_TYPE_VIDEO)
354         ret = pkt->size;
355
356 #if FF_API_AVCTX_TIMEBASE
357     if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
358         avctx->time_base = av_inv_q(avctx->framerate);
359 #endif
360
361     if (avctx->internal->draining && !got_frame)
362         avci->draining_done = 1;
363
364     avci->compat_decode_consumed += ret;
365
366     if (ret >= pkt->size || ret < 0) {
367         av_packet_unref(pkt);
368     } else {
369         int consumed = ret;
370
371         pkt->data                += consumed;
372         pkt->size                -= consumed;
373         pkt->pts                  = AV_NOPTS_VALUE;
374         pkt->dts                  = AV_NOPTS_VALUE;
375         avci->last_pkt_props->pts = AV_NOPTS_VALUE;
376         avci->last_pkt_props->dts = AV_NOPTS_VALUE;
377     }
378
379     if (got_frame)
380         av_assert0(frame->buf[0]);
381
382     return ret < 0 ? ret : 0;
383 }
384
385 static int decode_simple_receive_frame(AVCodecContext *avctx, AVFrame *frame)
386 {
387     int ret;
388
389     while (!frame->buf[0]) {
390         ret = decode_simple_internal(avctx, frame);
391         if (ret < 0)
392             return ret;
393     }
394
395     return 0;
396 }
397
398 static int decode_receive_frame_internal(AVCodecContext *avctx, AVFrame *frame)
399 {
400     AVCodecInternal *avci = avctx->internal;
401     int ret;
402
403     av_assert0(!frame->buf[0]);
404
405     if (avctx->codec->receive_frame)
406         ret = avctx->codec->receive_frame(avctx, frame);
407     else
408         ret = decode_simple_receive_frame(avctx, frame);
409
410     if (ret == AVERROR_EOF)
411         avci->draining_done = 1;
412
413     return ret;
414 }
415
416 int attribute_align_arg avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)
417 {
418     AVCodecInternal *avci = avctx->internal;
419     int ret = 0;
420
421     if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
422         return AVERROR(EINVAL);
423
424     if (avctx->internal->draining)
425         return AVERROR_EOF;
426
427     ret = bsfs_init(avctx);
428     if (ret < 0)
429         return ret;
430
431     av_packet_unref(avci->buffer_pkt);
432     if (avpkt && (avpkt->data || avpkt->side_data_elems)) {
433         ret = av_packet_ref(avci->buffer_pkt, avpkt);
434         if (ret < 0)
435             return ret;
436     }
437
438     ret = av_bsf_send_packet(avci->filter.bsfs[0], avci->buffer_pkt);
439     if (ret < 0) {
440         av_packet_unref(avci->buffer_pkt);
441         return ret;
442     }
443
444     if (!avci->buffer_frame->buf[0]) {
445         ret = decode_receive_frame_internal(avctx, avci->buffer_frame);
446         if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
447             return ret;
448     }
449
450     return 0;
451 }
452
453 int attribute_align_arg avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
454 {
455     AVCodecInternal *avci = avctx->internal;
456     int ret;
457
458     av_frame_unref(frame);
459
460     if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
461         return AVERROR(EINVAL);
462
463     ret = bsfs_init(avctx);
464     if (ret < 0)
465         return ret;
466
467     if (avci->buffer_frame->buf[0]) {
468         av_frame_move_ref(frame, avci->buffer_frame);
469     } else {
470         ret = decode_receive_frame_internal(avctx, frame);
471         if (ret < 0)
472             return ret;
473     }
474
475     avctx->frame_number++;
476
477     return 0;
478 }
479
480 static int compat_decode(AVCodecContext *avctx, AVFrame *frame,
481                          int *got_frame, AVPacket *pkt)
482 {
483     AVCodecInternal *avci = avctx->internal;
484     int ret;
485
486     av_assert0(avci->compat_decode_consumed == 0);
487
488     *got_frame = 0;
489     avci->compat_decode = 1;
490
491     if (avci->compat_decode_partial_size > 0 &&
492         avci->compat_decode_partial_size != pkt->size) {
493         av_log(avctx, AV_LOG_ERROR,
494                "Got unexpected packet size after a partial decode\n");
495         ret = AVERROR(EINVAL);
496         goto finish;
497     }
498
499     if (!avci->compat_decode_partial_size) {
500         ret = avcodec_send_packet(avctx, pkt);
501         if (ret == AVERROR_EOF)
502             ret = 0;
503         else if (ret == AVERROR(EAGAIN)) {
504             /* we fully drain all the output in each decode call, so this should not
505              * ever happen */
506             ret = AVERROR_BUG;
507             goto finish;
508         } else if (ret < 0)
509             goto finish;
510     }
511
512     while (ret >= 0) {
513         ret = avcodec_receive_frame(avctx, frame);
514         if (ret < 0) {
515             if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
516                 ret = 0;
517             goto finish;
518         }
519
520         if (frame != avci->compat_decode_frame) {
521             if (!avctx->refcounted_frames) {
522                 ret = unrefcount_frame(avci, frame);
523                 if (ret < 0)
524                     goto finish;
525             }
526
527             *got_frame = 1;
528             frame = avci->compat_decode_frame;
529         } else {
530             if (!avci->compat_decode_warned) {
531                 av_log(avctx, AV_LOG_WARNING, "The deprecated avcodec_decode_* "
532                        "API cannot return all the frames for this decoder. "
533                        "Some frames will be dropped. Update your code to the "
534                        "new decoding API to fix this.\n");
535                 avci->compat_decode_warned = 1;
536             }
537         }
538
539         if (avci->draining || (!avctx->codec->bsfs && avci->compat_decode_consumed < pkt->size))
540             break;
541     }
542
543 finish:
544     if (ret == 0) {
545         /* if there are any bsfs then assume full packet is always consumed */
546         if (avctx->codec->bsfs)
547             ret = pkt->size;
548         else
549             ret = FFMIN(avci->compat_decode_consumed, pkt->size);
550     }
551     avci->compat_decode_consumed = 0;
552     avci->compat_decode_partial_size = (ret >= 0) ? pkt->size - ret : 0;
553
554     return ret;
555 }
556
557 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
558                                               int *got_picture_ptr,
559                                               AVPacket *avpkt)
560 {
561     return compat_decode(avctx, picture, got_picture_ptr, avpkt);
562 }
563
564 int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
565                                               AVFrame *frame,
566                                               int *got_frame_ptr,
567                                               AVPacket *avpkt)
568 {
569     return compat_decode(avctx, frame, got_frame_ptr, avpkt);
570 }
571
572 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
573                              int *got_sub_ptr,
574                              AVPacket *avpkt)
575 {
576     int ret;
577
578     ret = extract_packet_props(avctx->internal, avpkt);
579     if (ret < 0)
580         return ret;
581
582     *got_sub_ptr = 0;
583     ret = avctx->codec->decode(avctx, sub, got_sub_ptr, avpkt);
584     if (*got_sub_ptr)
585         avctx->frame_number++;
586     return ret;
587 }
588
589 static int is_hwaccel_pix_fmt(enum AVPixelFormat pix_fmt)
590 {
591     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
592     return desc->flags & AV_PIX_FMT_FLAG_HWACCEL;
593 }
594
595 enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
596 {
597     while (*fmt != AV_PIX_FMT_NONE && is_hwaccel_pix_fmt(*fmt))
598         ++fmt;
599     return fmt[0];
600 }
601
602 static AVHWAccel *find_hwaccel(enum AVCodecID codec_id,
603                                enum AVPixelFormat pix_fmt)
604 {
605     AVHWAccel *hwaccel = NULL;
606
607     while ((hwaccel = av_hwaccel_next(hwaccel)))
608         if (hwaccel->id == codec_id
609             && hwaccel->pix_fmt == pix_fmt)
610             return hwaccel;
611     return NULL;
612 }
613
614 static int setup_hwaccel(AVCodecContext *avctx,
615                          const enum AVPixelFormat fmt,
616                          const char *name)
617 {
618     AVHWAccel *hwa = find_hwaccel(avctx->codec_id, fmt);
619     int ret        = 0;
620
621     if (!hwa) {
622         av_log(avctx, AV_LOG_ERROR,
623                "Could not find an AVHWAccel for the pixel format: %s",
624                name);
625         return AVERROR(ENOENT);
626     }
627
628     if (hwa->priv_data_size) {
629         avctx->internal->hwaccel_priv_data = av_mallocz(hwa->priv_data_size);
630         if (!avctx->internal->hwaccel_priv_data)
631             return AVERROR(ENOMEM);
632     }
633
634     if (hwa->init) {
635         ret = hwa->init(avctx);
636         if (ret < 0) {
637             av_freep(&avctx->internal->hwaccel_priv_data);
638             return ret;
639         }
640     }
641
642     avctx->hwaccel = hwa;
643
644     return 0;
645 }
646
647 int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
648 {
649     const AVPixFmtDescriptor *desc;
650     enum AVPixelFormat *choices;
651     enum AVPixelFormat ret;
652     unsigned n = 0;
653
654     while (fmt[n] != AV_PIX_FMT_NONE)
655         ++n;
656
657     av_assert0(n >= 1);
658     avctx->sw_pix_fmt = fmt[n - 1];
659     av_assert2(!is_hwaccel_pix_fmt(avctx->sw_pix_fmt));
660
661     choices = av_malloc_array(n + 1, sizeof(*choices));
662     if (!choices)
663         return AV_PIX_FMT_NONE;
664
665     memcpy(choices, fmt, (n + 1) * sizeof(*choices));
666
667     for (;;) {
668         if (avctx->hwaccel && avctx->hwaccel->uninit)
669             avctx->hwaccel->uninit(avctx);
670         av_freep(&avctx->internal->hwaccel_priv_data);
671         avctx->hwaccel = NULL;
672
673         av_buffer_unref(&avctx->hw_frames_ctx);
674
675         ret = avctx->get_format(avctx, choices);
676
677         desc = av_pix_fmt_desc_get(ret);
678         if (!desc) {
679             ret = AV_PIX_FMT_NONE;
680             break;
681         }
682
683         if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
684             break;
685
686         if (avctx->hw_frames_ctx) {
687             AVHWFramesContext *hw_frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
688             if (hw_frames_ctx->format != ret) {
689                 av_log(avctx, AV_LOG_ERROR, "Format returned from get_buffer() "
690                        "does not match the format of provided AVHWFramesContext\n");
691                 ret = AV_PIX_FMT_NONE;
692                 break;
693             }
694         }
695
696         if (!setup_hwaccel(avctx, ret, desc->name))
697             break;
698
699         /* Remove failed hwaccel from choices */
700         for (n = 0; choices[n] != ret; n++)
701             av_assert0(choices[n] != AV_PIX_FMT_NONE);
702
703         do
704             choices[n] = choices[n + 1];
705         while (choices[n++] != AV_PIX_FMT_NONE);
706     }
707
708     av_freep(&choices);
709     return ret;
710 }
711
712 static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame)
713 {
714     FramePool *pool = avctx->internal->pool;
715     int i, ret;
716
717     switch (avctx->codec_type) {
718     case AVMEDIA_TYPE_VIDEO: {
719         uint8_t *data[4];
720         int linesize[4];
721         int size[4] = { 0 };
722         int w = frame->width;
723         int h = frame->height;
724         int tmpsize, unaligned;
725
726         if (pool->format == frame->format &&
727             pool->width == frame->width && pool->height == frame->height)
728             return 0;
729
730         avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align);
731
732         do {
733             // NOTE: do not align linesizes individually, this breaks e.g. assumptions
734             // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
735             av_image_fill_linesizes(linesize, avctx->pix_fmt, w);
736             // increase alignment of w for next try (rhs gives the lowest bit set in w)
737             w += w & ~(w - 1);
738
739             unaligned = 0;
740             for (i = 0; i < 4; i++)
741                 unaligned |= linesize[i] % pool->stride_align[i];
742         } while (unaligned);
743
744         tmpsize = av_image_fill_pointers(data, avctx->pix_fmt, h,
745                                          NULL, linesize);
746         if (tmpsize < 0)
747             return -1;
748
749         for (i = 0; i < 3 && data[i + 1]; i++)
750             size[i] = data[i + 1] - data[i];
751         size[i] = tmpsize - (data[i] - data[0]);
752
753         for (i = 0; i < 4; i++) {
754             av_buffer_pool_uninit(&pool->pools[i]);
755             pool->linesize[i] = linesize[i];
756             if (size[i]) {
757                 pool->pools[i] = av_buffer_pool_init(size[i] + 16, NULL);
758                 if (!pool->pools[i]) {
759                     ret = AVERROR(ENOMEM);
760                     goto fail;
761                 }
762             }
763         }
764         pool->format = frame->format;
765         pool->width  = frame->width;
766         pool->height = frame->height;
767
768         break;
769         }
770     case AVMEDIA_TYPE_AUDIO: {
771         int ch     = av_get_channel_layout_nb_channels(frame->channel_layout);
772         int planar = av_sample_fmt_is_planar(frame->format);
773         int planes = planar ? ch : 1;
774
775         if (pool->format == frame->format && pool->planes == planes &&
776             pool->channels == ch && frame->nb_samples == pool->samples)
777             return 0;
778
779         av_buffer_pool_uninit(&pool->pools[0]);
780         ret = av_samples_get_buffer_size(&pool->linesize[0], ch,
781                                          frame->nb_samples, frame->format, 0);
782         if (ret < 0)
783             goto fail;
784
785         pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL);
786         if (!pool->pools[0]) {
787             ret = AVERROR(ENOMEM);
788             goto fail;
789         }
790
791         pool->format     = frame->format;
792         pool->planes     = planes;
793         pool->channels   = ch;
794         pool->samples = frame->nb_samples;
795         break;
796         }
797     default: av_assert0(0);
798     }
799     return 0;
800 fail:
801     for (i = 0; i < 4; i++)
802         av_buffer_pool_uninit(&pool->pools[i]);
803     pool->format = -1;
804     pool->planes = pool->channels = pool->samples = 0;
805     pool->width  = pool->height = 0;
806     return ret;
807 }
808
809 static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
810 {
811     FramePool *pool = avctx->internal->pool;
812     int planes = pool->planes;
813     int i;
814
815     frame->linesize[0] = pool->linesize[0];
816
817     if (planes > AV_NUM_DATA_POINTERS) {
818         frame->extended_data = av_mallocz(planes * sizeof(*frame->extended_data));
819         frame->nb_extended_buf = planes - AV_NUM_DATA_POINTERS;
820         frame->extended_buf  = av_mallocz(frame->nb_extended_buf *
821                                           sizeof(*frame->extended_buf));
822         if (!frame->extended_data || !frame->extended_buf) {
823             av_freep(&frame->extended_data);
824             av_freep(&frame->extended_buf);
825             return AVERROR(ENOMEM);
826         }
827     } else
828         frame->extended_data = frame->data;
829
830     for (i = 0; i < FFMIN(planes, AV_NUM_DATA_POINTERS); i++) {
831         frame->buf[i] = av_buffer_pool_get(pool->pools[0]);
832         if (!frame->buf[i])
833             goto fail;
834         frame->extended_data[i] = frame->data[i] = frame->buf[i]->data;
835     }
836     for (i = 0; i < frame->nb_extended_buf; i++) {
837         frame->extended_buf[i] = av_buffer_pool_get(pool->pools[0]);
838         if (!frame->extended_buf[i])
839             goto fail;
840         frame->extended_data[i + AV_NUM_DATA_POINTERS] = frame->extended_buf[i]->data;
841     }
842
843     if (avctx->debug & FF_DEBUG_BUFFERS)
844         av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p", frame);
845
846     return 0;
847 fail:
848     av_frame_unref(frame);
849     return AVERROR(ENOMEM);
850 }
851
852 static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
853 {
854     FramePool *pool = s->internal->pool;
855     int i;
856
857     if (pic->data[0]) {
858         av_log(s, AV_LOG_ERROR, "pic->data[0]!=NULL in avcodec_default_get_buffer\n");
859         return -1;
860     }
861
862     memset(pic->data, 0, sizeof(pic->data));
863     pic->extended_data = pic->data;
864
865     for (i = 0; i < 4 && pool->pools[i]; i++) {
866         pic->linesize[i] = pool->linesize[i];
867
868         pic->buf[i] = av_buffer_pool_get(pool->pools[i]);
869         if (!pic->buf[i])
870             goto fail;
871
872         pic->data[i] = pic->buf[i]->data;
873     }
874     for (; i < AV_NUM_DATA_POINTERS; i++) {
875         pic->data[i] = NULL;
876         pic->linesize[i] = 0;
877     }
878     if (pic->data[1] && !pic->data[2])
879         avpriv_set_systematic_pal2((uint32_t *)pic->data[1], s->pix_fmt);
880
881     if (s->debug & FF_DEBUG_BUFFERS)
882         av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p\n", pic);
883
884     return 0;
885 fail:
886     av_frame_unref(pic);
887     return AVERROR(ENOMEM);
888 }
889
890 int avcodec_default_get_buffer2(AVCodecContext *avctx, AVFrame *frame, int flags)
891 {
892     int ret;
893
894     if (avctx->hw_frames_ctx)
895         return av_hwframe_get_buffer(avctx->hw_frames_ctx, frame, 0);
896
897     if ((ret = update_frame_pool(avctx, frame)) < 0)
898         return ret;
899
900     switch (avctx->codec_type) {
901     case AVMEDIA_TYPE_VIDEO:
902         return video_get_buffer(avctx, frame);
903     case AVMEDIA_TYPE_AUDIO:
904         return audio_get_buffer(avctx, frame);
905     default:
906         return -1;
907     }
908 }
909
910 int ff_decode_frame_props(AVCodecContext *avctx, AVFrame *frame)
911 {
912     AVPacket *pkt = avctx->internal->last_pkt_props;
913     int i;
914     struct {
915         enum AVPacketSideDataType packet;
916         enum AVFrameSideDataType frame;
917     } sd[] = {
918         { AV_PKT_DATA_REPLAYGAIN ,   AV_FRAME_DATA_REPLAYGAIN },
919         { AV_PKT_DATA_DISPLAYMATRIX, AV_FRAME_DATA_DISPLAYMATRIX },
920         { AV_PKT_DATA_SPHERICAL,     AV_FRAME_DATA_SPHERICAL },
921         { AV_PKT_DATA_STEREO3D,      AV_FRAME_DATA_STEREO3D },
922         { AV_PKT_DATA_AUDIO_SERVICE_TYPE, AV_FRAME_DATA_AUDIO_SERVICE_TYPE },
923     };
924
925     frame->color_primaries = avctx->color_primaries;
926     frame->color_trc       = avctx->color_trc;
927     frame->colorspace      = avctx->colorspace;
928     frame->color_range     = avctx->color_range;
929     frame->chroma_location = avctx->chroma_sample_location;
930
931     frame->reordered_opaque = avctx->reordered_opaque;
932
933 #if FF_API_PKT_PTS
934 FF_DISABLE_DEPRECATION_WARNINGS
935     frame->pkt_pts = pkt->pts;
936 FF_ENABLE_DEPRECATION_WARNINGS
937 #endif
938     frame->pts     = pkt->pts;
939
940     for (i = 0; i < FF_ARRAY_ELEMS(sd); i++) {
941         int size;
942         uint8_t *packet_sd = av_packet_get_side_data(pkt, sd[i].packet, &size);
943         if (packet_sd) {
944             AVFrameSideData *frame_sd = av_frame_new_side_data(frame,
945                                                                sd[i].frame,
946                                                                size);
947             if (!frame_sd)
948                 return AVERROR(ENOMEM);
949
950             memcpy(frame_sd->data, packet_sd, size);
951         }
952     }
953
954     return 0;
955 }
956
957 int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
958 {
959     const AVHWAccel *hwaccel = avctx->hwaccel;
960     int override_dimensions = 1;
961     int ret;
962
963     switch (avctx->codec_type) {
964     case AVMEDIA_TYPE_VIDEO:
965         if (frame->width <= 0 || frame->height <= 0) {
966             frame->width  = FFMAX(avctx->width, avctx->coded_width);
967             frame->height = FFMAX(avctx->height, avctx->coded_height);
968             override_dimensions = 0;
969         }
970         if (frame->format < 0)
971             frame->format              = avctx->pix_fmt;
972         if (!frame->sample_aspect_ratio.num)
973             frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
974
975         if (av_image_check_sar(frame->width, frame->height,
976                                frame->sample_aspect_ratio) < 0) {
977             av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
978                    frame->sample_aspect_ratio.num,
979                    frame->sample_aspect_ratio.den);
980             frame->sample_aspect_ratio = (AVRational){ 0, 1 };
981         }
982
983         if ((ret = av_image_check_size(avctx->width, avctx->height, 0, avctx)) < 0)
984             return ret;
985         break;
986     case AVMEDIA_TYPE_AUDIO:
987         if (!frame->sample_rate)
988             frame->sample_rate    = avctx->sample_rate;
989         if (frame->format < 0)
990             frame->format         = avctx->sample_fmt;
991         if (!frame->channel_layout) {
992             if (avctx->channel_layout) {
993                  if (av_get_channel_layout_nb_channels(avctx->channel_layout) !=
994                      avctx->channels) {
995                      av_log(avctx, AV_LOG_ERROR, "Inconsistent channel "
996                             "configuration.\n");
997                      return AVERROR(EINVAL);
998                  }
999
1000                 frame->channel_layout = avctx->channel_layout;
1001             } else {
1002                 if (avctx->channels > FF_SANE_NB_CHANNELS) {
1003                     av_log(avctx, AV_LOG_ERROR, "Too many channels: %d.\n",
1004                            avctx->channels);
1005                     return AVERROR(ENOSYS);
1006                 }
1007
1008                 frame->channel_layout = av_get_default_channel_layout(avctx->channels);
1009                 if (!frame->channel_layout)
1010                     frame->channel_layout = (1ULL << avctx->channels) - 1;
1011             }
1012         }
1013         break;
1014     default: return AVERROR(EINVAL);
1015     }
1016
1017     ret = ff_decode_frame_props(avctx, frame);
1018     if (ret < 0)
1019         return ret;
1020
1021     if (hwaccel) {
1022         if (hwaccel->alloc_frame) {
1023             ret = hwaccel->alloc_frame(avctx, frame);
1024             goto end;
1025         }
1026     } else
1027         avctx->sw_pix_fmt = avctx->pix_fmt;
1028
1029     ret = avctx->get_buffer2(avctx, frame, flags);
1030
1031 end:
1032     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO && !override_dimensions) {
1033         frame->width  = avctx->width;
1034         frame->height = avctx->height;
1035     }
1036
1037     return ret;
1038 }
1039
1040 int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame)
1041 {
1042     AVFrame *tmp;
1043     int ret;
1044
1045     av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
1046
1047     if (!frame->data[0])
1048         return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1049
1050     if (av_frame_is_writable(frame))
1051         return ff_decode_frame_props(avctx, frame);
1052
1053     tmp = av_frame_alloc();
1054     if (!tmp)
1055         return AVERROR(ENOMEM);
1056
1057     av_frame_move_ref(tmp, frame);
1058
1059     ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1060     if (ret < 0) {
1061         av_frame_free(&tmp);
1062         return ret;
1063     }
1064
1065     av_frame_copy(frame, tmp);
1066     av_frame_free(&tmp);
1067
1068     return 0;
1069 }
1070
1071 void avcodec_flush_buffers(AVCodecContext *avctx)
1072 {
1073     avctx->internal->draining      = 0;
1074     avctx->internal->draining_done = 0;
1075     av_frame_unref(avctx->internal->buffer_frame);
1076     av_frame_unref(avctx->internal->compat_decode_frame);
1077     av_packet_unref(avctx->internal->buffer_pkt);
1078     avctx->internal->buffer_pkt_valid = 0;
1079
1080     av_packet_unref(avctx->internal->ds.in_pkt);
1081
1082     if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
1083         ff_thread_flush(avctx);
1084     else if (avctx->codec->flush)
1085         avctx->codec->flush(avctx);
1086
1087     ff_decode_bsfs_uninit(avctx);
1088
1089     if (!avctx->refcounted_frames)
1090         av_frame_unref(avctx->internal->to_free);
1091 }
1092
1093 void ff_decode_bsfs_uninit(AVCodecContext *avctx)
1094 {
1095     DecodeFilterContext *s = &avctx->internal->filter;
1096     int i;
1097
1098     for (i = 0; i < s->nb_bsfs; i++)
1099         av_bsf_free(&s->bsfs[i]);
1100     av_freep(&s->bsfs);
1101     s->nb_bsfs = 0;
1102 }