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