]> git.sesse.net Git - ffmpeg/blob - libavcodec/decode.c
avcodec/decode: also update consumed bytes on last_pkt_props->size
[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
39 #include "avcodec.h"
40 #include "bytestream.h"
41 #include "decode.h"
42 #include "internal.h"
43 #include "thread.h"
44
45 static int apply_param_change(AVCodecContext *avctx, const AVPacket *avpkt)
46 {
47     int size = 0, ret;
48     const uint8_t *data;
49     uint32_t flags;
50     int64_t val;
51
52     data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
53     if (!data)
54         return 0;
55
56     if (!(avctx->codec->capabilities & AV_CODEC_CAP_PARAM_CHANGE)) {
57         av_log(avctx, AV_LOG_ERROR, "This decoder does not support parameter "
58                "changes, but PARAM_CHANGE side data was sent to it.\n");
59         ret = AVERROR(EINVAL);
60         goto fail2;
61     }
62
63     if (size < 4)
64         goto fail;
65
66     flags = bytestream_get_le32(&data);
67     size -= 4;
68
69     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
70         if (size < 4)
71             goto fail;
72         val = bytestream_get_le32(&data);
73         if (val <= 0 || val > INT_MAX) {
74             av_log(avctx, AV_LOG_ERROR, "Invalid channel count");
75             ret = AVERROR_INVALIDDATA;
76             goto fail2;
77         }
78         avctx->channels = val;
79         size -= 4;
80     }
81     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
82         if (size < 8)
83             goto fail;
84         avctx->channel_layout = bytestream_get_le64(&data);
85         size -= 8;
86     }
87     if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
88         if (size < 4)
89             goto fail;
90         val = bytestream_get_le32(&data);
91         if (val <= 0 || val > INT_MAX) {
92             av_log(avctx, AV_LOG_ERROR, "Invalid sample rate");
93             ret = AVERROR_INVALIDDATA;
94             goto fail2;
95         }
96         avctx->sample_rate = val;
97         size -= 4;
98     }
99     if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
100         if (size < 8)
101             goto fail;
102         avctx->width  = bytestream_get_le32(&data);
103         avctx->height = bytestream_get_le32(&data);
104         size -= 8;
105         ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
106         if (ret < 0)
107             goto fail2;
108     }
109
110     return 0;
111 fail:
112     av_log(avctx, AV_LOG_ERROR, "PARAM_CHANGE side data too small.\n");
113     ret = AVERROR_INVALIDDATA;
114 fail2:
115     if (ret < 0) {
116         av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n");
117         if (avctx->err_recognition & AV_EF_EXPLODE)
118             return ret;
119     }
120     return 0;
121 }
122
123 static int extract_packet_props(AVCodecInternal *avci, const AVPacket *pkt)
124 {
125     int ret = 0;
126
127     av_packet_unref(avci->last_pkt_props);
128     if (pkt) {
129         ret = av_packet_copy_props(avci->last_pkt_props, pkt);
130         if (!ret)
131             avci->last_pkt_props->size = pkt->size; // HACK: Needed for ff_init_buffer_info().
132     }
133     return ret;
134 }
135
136 static int unrefcount_frame(AVCodecInternal *avci, AVFrame *frame)
137 {
138     int ret;
139
140     /* move the original frame to our backup */
141     av_frame_unref(avci->to_free);
142     av_frame_move_ref(avci->to_free, frame);
143
144     /* now copy everything except the AVBufferRefs back
145      * note that we make a COPY of the side data, so calling av_frame_free() on
146      * the caller's frame will work properly */
147     ret = av_frame_copy_props(frame, avci->to_free);
148     if (ret < 0)
149         return ret;
150
151     memcpy(frame->data,     avci->to_free->data,     sizeof(frame->data));
152     memcpy(frame->linesize, avci->to_free->linesize, sizeof(frame->linesize));
153     if (avci->to_free->extended_data != avci->to_free->data) {
154         int planes = avci->to_free->channels;
155         int size   = planes * sizeof(*frame->extended_data);
156
157         if (!size) {
158             av_frame_unref(frame);
159             return AVERROR_BUG;
160         }
161
162         frame->extended_data = av_malloc(size);
163         if (!frame->extended_data) {
164             av_frame_unref(frame);
165             return AVERROR(ENOMEM);
166         }
167         memcpy(frame->extended_data, avci->to_free->extended_data,
168                size);
169     } else
170         frame->extended_data = frame->data;
171
172     frame->format         = avci->to_free->format;
173     frame->width          = avci->to_free->width;
174     frame->height         = avci->to_free->height;
175     frame->channel_layout = avci->to_free->channel_layout;
176     frame->nb_samples     = avci->to_free->nb_samples;
177     frame->channels       = avci->to_free->channels;
178
179     return 0;
180 }
181
182 static int bsfs_init(AVCodecContext *avctx)
183 {
184     AVCodecInternal *avci = avctx->internal;
185     DecodeFilterContext *s = &avci->filter;
186     const char *bsfs_str;
187     int ret;
188
189     if (s->nb_bsfs)
190         return 0;
191
192     bsfs_str = avctx->codec->bsfs ? avctx->codec->bsfs : "null";
193     while (bsfs_str && *bsfs_str) {
194         AVBSFContext **tmp;
195         const AVBitStreamFilter *filter;
196         char *bsf;
197
198         bsf = av_get_token(&bsfs_str, ",");
199         if (!bsf) {
200             ret = AVERROR(ENOMEM);
201             goto fail;
202         }
203
204         filter = av_bsf_get_by_name(bsf);
205         if (!filter) {
206             av_log(avctx, AV_LOG_ERROR, "A non-existing bitstream filter %s "
207                    "requested by a decoder. This is a bug, please report it.\n",
208                    bsf);
209             ret = AVERROR_BUG;
210             av_freep(&bsf);
211             goto fail;
212         }
213         av_freep(&bsf);
214
215         tmp = av_realloc_array(s->bsfs, s->nb_bsfs + 1, sizeof(*s->bsfs));
216         if (!tmp) {
217             ret = AVERROR(ENOMEM);
218             goto fail;
219         }
220         s->bsfs = tmp;
221         s->nb_bsfs++;
222
223         ret = av_bsf_alloc(filter, &s->bsfs[s->nb_bsfs - 1]);
224         if (ret < 0)
225             goto fail;
226
227         if (s->nb_bsfs == 1) {
228             /* We do not currently have an API for passing the input timebase into decoders,
229              * but no filters used here should actually need it.
230              * So we make up some plausible-looking number (the MPEG 90kHz timebase) */
231             s->bsfs[s->nb_bsfs - 1]->time_base_in = (AVRational){ 1, 90000 };
232             ret = avcodec_parameters_from_context(s->bsfs[s->nb_bsfs - 1]->par_in,
233                                                   avctx);
234         } else {
235             s->bsfs[s->nb_bsfs - 1]->time_base_in = s->bsfs[s->nb_bsfs - 2]->time_base_out;
236             ret = avcodec_parameters_copy(s->bsfs[s->nb_bsfs - 1]->par_in,
237                                           s->bsfs[s->nb_bsfs - 2]->par_out);
238         }
239         if (ret < 0)
240             goto fail;
241
242         ret = av_bsf_init(s->bsfs[s->nb_bsfs - 1]);
243         if (ret < 0)
244             goto fail;
245     }
246
247     return 0;
248 fail:
249     ff_decode_bsfs_uninit(avctx);
250     return ret;
251 }
252
253 /* try to get one output packet from the filter chain */
254 static int bsfs_poll(AVCodecContext *avctx, AVPacket *pkt)
255 {
256     DecodeFilterContext *s = &avctx->internal->filter;
257     int idx, ret;
258
259     /* start with the last filter in the chain */
260     idx = s->nb_bsfs - 1;
261     while (idx >= 0) {
262         /* request a packet from the currently selected filter */
263         ret = av_bsf_receive_packet(s->bsfs[idx], pkt);
264         if (ret == AVERROR(EAGAIN)) {
265             /* no packets available, try the next filter up the chain */
266             ret = 0;
267             idx--;
268             continue;
269         } else if (ret < 0 && ret != AVERROR_EOF) {
270             return ret;
271         }
272
273         /* got a packet or EOF -- pass it to the caller or to the next filter
274          * down the chain */
275         if (idx == s->nb_bsfs - 1) {
276             return ret;
277         } else {
278             idx++;
279             ret = av_bsf_send_packet(s->bsfs[idx], ret < 0 ? NULL : pkt);
280             if (ret < 0) {
281                 av_log(avctx, AV_LOG_ERROR,
282                        "Error pre-processing a packet before decoding\n");
283                 av_packet_unref(pkt);
284                 return ret;
285             }
286         }
287     }
288
289     return AVERROR(EAGAIN);
290 }
291
292 int ff_decode_get_packet(AVCodecContext *avctx, AVPacket *pkt)
293 {
294     AVCodecInternal *avci = avctx->internal;
295     int ret;
296
297     if (avci->draining)
298         return AVERROR_EOF;
299
300     ret = bsfs_poll(avctx, pkt);
301     if (ret == AVERROR_EOF)
302         avci->draining = 1;
303     if (ret < 0)
304         return ret;
305
306     ret = extract_packet_props(avctx->internal, pkt);
307     if (ret < 0)
308         goto finish;
309
310     ret = apply_param_change(avctx, pkt);
311     if (ret < 0)
312         goto finish;
313
314     if (avctx->codec->receive_frame)
315         avci->compat_decode_consumed += pkt->size;
316
317     return 0;
318 finish:
319     av_packet_unref(pkt);
320     return ret;
321 }
322
323 /**
324  * Attempt to guess proper monotonic timestamps for decoded video frames
325  * which might have incorrect times. Input timestamps may wrap around, in
326  * which case the output will as well.
327  *
328  * @param pts the pts field of the decoded AVPacket, as passed through
329  * AVFrame.pts
330  * @param dts the dts field of the decoded AVPacket
331  * @return one of the input values, may be AV_NOPTS_VALUE
332  */
333 static int64_t guess_correct_pts(AVCodecContext *ctx,
334                                  int64_t reordered_pts, int64_t dts)
335 {
336     int64_t pts = AV_NOPTS_VALUE;
337
338     if (dts != AV_NOPTS_VALUE) {
339         ctx->pts_correction_num_faulty_dts += dts <= ctx->pts_correction_last_dts;
340         ctx->pts_correction_last_dts = dts;
341     } else if (reordered_pts != AV_NOPTS_VALUE)
342         ctx->pts_correction_last_dts = reordered_pts;
343
344     if (reordered_pts != AV_NOPTS_VALUE) {
345         ctx->pts_correction_num_faulty_pts += reordered_pts <= ctx->pts_correction_last_pts;
346         ctx->pts_correction_last_pts = reordered_pts;
347     } else if(dts != AV_NOPTS_VALUE)
348         ctx->pts_correction_last_pts = dts;
349
350     if ((ctx->pts_correction_num_faulty_pts<=ctx->pts_correction_num_faulty_dts || dts == AV_NOPTS_VALUE)
351        && reordered_pts != AV_NOPTS_VALUE)
352         pts = reordered_pts;
353     else
354         pts = dts;
355
356     return pts;
357 }
358
359 /*
360  * The core of the receive_frame_wrapper for the decoders implementing
361  * the simple API. Certain decoders might consume partial packets without
362  * returning any output, so this function needs to be called in a loop until it
363  * returns EAGAIN.
364  **/
365 static int decode_simple_internal(AVCodecContext *avctx, AVFrame *frame)
366 {
367     AVCodecInternal   *avci = avctx->internal;
368     DecodeSimpleContext *ds = &avci->ds;
369     AVPacket           *pkt = ds->in_pkt;
370     // copy to ensure we do not change pkt
371     AVPacket tmp;
372     int got_frame, did_split;
373     int ret;
374
375     if (!pkt->data && !avci->draining) {
376         av_packet_unref(pkt);
377         ret = ff_decode_get_packet(avctx, pkt);
378         if (ret < 0 && ret != AVERROR_EOF)
379             return ret;
380     }
381
382     // Some codecs (at least wma lossless) will crash when feeding drain packets
383     // after EOF was signaled.
384     if (avci->draining_done)
385         return AVERROR_EOF;
386
387     if (!pkt->data &&
388         !(avctx->codec->capabilities & AV_CODEC_CAP_DELAY ||
389           avctx->active_thread_type & FF_THREAD_FRAME))
390         return AVERROR_EOF;
391
392     tmp = *pkt;
393 #if FF_API_MERGE_SD
394 FF_DISABLE_DEPRECATION_WARNINGS
395     did_split = av_packet_split_side_data(&tmp);
396
397     if (did_split) {
398         ret = extract_packet_props(avctx->internal, &tmp);
399         if (ret < 0)
400             return ret;
401
402         ret = apply_param_change(avctx, &tmp);
403         if (ret < 0)
404             return ret;
405     }
406 FF_ENABLE_DEPRECATION_WARNINGS
407 #endif
408
409     got_frame = 0;
410
411     if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME) {
412         ret = ff_thread_decode_frame(avctx, frame, &got_frame, &tmp);
413     } else {
414         ret = avctx->codec->decode(avctx, frame, &got_frame, &tmp);
415
416         if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
417             if (!(avctx->codec->caps_internal & FF_CODEC_CAP_SETS_PKT_DTS))
418                 frame->pkt_dts = pkt->dts;
419             if(!avctx->has_b_frames)
420                 frame->pkt_pos = pkt->pos;
421             //FIXME these should be under if(!avctx->has_b_frames)
422             /* get_buffer is supposed to set frame parameters */
423             if (!(avctx->codec->capabilities & AV_CODEC_CAP_DR1)) {
424                 if (!frame->sample_aspect_ratio.num)  frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
425                 if (!frame->width)                    frame->width               = avctx->width;
426                 if (!frame->height)                   frame->height              = avctx->height;
427                 if (frame->format == AV_PIX_FMT_NONE) frame->format              = avctx->pix_fmt;
428             }
429         } else if (avctx->codec->type == AVMEDIA_TYPE_AUDIO) {
430             frame->pkt_dts = pkt->dts;
431         }
432     }
433     emms_c();
434
435     if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
436         if (frame->flags & AV_FRAME_FLAG_DISCARD)
437             got_frame = 0;
438         if (got_frame)
439             frame->best_effort_timestamp = guess_correct_pts(avctx,
440                                                              frame->pts,
441                                                              frame->pkt_dts);
442     } else if (avctx->codec->type == AVMEDIA_TYPE_AUDIO) {
443         uint8_t *side;
444         int side_size;
445         uint32_t discard_padding = 0;
446         uint8_t skip_reason = 0;
447         uint8_t discard_reason = 0;
448
449         if (ret >= 0 && got_frame) {
450             frame->best_effort_timestamp = guess_correct_pts(avctx,
451                                                              frame->pts,
452                                                              frame->pkt_dts);
453             if (frame->format == AV_SAMPLE_FMT_NONE)
454                 frame->format = avctx->sample_fmt;
455             if (!frame->channel_layout)
456                 frame->channel_layout = avctx->channel_layout;
457             if (!frame->channels)
458                 frame->channels = avctx->channels;
459             if (!frame->sample_rate)
460                 frame->sample_rate = avctx->sample_rate;
461         }
462
463         side= av_packet_get_side_data(pkt, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
464         if(side && side_size>=10) {
465             avctx->internal->skip_samples = AV_RL32(side) * avctx->internal->skip_samples_multiplier;
466             discard_padding = AV_RL32(side + 4);
467             av_log(avctx, AV_LOG_DEBUG, "skip %d / discard %d samples due to side data\n",
468                    avctx->internal->skip_samples, (int)discard_padding);
469             skip_reason = AV_RL8(side + 8);
470             discard_reason = AV_RL8(side + 9);
471         }
472
473         if ((frame->flags & AV_FRAME_FLAG_DISCARD) && got_frame &&
474             !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
475             avctx->internal->skip_samples = FFMAX(0, avctx->internal->skip_samples - frame->nb_samples);
476             got_frame = 0;
477         }
478
479         if (avctx->internal->skip_samples > 0 && got_frame &&
480             !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
481             if(frame->nb_samples <= avctx->internal->skip_samples){
482                 got_frame = 0;
483                 avctx->internal->skip_samples -= frame->nb_samples;
484                 av_log(avctx, AV_LOG_DEBUG, "skip whole frame, skip left: %d\n",
485                        avctx->internal->skip_samples);
486             } else {
487                 av_samples_copy(frame->extended_data, frame->extended_data, 0, avctx->internal->skip_samples,
488                                 frame->nb_samples - avctx->internal->skip_samples, avctx->channels, frame->format);
489                 if(avctx->pkt_timebase.num && avctx->sample_rate) {
490                     int64_t diff_ts = av_rescale_q(avctx->internal->skip_samples,
491                                                    (AVRational){1, avctx->sample_rate},
492                                                    avctx->pkt_timebase);
493                     if(frame->pts!=AV_NOPTS_VALUE)
494                         frame->pts += diff_ts;
495 #if FF_API_PKT_PTS
496 FF_DISABLE_DEPRECATION_WARNINGS
497                     if(frame->pkt_pts!=AV_NOPTS_VALUE)
498                         frame->pkt_pts += diff_ts;
499 FF_ENABLE_DEPRECATION_WARNINGS
500 #endif
501                     if(frame->pkt_dts!=AV_NOPTS_VALUE)
502                         frame->pkt_dts += diff_ts;
503                     if (frame->pkt_duration >= diff_ts)
504                         frame->pkt_duration -= diff_ts;
505                 } else {
506                     av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for skipped samples.\n");
507                 }
508                 av_log(avctx, AV_LOG_DEBUG, "skip %d/%d samples\n",
509                        avctx->internal->skip_samples, frame->nb_samples);
510                 frame->nb_samples -= avctx->internal->skip_samples;
511                 avctx->internal->skip_samples = 0;
512             }
513         }
514
515         if (discard_padding > 0 && discard_padding <= frame->nb_samples && got_frame &&
516             !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
517             if (discard_padding == frame->nb_samples) {
518                 got_frame = 0;
519             } else {
520                 if(avctx->pkt_timebase.num && avctx->sample_rate) {
521                     int64_t diff_ts = av_rescale_q(frame->nb_samples - discard_padding,
522                                                    (AVRational){1, avctx->sample_rate},
523                                                    avctx->pkt_timebase);
524                     frame->pkt_duration = diff_ts;
525                 } else {
526                     av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for discarded samples.\n");
527                 }
528                 av_log(avctx, AV_LOG_DEBUG, "discard %d/%d samples\n",
529                        (int)discard_padding, frame->nb_samples);
530                 frame->nb_samples -= discard_padding;
531             }
532         }
533
534         if ((avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL) && got_frame) {
535             AVFrameSideData *fside = av_frame_new_side_data(frame, AV_FRAME_DATA_SKIP_SAMPLES, 10);
536             if (fside) {
537                 AV_WL32(fside->data, avctx->internal->skip_samples);
538                 AV_WL32(fside->data + 4, discard_padding);
539                 AV_WL8(fside->data + 8, skip_reason);
540                 AV_WL8(fside->data + 9, discard_reason);
541                 avctx->internal->skip_samples = 0;
542             }
543         }
544     }
545 #if FF_API_MERGE_SD
546     if (did_split) {
547         av_packet_free_side_data(&tmp);
548         if(ret == tmp.size)
549             ret = pkt->size;
550     }
551 #endif
552
553     if (avctx->codec->type == AVMEDIA_TYPE_AUDIO &&
554         !avci->showed_multi_packet_warning &&
555         ret >= 0 && ret != pkt->size && !(avctx->codec->capabilities & AV_CODEC_CAP_SUBFRAMES)) {
556         av_log(avctx, AV_LOG_WARNING, "Multiple frames in a packet.\n");
557         avci->showed_multi_packet_warning = 1;
558     }
559
560     if (!got_frame)
561         av_frame_unref(frame);
562
563     if (ret >= 0 && avctx->codec->type == AVMEDIA_TYPE_VIDEO && !(avctx->flags & AV_CODEC_FLAG_TRUNCATED))
564         ret = pkt->size;
565
566 #if FF_API_AVCTX_TIMEBASE
567     if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
568         avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1}));
569 #endif
570
571     if (avctx->internal->draining && !got_frame)
572         avci->draining_done = 1;
573
574     avci->compat_decode_consumed += ret;
575
576     if (ret >= pkt->size || ret < 0) {
577         av_packet_unref(pkt);
578     } else {
579         int consumed = ret;
580
581         pkt->data                += consumed;
582         pkt->size                -= consumed;
583         avci->last_pkt_props->size -= consumed; // See extract_packet_props() comment.
584         pkt->pts                  = AV_NOPTS_VALUE;
585         pkt->dts                  = AV_NOPTS_VALUE;
586         avci->last_pkt_props->pts = AV_NOPTS_VALUE;
587         avci->last_pkt_props->dts = AV_NOPTS_VALUE;
588     }
589
590     if (got_frame)
591         av_assert0(frame->buf[0]);
592
593     return ret < 0 ? ret : 0;
594 }
595
596 static int decode_simple_receive_frame(AVCodecContext *avctx, AVFrame *frame)
597 {
598     int ret;
599
600     while (!frame->buf[0]) {
601         ret = decode_simple_internal(avctx, frame);
602         if (ret < 0)
603             return ret;
604     }
605
606     return 0;
607 }
608
609 static int decode_receive_frame_internal(AVCodecContext *avctx, AVFrame *frame)
610 {
611     AVCodecInternal *avci = avctx->internal;
612     int ret;
613
614     av_assert0(!frame->buf[0]);
615
616     if (avctx->codec->receive_frame)
617         ret = avctx->codec->receive_frame(avctx, frame);
618     else
619         ret = decode_simple_receive_frame(avctx, frame);
620
621     if (ret == AVERROR_EOF)
622         avci->draining_done = 1;
623
624     return ret;
625 }
626
627 int attribute_align_arg avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)
628 {
629     AVCodecInternal *avci = avctx->internal;
630     int ret;
631
632     if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
633         return AVERROR(EINVAL);
634
635     if (avctx->internal->draining)
636         return AVERROR_EOF;
637
638     if (avpkt && !avpkt->size && avpkt->data)
639         return AVERROR(EINVAL);
640
641     ret = bsfs_init(avctx);
642     if (ret < 0)
643         return ret;
644
645     av_packet_unref(avci->buffer_pkt);
646     if (avpkt && (avpkt->data || avpkt->side_data_elems)) {
647         ret = av_packet_ref(avci->buffer_pkt, avpkt);
648         if (ret < 0)
649             return ret;
650     }
651
652     ret = av_bsf_send_packet(avci->filter.bsfs[0], avci->buffer_pkt);
653     if (ret < 0) {
654         av_packet_unref(avci->buffer_pkt);
655         return ret;
656     }
657
658     if (!avci->buffer_frame->buf[0]) {
659         ret = decode_receive_frame_internal(avctx, avci->buffer_frame);
660         if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
661             return ret;
662     }
663
664     return 0;
665 }
666
667 int attribute_align_arg avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
668 {
669     AVCodecInternal *avci = avctx->internal;
670     int ret;
671
672     av_frame_unref(frame);
673
674     if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
675         return AVERROR(EINVAL);
676
677     ret = bsfs_init(avctx);
678     if (ret < 0)
679         return ret;
680
681     if (avci->buffer_frame->buf[0]) {
682         av_frame_move_ref(frame, avci->buffer_frame);
683     } else {
684         ret = decode_receive_frame_internal(avctx, frame);
685         if (ret < 0)
686             return ret;
687     }
688
689     avctx->frame_number++;
690
691     return 0;
692 }
693
694 static int compat_decode(AVCodecContext *avctx, AVFrame *frame,
695                          int *got_frame, const AVPacket *pkt)
696 {
697     AVCodecInternal *avci = avctx->internal;
698     int ret;
699
700     av_assert0(avci->compat_decode_consumed == 0);
701
702     *got_frame = 0;
703     avci->compat_decode = 1;
704
705     if (avci->compat_decode_partial_size > 0 &&
706         avci->compat_decode_partial_size != pkt->size) {
707         av_log(avctx, AV_LOG_ERROR,
708                "Got unexpected packet size after a partial decode\n");
709         ret = AVERROR(EINVAL);
710         goto finish;
711     }
712
713     if (!avci->compat_decode_partial_size) {
714         ret = avcodec_send_packet(avctx, pkt);
715         if (ret == AVERROR_EOF)
716             ret = 0;
717         else if (ret == AVERROR(EAGAIN)) {
718             /* we fully drain all the output in each decode call, so this should not
719              * ever happen */
720             ret = AVERROR_BUG;
721             goto finish;
722         } else if (ret < 0)
723             goto finish;
724     }
725
726     while (ret >= 0) {
727         ret = avcodec_receive_frame(avctx, frame);
728         if (ret < 0) {
729             if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
730                 ret = 0;
731             goto finish;
732         }
733
734         if (frame != avci->compat_decode_frame) {
735             if (!avctx->refcounted_frames) {
736                 ret = unrefcount_frame(avci, frame);
737                 if (ret < 0)
738                     goto finish;
739             }
740
741             *got_frame = 1;
742             frame = avci->compat_decode_frame;
743         } else {
744             if (!avci->compat_decode_warned) {
745                 av_log(avctx, AV_LOG_WARNING, "The deprecated avcodec_decode_* "
746                        "API cannot return all the frames for this decoder. "
747                        "Some frames will be dropped. Update your code to the "
748                        "new decoding API to fix this.\n");
749                 avci->compat_decode_warned = 1;
750             }
751         }
752
753         if (avci->draining || (!avctx->codec->bsfs && avci->compat_decode_consumed < pkt->size))
754             break;
755     }
756
757 finish:
758     if (ret == 0) {
759         /* if there are any bsfs then assume full packet is always consumed */
760         if (avctx->codec->bsfs)
761             ret = pkt->size;
762         else
763             ret = FFMIN(avci->compat_decode_consumed, pkt->size);
764     }
765     avci->compat_decode_consumed = 0;
766     avci->compat_decode_partial_size = (ret >= 0) ? pkt->size - ret : 0;
767
768     return ret;
769 }
770
771 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
772                                               int *got_picture_ptr,
773                                               const AVPacket *avpkt)
774 {
775     return compat_decode(avctx, picture, got_picture_ptr, avpkt);
776 }
777
778 int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
779                                               AVFrame *frame,
780                                               int *got_frame_ptr,
781                                               const AVPacket *avpkt)
782 {
783     return compat_decode(avctx, frame, got_frame_ptr, avpkt);
784 }
785
786 static void get_subtitle_defaults(AVSubtitle *sub)
787 {
788     memset(sub, 0, sizeof(*sub));
789     sub->pts = AV_NOPTS_VALUE;
790 }
791
792 #define UTF8_MAX_BYTES 4 /* 5 and 6 bytes sequences should not be used */
793 static int recode_subtitle(AVCodecContext *avctx,
794                            AVPacket *outpkt, const AVPacket *inpkt)
795 {
796 #if CONFIG_ICONV
797     iconv_t cd = (iconv_t)-1;
798     int ret = 0;
799     char *inb, *outb;
800     size_t inl, outl;
801     AVPacket tmp;
802 #endif
803
804     if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_PRE_DECODER || inpkt->size == 0)
805         return 0;
806
807 #if CONFIG_ICONV
808     cd = iconv_open("UTF-8", avctx->sub_charenc);
809     av_assert0(cd != (iconv_t)-1);
810
811     inb = inpkt->data;
812     inl = inpkt->size;
813
814     if (inl >= INT_MAX / UTF8_MAX_BYTES - AV_INPUT_BUFFER_PADDING_SIZE) {
815         av_log(avctx, AV_LOG_ERROR, "Subtitles packet is too big for recoding\n");
816         ret = AVERROR(ENOMEM);
817         goto end;
818     }
819
820     ret = av_new_packet(&tmp, inl * UTF8_MAX_BYTES);
821     if (ret < 0)
822         goto end;
823     outpkt->buf  = tmp.buf;
824     outpkt->data = tmp.data;
825     outpkt->size = tmp.size;
826     outb = outpkt->data;
827     outl = outpkt->size;
828
829     if (iconv(cd, &inb, &inl, &outb, &outl) == (size_t)-1 ||
830         iconv(cd, NULL, NULL, &outb, &outl) == (size_t)-1 ||
831         outl >= outpkt->size || inl != 0) {
832         ret = FFMIN(AVERROR(errno), -1);
833         av_log(avctx, AV_LOG_ERROR, "Unable to recode subtitle event \"%s\" "
834                "from %s to UTF-8\n", inpkt->data, avctx->sub_charenc);
835         av_packet_unref(&tmp);
836         goto end;
837     }
838     outpkt->size -= outl;
839     memset(outpkt->data + outpkt->size, 0, outl);
840
841 end:
842     if (cd != (iconv_t)-1)
843         iconv_close(cd);
844     return ret;
845 #else
846     av_log(avctx, AV_LOG_ERROR, "requesting subtitles recoding without iconv");
847     return AVERROR(EINVAL);
848 #endif
849 }
850
851 static int utf8_check(const uint8_t *str)
852 {
853     const uint8_t *byte;
854     uint32_t codepoint, min;
855
856     while (*str) {
857         byte = str;
858         GET_UTF8(codepoint, *(byte++), return 0;);
859         min = byte - str == 1 ? 0 : byte - str == 2 ? 0x80 :
860               1 << (5 * (byte - str) - 4);
861         if (codepoint < min || codepoint >= 0x110000 ||
862             codepoint == 0xFFFE /* BOM */ ||
863             codepoint >= 0xD800 && codepoint <= 0xDFFF /* surrogates */)
864             return 0;
865         str = byte;
866     }
867     return 1;
868 }
869
870 #if FF_API_ASS_TIMING
871 static void insert_ts(AVBPrint *buf, int ts)
872 {
873     if (ts == -1) {
874         av_bprintf(buf, "9:59:59.99,");
875     } else {
876         int h, m, s;
877
878         h = ts/360000;  ts -= 360000*h;
879         m = ts/  6000;  ts -=   6000*m;
880         s = ts/   100;  ts -=    100*s;
881         av_bprintf(buf, "%d:%02d:%02d.%02d,", h, m, s, ts);
882     }
883 }
884
885 static int convert_sub_to_old_ass_form(AVSubtitle *sub, const AVPacket *pkt, AVRational tb)
886 {
887     int i;
888     AVBPrint buf;
889
890     av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
891
892     for (i = 0; i < sub->num_rects; i++) {
893         char *final_dialog;
894         const char *dialog;
895         AVSubtitleRect *rect = sub->rects[i];
896         int ts_start, ts_duration = -1;
897         long int layer;
898
899         if (rect->type != SUBTITLE_ASS || !strncmp(rect->ass, "Dialogue: ", 10))
900             continue;
901
902         av_bprint_clear(&buf);
903
904         /* skip ReadOrder */
905         dialog = strchr(rect->ass, ',');
906         if (!dialog)
907             continue;
908         dialog++;
909
910         /* extract Layer or Marked */
911         layer = strtol(dialog, (char**)&dialog, 10);
912         if (*dialog != ',')
913             continue;
914         dialog++;
915
916         /* rescale timing to ASS time base (ms) */
917         ts_start = av_rescale_q(pkt->pts, tb, av_make_q(1, 100));
918         if (pkt->duration != -1)
919             ts_duration = av_rescale_q(pkt->duration, tb, av_make_q(1, 100));
920         sub->end_display_time = FFMAX(sub->end_display_time, 10 * ts_duration);
921
922         /* construct ASS (standalone file form with timestamps) string */
923         av_bprintf(&buf, "Dialogue: %ld,", layer);
924         insert_ts(&buf, ts_start);
925         insert_ts(&buf, ts_duration == -1 ? -1 : ts_start + ts_duration);
926         av_bprintf(&buf, "%s\r\n", dialog);
927
928         final_dialog = av_strdup(buf.str);
929         if (!av_bprint_is_complete(&buf) || !final_dialog) {
930             av_freep(&final_dialog);
931             av_bprint_finalize(&buf, NULL);
932             return AVERROR(ENOMEM);
933         }
934         av_freep(&rect->ass);
935         rect->ass = final_dialog;
936     }
937
938     av_bprint_finalize(&buf, NULL);
939     return 0;
940 }
941 #endif
942
943 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
944                              int *got_sub_ptr,
945                              AVPacket *avpkt)
946 {
947     int i, ret = 0;
948
949     if (!avpkt->data && avpkt->size) {
950         av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
951         return AVERROR(EINVAL);
952     }
953     if (!avctx->codec)
954         return AVERROR(EINVAL);
955     if (avctx->codec->type != AVMEDIA_TYPE_SUBTITLE) {
956         av_log(avctx, AV_LOG_ERROR, "Invalid media type for subtitles\n");
957         return AVERROR(EINVAL);
958     }
959
960     *got_sub_ptr = 0;
961     get_subtitle_defaults(sub);
962
963     if ((avctx->codec->capabilities & AV_CODEC_CAP_DELAY) || avpkt->size) {
964         AVPacket pkt_recoded;
965         AVPacket tmp = *avpkt;
966 #if FF_API_MERGE_SD
967 FF_DISABLE_DEPRECATION_WARNINGS
968         int did_split = av_packet_split_side_data(&tmp);
969         //apply_param_change(avctx, &tmp);
970
971         if (did_split) {
972             /* FFMIN() prevents overflow in case the packet wasn't allocated with
973              * proper padding.
974              * If the side data is smaller than the buffer padding size, the
975              * remaining bytes should have already been filled with zeros by the
976              * original packet allocation anyway. */
977             memset(tmp.data + tmp.size, 0,
978                    FFMIN(avpkt->size - tmp.size, AV_INPUT_BUFFER_PADDING_SIZE));
979         }
980 FF_ENABLE_DEPRECATION_WARNINGS
981 #endif
982
983         pkt_recoded = tmp;
984         ret = recode_subtitle(avctx, &pkt_recoded, &tmp);
985         if (ret < 0) {
986             *got_sub_ptr = 0;
987         } else {
988              ret = extract_packet_props(avctx->internal, &pkt_recoded);
989              if (ret < 0)
990                 return ret;
991
992             if (avctx->pkt_timebase.num && avpkt->pts != AV_NOPTS_VALUE)
993                 sub->pts = av_rescale_q(avpkt->pts,
994                                         avctx->pkt_timebase, AV_TIME_BASE_Q);
995             ret = avctx->codec->decode(avctx, sub, got_sub_ptr, &pkt_recoded);
996             av_assert1((ret >= 0) >= !!*got_sub_ptr &&
997                        !!*got_sub_ptr >= !!sub->num_rects);
998
999 #if FF_API_ASS_TIMING
1000             if (avctx->sub_text_format == FF_SUB_TEXT_FMT_ASS_WITH_TIMINGS
1001                 && *got_sub_ptr && sub->num_rects) {
1002                 const AVRational tb = avctx->pkt_timebase.num ? avctx->pkt_timebase
1003                                                               : avctx->time_base;
1004                 int err = convert_sub_to_old_ass_form(sub, avpkt, tb);
1005                 if (err < 0)
1006                     ret = err;
1007             }
1008 #endif
1009
1010             if (sub->num_rects && !sub->end_display_time && avpkt->duration &&
1011                 avctx->pkt_timebase.num) {
1012                 AVRational ms = { 1, 1000 };
1013                 sub->end_display_time = av_rescale_q(avpkt->duration,
1014                                                      avctx->pkt_timebase, ms);
1015             }
1016
1017             if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB)
1018                 sub->format = 0;
1019             else if (avctx->codec_descriptor->props & AV_CODEC_PROP_TEXT_SUB)
1020                 sub->format = 1;
1021
1022             for (i = 0; i < sub->num_rects; i++) {
1023                 if (sub->rects[i]->ass && !utf8_check(sub->rects[i]->ass)) {
1024                     av_log(avctx, AV_LOG_ERROR,
1025                            "Invalid UTF-8 in decoded subtitles text; "
1026                            "maybe missing -sub_charenc option\n");
1027                     avsubtitle_free(sub);
1028                     ret = AVERROR_INVALIDDATA;
1029                     break;
1030                 }
1031             }
1032
1033             if (tmp.data != pkt_recoded.data) { // did we recode?
1034                 /* prevent from destroying side data from original packet */
1035                 pkt_recoded.side_data = NULL;
1036                 pkt_recoded.side_data_elems = 0;
1037
1038                 av_packet_unref(&pkt_recoded);
1039             }
1040         }
1041
1042 #if FF_API_MERGE_SD
1043         if (did_split) {
1044             av_packet_free_side_data(&tmp);
1045             if(ret == tmp.size)
1046                 ret = avpkt->size;
1047         }
1048 #endif
1049
1050         if (*got_sub_ptr)
1051             avctx->frame_number++;
1052     }
1053
1054     return ret;
1055 }
1056
1057 static int is_hwaccel_pix_fmt(enum AVPixelFormat pix_fmt)
1058 {
1059     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
1060     return desc->flags & AV_PIX_FMT_FLAG_HWACCEL;
1061 }
1062
1063 enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
1064 {
1065     while (*fmt != AV_PIX_FMT_NONE && is_hwaccel_pix_fmt(*fmt))
1066         ++fmt;
1067     return fmt[0];
1068 }
1069
1070 static AVHWAccel *find_hwaccel(enum AVCodecID codec_id,
1071                                enum AVPixelFormat pix_fmt)
1072 {
1073     AVHWAccel *hwaccel = NULL;
1074
1075     while ((hwaccel = av_hwaccel_next(hwaccel)))
1076         if (hwaccel->id == codec_id
1077             && hwaccel->pix_fmt == pix_fmt)
1078             return hwaccel;
1079     return NULL;
1080 }
1081
1082 static int setup_hwaccel(AVCodecContext *avctx,
1083                          const enum AVPixelFormat fmt,
1084                          const char *name)
1085 {
1086     AVHWAccel *hwa = find_hwaccel(avctx->codec_id, fmt);
1087     int ret        = 0;
1088
1089     if (!hwa) {
1090         av_log(avctx, AV_LOG_ERROR,
1091                "Could not find an AVHWAccel for the pixel format: %s",
1092                name);
1093         return AVERROR(ENOENT);
1094     }
1095
1096     if (hwa->capabilities & HWACCEL_CODEC_CAP_EXPERIMENTAL &&
1097         avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
1098         av_log(avctx, AV_LOG_WARNING, "Ignoring experimental hwaccel: %s\n",
1099                hwa->name);
1100         return AVERROR_PATCHWELCOME;
1101     }
1102
1103     if (hwa->priv_data_size) {
1104         avctx->internal->hwaccel_priv_data = av_mallocz(hwa->priv_data_size);
1105         if (!avctx->internal->hwaccel_priv_data)
1106             return AVERROR(ENOMEM);
1107     }
1108
1109     if (hwa->init) {
1110         ret = hwa->init(avctx);
1111         if (ret < 0) {
1112             av_freep(&avctx->internal->hwaccel_priv_data);
1113             return ret;
1114         }
1115     }
1116
1117     avctx->hwaccel = hwa;
1118
1119     return 0;
1120 }
1121
1122 int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
1123 {
1124     const AVPixFmtDescriptor *desc;
1125     enum AVPixelFormat *choices;
1126     enum AVPixelFormat ret;
1127     unsigned n = 0;
1128
1129     while (fmt[n] != AV_PIX_FMT_NONE)
1130         ++n;
1131
1132     av_assert0(n >= 1);
1133     avctx->sw_pix_fmt = fmt[n - 1];
1134     av_assert2(!is_hwaccel_pix_fmt(avctx->sw_pix_fmt));
1135
1136     choices = av_malloc_array(n + 1, sizeof(*choices));
1137     if (!choices)
1138         return AV_PIX_FMT_NONE;
1139
1140     memcpy(choices, fmt, (n + 1) * sizeof(*choices));
1141
1142     for (;;) {
1143         if (avctx->hwaccel && avctx->hwaccel->uninit)
1144             avctx->hwaccel->uninit(avctx);
1145         av_freep(&avctx->internal->hwaccel_priv_data);
1146         avctx->hwaccel = NULL;
1147
1148         av_buffer_unref(&avctx->hw_frames_ctx);
1149
1150         ret = avctx->get_format(avctx, choices);
1151
1152         desc = av_pix_fmt_desc_get(ret);
1153         if (!desc) {
1154             ret = AV_PIX_FMT_NONE;
1155             break;
1156         }
1157
1158         if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
1159             break;
1160 #if FF_API_CAP_VDPAU
1161         if (avctx->codec->capabilities&AV_CODEC_CAP_HWACCEL_VDPAU)
1162             break;
1163 #endif
1164
1165         if (avctx->hw_frames_ctx) {
1166             AVHWFramesContext *hw_frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1167             if (hw_frames_ctx->format != ret) {
1168                 av_log(avctx, AV_LOG_ERROR, "Format returned from get_buffer() "
1169                        "does not match the format of provided AVHWFramesContext\n");
1170                 ret = AV_PIX_FMT_NONE;
1171                 break;
1172             }
1173         }
1174
1175         if (!setup_hwaccel(avctx, ret, desc->name))
1176             break;
1177
1178         /* Remove failed hwaccel from choices */
1179         for (n = 0; choices[n] != ret; n++)
1180             av_assert0(choices[n] != AV_PIX_FMT_NONE);
1181
1182         do
1183             choices[n] = choices[n + 1];
1184         while (choices[n++] != AV_PIX_FMT_NONE);
1185     }
1186
1187     av_freep(&choices);
1188     return ret;
1189 }
1190
1191 static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame)
1192 {
1193     FramePool *pool = avctx->internal->pool;
1194     int i, ret;
1195
1196     switch (avctx->codec_type) {
1197     case AVMEDIA_TYPE_VIDEO: {
1198         uint8_t *data[4];
1199         int linesize[4];
1200         int size[4] = { 0 };
1201         int w = frame->width;
1202         int h = frame->height;
1203         int tmpsize, unaligned;
1204
1205         if (pool->format == frame->format &&
1206             pool->width == frame->width && pool->height == frame->height)
1207             return 0;
1208
1209         avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align);
1210
1211         do {
1212             // NOTE: do not align linesizes individually, this breaks e.g. assumptions
1213             // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
1214             ret = av_image_fill_linesizes(linesize, avctx->pix_fmt, w);
1215             if (ret < 0)
1216                 return ret;
1217             // increase alignment of w for next try (rhs gives the lowest bit set in w)
1218             w += w & ~(w - 1);
1219
1220             unaligned = 0;
1221             for (i = 0; i < 4; i++)
1222                 unaligned |= linesize[i] % pool->stride_align[i];
1223         } while (unaligned);
1224
1225         tmpsize = av_image_fill_pointers(data, avctx->pix_fmt, h,
1226                                          NULL, linesize);
1227         if (tmpsize < 0)
1228             return -1;
1229
1230         for (i = 0; i < 3 && data[i + 1]; i++)
1231             size[i] = data[i + 1] - data[i];
1232         size[i] = tmpsize - (data[i] - data[0]);
1233
1234         for (i = 0; i < 4; i++) {
1235             av_buffer_pool_uninit(&pool->pools[i]);
1236             pool->linesize[i] = linesize[i];
1237             if (size[i]) {
1238                 pool->pools[i] = av_buffer_pool_init(size[i] + 16 + STRIDE_ALIGN - 1,
1239                                                      CONFIG_MEMORY_POISONING ?
1240                                                         NULL :
1241                                                         av_buffer_allocz);
1242                 if (!pool->pools[i]) {
1243                     ret = AVERROR(ENOMEM);
1244                     goto fail;
1245                 }
1246             }
1247         }
1248         pool->format = frame->format;
1249         pool->width  = frame->width;
1250         pool->height = frame->height;
1251
1252         break;
1253         }
1254     case AVMEDIA_TYPE_AUDIO: {
1255         int ch     = frame->channels; //av_get_channel_layout_nb_channels(frame->channel_layout);
1256         int planar = av_sample_fmt_is_planar(frame->format);
1257         int planes = planar ? ch : 1;
1258
1259         if (pool->format == frame->format && pool->planes == planes &&
1260             pool->channels == ch && frame->nb_samples == pool->samples)
1261             return 0;
1262
1263         av_buffer_pool_uninit(&pool->pools[0]);
1264         ret = av_samples_get_buffer_size(&pool->linesize[0], ch,
1265                                          frame->nb_samples, frame->format, 0);
1266         if (ret < 0)
1267             goto fail;
1268
1269         pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL);
1270         if (!pool->pools[0]) {
1271             ret = AVERROR(ENOMEM);
1272             goto fail;
1273         }
1274
1275         pool->format     = frame->format;
1276         pool->planes     = planes;
1277         pool->channels   = ch;
1278         pool->samples = frame->nb_samples;
1279         break;
1280         }
1281     default: av_assert0(0);
1282     }
1283     return 0;
1284 fail:
1285     for (i = 0; i < 4; i++)
1286         av_buffer_pool_uninit(&pool->pools[i]);
1287     pool->format = -1;
1288     pool->planes = pool->channels = pool->samples = 0;
1289     pool->width  = pool->height = 0;
1290     return ret;
1291 }
1292
1293 static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
1294 {
1295     FramePool *pool = avctx->internal->pool;
1296     int planes = pool->planes;
1297     int i;
1298
1299     frame->linesize[0] = pool->linesize[0];
1300
1301     if (planes > AV_NUM_DATA_POINTERS) {
1302         frame->extended_data = av_mallocz_array(planes, sizeof(*frame->extended_data));
1303         frame->nb_extended_buf = planes - AV_NUM_DATA_POINTERS;
1304         frame->extended_buf  = av_mallocz_array(frame->nb_extended_buf,
1305                                           sizeof(*frame->extended_buf));
1306         if (!frame->extended_data || !frame->extended_buf) {
1307             av_freep(&frame->extended_data);
1308             av_freep(&frame->extended_buf);
1309             return AVERROR(ENOMEM);
1310         }
1311     } else {
1312         frame->extended_data = frame->data;
1313         av_assert0(frame->nb_extended_buf == 0);
1314     }
1315
1316     for (i = 0; i < FFMIN(planes, AV_NUM_DATA_POINTERS); i++) {
1317         frame->buf[i] = av_buffer_pool_get(pool->pools[0]);
1318         if (!frame->buf[i])
1319             goto fail;
1320         frame->extended_data[i] = frame->data[i] = frame->buf[i]->data;
1321     }
1322     for (i = 0; i < frame->nb_extended_buf; i++) {
1323         frame->extended_buf[i] = av_buffer_pool_get(pool->pools[0]);
1324         if (!frame->extended_buf[i])
1325             goto fail;
1326         frame->extended_data[i + AV_NUM_DATA_POINTERS] = frame->extended_buf[i]->data;
1327     }
1328
1329     if (avctx->debug & FF_DEBUG_BUFFERS)
1330         av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p", frame);
1331
1332     return 0;
1333 fail:
1334     av_frame_unref(frame);
1335     return AVERROR(ENOMEM);
1336 }
1337
1338 static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
1339 {
1340     FramePool *pool = s->internal->pool;
1341     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pic->format);
1342     int i;
1343
1344     if (pic->data[0] || pic->data[1] || pic->data[2] || pic->data[3]) {
1345         av_log(s, AV_LOG_ERROR, "pic->data[*]!=NULL in avcodec_default_get_buffer\n");
1346         return -1;
1347     }
1348
1349     if (!desc) {
1350         av_log(s, AV_LOG_ERROR,
1351             "Unable to get pixel format descriptor for format %s\n",
1352             av_get_pix_fmt_name(pic->format));
1353         return AVERROR(EINVAL);
1354     }
1355
1356     memset(pic->data, 0, sizeof(pic->data));
1357     pic->extended_data = pic->data;
1358
1359     for (i = 0; i < 4 && pool->pools[i]; i++) {
1360         pic->linesize[i] = pool->linesize[i];
1361
1362         pic->buf[i] = av_buffer_pool_get(pool->pools[i]);
1363         if (!pic->buf[i])
1364             goto fail;
1365
1366         pic->data[i] = pic->buf[i]->data;
1367     }
1368     for (; i < AV_NUM_DATA_POINTERS; i++) {
1369         pic->data[i] = NULL;
1370         pic->linesize[i] = 0;
1371     }
1372     if (desc->flags & AV_PIX_FMT_FLAG_PAL ||
1373         desc->flags & AV_PIX_FMT_FLAG_PSEUDOPAL)
1374         avpriv_set_systematic_pal2((uint32_t *)pic->data[1], pic->format);
1375
1376     if (s->debug & FF_DEBUG_BUFFERS)
1377         av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p\n", pic);
1378
1379     return 0;
1380 fail:
1381     av_frame_unref(pic);
1382     return AVERROR(ENOMEM);
1383 }
1384
1385 int avcodec_default_get_buffer2(AVCodecContext *avctx, AVFrame *frame, int flags)
1386 {
1387     int ret;
1388
1389     if (avctx->hw_frames_ctx)
1390         return av_hwframe_get_buffer(avctx->hw_frames_ctx, frame, 0);
1391
1392     if ((ret = update_frame_pool(avctx, frame)) < 0)
1393         return ret;
1394
1395     switch (avctx->codec_type) {
1396     case AVMEDIA_TYPE_VIDEO:
1397         return video_get_buffer(avctx, frame);
1398     case AVMEDIA_TYPE_AUDIO:
1399         return audio_get_buffer(avctx, frame);
1400     default:
1401         return -1;
1402     }
1403 }
1404
1405 static int add_metadata_from_side_data(const AVPacket *avpkt, AVFrame *frame)
1406 {
1407     int size;
1408     const uint8_t *side_metadata;
1409
1410     AVDictionary **frame_md = &frame->metadata;
1411
1412     side_metadata = av_packet_get_side_data(avpkt,
1413                                             AV_PKT_DATA_STRINGS_METADATA, &size);
1414     return av_packet_unpack_dictionary(side_metadata, size, frame_md);
1415 }
1416
1417 int ff_init_buffer_info(AVCodecContext *avctx, AVFrame *frame)
1418 {
1419     const AVPacket *pkt = avctx->internal->last_pkt_props;
1420     int i;
1421     static const struct {
1422         enum AVPacketSideDataType packet;
1423         enum AVFrameSideDataType frame;
1424     } sd[] = {
1425         { AV_PKT_DATA_REPLAYGAIN ,                AV_FRAME_DATA_REPLAYGAIN },
1426         { AV_PKT_DATA_DISPLAYMATRIX,              AV_FRAME_DATA_DISPLAYMATRIX },
1427         { AV_PKT_DATA_SPHERICAL,                  AV_FRAME_DATA_SPHERICAL },
1428         { AV_PKT_DATA_STEREO3D,                   AV_FRAME_DATA_STEREO3D },
1429         { AV_PKT_DATA_AUDIO_SERVICE_TYPE,         AV_FRAME_DATA_AUDIO_SERVICE_TYPE },
1430         { AV_PKT_DATA_MASTERING_DISPLAY_METADATA, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA },
1431         { AV_PKT_DATA_CONTENT_LIGHT_LEVEL,        AV_FRAME_DATA_CONTENT_LIGHT_LEVEL },
1432     };
1433
1434     if (pkt) {
1435         frame->pts = pkt->pts;
1436 #if FF_API_PKT_PTS
1437 FF_DISABLE_DEPRECATION_WARNINGS
1438         frame->pkt_pts = pkt->pts;
1439 FF_ENABLE_DEPRECATION_WARNINGS
1440 #endif
1441         frame->pkt_pos      = pkt->pos;
1442         frame->pkt_duration = pkt->duration;
1443         frame->pkt_size     = pkt->size;
1444
1445         for (i = 0; i < FF_ARRAY_ELEMS(sd); i++) {
1446             int size;
1447             uint8_t *packet_sd = av_packet_get_side_data(pkt, sd[i].packet, &size);
1448             if (packet_sd) {
1449                 AVFrameSideData *frame_sd = av_frame_new_side_data(frame,
1450                                                                    sd[i].frame,
1451                                                                    size);
1452                 if (!frame_sd)
1453                     return AVERROR(ENOMEM);
1454
1455                 memcpy(frame_sd->data, packet_sd, size);
1456             }
1457         }
1458         add_metadata_from_side_data(pkt, frame);
1459
1460         if (pkt->flags & AV_PKT_FLAG_DISCARD) {
1461             frame->flags |= AV_FRAME_FLAG_DISCARD;
1462         } else {
1463             frame->flags = (frame->flags & ~AV_FRAME_FLAG_DISCARD);
1464         }
1465     }
1466     frame->reordered_opaque = avctx->reordered_opaque;
1467
1468     if (frame->color_primaries == AVCOL_PRI_UNSPECIFIED)
1469         frame->color_primaries = avctx->color_primaries;
1470     if (frame->color_trc == AVCOL_TRC_UNSPECIFIED)
1471         frame->color_trc = avctx->color_trc;
1472     if (frame->colorspace == AVCOL_SPC_UNSPECIFIED)
1473         frame->colorspace = avctx->colorspace;
1474     if (frame->color_range == AVCOL_RANGE_UNSPECIFIED)
1475         frame->color_range = avctx->color_range;
1476     if (frame->chroma_location == AVCHROMA_LOC_UNSPECIFIED)
1477         frame->chroma_location = avctx->chroma_sample_location;
1478
1479     switch (avctx->codec->type) {
1480     case AVMEDIA_TYPE_VIDEO:
1481         frame->format              = avctx->pix_fmt;
1482         if (!frame->sample_aspect_ratio.num)
1483             frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
1484
1485         if (frame->width && frame->height &&
1486             av_image_check_sar(frame->width, frame->height,
1487                                frame->sample_aspect_ratio) < 0) {
1488             av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
1489                    frame->sample_aspect_ratio.num,
1490                    frame->sample_aspect_ratio.den);
1491             frame->sample_aspect_ratio = (AVRational){ 0, 1 };
1492         }
1493
1494         break;
1495     case AVMEDIA_TYPE_AUDIO:
1496         if (!frame->sample_rate)
1497             frame->sample_rate    = avctx->sample_rate;
1498         if (frame->format < 0)
1499             frame->format         = avctx->sample_fmt;
1500         if (!frame->channel_layout) {
1501             if (avctx->channel_layout) {
1502                  if (av_get_channel_layout_nb_channels(avctx->channel_layout) !=
1503                      avctx->channels) {
1504                      av_log(avctx, AV_LOG_ERROR, "Inconsistent channel "
1505                             "configuration.\n");
1506                      return AVERROR(EINVAL);
1507                  }
1508
1509                 frame->channel_layout = avctx->channel_layout;
1510             } else {
1511                 if (avctx->channels > FF_SANE_NB_CHANNELS) {
1512                     av_log(avctx, AV_LOG_ERROR, "Too many channels: %d.\n",
1513                            avctx->channels);
1514                     return AVERROR(ENOSYS);
1515                 }
1516             }
1517         }
1518         frame->channels = avctx->channels;
1519         break;
1520     }
1521     return 0;
1522 }
1523
1524 int ff_decode_frame_props(AVCodecContext *avctx, AVFrame *frame)
1525 {
1526     return ff_init_buffer_info(avctx, frame);
1527 }
1528
1529 static void validate_avframe_allocation(AVCodecContext *avctx, AVFrame *frame)
1530 {
1531     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1532         int i;
1533         int num_planes = av_pix_fmt_count_planes(frame->format);
1534         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
1535         int flags = desc ? desc->flags : 0;
1536         if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PAL))
1537             num_planes = 2;
1538         for (i = 0; i < num_planes; i++) {
1539             av_assert0(frame->data[i]);
1540         }
1541         // For now do not enforce anything for palette of pseudopal formats
1542         if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PSEUDOPAL))
1543             num_planes = 2;
1544         // For formats without data like hwaccel allow unused pointers to be non-NULL.
1545         for (i = num_planes; num_planes > 0 && i < FF_ARRAY_ELEMS(frame->data); i++) {
1546             if (frame->data[i])
1547                 av_log(avctx, AV_LOG_ERROR, "Buffer returned by get_buffer2() did not zero unused plane pointers\n");
1548             frame->data[i] = NULL;
1549         }
1550     }
1551 }
1552
1553 static int get_buffer_internal(AVCodecContext *avctx, AVFrame *frame, int flags)
1554 {
1555     const AVHWAccel *hwaccel = avctx->hwaccel;
1556     int override_dimensions = 1;
1557     int ret;
1558
1559     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1560         if ((ret = av_image_check_size2(avctx->width, avctx->height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx)) < 0 || avctx->pix_fmt<0) {
1561             av_log(avctx, AV_LOG_ERROR, "video_get_buffer: image parameters invalid\n");
1562             return AVERROR(EINVAL);
1563         }
1564
1565         if (frame->width <= 0 || frame->height <= 0) {
1566             frame->width  = FFMAX(avctx->width,  AV_CEIL_RSHIFT(avctx->coded_width,  avctx->lowres));
1567             frame->height = FFMAX(avctx->height, AV_CEIL_RSHIFT(avctx->coded_height, avctx->lowres));
1568             override_dimensions = 0;
1569         }
1570
1571         if (frame->data[0] || frame->data[1] || frame->data[2] || frame->data[3]) {
1572             av_log(avctx, AV_LOG_ERROR, "pic->data[*]!=NULL in get_buffer_internal\n");
1573             return AVERROR(EINVAL);
1574         }
1575     }
1576     ret = ff_decode_frame_props(avctx, frame);
1577     if (ret < 0)
1578         return ret;
1579
1580     if (hwaccel) {
1581         if (hwaccel->alloc_frame) {
1582             ret = hwaccel->alloc_frame(avctx, frame);
1583             goto end;
1584         }
1585     } else
1586         avctx->sw_pix_fmt = avctx->pix_fmt;
1587
1588     ret = avctx->get_buffer2(avctx, frame, flags);
1589     if (ret >= 0)
1590         validate_avframe_allocation(avctx, frame);
1591
1592 end:
1593     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO && !override_dimensions) {
1594         frame->width  = avctx->width;
1595         frame->height = avctx->height;
1596     }
1597
1598     return ret;
1599 }
1600
1601 int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
1602 {
1603     int ret = get_buffer_internal(avctx, frame, flags);
1604     if (ret < 0) {
1605         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1606         frame->width = frame->height = 0;
1607     }
1608     return ret;
1609 }
1610
1611 static int reget_buffer_internal(AVCodecContext *avctx, AVFrame *frame)
1612 {
1613     AVFrame *tmp;
1614     int ret;
1615
1616     av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
1617
1618     if (frame->data[0] && (frame->width != avctx->width || frame->height != avctx->height || frame->format != avctx->pix_fmt)) {
1619         av_log(avctx, AV_LOG_WARNING, "Picture changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s in reget buffer()\n",
1620                frame->width, frame->height, av_get_pix_fmt_name(frame->format), avctx->width, avctx->height, av_get_pix_fmt_name(avctx->pix_fmt));
1621         av_frame_unref(frame);
1622     }
1623
1624     ff_init_buffer_info(avctx, frame);
1625
1626     if (!frame->data[0])
1627         return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1628
1629     if (av_frame_is_writable(frame))
1630         return ff_decode_frame_props(avctx, frame);
1631
1632     tmp = av_frame_alloc();
1633     if (!tmp)
1634         return AVERROR(ENOMEM);
1635
1636     av_frame_move_ref(tmp, frame);
1637
1638     ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1639     if (ret < 0) {
1640         av_frame_free(&tmp);
1641         return ret;
1642     }
1643
1644     av_frame_copy(frame, tmp);
1645     av_frame_free(&tmp);
1646
1647     return 0;
1648 }
1649
1650 int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame)
1651 {
1652     int ret = reget_buffer_internal(avctx, frame);
1653     if (ret < 0)
1654         av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
1655     return ret;
1656 }
1657
1658 void avcodec_flush_buffers(AVCodecContext *avctx)
1659 {
1660     avctx->internal->draining      = 0;
1661     avctx->internal->draining_done = 0;
1662     av_frame_unref(avctx->internal->buffer_frame);
1663     av_frame_unref(avctx->internal->compat_decode_frame);
1664     av_packet_unref(avctx->internal->buffer_pkt);
1665     avctx->internal->buffer_pkt_valid = 0;
1666
1667     av_packet_unref(avctx->internal->ds.in_pkt);
1668
1669     if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
1670         ff_thread_flush(avctx);
1671     else if (avctx->codec->flush)
1672         avctx->codec->flush(avctx);
1673
1674     avctx->pts_correction_last_pts =
1675     avctx->pts_correction_last_dts = INT64_MIN;
1676
1677     ff_decode_bsfs_uninit(avctx);
1678
1679     if (!avctx->refcounted_frames)
1680         av_frame_unref(avctx->internal->to_free);
1681 }
1682
1683 void ff_decode_bsfs_uninit(AVCodecContext *avctx)
1684 {
1685     DecodeFilterContext *s = &avctx->internal->filter;
1686     int i;
1687
1688     for (i = 0; i < s->nb_bsfs; i++)
1689         av_bsf_free(&s->bsfs[i]);
1690     av_freep(&s->bsfs);
1691     s->nb_bsfs = 0;
1692 }