]> git.sesse.net Git - ffmpeg/blob - libavcodec/decode.c
lavc: Rename hwaccel.h to hwconfig.h
[ffmpeg] / libavcodec / decode.c
1 /*
2  * generic decoding-related code
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 #include <stdint.h>
22 #include <string.h>
23
24 #include "config.h"
25
26 #if CONFIG_ICONV
27 # include <iconv.h>
28 #endif
29
30 #include "libavutil/avassert.h"
31 #include "libavutil/avstring.h"
32 #include "libavutil/bprint.h"
33 #include "libavutil/common.h"
34 #include "libavutil/frame.h"
35 #include "libavutil/hwcontext.h"
36 #include "libavutil/imgutils.h"
37 #include "libavutil/internal.h"
38 #include "libavutil/intmath.h"
39 #include "libavutil/opt.h"
40
41 #include "avcodec.h"
42 #include "bytestream.h"
43 #include "decode.h"
44 #include "hwconfig.h"
45 #include "internal.h"
46 #include "thread.h"
47
48 typedef struct FramePool {
49     /**
50      * Pools for each data plane. For audio all the planes have the same size,
51      * so only pools[0] is used.
52      */
53     AVBufferPool *pools[4];
54
55     /*
56      * Pool parameters
57      */
58     int format;
59     int width, height;
60     int stride_align[AV_NUM_DATA_POINTERS];
61     int linesize[4];
62     int planes;
63     int channels;
64     int samples;
65 } FramePool;
66
67 static int apply_param_change(AVCodecContext *avctx, const AVPacket *avpkt)
68 {
69     int size = 0, ret;
70     const uint8_t *data;
71     uint32_t flags;
72     int64_t val;
73
74     data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
75     if (!data)
76         return 0;
77
78     if (!(avctx->codec->capabilities & AV_CODEC_CAP_PARAM_CHANGE)) {
79         av_log(avctx, AV_LOG_ERROR, "This decoder does not support parameter "
80                "changes, but PARAM_CHANGE side data was sent to it.\n");
81         ret = AVERROR(EINVAL);
82         goto fail2;
83     }
84
85     if (size < 4)
86         goto fail;
87
88     flags = bytestream_get_le32(&data);
89     size -= 4;
90
91     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
92         if (size < 4)
93             goto fail;
94         val = bytestream_get_le32(&data);
95         if (val <= 0 || val > INT_MAX) {
96             av_log(avctx, AV_LOG_ERROR, "Invalid channel count");
97             ret = AVERROR_INVALIDDATA;
98             goto fail2;
99         }
100         avctx->channels = val;
101         size -= 4;
102     }
103     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
104         if (size < 8)
105             goto fail;
106         avctx->channel_layout = bytestream_get_le64(&data);
107         size -= 8;
108     }
109     if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
110         if (size < 4)
111             goto fail;
112         val = bytestream_get_le32(&data);
113         if (val <= 0 || val > INT_MAX) {
114             av_log(avctx, AV_LOG_ERROR, "Invalid sample rate");
115             ret = AVERROR_INVALIDDATA;
116             goto fail2;
117         }
118         avctx->sample_rate = val;
119         size -= 4;
120     }
121     if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
122         if (size < 8)
123             goto fail;
124         avctx->width  = bytestream_get_le32(&data);
125         avctx->height = bytestream_get_le32(&data);
126         size -= 8;
127         ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
128         if (ret < 0)
129             goto fail2;
130     }
131
132     return 0;
133 fail:
134     av_log(avctx, AV_LOG_ERROR, "PARAM_CHANGE side data too small.\n");
135     ret = AVERROR_INVALIDDATA;
136 fail2:
137     if (ret < 0) {
138         av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n");
139         if (avctx->err_recognition & AV_EF_EXPLODE)
140             return ret;
141     }
142     return 0;
143 }
144
145 static int extract_packet_props(AVCodecInternal *avci, const AVPacket *pkt)
146 {
147     int ret = 0;
148
149     av_packet_unref(avci->last_pkt_props);
150     if (pkt) {
151         ret = av_packet_copy_props(avci->last_pkt_props, pkt);
152         if (!ret)
153             avci->last_pkt_props->size = pkt->size; // HACK: Needed for ff_decode_frame_props().
154     }
155     return ret;
156 }
157
158 static int unrefcount_frame(AVCodecInternal *avci, AVFrame *frame)
159 {
160     int ret;
161
162     /* move the original frame to our backup */
163     av_frame_unref(avci->to_free);
164     av_frame_move_ref(avci->to_free, frame);
165
166     /* now copy everything except the AVBufferRefs back
167      * note that we make a COPY of the side data, so calling av_frame_free() on
168      * the caller's frame will work properly */
169     ret = av_frame_copy_props(frame, avci->to_free);
170     if (ret < 0)
171         return ret;
172
173     memcpy(frame->data,     avci->to_free->data,     sizeof(frame->data));
174     memcpy(frame->linesize, avci->to_free->linesize, sizeof(frame->linesize));
175     if (avci->to_free->extended_data != avci->to_free->data) {
176         int planes = avci->to_free->channels;
177         int size   = planes * sizeof(*frame->extended_data);
178
179         if (!size) {
180             av_frame_unref(frame);
181             return AVERROR_BUG;
182         }
183
184         frame->extended_data = av_malloc(size);
185         if (!frame->extended_data) {
186             av_frame_unref(frame);
187             return AVERROR(ENOMEM);
188         }
189         memcpy(frame->extended_data, avci->to_free->extended_data,
190                size);
191     } else
192         frame->extended_data = frame->data;
193
194     frame->format         = avci->to_free->format;
195     frame->width          = avci->to_free->width;
196     frame->height         = avci->to_free->height;
197     frame->channel_layout = avci->to_free->channel_layout;
198     frame->nb_samples     = avci->to_free->nb_samples;
199     frame->channels       = avci->to_free->channels;
200
201     return 0;
202 }
203
204 int ff_decode_bsfs_init(AVCodecContext *avctx)
205 {
206     AVCodecInternal *avci = avctx->internal;
207     DecodeFilterContext *s = &avci->filter;
208     const char *bsfs_str;
209     int ret;
210
211     if (s->nb_bsfs)
212         return 0;
213
214     bsfs_str = avctx->codec->bsfs ? avctx->codec->bsfs : "null";
215     while (bsfs_str && *bsfs_str) {
216         AVBSFContext **tmp;
217         const AVBitStreamFilter *filter;
218         char *bsf, *bsf_options_str, *bsf_name;
219
220         bsf = av_get_token(&bsfs_str, ",");
221         if (!bsf) {
222             ret = AVERROR(ENOMEM);
223             goto fail;
224         }
225         bsf_name = av_strtok(bsf, "=", &bsf_options_str);
226         if (!bsf_name) {
227             av_freep(&bsf);
228             ret = AVERROR(ENOMEM);
229             goto fail;
230         }
231
232         filter = av_bsf_get_by_name(bsf_name);
233         if (!filter) {
234             av_log(avctx, AV_LOG_ERROR, "A non-existing bitstream filter %s "
235                    "requested by a decoder. This is a bug, please report it.\n",
236                    bsf_name);
237             av_freep(&bsf);
238             ret = AVERROR_BUG;
239             goto fail;
240         }
241
242         tmp = av_realloc_array(s->bsfs, s->nb_bsfs + 1, sizeof(*s->bsfs));
243         if (!tmp) {
244             av_freep(&bsf);
245             ret = AVERROR(ENOMEM);
246             goto fail;
247         }
248         s->bsfs = tmp;
249
250         ret = av_bsf_alloc(filter, &s->bsfs[s->nb_bsfs]);
251         if (ret < 0) {
252             av_freep(&bsf);
253             goto fail;
254         }
255         s->nb_bsfs++;
256
257         if (s->nb_bsfs == 1) {
258             /* We do not currently have an API for passing the input timebase into decoders,
259              * but no filters used here should actually need it.
260              * So we make up some plausible-looking number (the MPEG 90kHz timebase) */
261             s->bsfs[s->nb_bsfs - 1]->time_base_in = (AVRational){ 1, 90000 };
262             ret = avcodec_parameters_from_context(s->bsfs[s->nb_bsfs - 1]->par_in,
263                                                   avctx);
264         } else {
265             s->bsfs[s->nb_bsfs - 1]->time_base_in = s->bsfs[s->nb_bsfs - 2]->time_base_out;
266             ret = avcodec_parameters_copy(s->bsfs[s->nb_bsfs - 1]->par_in,
267                                           s->bsfs[s->nb_bsfs - 2]->par_out);
268         }
269         if (ret < 0) {
270             av_freep(&bsf);
271             goto fail;
272         }
273
274         if (bsf_options_str && filter->priv_class) {
275             const AVOption *opt = av_opt_next(s->bsfs[s->nb_bsfs - 1]->priv_data, NULL);
276             const char * shorthand[2] = {NULL};
277
278             if (opt)
279                 shorthand[0] = opt->name;
280
281             ret = av_opt_set_from_string(s->bsfs[s->nb_bsfs - 1]->priv_data, bsf_options_str, shorthand, "=", ":");
282             if (ret < 0) {
283                 if (ret != AVERROR(ENOMEM)) {
284                     av_log(avctx, AV_LOG_ERROR, "Invalid options for bitstream filter %s "
285                            "requested by the decoder. This is a bug, please report it.\n",
286                            bsf_name);
287                     ret = AVERROR_BUG;
288                 }
289                 av_freep(&bsf);
290                 goto fail;
291             }
292         }
293         av_freep(&bsf);
294
295         ret = av_bsf_init(s->bsfs[s->nb_bsfs - 1]);
296         if (ret < 0)
297             goto fail;
298
299         if (*bsfs_str)
300             bsfs_str++;
301     }
302
303     return 0;
304 fail:
305     ff_decode_bsfs_uninit(avctx);
306     return ret;
307 }
308
309 /* try to get one output packet from the filter chain */
310 static int bsfs_poll(AVCodecContext *avctx, AVPacket *pkt)
311 {
312     DecodeFilterContext *s = &avctx->internal->filter;
313     int idx, ret;
314
315     /* start with the last filter in the chain */
316     idx = s->nb_bsfs - 1;
317     while (idx >= 0) {
318         /* request a packet from the currently selected filter */
319         ret = av_bsf_receive_packet(s->bsfs[idx], pkt);
320         if (ret == AVERROR(EAGAIN)) {
321             /* no packets available, try the next filter up the chain */
322             idx--;
323             continue;
324         } else if (ret < 0 && ret != AVERROR_EOF) {
325             return ret;
326         }
327
328         /* got a packet or EOF -- pass it to the caller or to the next filter
329          * down the chain */
330         if (idx == s->nb_bsfs - 1) {
331             return ret;
332         } else {
333             idx++;
334             ret = av_bsf_send_packet(s->bsfs[idx], ret < 0 ? NULL : pkt);
335             if (ret < 0) {
336                 av_log(avctx, AV_LOG_ERROR,
337                        "Error pre-processing a packet before decoding\n");
338                 av_packet_unref(pkt);
339                 return ret;
340             }
341         }
342     }
343
344     return AVERROR(EAGAIN);
345 }
346
347 int ff_decode_get_packet(AVCodecContext *avctx, AVPacket *pkt)
348 {
349     AVCodecInternal *avci = avctx->internal;
350     int ret;
351
352     if (avci->draining)
353         return AVERROR_EOF;
354
355     ret = bsfs_poll(avctx, pkt);
356     if (ret == AVERROR_EOF)
357         avci->draining = 1;
358     if (ret < 0)
359         return ret;
360
361     ret = extract_packet_props(avctx->internal, pkt);
362     if (ret < 0)
363         goto finish;
364
365     ret = apply_param_change(avctx, pkt);
366     if (ret < 0)
367         goto finish;
368
369     if (avctx->codec->receive_frame)
370         avci->compat_decode_consumed += pkt->size;
371
372     return 0;
373 finish:
374     av_packet_unref(pkt);
375     return ret;
376 }
377
378 /**
379  * Attempt to guess proper monotonic timestamps for decoded video frames
380  * which might have incorrect times. Input timestamps may wrap around, in
381  * which case the output will as well.
382  *
383  * @param pts the pts field of the decoded AVPacket, as passed through
384  * AVFrame.pts
385  * @param dts the dts field of the decoded AVPacket
386  * @return one of the input values, may be AV_NOPTS_VALUE
387  */
388 static int64_t guess_correct_pts(AVCodecContext *ctx,
389                                  int64_t reordered_pts, int64_t dts)
390 {
391     int64_t pts = AV_NOPTS_VALUE;
392
393     if (dts != AV_NOPTS_VALUE) {
394         ctx->pts_correction_num_faulty_dts += dts <= ctx->pts_correction_last_dts;
395         ctx->pts_correction_last_dts = dts;
396     } else if (reordered_pts != AV_NOPTS_VALUE)
397         ctx->pts_correction_last_dts = reordered_pts;
398
399     if (reordered_pts != AV_NOPTS_VALUE) {
400         ctx->pts_correction_num_faulty_pts += reordered_pts <= ctx->pts_correction_last_pts;
401         ctx->pts_correction_last_pts = reordered_pts;
402     } else if(dts != AV_NOPTS_VALUE)
403         ctx->pts_correction_last_pts = dts;
404
405     if ((ctx->pts_correction_num_faulty_pts<=ctx->pts_correction_num_faulty_dts || dts == AV_NOPTS_VALUE)
406        && reordered_pts != AV_NOPTS_VALUE)
407         pts = reordered_pts;
408     else
409         pts = dts;
410
411     return pts;
412 }
413
414 /*
415  * The core of the receive_frame_wrapper for the decoders implementing
416  * the simple API. Certain decoders might consume partial packets without
417  * returning any output, so this function needs to be called in a loop until it
418  * returns EAGAIN.
419  **/
420 static int decode_simple_internal(AVCodecContext *avctx, AVFrame *frame)
421 {
422     AVCodecInternal   *avci = avctx->internal;
423     DecodeSimpleContext *ds = &avci->ds;
424     AVPacket           *pkt = ds->in_pkt;
425     // copy to ensure we do not change pkt
426     int got_frame, actual_got_frame;
427     int ret;
428
429     if (!pkt->data && !avci->draining) {
430         av_packet_unref(pkt);
431         ret = ff_decode_get_packet(avctx, pkt);
432         if (ret < 0 && ret != AVERROR_EOF)
433             return ret;
434     }
435
436     // Some codecs (at least wma lossless) will crash when feeding drain packets
437     // after EOF was signaled.
438     if (avci->draining_done)
439         return AVERROR_EOF;
440
441     if (!pkt->data &&
442         !(avctx->codec->capabilities & AV_CODEC_CAP_DELAY ||
443           avctx->active_thread_type & FF_THREAD_FRAME))
444         return AVERROR_EOF;
445
446     got_frame = 0;
447
448     if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME) {
449         ret = ff_thread_decode_frame(avctx, frame, &got_frame, pkt);
450     } else {
451         ret = avctx->codec->decode(avctx, frame, &got_frame, pkt);
452
453         if (!(avctx->codec->caps_internal & FF_CODEC_CAP_SETS_PKT_DTS))
454             frame->pkt_dts = pkt->dts;
455         if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
456             if(!avctx->has_b_frames)
457                 frame->pkt_pos = pkt->pos;
458             //FIXME these should be under if(!avctx->has_b_frames)
459             /* get_buffer is supposed to set frame parameters */
460             if (!(avctx->codec->capabilities & AV_CODEC_CAP_DR1)) {
461                 if (!frame->sample_aspect_ratio.num)  frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
462                 if (!frame->width)                    frame->width               = avctx->width;
463                 if (!frame->height)                   frame->height              = avctx->height;
464                 if (frame->format == AV_PIX_FMT_NONE) frame->format              = avctx->pix_fmt;
465             }
466         }
467     }
468     emms_c();
469     actual_got_frame = got_frame;
470
471     if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
472         if (frame->flags & AV_FRAME_FLAG_DISCARD)
473             got_frame = 0;
474         if (got_frame)
475             frame->best_effort_timestamp = guess_correct_pts(avctx,
476                                                              frame->pts,
477                                                              frame->pkt_dts);
478     } else if (avctx->codec->type == AVMEDIA_TYPE_AUDIO) {
479         uint8_t *side;
480         int side_size;
481         uint32_t discard_padding = 0;
482         uint8_t skip_reason = 0;
483         uint8_t discard_reason = 0;
484
485         if (ret >= 0 && got_frame) {
486             frame->best_effort_timestamp = guess_correct_pts(avctx,
487                                                              frame->pts,
488                                                              frame->pkt_dts);
489             if (frame->format == AV_SAMPLE_FMT_NONE)
490                 frame->format = avctx->sample_fmt;
491             if (!frame->channel_layout)
492                 frame->channel_layout = avctx->channel_layout;
493             if (!frame->channels)
494                 frame->channels = avctx->channels;
495             if (!frame->sample_rate)
496                 frame->sample_rate = avctx->sample_rate;
497         }
498
499         side= av_packet_get_side_data(avci->last_pkt_props, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
500         if(side && side_size>=10) {
501             avci->skip_samples = AV_RL32(side) * avci->skip_samples_multiplier;
502             discard_padding = AV_RL32(side + 4);
503             av_log(avctx, AV_LOG_DEBUG, "skip %d / discard %d samples due to side data\n",
504                    avci->skip_samples, (int)discard_padding);
505             skip_reason = AV_RL8(side + 8);
506             discard_reason = AV_RL8(side + 9);
507         }
508
509         if ((frame->flags & AV_FRAME_FLAG_DISCARD) && got_frame &&
510             !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
511             avci->skip_samples = FFMAX(0, avci->skip_samples - frame->nb_samples);
512             got_frame = 0;
513         }
514
515         if (avci->skip_samples > 0 && got_frame &&
516             !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
517             if(frame->nb_samples <= avci->skip_samples){
518                 got_frame = 0;
519                 avci->skip_samples -= frame->nb_samples;
520                 av_log(avctx, AV_LOG_DEBUG, "skip whole frame, skip left: %d\n",
521                        avci->skip_samples);
522             } else {
523                 av_samples_copy(frame->extended_data, frame->extended_data, 0, avci->skip_samples,
524                                 frame->nb_samples - avci->skip_samples, avctx->channels, frame->format);
525                 if(avctx->pkt_timebase.num && avctx->sample_rate) {
526                     int64_t diff_ts = av_rescale_q(avci->skip_samples,
527                                                    (AVRational){1, avctx->sample_rate},
528                                                    avctx->pkt_timebase);
529                     if(frame->pts!=AV_NOPTS_VALUE)
530                         frame->pts += diff_ts;
531 #if FF_API_PKT_PTS
532 FF_DISABLE_DEPRECATION_WARNINGS
533                     if(frame->pkt_pts!=AV_NOPTS_VALUE)
534                         frame->pkt_pts += diff_ts;
535 FF_ENABLE_DEPRECATION_WARNINGS
536 #endif
537                     if(frame->pkt_dts!=AV_NOPTS_VALUE)
538                         frame->pkt_dts += diff_ts;
539                     if (frame->pkt_duration >= diff_ts)
540                         frame->pkt_duration -= diff_ts;
541                 } else {
542                     av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for skipped samples.\n");
543                 }
544                 av_log(avctx, AV_LOG_DEBUG, "skip %d/%d samples\n",
545                        avci->skip_samples, frame->nb_samples);
546                 frame->nb_samples -= avci->skip_samples;
547                 avci->skip_samples = 0;
548             }
549         }
550
551         if (discard_padding > 0 && discard_padding <= frame->nb_samples && got_frame &&
552             !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
553             if (discard_padding == frame->nb_samples) {
554                 got_frame = 0;
555             } else {
556                 if(avctx->pkt_timebase.num && avctx->sample_rate) {
557                     int64_t diff_ts = av_rescale_q(frame->nb_samples - discard_padding,
558                                                    (AVRational){1, avctx->sample_rate},
559                                                    avctx->pkt_timebase);
560                     frame->pkt_duration = diff_ts;
561                 } else {
562                     av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for discarded samples.\n");
563                 }
564                 av_log(avctx, AV_LOG_DEBUG, "discard %d/%d samples\n",
565                        (int)discard_padding, frame->nb_samples);
566                 frame->nb_samples -= discard_padding;
567             }
568         }
569
570         if ((avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL) && got_frame) {
571             AVFrameSideData *fside = av_frame_new_side_data(frame, AV_FRAME_DATA_SKIP_SAMPLES, 10);
572             if (fside) {
573                 AV_WL32(fside->data, avci->skip_samples);
574                 AV_WL32(fside->data + 4, discard_padding);
575                 AV_WL8(fside->data + 8, skip_reason);
576                 AV_WL8(fside->data + 9, discard_reason);
577                 avci->skip_samples = 0;
578             }
579         }
580     }
581
582     if (avctx->codec->type == AVMEDIA_TYPE_AUDIO &&
583         !avci->showed_multi_packet_warning &&
584         ret >= 0 && ret != pkt->size && !(avctx->codec->capabilities & AV_CODEC_CAP_SUBFRAMES)) {
585         av_log(avctx, AV_LOG_WARNING, "Multiple frames in a packet.\n");
586         avci->showed_multi_packet_warning = 1;
587     }
588
589     if (!got_frame)
590         av_frame_unref(frame);
591
592     if (ret >= 0 && avctx->codec->type == AVMEDIA_TYPE_VIDEO && !(avctx->flags & AV_CODEC_FLAG_TRUNCATED))
593         ret = pkt->size;
594
595 #if FF_API_AVCTX_TIMEBASE
596     if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
597         avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1}));
598 #endif
599
600     /* do not stop draining when actual_got_frame != 0 or ret < 0 */
601     /* got_frame == 0 but actual_got_frame != 0 when frame is discarded */
602     if (avci->draining && !actual_got_frame) {
603         if (ret < 0) {
604             /* prevent infinite loop if a decoder wrongly always return error on draining */
605             /* reasonable nb_errors_max = maximum b frames + thread count */
606             int nb_errors_max = 20 + (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME ?
607                                 avctx->thread_count : 1);
608
609             if (avci->nb_draining_errors++ >= nb_errors_max) {
610                 av_log(avctx, AV_LOG_ERROR, "Too many errors when draining, this is a bug. "
611                        "Stop draining and force EOF.\n");
612                 avci->draining_done = 1;
613                 ret = AVERROR_BUG;
614             }
615         } else {
616             avci->draining_done = 1;
617         }
618     }
619
620     avci->compat_decode_consumed += ret;
621
622     if (ret >= pkt->size || ret < 0) {
623         av_packet_unref(pkt);
624     } else {
625         int consumed = ret;
626
627         pkt->data                += consumed;
628         pkt->size                -= consumed;
629         avci->last_pkt_props->size -= consumed; // See extract_packet_props() comment.
630         pkt->pts                  = AV_NOPTS_VALUE;
631         pkt->dts                  = AV_NOPTS_VALUE;
632         avci->last_pkt_props->pts = AV_NOPTS_VALUE;
633         avci->last_pkt_props->dts = AV_NOPTS_VALUE;
634     }
635
636     if (got_frame)
637         av_assert0(frame->buf[0]);
638
639     return ret < 0 ? ret : 0;
640 }
641
642 static int decode_simple_receive_frame(AVCodecContext *avctx, AVFrame *frame)
643 {
644     int ret;
645
646     while (!frame->buf[0]) {
647         ret = decode_simple_internal(avctx, frame);
648         if (ret < 0)
649             return ret;
650     }
651
652     return 0;
653 }
654
655 static int decode_receive_frame_internal(AVCodecContext *avctx, AVFrame *frame)
656 {
657     AVCodecInternal *avci = avctx->internal;
658     int ret;
659
660     av_assert0(!frame->buf[0]);
661
662     if (avctx->codec->receive_frame)
663         ret = avctx->codec->receive_frame(avctx, frame);
664     else
665         ret = decode_simple_receive_frame(avctx, frame);
666
667     if (ret == AVERROR_EOF)
668         avci->draining_done = 1;
669
670     if (!ret) {
671         /* the only case where decode data is not set should be decoders
672          * that do not call ff_get_buffer() */
673         av_assert0((frame->private_ref && frame->private_ref->size == sizeof(FrameDecodeData)) ||
674                    !(avctx->codec->capabilities & AV_CODEC_CAP_DR1));
675
676         if (frame->private_ref) {
677             FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
678
679             if (fdd->post_process) {
680                 ret = fdd->post_process(avctx, frame);
681                 if (ret < 0) {
682                     av_frame_unref(frame);
683                     return ret;
684                 }
685             }
686         }
687     }
688
689     /* free the per-frame decode data */
690     av_buffer_unref(&frame->private_ref);
691
692     return ret;
693 }
694
695 int attribute_align_arg avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)
696 {
697     AVCodecInternal *avci = avctx->internal;
698     int ret;
699
700     if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
701         return AVERROR(EINVAL);
702
703     if (avctx->internal->draining)
704         return AVERROR_EOF;
705
706     if (avpkt && !avpkt->size && avpkt->data)
707         return AVERROR(EINVAL);
708
709     av_packet_unref(avci->buffer_pkt);
710     if (avpkt && (avpkt->data || avpkt->side_data_elems)) {
711         ret = av_packet_ref(avci->buffer_pkt, avpkt);
712         if (ret < 0)
713             return ret;
714     }
715
716     ret = av_bsf_send_packet(avci->filter.bsfs[0], avci->buffer_pkt);
717     if (ret < 0) {
718         av_packet_unref(avci->buffer_pkt);
719         return ret;
720     }
721
722     if (!avci->buffer_frame->buf[0]) {
723         ret = decode_receive_frame_internal(avctx, avci->buffer_frame);
724         if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
725             return ret;
726     }
727
728     return 0;
729 }
730
731 static int apply_cropping(AVCodecContext *avctx, AVFrame *frame)
732 {
733     /* make sure we are noisy about decoders returning invalid cropping data */
734     if (frame->crop_left >= INT_MAX - frame->crop_right        ||
735         frame->crop_top  >= INT_MAX - frame->crop_bottom       ||
736         (frame->crop_left + frame->crop_right) >= frame->width ||
737         (frame->crop_top + frame->crop_bottom) >= frame->height) {
738         av_log(avctx, AV_LOG_WARNING,
739                "Invalid cropping information set by a decoder: "
740                "%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER" "
741                "(frame size %dx%d). This is a bug, please report it\n",
742                frame->crop_left, frame->crop_right, frame->crop_top, frame->crop_bottom,
743                frame->width, frame->height);
744         frame->crop_left   = 0;
745         frame->crop_right  = 0;
746         frame->crop_top    = 0;
747         frame->crop_bottom = 0;
748         return 0;
749     }
750
751     if (!avctx->apply_cropping)
752         return 0;
753
754     return av_frame_apply_cropping(frame, avctx->flags & AV_CODEC_FLAG_UNALIGNED ?
755                                           AV_FRAME_CROP_UNALIGNED : 0);
756 }
757
758 int attribute_align_arg avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
759 {
760     AVCodecInternal *avci = avctx->internal;
761     int ret, changed;
762
763     av_frame_unref(frame);
764
765     if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
766         return AVERROR(EINVAL);
767
768     if (avci->buffer_frame->buf[0]) {
769         av_frame_move_ref(frame, avci->buffer_frame);
770     } else {
771         ret = decode_receive_frame_internal(avctx, frame);
772         if (ret < 0)
773             return ret;
774     }
775
776     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
777         ret = apply_cropping(avctx, frame);
778         if (ret < 0) {
779             av_frame_unref(frame);
780             return ret;
781         }
782     }
783
784     avctx->frame_number++;
785
786     if (avctx->flags & AV_CODEC_FLAG_DROPCHANGED) {
787
788         if (avctx->frame_number == 1) {
789             avci->initial_format = frame->format;
790             switch(avctx->codec_type) {
791             case AVMEDIA_TYPE_VIDEO:
792                 avci->initial_width  = frame->width;
793                 avci->initial_height = frame->height;
794                 break;
795             case AVMEDIA_TYPE_AUDIO:
796                 avci->initial_sample_rate = frame->sample_rate ? frame->sample_rate :
797                                                                  avctx->sample_rate;
798                 avci->initial_channels       = frame->channels;
799                 avci->initial_channel_layout = frame->channel_layout;
800                 break;
801             }
802         }
803
804         if (avctx->frame_number > 1) {
805             changed = avci->initial_format != frame->format;
806
807             switch(avctx->codec_type) {
808             case AVMEDIA_TYPE_VIDEO:
809                 changed |= avci->initial_width  != frame->width ||
810                            avci->initial_height != frame->height;
811                 break;
812             case AVMEDIA_TYPE_AUDIO:
813                 changed |= avci->initial_sample_rate    != frame->sample_rate ||
814                            avci->initial_sample_rate    != avctx->sample_rate ||
815                            avci->initial_channels       != frame->channels ||
816                            avci->initial_channel_layout != frame->channel_layout;
817                 break;
818             }
819
820             if (changed) {
821                 avci->changed_frames_dropped++;
822                 av_log(avctx, AV_LOG_INFO, "dropped changed frame #%d pts %"PRId64
823                                             " drop count: %d \n",
824                                             avctx->frame_number, frame->pts,
825                                             avci->changed_frames_dropped);
826                 av_frame_unref(frame);
827                 return AVERROR_INPUT_CHANGED;
828             }
829         }
830     }
831     return 0;
832 }
833
834 static int compat_decode(AVCodecContext *avctx, AVFrame *frame,
835                          int *got_frame, const AVPacket *pkt)
836 {
837     AVCodecInternal *avci = avctx->internal;
838     int ret = 0;
839
840     av_assert0(avci->compat_decode_consumed == 0);
841
842     if (avci->draining_done && pkt && pkt->size != 0) {
843         av_log(avctx, AV_LOG_WARNING, "Got unexpected packet after EOF\n");
844         avcodec_flush_buffers(avctx);
845     }
846
847     *got_frame = 0;
848     avci->compat_decode = 1;
849
850     if (avci->compat_decode_partial_size > 0 &&
851         avci->compat_decode_partial_size != pkt->size) {
852         av_log(avctx, AV_LOG_ERROR,
853                "Got unexpected packet size after a partial decode\n");
854         ret = AVERROR(EINVAL);
855         goto finish;
856     }
857
858     if (!avci->compat_decode_partial_size) {
859         ret = avcodec_send_packet(avctx, pkt);
860         if (ret == AVERROR_EOF)
861             ret = 0;
862         else if (ret == AVERROR(EAGAIN)) {
863             /* we fully drain all the output in each decode call, so this should not
864              * ever happen */
865             ret = AVERROR_BUG;
866             goto finish;
867         } else if (ret < 0)
868             goto finish;
869     }
870
871     while (ret >= 0) {
872         ret = avcodec_receive_frame(avctx, frame);
873         if (ret < 0) {
874             if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
875                 ret = 0;
876             goto finish;
877         }
878
879         if (frame != avci->compat_decode_frame) {
880             if (!avctx->refcounted_frames) {
881                 ret = unrefcount_frame(avci, frame);
882                 if (ret < 0)
883                     goto finish;
884             }
885
886             *got_frame = 1;
887             frame = avci->compat_decode_frame;
888         } else {
889             if (!avci->compat_decode_warned) {
890                 av_log(avctx, AV_LOG_WARNING, "The deprecated avcodec_decode_* "
891                        "API cannot return all the frames for this decoder. "
892                        "Some frames will be dropped. Update your code to the "
893                        "new decoding API to fix this.\n");
894                 avci->compat_decode_warned = 1;
895             }
896         }
897
898         if (avci->draining || (!avctx->codec->bsfs && avci->compat_decode_consumed < pkt->size))
899             break;
900     }
901
902 finish:
903     if (ret == 0) {
904         /* if there are any bsfs then assume full packet is always consumed */
905         if (avctx->codec->bsfs)
906             ret = pkt->size;
907         else
908             ret = FFMIN(avci->compat_decode_consumed, pkt->size);
909     }
910     avci->compat_decode_consumed = 0;
911     avci->compat_decode_partial_size = (ret >= 0) ? pkt->size - ret : 0;
912
913     return ret;
914 }
915
916 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
917                                               int *got_picture_ptr,
918                                               const AVPacket *avpkt)
919 {
920     return compat_decode(avctx, picture, got_picture_ptr, avpkt);
921 }
922
923 int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
924                                               AVFrame *frame,
925                                               int *got_frame_ptr,
926                                               const AVPacket *avpkt)
927 {
928     return compat_decode(avctx, frame, got_frame_ptr, avpkt);
929 }
930
931 static void get_subtitle_defaults(AVSubtitle *sub)
932 {
933     memset(sub, 0, sizeof(*sub));
934     sub->pts = AV_NOPTS_VALUE;
935 }
936
937 #define UTF8_MAX_BYTES 4 /* 5 and 6 bytes sequences should not be used */
938 static int recode_subtitle(AVCodecContext *avctx,
939                            AVPacket *outpkt, const AVPacket *inpkt)
940 {
941 #if CONFIG_ICONV
942     iconv_t cd = (iconv_t)-1;
943     int ret = 0;
944     char *inb, *outb;
945     size_t inl, outl;
946     AVPacket tmp;
947 #endif
948
949     if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_PRE_DECODER || inpkt->size == 0)
950         return 0;
951
952 #if CONFIG_ICONV
953     cd = iconv_open("UTF-8", avctx->sub_charenc);
954     av_assert0(cd != (iconv_t)-1);
955
956     inb = inpkt->data;
957     inl = inpkt->size;
958
959     if (inl >= INT_MAX / UTF8_MAX_BYTES - AV_INPUT_BUFFER_PADDING_SIZE) {
960         av_log(avctx, AV_LOG_ERROR, "Subtitles packet is too big for recoding\n");
961         ret = AVERROR(ENOMEM);
962         goto end;
963     }
964
965     ret = av_new_packet(&tmp, inl * UTF8_MAX_BYTES);
966     if (ret < 0)
967         goto end;
968     outpkt->buf  = tmp.buf;
969     outpkt->data = tmp.data;
970     outpkt->size = tmp.size;
971     outb = outpkt->data;
972     outl = outpkt->size;
973
974     if (iconv(cd, &inb, &inl, &outb, &outl) == (size_t)-1 ||
975         iconv(cd, NULL, NULL, &outb, &outl) == (size_t)-1 ||
976         outl >= outpkt->size || inl != 0) {
977         ret = FFMIN(AVERROR(errno), -1);
978         av_log(avctx, AV_LOG_ERROR, "Unable to recode subtitle event \"%s\" "
979                "from %s to UTF-8\n", inpkt->data, avctx->sub_charenc);
980         av_packet_unref(&tmp);
981         goto end;
982     }
983     outpkt->size -= outl;
984     memset(outpkt->data + outpkt->size, 0, outl);
985
986 end:
987     if (cd != (iconv_t)-1)
988         iconv_close(cd);
989     return ret;
990 #else
991     av_log(avctx, AV_LOG_ERROR, "requesting subtitles recoding without iconv");
992     return AVERROR(EINVAL);
993 #endif
994 }
995
996 static int utf8_check(const uint8_t *str)
997 {
998     const uint8_t *byte;
999     uint32_t codepoint, min;
1000
1001     while (*str) {
1002         byte = str;
1003         GET_UTF8(codepoint, *(byte++), return 0;);
1004         min = byte - str == 1 ? 0 : byte - str == 2 ? 0x80 :
1005               1 << (5 * (byte - str) - 4);
1006         if (codepoint < min || codepoint >= 0x110000 ||
1007             codepoint == 0xFFFE /* BOM */ ||
1008             codepoint >= 0xD800 && codepoint <= 0xDFFF /* surrogates */)
1009             return 0;
1010         str = byte;
1011     }
1012     return 1;
1013 }
1014
1015 #if FF_API_ASS_TIMING
1016 static void insert_ts(AVBPrint *buf, int ts)
1017 {
1018     if (ts == -1) {
1019         av_bprintf(buf, "9:59:59.99,");
1020     } else {
1021         int h, m, s;
1022
1023         h = ts/360000;  ts -= 360000*h;
1024         m = ts/  6000;  ts -=   6000*m;
1025         s = ts/   100;  ts -=    100*s;
1026         av_bprintf(buf, "%d:%02d:%02d.%02d,", h, m, s, ts);
1027     }
1028 }
1029
1030 static int convert_sub_to_old_ass_form(AVSubtitle *sub, const AVPacket *pkt, AVRational tb)
1031 {
1032     int i;
1033     AVBPrint buf;
1034
1035     av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
1036
1037     for (i = 0; i < sub->num_rects; i++) {
1038         char *final_dialog;
1039         const char *dialog;
1040         AVSubtitleRect *rect = sub->rects[i];
1041         int ts_start, ts_duration = -1;
1042         long int layer;
1043
1044         if (rect->type != SUBTITLE_ASS || !strncmp(rect->ass, "Dialogue: ", 10))
1045             continue;
1046
1047         av_bprint_clear(&buf);
1048
1049         /* skip ReadOrder */
1050         dialog = strchr(rect->ass, ',');
1051         if (!dialog)
1052             continue;
1053         dialog++;
1054
1055         /* extract Layer or Marked */
1056         layer = strtol(dialog, (char**)&dialog, 10);
1057         if (*dialog != ',')
1058             continue;
1059         dialog++;
1060
1061         /* rescale timing to ASS time base (ms) */
1062         ts_start = av_rescale_q(pkt->pts, tb, av_make_q(1, 100));
1063         if (pkt->duration != -1)
1064             ts_duration = av_rescale_q(pkt->duration, tb, av_make_q(1, 100));
1065         sub->end_display_time = FFMAX(sub->end_display_time, 10 * ts_duration);
1066
1067         /* construct ASS (standalone file form with timestamps) string */
1068         av_bprintf(&buf, "Dialogue: %ld,", layer);
1069         insert_ts(&buf, ts_start);
1070         insert_ts(&buf, ts_duration == -1 ? -1 : ts_start + ts_duration);
1071         av_bprintf(&buf, "%s\r\n", dialog);
1072
1073         final_dialog = av_strdup(buf.str);
1074         if (!av_bprint_is_complete(&buf) || !final_dialog) {
1075             av_freep(&final_dialog);
1076             av_bprint_finalize(&buf, NULL);
1077             return AVERROR(ENOMEM);
1078         }
1079         av_freep(&rect->ass);
1080         rect->ass = final_dialog;
1081     }
1082
1083     av_bprint_finalize(&buf, NULL);
1084     return 0;
1085 }
1086 #endif
1087
1088 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
1089                              int *got_sub_ptr,
1090                              AVPacket *avpkt)
1091 {
1092     int i, ret = 0;
1093
1094     if (!avpkt->data && avpkt->size) {
1095         av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
1096         return AVERROR(EINVAL);
1097     }
1098     if (!avctx->codec)
1099         return AVERROR(EINVAL);
1100     if (avctx->codec->type != AVMEDIA_TYPE_SUBTITLE) {
1101         av_log(avctx, AV_LOG_ERROR, "Invalid media type for subtitles\n");
1102         return AVERROR(EINVAL);
1103     }
1104
1105     *got_sub_ptr = 0;
1106     get_subtitle_defaults(sub);
1107
1108     if ((avctx->codec->capabilities & AV_CODEC_CAP_DELAY) || avpkt->size) {
1109         AVPacket pkt_recoded = *avpkt;
1110
1111         ret = recode_subtitle(avctx, &pkt_recoded, avpkt);
1112         if (ret < 0) {
1113             *got_sub_ptr = 0;
1114         } else {
1115              ret = extract_packet_props(avctx->internal, &pkt_recoded);
1116              if (ret < 0)
1117                 return ret;
1118
1119             if (avctx->pkt_timebase.num && avpkt->pts != AV_NOPTS_VALUE)
1120                 sub->pts = av_rescale_q(avpkt->pts,
1121                                         avctx->pkt_timebase, AV_TIME_BASE_Q);
1122             ret = avctx->codec->decode(avctx, sub, got_sub_ptr, &pkt_recoded);
1123             av_assert1((ret >= 0) >= !!*got_sub_ptr &&
1124                        !!*got_sub_ptr >= !!sub->num_rects);
1125
1126 #if FF_API_ASS_TIMING
1127             if (avctx->sub_text_format == FF_SUB_TEXT_FMT_ASS_WITH_TIMINGS
1128                 && *got_sub_ptr && sub->num_rects) {
1129                 const AVRational tb = avctx->pkt_timebase.num ? avctx->pkt_timebase
1130                                                               : avctx->time_base;
1131                 int err = convert_sub_to_old_ass_form(sub, avpkt, tb);
1132                 if (err < 0)
1133                     ret = err;
1134             }
1135 #endif
1136
1137             if (sub->num_rects && !sub->end_display_time && avpkt->duration &&
1138                 avctx->pkt_timebase.num) {
1139                 AVRational ms = { 1, 1000 };
1140                 sub->end_display_time = av_rescale_q(avpkt->duration,
1141                                                      avctx->pkt_timebase, ms);
1142             }
1143
1144             if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB)
1145                 sub->format = 0;
1146             else if (avctx->codec_descriptor->props & AV_CODEC_PROP_TEXT_SUB)
1147                 sub->format = 1;
1148
1149             for (i = 0; i < sub->num_rects; i++) {
1150                 if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_IGNORE &&
1151                     sub->rects[i]->ass && !utf8_check(sub->rects[i]->ass)) {
1152                     av_log(avctx, AV_LOG_ERROR,
1153                            "Invalid UTF-8 in decoded subtitles text; "
1154                            "maybe missing -sub_charenc option\n");
1155                     avsubtitle_free(sub);
1156                     ret = AVERROR_INVALIDDATA;
1157                     break;
1158                 }
1159             }
1160
1161             if (avpkt->data != pkt_recoded.data) { // did we recode?
1162                 /* prevent from destroying side data from original packet */
1163                 pkt_recoded.side_data = NULL;
1164                 pkt_recoded.side_data_elems = 0;
1165
1166                 av_packet_unref(&pkt_recoded);
1167             }
1168         }
1169
1170         if (*got_sub_ptr)
1171             avctx->frame_number++;
1172     }
1173
1174     return ret;
1175 }
1176
1177 enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *avctx,
1178                                               const enum AVPixelFormat *fmt)
1179 {
1180     const AVPixFmtDescriptor *desc;
1181     const AVCodecHWConfig *config;
1182     int i, n;
1183
1184     // If a device was supplied when the codec was opened, assume that the
1185     // user wants to use it.
1186     if (avctx->hw_device_ctx && avctx->codec->hw_configs) {
1187         AVHWDeviceContext *device_ctx =
1188             (AVHWDeviceContext*)avctx->hw_device_ctx->data;
1189         for (i = 0;; i++) {
1190             config = &avctx->codec->hw_configs[i]->public;
1191             if (!config)
1192                 break;
1193             if (!(config->methods &
1194                   AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX))
1195                 continue;
1196             if (device_ctx->type != config->device_type)
1197                 continue;
1198             for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++) {
1199                 if (config->pix_fmt == fmt[n])
1200                     return fmt[n];
1201             }
1202         }
1203     }
1204     // No device or other setup, so we have to choose from things which
1205     // don't any other external information.
1206
1207     // If the last element of the list is a software format, choose it
1208     // (this should be best software format if any exist).
1209     for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++);
1210     desc = av_pix_fmt_desc_get(fmt[n - 1]);
1211     if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
1212         return fmt[n - 1];
1213
1214     // Finally, traverse the list in order and choose the first entry
1215     // with no external dependencies (if there is no hardware configuration
1216     // information available then this just picks the first entry).
1217     for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++) {
1218         for (i = 0;; i++) {
1219             config = avcodec_get_hw_config(avctx->codec, i);
1220             if (!config)
1221                 break;
1222             if (config->pix_fmt == fmt[n])
1223                 break;
1224         }
1225         if (!config) {
1226             // No specific config available, so the decoder must be able
1227             // to handle this format without any additional setup.
1228             return fmt[n];
1229         }
1230         if (config->methods & AV_CODEC_HW_CONFIG_METHOD_INTERNAL) {
1231             // Usable with only internal setup.
1232             return fmt[n];
1233         }
1234     }
1235
1236     // Nothing is usable, give up.
1237     return AV_PIX_FMT_NONE;
1238 }
1239
1240 int ff_decode_get_hw_frames_ctx(AVCodecContext *avctx,
1241                                 enum AVHWDeviceType dev_type)
1242 {
1243     AVHWDeviceContext *device_ctx;
1244     AVHWFramesContext *frames_ctx;
1245     int ret;
1246
1247     if (!avctx->hwaccel)
1248         return AVERROR(ENOSYS);
1249
1250     if (avctx->hw_frames_ctx)
1251         return 0;
1252     if (!avctx->hw_device_ctx) {
1253         av_log(avctx, AV_LOG_ERROR, "A hardware frames or device context is "
1254                 "required for hardware accelerated decoding.\n");
1255         return AVERROR(EINVAL);
1256     }
1257
1258     device_ctx = (AVHWDeviceContext *)avctx->hw_device_ctx->data;
1259     if (device_ctx->type != dev_type) {
1260         av_log(avctx, AV_LOG_ERROR, "Device type %s expected for hardware "
1261                "decoding, but got %s.\n", av_hwdevice_get_type_name(dev_type),
1262                av_hwdevice_get_type_name(device_ctx->type));
1263         return AVERROR(EINVAL);
1264     }
1265
1266     ret = avcodec_get_hw_frames_parameters(avctx,
1267                                            avctx->hw_device_ctx,
1268                                            avctx->hwaccel->pix_fmt,
1269                                            &avctx->hw_frames_ctx);
1270     if (ret < 0)
1271         return ret;
1272
1273     frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1274
1275
1276     if (frames_ctx->initial_pool_size) {
1277         // We guarantee 4 base work surfaces. The function above guarantees 1
1278         // (the absolute minimum), so add the missing count.
1279         frames_ctx->initial_pool_size += 3;
1280     }
1281
1282     ret = av_hwframe_ctx_init(avctx->hw_frames_ctx);
1283     if (ret < 0) {
1284         av_buffer_unref(&avctx->hw_frames_ctx);
1285         return ret;
1286     }
1287
1288     return 0;
1289 }
1290
1291 int avcodec_get_hw_frames_parameters(AVCodecContext *avctx,
1292                                      AVBufferRef *device_ref,
1293                                      enum AVPixelFormat hw_pix_fmt,
1294                                      AVBufferRef **out_frames_ref)
1295 {
1296     AVBufferRef *frames_ref = NULL;
1297     const AVCodecHWConfigInternal *hw_config;
1298     const AVHWAccel *hwa;
1299     int i, ret;
1300
1301     for (i = 0;; i++) {
1302         hw_config = avctx->codec->hw_configs[i];
1303         if (!hw_config)
1304             return AVERROR(ENOENT);
1305         if (hw_config->public.pix_fmt == hw_pix_fmt)
1306             break;
1307     }
1308
1309     hwa = hw_config->hwaccel;
1310     if (!hwa || !hwa->frame_params)
1311         return AVERROR(ENOENT);
1312
1313     frames_ref = av_hwframe_ctx_alloc(device_ref);
1314     if (!frames_ref)
1315         return AVERROR(ENOMEM);
1316
1317     ret = hwa->frame_params(avctx, frames_ref);
1318     if (ret >= 0) {
1319         AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frames_ref->data;
1320
1321         if (frames_ctx->initial_pool_size) {
1322             // If the user has requested that extra output surfaces be
1323             // available then add them here.
1324             if (avctx->extra_hw_frames > 0)
1325                 frames_ctx->initial_pool_size += avctx->extra_hw_frames;
1326
1327             // If frame threading is enabled then an extra surface per thread
1328             // is also required.
1329             if (avctx->active_thread_type & FF_THREAD_FRAME)
1330                 frames_ctx->initial_pool_size += avctx->thread_count;
1331         }
1332
1333         *out_frames_ref = frames_ref;
1334     } else {
1335         av_buffer_unref(&frames_ref);
1336     }
1337     return ret;
1338 }
1339
1340 static int hwaccel_init(AVCodecContext *avctx,
1341                         const AVCodecHWConfigInternal *hw_config)
1342 {
1343     const AVHWAccel *hwaccel;
1344     int err;
1345
1346     hwaccel = hw_config->hwaccel;
1347     if (hwaccel->capabilities & AV_HWACCEL_CODEC_CAP_EXPERIMENTAL &&
1348         avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
1349         av_log(avctx, AV_LOG_WARNING, "Ignoring experimental hwaccel: %s\n",
1350                hwaccel->name);
1351         return AVERROR_PATCHWELCOME;
1352     }
1353
1354     if (hwaccel->priv_data_size) {
1355         avctx->internal->hwaccel_priv_data =
1356             av_mallocz(hwaccel->priv_data_size);
1357         if (!avctx->internal->hwaccel_priv_data)
1358             return AVERROR(ENOMEM);
1359     }
1360
1361     avctx->hwaccel = hwaccel;
1362     if (hwaccel->init) {
1363         err = hwaccel->init(avctx);
1364         if (err < 0) {
1365             av_log(avctx, AV_LOG_ERROR, "Failed setup for format %s: "
1366                    "hwaccel initialisation returned error.\n",
1367                    av_get_pix_fmt_name(hw_config->public.pix_fmt));
1368             av_freep(&avctx->internal->hwaccel_priv_data);
1369             avctx->hwaccel = NULL;
1370             return err;
1371         }
1372     }
1373
1374     return 0;
1375 }
1376
1377 static void hwaccel_uninit(AVCodecContext *avctx)
1378 {
1379     if (avctx->hwaccel && avctx->hwaccel->uninit)
1380         avctx->hwaccel->uninit(avctx);
1381
1382     av_freep(&avctx->internal->hwaccel_priv_data);
1383
1384     avctx->hwaccel = NULL;
1385
1386     av_buffer_unref(&avctx->hw_frames_ctx);
1387 }
1388
1389 int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
1390 {
1391     const AVPixFmtDescriptor *desc;
1392     enum AVPixelFormat *choices;
1393     enum AVPixelFormat ret, user_choice;
1394     const AVCodecHWConfigInternal *hw_config;
1395     const AVCodecHWConfig *config;
1396     int i, n, err;
1397
1398     // Find end of list.
1399     for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++);
1400     // Must contain at least one entry.
1401     av_assert0(n >= 1);
1402     // If a software format is available, it must be the last entry.
1403     desc = av_pix_fmt_desc_get(fmt[n - 1]);
1404     if (desc->flags & AV_PIX_FMT_FLAG_HWACCEL) {
1405         // No software format is available.
1406     } else {
1407         avctx->sw_pix_fmt = fmt[n - 1];
1408     }
1409
1410     choices = av_malloc_array(n + 1, sizeof(*choices));
1411     if (!choices)
1412         return AV_PIX_FMT_NONE;
1413
1414     memcpy(choices, fmt, (n + 1) * sizeof(*choices));
1415
1416     for (;;) {
1417         // Remove the previous hwaccel, if there was one.
1418         hwaccel_uninit(avctx);
1419
1420         user_choice = avctx->get_format(avctx, choices);
1421         if (user_choice == AV_PIX_FMT_NONE) {
1422             // Explicitly chose nothing, give up.
1423             ret = AV_PIX_FMT_NONE;
1424             break;
1425         }
1426
1427         desc = av_pix_fmt_desc_get(user_choice);
1428         if (!desc) {
1429             av_log(avctx, AV_LOG_ERROR, "Invalid format returned by "
1430                    "get_format() callback.\n");
1431             ret = AV_PIX_FMT_NONE;
1432             break;
1433         }
1434         av_log(avctx, AV_LOG_DEBUG, "Format %s chosen by get_format().\n",
1435                desc->name);
1436
1437         for (i = 0; i < n; i++) {
1438             if (choices[i] == user_choice)
1439                 break;
1440         }
1441         if (i == n) {
1442             av_log(avctx, AV_LOG_ERROR, "Invalid return from get_format(): "
1443                    "%s not in possible list.\n", desc->name);
1444             ret = AV_PIX_FMT_NONE;
1445             break;
1446         }
1447
1448         if (avctx->codec->hw_configs) {
1449             for (i = 0;; i++) {
1450                 hw_config = avctx->codec->hw_configs[i];
1451                 if (!hw_config)
1452                     break;
1453                 if (hw_config->public.pix_fmt == user_choice)
1454                     break;
1455             }
1456         } else {
1457             hw_config = NULL;
1458         }
1459
1460         if (!hw_config) {
1461             // No config available, so no extra setup required.
1462             ret = user_choice;
1463             break;
1464         }
1465         config = &hw_config->public;
1466
1467         if (config->methods &
1468             AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX &&
1469             avctx->hw_frames_ctx) {
1470             const AVHWFramesContext *frames_ctx =
1471                 (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1472             if (frames_ctx->format != user_choice) {
1473                 av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1474                        "does not match the format of the provided frames "
1475                        "context.\n", desc->name);
1476                 goto try_again;
1477             }
1478         } else if (config->methods &
1479                    AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX &&
1480                    avctx->hw_device_ctx) {
1481             const AVHWDeviceContext *device_ctx =
1482                 (AVHWDeviceContext*)avctx->hw_device_ctx->data;
1483             if (device_ctx->type != config->device_type) {
1484                 av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1485                        "does not match the type of the provided device "
1486                        "context.\n", desc->name);
1487                 goto try_again;
1488             }
1489         } else if (config->methods &
1490                    AV_CODEC_HW_CONFIG_METHOD_INTERNAL) {
1491             // Internal-only setup, no additional configuration.
1492         } else if (config->methods &
1493                    AV_CODEC_HW_CONFIG_METHOD_AD_HOC) {
1494             // Some ad-hoc configuration we can't see and can't check.
1495         } else {
1496             av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1497                    "missing configuration.\n", desc->name);
1498             goto try_again;
1499         }
1500         if (hw_config->hwaccel) {
1501             av_log(avctx, AV_LOG_DEBUG, "Format %s requires hwaccel "
1502                    "initialisation.\n", desc->name);
1503             err = hwaccel_init(avctx, hw_config);
1504             if (err < 0)
1505                 goto try_again;
1506         }
1507         ret = user_choice;
1508         break;
1509
1510     try_again:
1511         av_log(avctx, AV_LOG_DEBUG, "Format %s not usable, retrying "
1512                "get_format() without it.\n", desc->name);
1513         for (i = 0; i < n; i++) {
1514             if (choices[i] == user_choice)
1515                 break;
1516         }
1517         for (; i + 1 < n; i++)
1518             choices[i] = choices[i + 1];
1519         --n;
1520     }
1521
1522     av_freep(&choices);
1523     return ret;
1524 }
1525
1526 static void frame_pool_free(void *opaque, uint8_t *data)
1527 {
1528     FramePool *pool = (FramePool*)data;
1529     int i;
1530
1531     for (i = 0; i < FF_ARRAY_ELEMS(pool->pools); i++)
1532         av_buffer_pool_uninit(&pool->pools[i]);
1533
1534     av_freep(&data);
1535 }
1536
1537 static AVBufferRef *frame_pool_alloc(void)
1538 {
1539     FramePool *pool = av_mallocz(sizeof(*pool));
1540     AVBufferRef *buf;
1541
1542     if (!pool)
1543         return NULL;
1544
1545     buf = av_buffer_create((uint8_t*)pool, sizeof(*pool),
1546                            frame_pool_free, NULL, 0);
1547     if (!buf) {
1548         av_freep(&pool);
1549         return NULL;
1550     }
1551
1552     return buf;
1553 }
1554
1555 static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame)
1556 {
1557     FramePool *pool = avctx->internal->pool ?
1558                       (FramePool*)avctx->internal->pool->data : NULL;
1559     AVBufferRef *pool_buf;
1560     int i, ret, ch, planes;
1561
1562     if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
1563         int planar = av_sample_fmt_is_planar(frame->format);
1564         ch     = frame->channels;
1565         planes = planar ? ch : 1;
1566     }
1567
1568     if (pool && pool->format == frame->format) {
1569         if (avctx->codec_type == AVMEDIA_TYPE_VIDEO &&
1570             pool->width == frame->width && pool->height == frame->height)
1571             return 0;
1572         if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && pool->planes == planes &&
1573             pool->channels == ch && frame->nb_samples == pool->samples)
1574             return 0;
1575     }
1576
1577     pool_buf = frame_pool_alloc();
1578     if (!pool_buf)
1579         return AVERROR(ENOMEM);
1580     pool = (FramePool*)pool_buf->data;
1581
1582     switch (avctx->codec_type) {
1583     case AVMEDIA_TYPE_VIDEO: {
1584         uint8_t *data[4];
1585         int linesize[4];
1586         int size[4] = { 0 };
1587         int w = frame->width;
1588         int h = frame->height;
1589         int tmpsize, unaligned;
1590
1591         avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align);
1592
1593         do {
1594             // NOTE: do not align linesizes individually, this breaks e.g. assumptions
1595             // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
1596             ret = av_image_fill_linesizes(linesize, avctx->pix_fmt, w);
1597             if (ret < 0)
1598                 goto fail;
1599             // increase alignment of w for next try (rhs gives the lowest bit set in w)
1600             w += w & ~(w - 1);
1601
1602             unaligned = 0;
1603             for (i = 0; i < 4; i++)
1604                 unaligned |= linesize[i] % pool->stride_align[i];
1605         } while (unaligned);
1606
1607         tmpsize = av_image_fill_pointers(data, avctx->pix_fmt, h,
1608                                          NULL, linesize);
1609         if (tmpsize < 0) {
1610             ret = tmpsize;
1611             goto fail;
1612         }
1613
1614         for (i = 0; i < 3 && data[i + 1]; i++)
1615             size[i] = data[i + 1] - data[i];
1616         size[i] = tmpsize - (data[i] - data[0]);
1617
1618         for (i = 0; i < 4; i++) {
1619             pool->linesize[i] = linesize[i];
1620             if (size[i]) {
1621                 pool->pools[i] = av_buffer_pool_init(size[i] + 16 + STRIDE_ALIGN - 1,
1622                                                      CONFIG_MEMORY_POISONING ?
1623                                                         NULL :
1624                                                         av_buffer_allocz);
1625                 if (!pool->pools[i]) {
1626                     ret = AVERROR(ENOMEM);
1627                     goto fail;
1628                 }
1629             }
1630         }
1631         pool->format = frame->format;
1632         pool->width  = frame->width;
1633         pool->height = frame->height;
1634
1635         break;
1636         }
1637     case AVMEDIA_TYPE_AUDIO: {
1638         ret = av_samples_get_buffer_size(&pool->linesize[0], ch,
1639                                          frame->nb_samples, frame->format, 0);
1640         if (ret < 0)
1641             goto fail;
1642
1643         pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL);
1644         if (!pool->pools[0]) {
1645             ret = AVERROR(ENOMEM);
1646             goto fail;
1647         }
1648
1649         pool->format     = frame->format;
1650         pool->planes     = planes;
1651         pool->channels   = ch;
1652         pool->samples = frame->nb_samples;
1653         break;
1654         }
1655     default: av_assert0(0);
1656     }
1657
1658     av_buffer_unref(&avctx->internal->pool);
1659     avctx->internal->pool = pool_buf;
1660
1661     return 0;
1662 fail:
1663     av_buffer_unref(&pool_buf);
1664     return ret;
1665 }
1666
1667 static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
1668 {
1669     FramePool *pool = (FramePool*)avctx->internal->pool->data;
1670     int planes = pool->planes;
1671     int i;
1672
1673     frame->linesize[0] = pool->linesize[0];
1674
1675     if (planes > AV_NUM_DATA_POINTERS) {
1676         frame->extended_data = av_mallocz_array(planes, sizeof(*frame->extended_data));
1677         frame->nb_extended_buf = planes - AV_NUM_DATA_POINTERS;
1678         frame->extended_buf  = av_mallocz_array(frame->nb_extended_buf,
1679                                           sizeof(*frame->extended_buf));
1680         if (!frame->extended_data || !frame->extended_buf) {
1681             av_freep(&frame->extended_data);
1682             av_freep(&frame->extended_buf);
1683             return AVERROR(ENOMEM);
1684         }
1685     } else {
1686         frame->extended_data = frame->data;
1687         av_assert0(frame->nb_extended_buf == 0);
1688     }
1689
1690     for (i = 0; i < FFMIN(planes, AV_NUM_DATA_POINTERS); i++) {
1691         frame->buf[i] = av_buffer_pool_get(pool->pools[0]);
1692         if (!frame->buf[i])
1693             goto fail;
1694         frame->extended_data[i] = frame->data[i] = frame->buf[i]->data;
1695     }
1696     for (i = 0; i < frame->nb_extended_buf; i++) {
1697         frame->extended_buf[i] = av_buffer_pool_get(pool->pools[0]);
1698         if (!frame->extended_buf[i])
1699             goto fail;
1700         frame->extended_data[i + AV_NUM_DATA_POINTERS] = frame->extended_buf[i]->data;
1701     }
1702
1703     if (avctx->debug & FF_DEBUG_BUFFERS)
1704         av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p", frame);
1705
1706     return 0;
1707 fail:
1708     av_frame_unref(frame);
1709     return AVERROR(ENOMEM);
1710 }
1711
1712 static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
1713 {
1714     FramePool *pool = (FramePool*)s->internal->pool->data;
1715     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pic->format);
1716     int i;
1717
1718     if (pic->data[0] || pic->data[1] || pic->data[2] || pic->data[3]) {
1719         av_log(s, AV_LOG_ERROR, "pic->data[*]!=NULL in avcodec_default_get_buffer\n");
1720         return -1;
1721     }
1722
1723     if (!desc) {
1724         av_log(s, AV_LOG_ERROR,
1725             "Unable to get pixel format descriptor for format %s\n",
1726             av_get_pix_fmt_name(pic->format));
1727         return AVERROR(EINVAL);
1728     }
1729
1730     memset(pic->data, 0, sizeof(pic->data));
1731     pic->extended_data = pic->data;
1732
1733     for (i = 0; i < 4 && pool->pools[i]; i++) {
1734         pic->linesize[i] = pool->linesize[i];
1735
1736         pic->buf[i] = av_buffer_pool_get(pool->pools[i]);
1737         if (!pic->buf[i])
1738             goto fail;
1739
1740         pic->data[i] = pic->buf[i]->data;
1741     }
1742     for (; i < AV_NUM_DATA_POINTERS; i++) {
1743         pic->data[i] = NULL;
1744         pic->linesize[i] = 0;
1745     }
1746     if (desc->flags & AV_PIX_FMT_FLAG_PAL ||
1747         ((desc->flags & FF_PSEUDOPAL) && pic->data[1]))
1748         avpriv_set_systematic_pal2((uint32_t *)pic->data[1], pic->format);
1749
1750     if (s->debug & FF_DEBUG_BUFFERS)
1751         av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p\n", pic);
1752
1753     return 0;
1754 fail:
1755     av_frame_unref(pic);
1756     return AVERROR(ENOMEM);
1757 }
1758
1759 int avcodec_default_get_buffer2(AVCodecContext *avctx, AVFrame *frame, int flags)
1760 {
1761     int ret;
1762
1763     if (avctx->hw_frames_ctx) {
1764         ret = av_hwframe_get_buffer(avctx->hw_frames_ctx, frame, 0);
1765         frame->width  = avctx->coded_width;
1766         frame->height = avctx->coded_height;
1767         return ret;
1768     }
1769
1770     if ((ret = update_frame_pool(avctx, frame)) < 0)
1771         return ret;
1772
1773     switch (avctx->codec_type) {
1774     case AVMEDIA_TYPE_VIDEO:
1775         return video_get_buffer(avctx, frame);
1776     case AVMEDIA_TYPE_AUDIO:
1777         return audio_get_buffer(avctx, frame);
1778     default:
1779         return -1;
1780     }
1781 }
1782
1783 static int add_metadata_from_side_data(const AVPacket *avpkt, AVFrame *frame)
1784 {
1785     int size;
1786     const uint8_t *side_metadata;
1787
1788     AVDictionary **frame_md = &frame->metadata;
1789
1790     side_metadata = av_packet_get_side_data(avpkt,
1791                                             AV_PKT_DATA_STRINGS_METADATA, &size);
1792     return av_packet_unpack_dictionary(side_metadata, size, frame_md);
1793 }
1794
1795 int ff_decode_frame_props(AVCodecContext *avctx, AVFrame *frame)
1796 {
1797     const AVPacket *pkt = avctx->internal->last_pkt_props;
1798     int i;
1799     static const struct {
1800         enum AVPacketSideDataType packet;
1801         enum AVFrameSideDataType frame;
1802     } sd[] = {
1803         { AV_PKT_DATA_REPLAYGAIN ,                AV_FRAME_DATA_REPLAYGAIN },
1804         { AV_PKT_DATA_DISPLAYMATRIX,              AV_FRAME_DATA_DISPLAYMATRIX },
1805         { AV_PKT_DATA_SPHERICAL,                  AV_FRAME_DATA_SPHERICAL },
1806         { AV_PKT_DATA_STEREO3D,                   AV_FRAME_DATA_STEREO3D },
1807         { AV_PKT_DATA_AUDIO_SERVICE_TYPE,         AV_FRAME_DATA_AUDIO_SERVICE_TYPE },
1808         { AV_PKT_DATA_MASTERING_DISPLAY_METADATA, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA },
1809         { AV_PKT_DATA_CONTENT_LIGHT_LEVEL,        AV_FRAME_DATA_CONTENT_LIGHT_LEVEL },
1810         { AV_PKT_DATA_A53_CC,                     AV_FRAME_DATA_A53_CC },
1811         { AV_PKT_DATA_ICC_PROFILE,                AV_FRAME_DATA_ICC_PROFILE },
1812     };
1813
1814     if (pkt) {
1815         frame->pts = pkt->pts;
1816 #if FF_API_PKT_PTS
1817 FF_DISABLE_DEPRECATION_WARNINGS
1818         frame->pkt_pts = pkt->pts;
1819 FF_ENABLE_DEPRECATION_WARNINGS
1820 #endif
1821         frame->pkt_pos      = pkt->pos;
1822         frame->pkt_duration = pkt->duration;
1823         frame->pkt_size     = pkt->size;
1824
1825         for (i = 0; i < FF_ARRAY_ELEMS(sd); i++) {
1826             int size;
1827             uint8_t *packet_sd = av_packet_get_side_data(pkt, sd[i].packet, &size);
1828             if (packet_sd) {
1829                 AVFrameSideData *frame_sd = av_frame_new_side_data(frame,
1830                                                                    sd[i].frame,
1831                                                                    size);
1832                 if (!frame_sd)
1833                     return AVERROR(ENOMEM);
1834
1835                 memcpy(frame_sd->data, packet_sd, size);
1836             }
1837         }
1838         add_metadata_from_side_data(pkt, frame);
1839
1840         if (pkt->flags & AV_PKT_FLAG_DISCARD) {
1841             frame->flags |= AV_FRAME_FLAG_DISCARD;
1842         } else {
1843             frame->flags = (frame->flags & ~AV_FRAME_FLAG_DISCARD);
1844         }
1845     }
1846     frame->reordered_opaque = avctx->reordered_opaque;
1847
1848     if (frame->color_primaries == AVCOL_PRI_UNSPECIFIED)
1849         frame->color_primaries = avctx->color_primaries;
1850     if (frame->color_trc == AVCOL_TRC_UNSPECIFIED)
1851         frame->color_trc = avctx->color_trc;
1852     if (frame->colorspace == AVCOL_SPC_UNSPECIFIED)
1853         frame->colorspace = avctx->colorspace;
1854     if (frame->color_range == AVCOL_RANGE_UNSPECIFIED)
1855         frame->color_range = avctx->color_range;
1856     if (frame->chroma_location == AVCHROMA_LOC_UNSPECIFIED)
1857         frame->chroma_location = avctx->chroma_sample_location;
1858
1859     switch (avctx->codec->type) {
1860     case AVMEDIA_TYPE_VIDEO:
1861         frame->format              = avctx->pix_fmt;
1862         if (!frame->sample_aspect_ratio.num)
1863             frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
1864
1865         if (frame->width && frame->height &&
1866             av_image_check_sar(frame->width, frame->height,
1867                                frame->sample_aspect_ratio) < 0) {
1868             av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
1869                    frame->sample_aspect_ratio.num,
1870                    frame->sample_aspect_ratio.den);
1871             frame->sample_aspect_ratio = (AVRational){ 0, 1 };
1872         }
1873
1874         break;
1875     case AVMEDIA_TYPE_AUDIO:
1876         if (!frame->sample_rate)
1877             frame->sample_rate    = avctx->sample_rate;
1878         if (frame->format < 0)
1879             frame->format         = avctx->sample_fmt;
1880         if (!frame->channel_layout) {
1881             if (avctx->channel_layout) {
1882                  if (av_get_channel_layout_nb_channels(avctx->channel_layout) !=
1883                      avctx->channels) {
1884                      av_log(avctx, AV_LOG_ERROR, "Inconsistent channel "
1885                             "configuration.\n");
1886                      return AVERROR(EINVAL);
1887                  }
1888
1889                 frame->channel_layout = avctx->channel_layout;
1890             } else {
1891                 if (avctx->channels > FF_SANE_NB_CHANNELS) {
1892                     av_log(avctx, AV_LOG_ERROR, "Too many channels: %d.\n",
1893                            avctx->channels);
1894                     return AVERROR(ENOSYS);
1895                 }
1896             }
1897         }
1898         frame->channels = avctx->channels;
1899         break;
1900     }
1901     return 0;
1902 }
1903
1904 static void validate_avframe_allocation(AVCodecContext *avctx, AVFrame *frame)
1905 {
1906     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1907         int i;
1908         int num_planes = av_pix_fmt_count_planes(frame->format);
1909         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
1910         int flags = desc ? desc->flags : 0;
1911         if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PAL))
1912             num_planes = 2;
1913         if ((flags & FF_PSEUDOPAL) && frame->data[1])
1914             num_planes = 2;
1915         for (i = 0; i < num_planes; i++) {
1916             av_assert0(frame->data[i]);
1917         }
1918         // For formats without data like hwaccel allow unused pointers to be non-NULL.
1919         for (i = num_planes; num_planes > 0 && i < FF_ARRAY_ELEMS(frame->data); i++) {
1920             if (frame->data[i])
1921                 av_log(avctx, AV_LOG_ERROR, "Buffer returned by get_buffer2() did not zero unused plane pointers\n");
1922             frame->data[i] = NULL;
1923         }
1924     }
1925 }
1926
1927 static void decode_data_free(void *opaque, uint8_t *data)
1928 {
1929     FrameDecodeData *fdd = (FrameDecodeData*)data;
1930
1931     if (fdd->post_process_opaque_free)
1932         fdd->post_process_opaque_free(fdd->post_process_opaque);
1933
1934     if (fdd->hwaccel_priv_free)
1935         fdd->hwaccel_priv_free(fdd->hwaccel_priv);
1936
1937     av_freep(&fdd);
1938 }
1939
1940 int ff_attach_decode_data(AVFrame *frame)
1941 {
1942     AVBufferRef *fdd_buf;
1943     FrameDecodeData *fdd;
1944
1945     av_assert1(!frame->private_ref);
1946     av_buffer_unref(&frame->private_ref);
1947
1948     fdd = av_mallocz(sizeof(*fdd));
1949     if (!fdd)
1950         return AVERROR(ENOMEM);
1951
1952     fdd_buf = av_buffer_create((uint8_t*)fdd, sizeof(*fdd), decode_data_free,
1953                                NULL, AV_BUFFER_FLAG_READONLY);
1954     if (!fdd_buf) {
1955         av_freep(&fdd);
1956         return AVERROR(ENOMEM);
1957     }
1958
1959     frame->private_ref = fdd_buf;
1960
1961     return 0;
1962 }
1963
1964 int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
1965 {
1966     const AVHWAccel *hwaccel = avctx->hwaccel;
1967     int override_dimensions = 1;
1968     int ret;
1969
1970     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1971         if ((ret = av_image_check_size2(FFALIGN(avctx->width, STRIDE_ALIGN), avctx->height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx)) < 0 || avctx->pix_fmt<0) {
1972             av_log(avctx, AV_LOG_ERROR, "video_get_buffer: image parameters invalid\n");
1973             ret = AVERROR(EINVAL);
1974             goto fail;
1975         }
1976
1977         if (frame->width <= 0 || frame->height <= 0) {
1978             frame->width  = FFMAX(avctx->width,  AV_CEIL_RSHIFT(avctx->coded_width,  avctx->lowres));
1979             frame->height = FFMAX(avctx->height, AV_CEIL_RSHIFT(avctx->coded_height, avctx->lowres));
1980             override_dimensions = 0;
1981         }
1982
1983         if (frame->data[0] || frame->data[1] || frame->data[2] || frame->data[3]) {
1984             av_log(avctx, AV_LOG_ERROR, "pic->data[*]!=NULL in get_buffer_internal\n");
1985             ret = AVERROR(EINVAL);
1986             goto fail;
1987         }
1988     } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
1989         if (frame->nb_samples * (int64_t)avctx->channels > avctx->max_samples) {
1990             av_log(avctx, AV_LOG_ERROR, "samples per frame %d, exceeds max_samples %"PRId64"\n", frame->nb_samples, avctx->max_samples);
1991             ret = AVERROR(EINVAL);
1992             goto fail;
1993         }
1994     }
1995     ret = ff_decode_frame_props(avctx, frame);
1996     if (ret < 0)
1997         goto fail;
1998
1999     if (hwaccel) {
2000         if (hwaccel->alloc_frame) {
2001             ret = hwaccel->alloc_frame(avctx, frame);
2002             goto fail;
2003         }
2004     } else
2005         avctx->sw_pix_fmt = avctx->pix_fmt;
2006
2007     ret = avctx->get_buffer2(avctx, frame, flags);
2008     if (ret < 0)
2009         goto fail;
2010
2011     validate_avframe_allocation(avctx, frame);
2012
2013     ret = ff_attach_decode_data(frame);
2014     if (ret < 0)
2015         goto fail;
2016
2017     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO && !override_dimensions &&
2018         !(avctx->codec->caps_internal & FF_CODEC_CAP_EXPORTS_CROPPING)) {
2019         frame->width  = avctx->width;
2020         frame->height = avctx->height;
2021     }
2022
2023     return 0;
2024 fail:
2025     av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
2026     av_frame_unref(frame);
2027     return ret;
2028 }
2029
2030 static int reget_buffer_internal(AVCodecContext *avctx, AVFrame *frame, int flags)
2031 {
2032     AVFrame *tmp;
2033     int ret;
2034
2035     av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
2036
2037     if (frame->data[0] && (frame->width != avctx->width || frame->height != avctx->height || frame->format != avctx->pix_fmt)) {
2038         av_log(avctx, AV_LOG_WARNING, "Picture changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s in reget buffer()\n",
2039                frame->width, frame->height, av_get_pix_fmt_name(frame->format), avctx->width, avctx->height, av_get_pix_fmt_name(avctx->pix_fmt));
2040         av_frame_unref(frame);
2041     }
2042
2043     if (!frame->data[0])
2044         return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
2045
2046     if ((flags & FF_REGET_BUFFER_FLAG_READONLY) || av_frame_is_writable(frame))
2047         return ff_decode_frame_props(avctx, frame);
2048
2049     tmp = av_frame_alloc();
2050     if (!tmp)
2051         return AVERROR(ENOMEM);
2052
2053     av_frame_move_ref(tmp, frame);
2054
2055     ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
2056     if (ret < 0) {
2057         av_frame_free(&tmp);
2058         return ret;
2059     }
2060
2061     av_frame_copy(frame, tmp);
2062     av_frame_free(&tmp);
2063
2064     return 0;
2065 }
2066
2067 int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
2068 {
2069     int ret = reget_buffer_internal(avctx, frame, flags);
2070     if (ret < 0)
2071         av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
2072     return ret;
2073 }
2074
2075 static void bsfs_flush(AVCodecContext *avctx)
2076 {
2077     DecodeFilterContext *s = &avctx->internal->filter;
2078
2079     for (int i = 0; i < s->nb_bsfs; i++)
2080         av_bsf_flush(s->bsfs[i]);
2081 }
2082
2083 void avcodec_flush_buffers(AVCodecContext *avctx)
2084 {
2085     AVCodecInternal *avci = avctx->internal;
2086
2087     if (av_codec_is_encoder(avctx->codec)) {
2088         int caps = avctx->codec->capabilities;
2089
2090         if (!(caps & AV_CODEC_CAP_ENCODER_FLUSH)) {
2091             // Only encoders that explicitly declare support for it can be
2092             // flushed. Otherwise, this is a no-op.
2093             av_log(avctx, AV_LOG_WARNING, "Ignoring attempt to flush encoder "
2094                    "that doesn't support it\n");
2095             return;
2096         }
2097
2098         // We haven't implemented flushing for frame-threaded encoders.
2099         av_assert0(!(caps & AV_CODEC_CAP_FRAME_THREADS));
2100     }
2101
2102     avci->draining      = 0;
2103     avci->draining_done = 0;
2104     avci->nb_draining_errors = 0;
2105     av_frame_unref(avci->buffer_frame);
2106     av_frame_unref(avci->compat_decode_frame);
2107     av_packet_unref(avci->buffer_pkt);
2108     avci->buffer_pkt_valid = 0;
2109
2110     av_packet_unref(avci->ds.in_pkt);
2111
2112     if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
2113         ff_thread_flush(avctx);
2114     else if (avctx->codec->flush)
2115         avctx->codec->flush(avctx);
2116
2117     avctx->pts_correction_last_pts =
2118     avctx->pts_correction_last_dts = INT64_MIN;
2119
2120     bsfs_flush(avctx);
2121
2122     if (!avctx->refcounted_frames)
2123         av_frame_unref(avci->to_free);
2124 }
2125
2126 void ff_decode_bsfs_uninit(AVCodecContext *avctx)
2127 {
2128     DecodeFilterContext *s = &avctx->internal->filter;
2129     int i;
2130
2131     for (i = 0; i < s->nb_bsfs; i++)
2132         av_bsf_free(&s->bsfs[i]);
2133     av_freep(&s->bsfs);
2134     s->nb_bsfs = 0;
2135 }