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