]> git.sesse.net Git - ffmpeg/blob - libavcodec/decode.c
pgssubdec: reset rle_data_len/rle_remaining_len on allocation error
[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 FF_API_AVCTX_TIMEBASE
358     if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
359         avctx->time_base = av_inv_q(avctx->framerate);
360 #endif
361
362     if (avctx->internal->draining && !got_frame)
363         avci->draining_done = 1;
364
365     avci->compat_decode_consumed += ret;
366
367     if (ret >= pkt->size || ret < 0) {
368         av_packet_unref(pkt);
369     } else {
370         int consumed = ret;
371
372         pkt->data                += consumed;
373         pkt->size                -= consumed;
374         pkt->pts                  = AV_NOPTS_VALUE;
375         pkt->dts                  = AV_NOPTS_VALUE;
376         avci->last_pkt_props->pts = AV_NOPTS_VALUE;
377         avci->last_pkt_props->dts = AV_NOPTS_VALUE;
378     }
379
380     if (got_frame)
381         av_assert0(frame->buf[0]);
382
383     return ret < 0 ? ret : 0;
384 }
385
386 static int decode_simple_receive_frame(AVCodecContext *avctx, AVFrame *frame)
387 {
388     int ret;
389
390     while (!frame->buf[0]) {
391         ret = decode_simple_internal(avctx, frame);
392         if (ret < 0)
393             return ret;
394     }
395
396     return 0;
397 }
398
399 static int decode_receive_frame_internal(AVCodecContext *avctx, AVFrame *frame)
400 {
401     AVCodecInternal *avci = avctx->internal;
402     int ret;
403
404     av_assert0(!frame->buf[0]);
405
406     if (avctx->codec->receive_frame)
407         ret = avctx->codec->receive_frame(avctx, frame);
408     else
409         ret = decode_simple_receive_frame(avctx, frame);
410
411     if (ret == AVERROR_EOF)
412         avci->draining_done = 1;
413
414     return ret;
415 }
416
417 int attribute_align_arg avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)
418 {
419     AVCodecInternal *avci = avctx->internal;
420     int ret = 0;
421
422     if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
423         return AVERROR(EINVAL);
424
425     if (avctx->internal->draining)
426         return AVERROR_EOF;
427
428     ret = bsfs_init(avctx);
429     if (ret < 0)
430         return ret;
431
432     av_packet_unref(avci->buffer_pkt);
433     if (avpkt && (avpkt->data || avpkt->side_data_elems)) {
434         ret = av_packet_ref(avci->buffer_pkt, avpkt);
435         if (ret < 0)
436             return ret;
437     }
438
439     ret = av_bsf_send_packet(avci->filter.bsfs[0], avci->buffer_pkt);
440     if (ret < 0) {
441         av_packet_unref(avci->buffer_pkt);
442         return ret;
443     }
444
445     if (!avci->buffer_frame->buf[0]) {
446         ret = decode_receive_frame_internal(avctx, avci->buffer_frame);
447         if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
448             return ret;
449     }
450
451     return 0;
452 }
453
454 static int calc_cropping_offsets(size_t offsets[4], const AVFrame *frame,
455                                  const AVPixFmtDescriptor *desc)
456 {
457     int i, j;
458
459     for (i = 0; frame->data[i]; i++) {
460         const AVComponentDescriptor *comp = NULL;
461         int shift_x = (i == 1 || i == 2) ? desc->log2_chroma_w : 0;
462         int shift_y = (i == 1 || i == 2) ? desc->log2_chroma_h : 0;
463
464         if (desc->flags & (AV_PIX_FMT_FLAG_PAL | AV_PIX_FMT_FLAG_PSEUDOPAL) && i == 1) {
465             offsets[i] = 0;
466             break;
467         }
468
469         /* find any component descriptor for this plane */
470         for (j = 0; j < desc->nb_components; j++) {
471             if (desc->comp[j].plane == i) {
472                 comp = &desc->comp[j];
473                 break;
474             }
475         }
476         if (!comp)
477             return AVERROR_BUG;
478
479         offsets[i] = (frame->crop_top  >> shift_y) * frame->linesize[i] +
480                      (frame->crop_left >> shift_x) * comp->step;
481     }
482
483     return 0;
484 }
485
486 static int apply_cropping(AVCodecContext *avctx, AVFrame *frame)
487 {
488     const AVPixFmtDescriptor *desc;
489     size_t offsets[4];
490     int i;
491
492     /* make sure we are noisy about decoders returning invalid cropping data */
493     if (frame->crop_left >= INT_MAX - frame->crop_right        ||
494         frame->crop_top  >= INT_MAX - frame->crop_bottom       ||
495         (frame->crop_left + frame->crop_right) >= frame->width ||
496         (frame->crop_top + frame->crop_bottom) >= frame->height) {
497         av_log(avctx, AV_LOG_WARNING,
498                "Invalid cropping information set by a decoder: %zu/%zu/%zu/%zu "
499                "(frame size %dx%d). This is a bug, please report it\n",
500                frame->crop_left, frame->crop_right, frame->crop_top, frame->crop_bottom,
501                frame->width, frame->height);
502         frame->crop_left   = 0;
503         frame->crop_right  = 0;
504         frame->crop_top    = 0;
505         frame->crop_bottom = 0;
506         return 0;
507     }
508
509     if (!avctx->apply_cropping)
510         return 0;
511
512     desc = av_pix_fmt_desc_get(frame->format);
513     if (!desc)
514         return AVERROR_BUG;
515
516     /* Apply just the right/bottom cropping for hwaccel formats. Bitstream
517      * formats cannot be easily handled here either (and corresponding decoders
518      * should not export any cropping anyway), so do the same for those as well.
519      * */
520     if (desc->flags & (AV_PIX_FMT_FLAG_BITSTREAM | AV_PIX_FMT_FLAG_HWACCEL)) {
521         frame->width      -= frame->crop_right;
522         frame->height     -= frame->crop_bottom;
523         frame->crop_right  = 0;
524         frame->crop_bottom = 0;
525         return 0;
526     }
527
528     /* calculate the offsets for each plane */
529     calc_cropping_offsets(offsets, frame, desc);
530
531     /* adjust the offsets to avoid breaking alignment */
532     if (!(avctx->flags & AV_CODEC_FLAG_UNALIGNED)) {
533         int min_log2_align = INT_MAX;
534
535         for (i = 0; frame->data[i]; i++) {
536             int log2_align = offsets[i] ? av_ctz(offsets[i]) : INT_MAX;
537             min_log2_align = FFMIN(log2_align, min_log2_align);
538         }
539
540         if (min_log2_align < 5) {
541             frame->crop_left &= ~((1 << min_log2_align) - 1);
542             calc_cropping_offsets(offsets, frame, desc);
543         }
544     }
545
546     for (i = 0; frame->data[i]; i++)
547         frame->data[i] += offsets[i];
548
549     frame->width      -= (frame->crop_left + frame->crop_right);
550     frame->height     -= (frame->crop_top  + frame->crop_bottom);
551     frame->crop_left   = 0;
552     frame->crop_right  = 0;
553     frame->crop_top    = 0;
554     frame->crop_bottom = 0;
555
556     return 0;
557 }
558
559 int attribute_align_arg avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
560 {
561     AVCodecInternal *avci = avctx->internal;
562     int ret;
563
564     av_frame_unref(frame);
565
566     if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
567         return AVERROR(EINVAL);
568
569     ret = bsfs_init(avctx);
570     if (ret < 0)
571         return ret;
572
573     if (avci->buffer_frame->buf[0]) {
574         av_frame_move_ref(frame, avci->buffer_frame);
575     } else {
576         ret = decode_receive_frame_internal(avctx, frame);
577         if (ret < 0)
578             return ret;
579     }
580
581     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
582         ret = apply_cropping(avctx, frame);
583         if (ret < 0) {
584             av_frame_unref(frame);
585             return ret;
586         }
587     }
588
589     avctx->frame_number++;
590
591     return 0;
592 }
593
594 static int compat_decode(AVCodecContext *avctx, AVFrame *frame,
595                          int *got_frame, AVPacket *pkt)
596 {
597     AVCodecInternal *avci = avctx->internal;
598     int ret;
599
600     av_assert0(avci->compat_decode_consumed == 0);
601
602     *got_frame = 0;
603     avci->compat_decode = 1;
604
605     if (avci->compat_decode_partial_size > 0 &&
606         avci->compat_decode_partial_size != pkt->size) {
607         av_log(avctx, AV_LOG_ERROR,
608                "Got unexpected packet size after a partial decode\n");
609         ret = AVERROR(EINVAL);
610         goto finish;
611     }
612
613     if (!avci->compat_decode_partial_size) {
614         ret = avcodec_send_packet(avctx, pkt);
615         if (ret == AVERROR_EOF)
616             ret = 0;
617         else if (ret == AVERROR(EAGAIN)) {
618             /* we fully drain all the output in each decode call, so this should not
619              * ever happen */
620             ret = AVERROR_BUG;
621             goto finish;
622         } else if (ret < 0)
623             goto finish;
624     }
625
626     while (ret >= 0) {
627         ret = avcodec_receive_frame(avctx, frame);
628         if (ret < 0) {
629             if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
630                 ret = 0;
631             goto finish;
632         }
633
634         if (frame != avci->compat_decode_frame) {
635             if (!avctx->refcounted_frames) {
636                 ret = unrefcount_frame(avci, frame);
637                 if (ret < 0)
638                     goto finish;
639             }
640
641             *got_frame = 1;
642             frame = avci->compat_decode_frame;
643         } else {
644             if (!avci->compat_decode_warned) {
645                 av_log(avctx, AV_LOG_WARNING, "The deprecated avcodec_decode_* "
646                        "API cannot return all the frames for this decoder. "
647                        "Some frames will be dropped. Update your code to the "
648                        "new decoding API to fix this.\n");
649                 avci->compat_decode_warned = 1;
650             }
651         }
652
653         if (avci->draining || (!avctx->codec->bsfs && avci->compat_decode_consumed < pkt->size))
654             break;
655     }
656
657 finish:
658     if (ret == 0) {
659         /* if there are any bsfs then assume full packet is always consumed */
660         if (avctx->codec->bsfs)
661             ret = pkt->size;
662         else
663             ret = FFMIN(avci->compat_decode_consumed, pkt->size);
664     }
665     avci->compat_decode_consumed = 0;
666     avci->compat_decode_partial_size = (ret >= 0) ? pkt->size - ret : 0;
667
668     return ret;
669 }
670
671 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
672                                               int *got_picture_ptr,
673                                               AVPacket *avpkt)
674 {
675     return compat_decode(avctx, picture, got_picture_ptr, avpkt);
676 }
677
678 int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
679                                               AVFrame *frame,
680                                               int *got_frame_ptr,
681                                               AVPacket *avpkt)
682 {
683     return compat_decode(avctx, frame, got_frame_ptr, avpkt);
684 }
685
686 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
687                              int *got_sub_ptr,
688                              AVPacket *avpkt)
689 {
690     int ret;
691
692     ret = extract_packet_props(avctx->internal, avpkt);
693     if (ret < 0)
694         return ret;
695
696     *got_sub_ptr = 0;
697     ret = avctx->codec->decode(avctx, sub, got_sub_ptr, avpkt);
698     if (*got_sub_ptr)
699         avctx->frame_number++;
700     return ret;
701 }
702
703 static int is_hwaccel_pix_fmt(enum AVPixelFormat pix_fmt)
704 {
705     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
706     return desc->flags & AV_PIX_FMT_FLAG_HWACCEL;
707 }
708
709 enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
710 {
711     while (*fmt != AV_PIX_FMT_NONE && is_hwaccel_pix_fmt(*fmt))
712         ++fmt;
713     return fmt[0];
714 }
715
716 static AVHWAccel *find_hwaccel(enum AVCodecID codec_id,
717                                enum AVPixelFormat pix_fmt)
718 {
719     AVHWAccel *hwaccel = NULL;
720
721     while ((hwaccel = av_hwaccel_next(hwaccel)))
722         if (hwaccel->id == codec_id
723             && hwaccel->pix_fmt == pix_fmt)
724             return hwaccel;
725     return NULL;
726 }
727
728 static int setup_hwaccel(AVCodecContext *avctx,
729                          const enum AVPixelFormat fmt,
730                          const char *name)
731 {
732     AVHWAccel *hwa = find_hwaccel(avctx->codec_id, fmt);
733     int ret        = 0;
734
735     if (!hwa) {
736         av_log(avctx, AV_LOG_ERROR,
737                "Could not find an AVHWAccel for the pixel format: %s",
738                name);
739         return AVERROR(ENOENT);
740     }
741
742     if (hwa->priv_data_size) {
743         avctx->internal->hwaccel_priv_data = av_mallocz(hwa->priv_data_size);
744         if (!avctx->internal->hwaccel_priv_data)
745             return AVERROR(ENOMEM);
746     }
747
748     if (hwa->init) {
749         ret = hwa->init(avctx);
750         if (ret < 0) {
751             av_freep(&avctx->internal->hwaccel_priv_data);
752             return ret;
753         }
754     }
755
756     avctx->hwaccel = hwa;
757
758     return 0;
759 }
760
761 int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
762 {
763     const AVPixFmtDescriptor *desc;
764     enum AVPixelFormat *choices;
765     enum AVPixelFormat ret;
766     unsigned n = 0;
767
768     while (fmt[n] != AV_PIX_FMT_NONE)
769         ++n;
770
771     av_assert0(n >= 1);
772     avctx->sw_pix_fmt = fmt[n - 1];
773     av_assert2(!is_hwaccel_pix_fmt(avctx->sw_pix_fmt));
774
775     choices = av_malloc_array(n + 1, sizeof(*choices));
776     if (!choices)
777         return AV_PIX_FMT_NONE;
778
779     memcpy(choices, fmt, (n + 1) * sizeof(*choices));
780
781     for (;;) {
782         if (avctx->hwaccel && avctx->hwaccel->uninit)
783             avctx->hwaccel->uninit(avctx);
784         av_freep(&avctx->internal->hwaccel_priv_data);
785         avctx->hwaccel = NULL;
786
787         av_buffer_unref(&avctx->hw_frames_ctx);
788
789         ret = avctx->get_format(avctx, choices);
790
791         desc = av_pix_fmt_desc_get(ret);
792         if (!desc) {
793             ret = AV_PIX_FMT_NONE;
794             break;
795         }
796
797         if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
798             break;
799
800         if (avctx->hw_frames_ctx) {
801             AVHWFramesContext *hw_frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
802             if (hw_frames_ctx->format != ret) {
803                 av_log(avctx, AV_LOG_ERROR, "Format returned from get_buffer() "
804                        "does not match the format of provided AVHWFramesContext\n");
805                 ret = AV_PIX_FMT_NONE;
806                 break;
807             }
808         }
809
810         if (!setup_hwaccel(avctx, ret, desc->name))
811             break;
812
813         /* Remove failed hwaccel from choices */
814         for (n = 0; choices[n] != ret; n++)
815             av_assert0(choices[n] != AV_PIX_FMT_NONE);
816
817         do
818             choices[n] = choices[n + 1];
819         while (choices[n++] != AV_PIX_FMT_NONE);
820     }
821
822     av_freep(&choices);
823     return ret;
824 }
825
826 static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame)
827 {
828     FramePool *pool = avctx->internal->pool;
829     int i, ret;
830
831     switch (avctx->codec_type) {
832     case AVMEDIA_TYPE_VIDEO: {
833         uint8_t *data[4];
834         int linesize[4];
835         int size[4] = { 0 };
836         int w = frame->width;
837         int h = frame->height;
838         int tmpsize, unaligned;
839
840         if (pool->format == frame->format &&
841             pool->width == frame->width && pool->height == frame->height)
842             return 0;
843
844         avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align);
845
846         do {
847             // NOTE: do not align linesizes individually, this breaks e.g. assumptions
848             // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
849             av_image_fill_linesizes(linesize, avctx->pix_fmt, w);
850             // increase alignment of w for next try (rhs gives the lowest bit set in w)
851             w += w & ~(w - 1);
852
853             unaligned = 0;
854             for (i = 0; i < 4; i++)
855                 unaligned |= linesize[i] % pool->stride_align[i];
856         } while (unaligned);
857
858         tmpsize = av_image_fill_pointers(data, avctx->pix_fmt, h,
859                                          NULL, linesize);
860         if (tmpsize < 0)
861             return -1;
862
863         for (i = 0; i < 3 && data[i + 1]; i++)
864             size[i] = data[i + 1] - data[i];
865         size[i] = tmpsize - (data[i] - data[0]);
866
867         for (i = 0; i < 4; i++) {
868             av_buffer_pool_uninit(&pool->pools[i]);
869             pool->linesize[i] = linesize[i];
870             if (size[i]) {
871                 pool->pools[i] = av_buffer_pool_init(size[i] + 16, NULL);
872                 if (!pool->pools[i]) {
873                     ret = AVERROR(ENOMEM);
874                     goto fail;
875                 }
876             }
877         }
878         pool->format = frame->format;
879         pool->width  = frame->width;
880         pool->height = frame->height;
881
882         break;
883         }
884     case AVMEDIA_TYPE_AUDIO: {
885         int ch     = av_get_channel_layout_nb_channels(frame->channel_layout);
886         int planar = av_sample_fmt_is_planar(frame->format);
887         int planes = planar ? ch : 1;
888
889         if (pool->format == frame->format && pool->planes == planes &&
890             pool->channels == ch && frame->nb_samples == pool->samples)
891             return 0;
892
893         av_buffer_pool_uninit(&pool->pools[0]);
894         ret = av_samples_get_buffer_size(&pool->linesize[0], ch,
895                                          frame->nb_samples, frame->format, 0);
896         if (ret < 0)
897             goto fail;
898
899         pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL);
900         if (!pool->pools[0]) {
901             ret = AVERROR(ENOMEM);
902             goto fail;
903         }
904
905         pool->format     = frame->format;
906         pool->planes     = planes;
907         pool->channels   = ch;
908         pool->samples = frame->nb_samples;
909         break;
910         }
911     default: av_assert0(0);
912     }
913     return 0;
914 fail:
915     for (i = 0; i < 4; i++)
916         av_buffer_pool_uninit(&pool->pools[i]);
917     pool->format = -1;
918     pool->planes = pool->channels = pool->samples = 0;
919     pool->width  = pool->height = 0;
920     return ret;
921 }
922
923 static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
924 {
925     FramePool *pool = avctx->internal->pool;
926     int planes = pool->planes;
927     int i;
928
929     frame->linesize[0] = pool->linesize[0];
930
931     if (planes > AV_NUM_DATA_POINTERS) {
932         frame->extended_data = av_mallocz(planes * sizeof(*frame->extended_data));
933         frame->nb_extended_buf = planes - AV_NUM_DATA_POINTERS;
934         frame->extended_buf  = av_mallocz(frame->nb_extended_buf *
935                                           sizeof(*frame->extended_buf));
936         if (!frame->extended_data || !frame->extended_buf) {
937             av_freep(&frame->extended_data);
938             av_freep(&frame->extended_buf);
939             return AVERROR(ENOMEM);
940         }
941     } else
942         frame->extended_data = frame->data;
943
944     for (i = 0; i < FFMIN(planes, AV_NUM_DATA_POINTERS); i++) {
945         frame->buf[i] = av_buffer_pool_get(pool->pools[0]);
946         if (!frame->buf[i])
947             goto fail;
948         frame->extended_data[i] = frame->data[i] = frame->buf[i]->data;
949     }
950     for (i = 0; i < frame->nb_extended_buf; i++) {
951         frame->extended_buf[i] = av_buffer_pool_get(pool->pools[0]);
952         if (!frame->extended_buf[i])
953             goto fail;
954         frame->extended_data[i + AV_NUM_DATA_POINTERS] = frame->extended_buf[i]->data;
955     }
956
957     if (avctx->debug & FF_DEBUG_BUFFERS)
958         av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p", frame);
959
960     return 0;
961 fail:
962     av_frame_unref(frame);
963     return AVERROR(ENOMEM);
964 }
965
966 static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
967 {
968     FramePool *pool = s->internal->pool;
969     int i;
970
971     if (pic->data[0]) {
972         av_log(s, AV_LOG_ERROR, "pic->data[0]!=NULL in avcodec_default_get_buffer\n");
973         return -1;
974     }
975
976     memset(pic->data, 0, sizeof(pic->data));
977     pic->extended_data = pic->data;
978
979     for (i = 0; i < 4 && pool->pools[i]; i++) {
980         pic->linesize[i] = pool->linesize[i];
981
982         pic->buf[i] = av_buffer_pool_get(pool->pools[i]);
983         if (!pic->buf[i])
984             goto fail;
985
986         pic->data[i] = pic->buf[i]->data;
987     }
988     for (; i < AV_NUM_DATA_POINTERS; i++) {
989         pic->data[i] = NULL;
990         pic->linesize[i] = 0;
991     }
992     if (pic->data[1] && !pic->data[2])
993         avpriv_set_systematic_pal2((uint32_t *)pic->data[1], s->pix_fmt);
994
995     if (s->debug & FF_DEBUG_BUFFERS)
996         av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p\n", pic);
997
998     return 0;
999 fail:
1000     av_frame_unref(pic);
1001     return AVERROR(ENOMEM);
1002 }
1003
1004 int avcodec_default_get_buffer2(AVCodecContext *avctx, AVFrame *frame, int flags)
1005 {
1006     int ret;
1007
1008     if (avctx->hw_frames_ctx)
1009         return av_hwframe_get_buffer(avctx->hw_frames_ctx, frame, 0);
1010
1011     if ((ret = update_frame_pool(avctx, frame)) < 0)
1012         return ret;
1013
1014     switch (avctx->codec_type) {
1015     case AVMEDIA_TYPE_VIDEO:
1016         return video_get_buffer(avctx, frame);
1017     case AVMEDIA_TYPE_AUDIO:
1018         return audio_get_buffer(avctx, frame);
1019     default:
1020         return -1;
1021     }
1022 }
1023
1024 int ff_decode_frame_props(AVCodecContext *avctx, AVFrame *frame)
1025 {
1026     AVPacket *pkt = avctx->internal->last_pkt_props;
1027     int i;
1028     struct {
1029         enum AVPacketSideDataType packet;
1030         enum AVFrameSideDataType frame;
1031     } sd[] = {
1032         { AV_PKT_DATA_REPLAYGAIN ,   AV_FRAME_DATA_REPLAYGAIN },
1033         { AV_PKT_DATA_DISPLAYMATRIX, AV_FRAME_DATA_DISPLAYMATRIX },
1034         { AV_PKT_DATA_SPHERICAL,     AV_FRAME_DATA_SPHERICAL },
1035         { AV_PKT_DATA_STEREO3D,      AV_FRAME_DATA_STEREO3D },
1036         { AV_PKT_DATA_AUDIO_SERVICE_TYPE, AV_FRAME_DATA_AUDIO_SERVICE_TYPE },
1037     };
1038
1039     frame->color_primaries = avctx->color_primaries;
1040     frame->color_trc       = avctx->color_trc;
1041     frame->colorspace      = avctx->colorspace;
1042     frame->color_range     = avctx->color_range;
1043     frame->chroma_location = avctx->chroma_sample_location;
1044
1045     frame->reordered_opaque = avctx->reordered_opaque;
1046
1047 #if FF_API_PKT_PTS
1048 FF_DISABLE_DEPRECATION_WARNINGS
1049     frame->pkt_pts = pkt->pts;
1050 FF_ENABLE_DEPRECATION_WARNINGS
1051 #endif
1052     frame->pts     = pkt->pts;
1053
1054     for (i = 0; i < FF_ARRAY_ELEMS(sd); i++) {
1055         int size;
1056         uint8_t *packet_sd = av_packet_get_side_data(pkt, sd[i].packet, &size);
1057         if (packet_sd) {
1058             AVFrameSideData *frame_sd = av_frame_new_side_data(frame,
1059                                                                sd[i].frame,
1060                                                                size);
1061             if (!frame_sd)
1062                 return AVERROR(ENOMEM);
1063
1064             memcpy(frame_sd->data, packet_sd, size);
1065         }
1066     }
1067
1068     return 0;
1069 }
1070
1071 int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
1072 {
1073     const AVHWAccel *hwaccel = avctx->hwaccel;
1074     int override_dimensions = 1;
1075     int ret;
1076
1077     switch (avctx->codec_type) {
1078     case AVMEDIA_TYPE_VIDEO:
1079         if (frame->width <= 0 || frame->height <= 0) {
1080             frame->width  = FFMAX(avctx->width, avctx->coded_width);
1081             frame->height = FFMAX(avctx->height, avctx->coded_height);
1082             override_dimensions = 0;
1083         }
1084         if (frame->format < 0)
1085             frame->format              = avctx->pix_fmt;
1086         if (!frame->sample_aspect_ratio.num)
1087             frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
1088
1089         if (av_image_check_sar(frame->width, frame->height,
1090                                frame->sample_aspect_ratio) < 0) {
1091             av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
1092                    frame->sample_aspect_ratio.num,
1093                    frame->sample_aspect_ratio.den);
1094             frame->sample_aspect_ratio = (AVRational){ 0, 1 };
1095         }
1096
1097         if ((ret = av_image_check_size(avctx->width, avctx->height, 0, avctx)) < 0)
1098             return ret;
1099         break;
1100     case AVMEDIA_TYPE_AUDIO:
1101         if (!frame->sample_rate)
1102             frame->sample_rate    = avctx->sample_rate;
1103         if (frame->format < 0)
1104             frame->format         = avctx->sample_fmt;
1105         if (!frame->channel_layout) {
1106             if (avctx->channel_layout) {
1107                  if (av_get_channel_layout_nb_channels(avctx->channel_layout) !=
1108                      avctx->channels) {
1109                      av_log(avctx, AV_LOG_ERROR, "Inconsistent channel "
1110                             "configuration.\n");
1111                      return AVERROR(EINVAL);
1112                  }
1113
1114                 frame->channel_layout = avctx->channel_layout;
1115             } else {
1116                 if (avctx->channels > FF_SANE_NB_CHANNELS) {
1117                     av_log(avctx, AV_LOG_ERROR, "Too many channels: %d.\n",
1118                            avctx->channels);
1119                     return AVERROR(ENOSYS);
1120                 }
1121
1122                 frame->channel_layout = av_get_default_channel_layout(avctx->channels);
1123                 if (!frame->channel_layout)
1124                     frame->channel_layout = (1ULL << avctx->channels) - 1;
1125             }
1126         }
1127         break;
1128     default: return AVERROR(EINVAL);
1129     }
1130
1131     ret = ff_decode_frame_props(avctx, frame);
1132     if (ret < 0)
1133         return ret;
1134
1135     if (hwaccel) {
1136         if (hwaccel->alloc_frame) {
1137             ret = hwaccel->alloc_frame(avctx, frame);
1138             goto end;
1139         }
1140     } else
1141         avctx->sw_pix_fmt = avctx->pix_fmt;
1142
1143     ret = avctx->get_buffer2(avctx, frame, flags);
1144
1145 end:
1146     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO && !override_dimensions &&
1147         !(avctx->codec->caps_internal & FF_CODEC_CAP_EXPORTS_CROPPING)) {
1148         frame->width  = avctx->width;
1149         frame->height = avctx->height;
1150     }
1151
1152     return ret;
1153 }
1154
1155 int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame)
1156 {
1157     AVFrame *tmp;
1158     int ret;
1159
1160     av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
1161
1162     if (!frame->data[0])
1163         return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1164
1165     if (av_frame_is_writable(frame))
1166         return ff_decode_frame_props(avctx, frame);
1167
1168     tmp = av_frame_alloc();
1169     if (!tmp)
1170         return AVERROR(ENOMEM);
1171
1172     av_frame_move_ref(tmp, frame);
1173
1174     ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1175     if (ret < 0) {
1176         av_frame_free(&tmp);
1177         return ret;
1178     }
1179
1180     av_frame_copy(frame, tmp);
1181     av_frame_free(&tmp);
1182
1183     return 0;
1184 }
1185
1186 void avcodec_flush_buffers(AVCodecContext *avctx)
1187 {
1188     avctx->internal->draining      = 0;
1189     avctx->internal->draining_done = 0;
1190     av_frame_unref(avctx->internal->buffer_frame);
1191     av_frame_unref(avctx->internal->compat_decode_frame);
1192     av_packet_unref(avctx->internal->buffer_pkt);
1193     avctx->internal->buffer_pkt_valid = 0;
1194
1195     av_packet_unref(avctx->internal->ds.in_pkt);
1196
1197     if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
1198         ff_thread_flush(avctx);
1199     else if (avctx->codec->flush)
1200         avctx->codec->flush(avctx);
1201
1202     ff_decode_bsfs_uninit(avctx);
1203
1204     if (!avctx->refcounted_frames)
1205         av_frame_unref(avctx->internal->to_free);
1206 }
1207
1208 void ff_decode_bsfs_uninit(AVCodecContext *avctx)
1209 {
1210     DecodeFilterContext *s = &avctx->internal->filter;
1211     int i;
1212
1213     for (i = 0; i < s->nb_bsfs; i++)
1214         av_bsf_free(&s->bsfs[i]);
1215     av_freep(&s->bsfs);
1216     s->nb_bsfs = 0;
1217 }