]> git.sesse.net Git - ffmpeg/blob - libavutil/frame.c
61c45f0f53247540b139b2a28eae3d3d6a3bed71
[ffmpeg] / libavutil / frame.c
1 /*
2  * This file is part of FFmpeg.
3  *
4  * FFmpeg is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * FFmpeg is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with FFmpeg; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  */
18
19 #include "channel_layout.h"
20 #include "avassert.h"
21 #include "buffer.h"
22 #include "common.h"
23 #include "dict.h"
24 #include "frame.h"
25 #include "imgutils.h"
26 #include "mem.h"
27 #include "samplefmt.h"
28
29 #if FF_API_FRAME_GET_SET
30 MAKE_ACCESSORS(AVFrame, frame, int64_t, best_effort_timestamp)
31 MAKE_ACCESSORS(AVFrame, frame, int64_t, pkt_duration)
32 MAKE_ACCESSORS(AVFrame, frame, int64_t, pkt_pos)
33 MAKE_ACCESSORS(AVFrame, frame, int64_t, channel_layout)
34 MAKE_ACCESSORS(AVFrame, frame, int,     channels)
35 MAKE_ACCESSORS(AVFrame, frame, int,     sample_rate)
36 MAKE_ACCESSORS(AVFrame, frame, AVDictionary *, metadata)
37 MAKE_ACCESSORS(AVFrame, frame, int,     decode_error_flags)
38 MAKE_ACCESSORS(AVFrame, frame, int,     pkt_size)
39 MAKE_ACCESSORS(AVFrame, frame, enum AVColorSpace, colorspace)
40 MAKE_ACCESSORS(AVFrame, frame, enum AVColorRange, color_range)
41 #endif
42
43 #define CHECK_CHANNELS_CONSISTENCY(frame) \
44     av_assert2(!(frame)->channel_layout || \
45                (frame)->channels == \
46                av_get_channel_layout_nb_channels((frame)->channel_layout))
47
48 #if FF_API_FRAME_QP
49 int av_frame_set_qp_table(AVFrame *f, AVBufferRef *buf, int stride, int qp_type)
50 {
51     av_buffer_unref(&f->qp_table_buf);
52
53     f->qp_table_buf = buf;
54
55 FF_DISABLE_DEPRECATION_WARNINGS
56     f->qscale_table = buf->data;
57     f->qstride      = stride;
58     f->qscale_type  = qp_type;
59 FF_ENABLE_DEPRECATION_WARNINGS
60
61     return 0;
62 }
63
64 int8_t *av_frame_get_qp_table(AVFrame *f, int *stride, int *type)
65 {
66 FF_DISABLE_DEPRECATION_WARNINGS
67     *stride = f->qstride;
68     *type   = f->qscale_type;
69 FF_ENABLE_DEPRECATION_WARNINGS
70
71     if (!f->qp_table_buf)
72         return NULL;
73
74     return f->qp_table_buf->data;
75 }
76 #endif
77
78 const char *av_get_colorspace_name(enum AVColorSpace val)
79 {
80     static const char * const name[] = {
81         [AVCOL_SPC_RGB]       = "GBR",
82         [AVCOL_SPC_BT709]     = "bt709",
83         [AVCOL_SPC_FCC]       = "fcc",
84         [AVCOL_SPC_BT470BG]   = "bt470bg",
85         [AVCOL_SPC_SMPTE170M] = "smpte170m",
86         [AVCOL_SPC_SMPTE240M] = "smpte240m",
87         [AVCOL_SPC_YCOCG]     = "YCgCo",
88     };
89     if ((unsigned)val >= FF_ARRAY_ELEMS(name))
90         return NULL;
91     return name[val];
92 }
93
94 static void get_frame_defaults(AVFrame *frame)
95 {
96     if (frame->extended_data != frame->data)
97         av_freep(&frame->extended_data);
98
99     memset(frame, 0, sizeof(*frame));
100
101     frame->pts                   =
102     frame->pkt_dts               = AV_NOPTS_VALUE;
103 #if FF_API_PKT_PTS
104 FF_DISABLE_DEPRECATION_WARNINGS
105     frame->pkt_pts               = AV_NOPTS_VALUE;
106 FF_ENABLE_DEPRECATION_WARNINGS
107 #endif
108     frame->best_effort_timestamp = AV_NOPTS_VALUE;
109     frame->pkt_duration        = 0;
110     frame->pkt_pos             = -1;
111     frame->pkt_size            = -1;
112     frame->key_frame           = 1;
113     frame->sample_aspect_ratio = (AVRational){ 0, 1 };
114     frame->format              = -1; /* unknown */
115     frame->extended_data       = frame->data;
116     frame->color_primaries     = AVCOL_PRI_UNSPECIFIED;
117     frame->color_trc           = AVCOL_TRC_UNSPECIFIED;
118     frame->colorspace          = AVCOL_SPC_UNSPECIFIED;
119     frame->color_range         = AVCOL_RANGE_UNSPECIFIED;
120     frame->chroma_location     = AVCHROMA_LOC_UNSPECIFIED;
121     frame->flags               = 0;
122 }
123
124 static void free_side_data(AVFrameSideData **ptr_sd)
125 {
126     AVFrameSideData *sd = *ptr_sd;
127
128     av_buffer_unref(&sd->buf);
129     av_dict_free(&sd->metadata);
130     av_freep(ptr_sd);
131 }
132
133 static void wipe_side_data(AVFrame *frame)
134 {
135     int i;
136
137     for (i = 0; i < frame->nb_side_data; i++) {
138         free_side_data(&frame->side_data[i]);
139     }
140     frame->nb_side_data = 0;
141
142     av_freep(&frame->side_data);
143 }
144
145 AVFrame *av_frame_alloc(void)
146 {
147     AVFrame *frame = av_mallocz(sizeof(*frame));
148
149     if (!frame)
150         return NULL;
151
152     frame->extended_data = NULL;
153     get_frame_defaults(frame);
154
155     return frame;
156 }
157
158 void av_frame_free(AVFrame **frame)
159 {
160     if (!frame || !*frame)
161         return;
162
163     av_frame_unref(*frame);
164     av_freep(frame);
165 }
166
167 static int get_video_buffer(AVFrame *frame, int align)
168 {
169     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
170     int ret, i;
171
172     if (!desc)
173         return AVERROR(EINVAL);
174
175     if ((ret = av_image_check_size(frame->width, frame->height, 0, NULL)) < 0)
176         return ret;
177
178     if (!frame->linesize[0]) {
179         if (align <= 0)
180             align = 32; /* STRIDE_ALIGN. Should be av_cpu_max_align() */
181
182         for(i=1; i<=align; i+=i) {
183             ret = av_image_fill_linesizes(frame->linesize, frame->format,
184                                           FFALIGN(frame->width, i));
185             if (ret < 0)
186                 return ret;
187             if (!(frame->linesize[0] & (align-1)))
188                 break;
189         }
190
191         for (i = 0; i < 4 && frame->linesize[i]; i++)
192             frame->linesize[i] = FFALIGN(frame->linesize[i], align);
193     }
194
195     for (i = 0; i < 4 && frame->linesize[i]; i++) {
196         int h = FFALIGN(frame->height, 32);
197         if (i == 1 || i == 2)
198             h = AV_CEIL_RSHIFT(h, desc->log2_chroma_h);
199
200         frame->buf[i] = av_buffer_alloc(frame->linesize[i] * h + 16 + 16/*STRIDE_ALIGN*/ - 1);
201         if (!frame->buf[i])
202             goto fail;
203
204         frame->data[i] = frame->buf[i]->data;
205     }
206     if (desc->flags & AV_PIX_FMT_FLAG_PAL || desc->flags & AV_PIX_FMT_FLAG_PSEUDOPAL) {
207         av_buffer_unref(&frame->buf[1]);
208         frame->buf[1] = av_buffer_alloc(AVPALETTE_SIZE);
209         if (!frame->buf[1])
210             goto fail;
211         frame->data[1] = frame->buf[1]->data;
212     }
213
214     frame->extended_data = frame->data;
215
216     return 0;
217 fail:
218     av_frame_unref(frame);
219     return AVERROR(ENOMEM);
220 }
221
222 static int get_audio_buffer(AVFrame *frame, int align)
223 {
224     int channels;
225     int planar   = av_sample_fmt_is_planar(frame->format);
226     int planes;
227     int ret, i;
228
229     if (!frame->channels)
230         frame->channels = av_get_channel_layout_nb_channels(frame->channel_layout);
231
232     channels = frame->channels;
233     planes = planar ? channels : 1;
234
235     CHECK_CHANNELS_CONSISTENCY(frame);
236     if (!frame->linesize[0]) {
237         ret = av_samples_get_buffer_size(&frame->linesize[0], channels,
238                                          frame->nb_samples, frame->format,
239                                          align);
240         if (ret < 0)
241             return ret;
242     }
243
244     if (planes > AV_NUM_DATA_POINTERS) {
245         frame->extended_data = av_mallocz_array(planes,
246                                           sizeof(*frame->extended_data));
247         frame->extended_buf  = av_mallocz_array((planes - AV_NUM_DATA_POINTERS),
248                                           sizeof(*frame->extended_buf));
249         if (!frame->extended_data || !frame->extended_buf) {
250             av_freep(&frame->extended_data);
251             av_freep(&frame->extended_buf);
252             return AVERROR(ENOMEM);
253         }
254         frame->nb_extended_buf = planes - AV_NUM_DATA_POINTERS;
255     } else
256         frame->extended_data = frame->data;
257
258     for (i = 0; i < FFMIN(planes, AV_NUM_DATA_POINTERS); i++) {
259         frame->buf[i] = av_buffer_alloc(frame->linesize[0]);
260         if (!frame->buf[i]) {
261             av_frame_unref(frame);
262             return AVERROR(ENOMEM);
263         }
264         frame->extended_data[i] = frame->data[i] = frame->buf[i]->data;
265     }
266     for (i = 0; i < planes - AV_NUM_DATA_POINTERS; i++) {
267         frame->extended_buf[i] = av_buffer_alloc(frame->linesize[0]);
268         if (!frame->extended_buf[i]) {
269             av_frame_unref(frame);
270             return AVERROR(ENOMEM);
271         }
272         frame->extended_data[i + AV_NUM_DATA_POINTERS] = frame->extended_buf[i]->data;
273     }
274     return 0;
275
276 }
277
278 int av_frame_get_buffer(AVFrame *frame, int align)
279 {
280     if (frame->format < 0)
281         return AVERROR(EINVAL);
282
283     if (frame->width > 0 && frame->height > 0)
284         return get_video_buffer(frame, align);
285     else if (frame->nb_samples > 0 && (frame->channel_layout || frame->channels > 0))
286         return get_audio_buffer(frame, align);
287
288     return AVERROR(EINVAL);
289 }
290
291 static int frame_copy_props(AVFrame *dst, const AVFrame *src, int force_copy)
292 {
293     int i;
294
295     dst->key_frame              = src->key_frame;
296     dst->pict_type              = src->pict_type;
297     dst->sample_aspect_ratio    = src->sample_aspect_ratio;
298     dst->crop_top               = src->crop_top;
299     dst->crop_bottom            = src->crop_bottom;
300     dst->crop_left              = src->crop_left;
301     dst->crop_right             = src->crop_right;
302     dst->pts                    = src->pts;
303     dst->repeat_pict            = src->repeat_pict;
304     dst->interlaced_frame       = src->interlaced_frame;
305     dst->top_field_first        = src->top_field_first;
306     dst->palette_has_changed    = src->palette_has_changed;
307     dst->sample_rate            = src->sample_rate;
308     dst->opaque                 = src->opaque;
309 #if FF_API_PKT_PTS
310 FF_DISABLE_DEPRECATION_WARNINGS
311     dst->pkt_pts                = src->pkt_pts;
312 FF_ENABLE_DEPRECATION_WARNINGS
313 #endif
314     dst->pkt_dts                = src->pkt_dts;
315     dst->pkt_pos                = src->pkt_pos;
316     dst->pkt_size               = src->pkt_size;
317     dst->pkt_duration           = src->pkt_duration;
318     dst->reordered_opaque       = src->reordered_opaque;
319     dst->quality                = src->quality;
320     dst->best_effort_timestamp  = src->best_effort_timestamp;
321     dst->coded_picture_number   = src->coded_picture_number;
322     dst->display_picture_number = src->display_picture_number;
323     dst->flags                  = src->flags;
324     dst->decode_error_flags     = src->decode_error_flags;
325     dst->color_primaries        = src->color_primaries;
326     dst->color_trc              = src->color_trc;
327     dst->colorspace             = src->colorspace;
328     dst->color_range            = src->color_range;
329     dst->chroma_location        = src->chroma_location;
330
331     av_dict_copy(&dst->metadata, src->metadata, 0);
332
333 #if FF_API_ERROR_FRAME
334 FF_DISABLE_DEPRECATION_WARNINGS
335     memcpy(dst->error, src->error, sizeof(dst->error));
336 FF_ENABLE_DEPRECATION_WARNINGS
337 #endif
338
339     for (i = 0; i < src->nb_side_data; i++) {
340         const AVFrameSideData *sd_src = src->side_data[i];
341         AVFrameSideData *sd_dst;
342         if (   sd_src->type == AV_FRAME_DATA_PANSCAN
343             && (src->width != dst->width || src->height != dst->height))
344             continue;
345         if (force_copy) {
346             sd_dst = av_frame_new_side_data(dst, sd_src->type,
347                                             sd_src->size);
348             if (!sd_dst) {
349                 wipe_side_data(dst);
350                 return AVERROR(ENOMEM);
351             }
352             memcpy(sd_dst->data, sd_src->data, sd_src->size);
353         } else {
354             AVBufferRef *ref = av_buffer_ref(sd_src->buf);
355             sd_dst = av_frame_new_side_data_from_buf(dst, sd_src->type, ref);
356             if (!sd_dst) {
357                 av_buffer_unref(&ref);
358                 wipe_side_data(dst);
359                 return AVERROR(ENOMEM);
360             }
361         }
362         av_dict_copy(&sd_dst->metadata, sd_src->metadata, 0);
363     }
364
365 #if FF_API_FRAME_QP
366 FF_DISABLE_DEPRECATION_WARNINGS
367     dst->qscale_table = NULL;
368     dst->qstride      = 0;
369     dst->qscale_type  = 0;
370     av_buffer_unref(&dst->qp_table_buf);
371     if (src->qp_table_buf) {
372         dst->qp_table_buf = av_buffer_ref(src->qp_table_buf);
373         if (dst->qp_table_buf) {
374             dst->qscale_table = dst->qp_table_buf->data;
375             dst->qstride      = src->qstride;
376             dst->qscale_type  = src->qscale_type;
377         }
378     }
379 FF_ENABLE_DEPRECATION_WARNINGS
380 #endif
381
382     av_buffer_unref(&dst->opaque_ref);
383     av_buffer_unref(&dst->private_ref);
384     if (src->opaque_ref) {
385         dst->opaque_ref = av_buffer_ref(src->opaque_ref);
386         if (!dst->opaque_ref)
387             return AVERROR(ENOMEM);
388     }
389     if (src->private_ref) {
390         dst->private_ref = av_buffer_ref(src->private_ref);
391         if (!dst->private_ref)
392             return AVERROR(ENOMEM);
393     }
394     return 0;
395 }
396
397 int av_frame_ref(AVFrame *dst, const AVFrame *src)
398 {
399     int i, ret = 0;
400
401     av_assert1(dst->width == 0 && dst->height == 0);
402     av_assert1(dst->channels == 0);
403
404     dst->format         = src->format;
405     dst->width          = src->width;
406     dst->height         = src->height;
407     dst->channels       = src->channels;
408     dst->channel_layout = src->channel_layout;
409     dst->nb_samples     = src->nb_samples;
410
411     ret = frame_copy_props(dst, src, 0);
412     if (ret < 0)
413         return ret;
414
415     /* duplicate the frame data if it's not refcounted */
416     if (!src->buf[0]) {
417         ret = av_frame_get_buffer(dst, 32);
418         if (ret < 0)
419             return ret;
420
421         ret = av_frame_copy(dst, src);
422         if (ret < 0)
423             av_frame_unref(dst);
424
425         return ret;
426     }
427
428     /* ref the buffers */
429     for (i = 0; i < FF_ARRAY_ELEMS(src->buf); i++) {
430         if (!src->buf[i])
431             continue;
432         dst->buf[i] = av_buffer_ref(src->buf[i]);
433         if (!dst->buf[i]) {
434             ret = AVERROR(ENOMEM);
435             goto fail;
436         }
437     }
438
439     if (src->extended_buf) {
440         dst->extended_buf = av_mallocz_array(sizeof(*dst->extended_buf),
441                                        src->nb_extended_buf);
442         if (!dst->extended_buf) {
443             ret = AVERROR(ENOMEM);
444             goto fail;
445         }
446         dst->nb_extended_buf = src->nb_extended_buf;
447
448         for (i = 0; i < src->nb_extended_buf; i++) {
449             dst->extended_buf[i] = av_buffer_ref(src->extended_buf[i]);
450             if (!dst->extended_buf[i]) {
451                 ret = AVERROR(ENOMEM);
452                 goto fail;
453             }
454         }
455     }
456
457     if (src->hw_frames_ctx) {
458         dst->hw_frames_ctx = av_buffer_ref(src->hw_frames_ctx);
459         if (!dst->hw_frames_ctx) {
460             ret = AVERROR(ENOMEM);
461             goto fail;
462         }
463     }
464
465     /* duplicate extended data */
466     if (src->extended_data != src->data) {
467         int ch = src->channels;
468
469         if (!ch) {
470             ret = AVERROR(EINVAL);
471             goto fail;
472         }
473         CHECK_CHANNELS_CONSISTENCY(src);
474
475         dst->extended_data = av_malloc_array(sizeof(*dst->extended_data), ch);
476         if (!dst->extended_data) {
477             ret = AVERROR(ENOMEM);
478             goto fail;
479         }
480         memcpy(dst->extended_data, src->extended_data, sizeof(*src->extended_data) * ch);
481     } else
482         dst->extended_data = dst->data;
483
484     memcpy(dst->data,     src->data,     sizeof(src->data));
485     memcpy(dst->linesize, src->linesize, sizeof(src->linesize));
486
487     return 0;
488
489 fail:
490     av_frame_unref(dst);
491     return ret;
492 }
493
494 AVFrame *av_frame_clone(const AVFrame *src)
495 {
496     AVFrame *ret = av_frame_alloc();
497
498     if (!ret)
499         return NULL;
500
501     if (av_frame_ref(ret, src) < 0)
502         av_frame_free(&ret);
503
504     return ret;
505 }
506
507 void av_frame_unref(AVFrame *frame)
508 {
509     int i;
510
511     if (!frame)
512         return;
513
514     wipe_side_data(frame);
515
516     for (i = 0; i < FF_ARRAY_ELEMS(frame->buf); i++)
517         av_buffer_unref(&frame->buf[i]);
518     for (i = 0; i < frame->nb_extended_buf; i++)
519         av_buffer_unref(&frame->extended_buf[i]);
520     av_freep(&frame->extended_buf);
521     av_dict_free(&frame->metadata);
522 #if FF_API_FRAME_QP
523     av_buffer_unref(&frame->qp_table_buf);
524 #endif
525
526     av_buffer_unref(&frame->hw_frames_ctx);
527
528     av_buffer_unref(&frame->opaque_ref);
529     av_buffer_unref(&frame->private_ref);
530
531     get_frame_defaults(frame);
532 }
533
534 void av_frame_move_ref(AVFrame *dst, AVFrame *src)
535 {
536     av_assert1(dst->width == 0 && dst->height == 0);
537     av_assert1(dst->channels == 0);
538
539     *dst = *src;
540     if (src->extended_data == src->data)
541         dst->extended_data = dst->data;
542     memset(src, 0, sizeof(*src));
543     get_frame_defaults(src);
544 }
545
546 int av_frame_is_writable(AVFrame *frame)
547 {
548     int i, ret = 1;
549
550     /* assume non-refcounted frames are not writable */
551     if (!frame->buf[0])
552         return 0;
553
554     for (i = 0; i < FF_ARRAY_ELEMS(frame->buf); i++)
555         if (frame->buf[i])
556             ret &= !!av_buffer_is_writable(frame->buf[i]);
557     for (i = 0; i < frame->nb_extended_buf; i++)
558         ret &= !!av_buffer_is_writable(frame->extended_buf[i]);
559
560     return ret;
561 }
562
563 int av_frame_make_writable(AVFrame *frame)
564 {
565     AVFrame tmp;
566     int ret;
567
568     if (!frame->buf[0])
569         return AVERROR(EINVAL);
570
571     if (av_frame_is_writable(frame))
572         return 0;
573
574     memset(&tmp, 0, sizeof(tmp));
575     tmp.format         = frame->format;
576     tmp.width          = frame->width;
577     tmp.height         = frame->height;
578     tmp.channels       = frame->channels;
579     tmp.channel_layout = frame->channel_layout;
580     tmp.nb_samples     = frame->nb_samples;
581     ret = av_frame_get_buffer(&tmp, 32);
582     if (ret < 0)
583         return ret;
584
585     ret = av_frame_copy(&tmp, frame);
586     if (ret < 0) {
587         av_frame_unref(&tmp);
588         return ret;
589     }
590
591     ret = av_frame_copy_props(&tmp, frame);
592     if (ret < 0) {
593         av_frame_unref(&tmp);
594         return ret;
595     }
596
597     av_frame_unref(frame);
598
599     *frame = tmp;
600     if (tmp.data == tmp.extended_data)
601         frame->extended_data = frame->data;
602
603     return 0;
604 }
605
606 int av_frame_copy_props(AVFrame *dst, const AVFrame *src)
607 {
608     return frame_copy_props(dst, src, 1);
609 }
610
611 AVBufferRef *av_frame_get_plane_buffer(AVFrame *frame, int plane)
612 {
613     uint8_t *data;
614     int planes, i;
615
616     if (frame->nb_samples) {
617         int channels = frame->channels;
618         if (!channels)
619             return NULL;
620         CHECK_CHANNELS_CONSISTENCY(frame);
621         planes = av_sample_fmt_is_planar(frame->format) ? channels : 1;
622     } else
623         planes = 4;
624
625     if (plane < 0 || plane >= planes || !frame->extended_data[plane])
626         return NULL;
627     data = frame->extended_data[plane];
628
629     for (i = 0; i < FF_ARRAY_ELEMS(frame->buf) && frame->buf[i]; i++) {
630         AVBufferRef *buf = frame->buf[i];
631         if (data >= buf->data && data < buf->data + buf->size)
632             return buf;
633     }
634     for (i = 0; i < frame->nb_extended_buf; i++) {
635         AVBufferRef *buf = frame->extended_buf[i];
636         if (data >= buf->data && data < buf->data + buf->size)
637             return buf;
638     }
639     return NULL;
640 }
641
642 AVFrameSideData *av_frame_new_side_data_from_buf(AVFrame *frame,
643                                                  enum AVFrameSideDataType type,
644                                                  AVBufferRef *buf)
645 {
646     AVFrameSideData *ret, **tmp;
647
648     if (!buf)
649         return NULL;
650
651     if (frame->nb_side_data > INT_MAX / sizeof(*frame->side_data) - 1)
652         return NULL;
653
654     tmp = av_realloc(frame->side_data,
655                      (frame->nb_side_data + 1) * sizeof(*frame->side_data));
656     if (!tmp)
657         return NULL;
658     frame->side_data = tmp;
659
660     ret = av_mallocz(sizeof(*ret));
661     if (!ret)
662         return NULL;
663
664     ret->buf = buf;
665     ret->data = ret->buf->data;
666     ret->size = buf->size;
667     ret->type = type;
668
669     frame->side_data[frame->nb_side_data++] = ret;
670
671     return ret;
672 }
673
674 AVFrameSideData *av_frame_new_side_data(AVFrame *frame,
675                                         enum AVFrameSideDataType type,
676                                         int size)
677 {
678     AVFrameSideData *ret;
679     AVBufferRef *buf = av_buffer_alloc(size);
680     ret = av_frame_new_side_data_from_buf(frame, type, buf);
681     if (!ret)
682         av_buffer_unref(&buf);
683     return ret;
684 }
685
686 AVFrameSideData *av_frame_get_side_data(const AVFrame *frame,
687                                         enum AVFrameSideDataType type)
688 {
689     int i;
690
691     for (i = 0; i < frame->nb_side_data; i++) {
692         if (frame->side_data[i]->type == type)
693             return frame->side_data[i];
694     }
695     return NULL;
696 }
697
698 static int frame_copy_video(AVFrame *dst, const AVFrame *src)
699 {
700     const uint8_t *src_data[4];
701     int i, planes;
702
703     if (dst->width  < src->width ||
704         dst->height < src->height)
705         return AVERROR(EINVAL);
706
707     planes = av_pix_fmt_count_planes(dst->format);
708     for (i = 0; i < planes; i++)
709         if (!dst->data[i] || !src->data[i])
710             return AVERROR(EINVAL);
711
712     memcpy(src_data, src->data, sizeof(src_data));
713     av_image_copy(dst->data, dst->linesize,
714                   src_data, src->linesize,
715                   dst->format, src->width, src->height);
716
717     return 0;
718 }
719
720 static int frame_copy_audio(AVFrame *dst, const AVFrame *src)
721 {
722     int planar   = av_sample_fmt_is_planar(dst->format);
723     int channels = dst->channels;
724     int planes   = planar ? channels : 1;
725     int i;
726
727     if (dst->nb_samples     != src->nb_samples ||
728         dst->channels       != src->channels ||
729         dst->channel_layout != src->channel_layout)
730         return AVERROR(EINVAL);
731
732     CHECK_CHANNELS_CONSISTENCY(src);
733
734     for (i = 0; i < planes; i++)
735         if (!dst->extended_data[i] || !src->extended_data[i])
736             return AVERROR(EINVAL);
737
738     av_samples_copy(dst->extended_data, src->extended_data, 0, 0,
739                     dst->nb_samples, channels, dst->format);
740
741     return 0;
742 }
743
744 int av_frame_copy(AVFrame *dst, const AVFrame *src)
745 {
746     if (dst->format != src->format || dst->format < 0)
747         return AVERROR(EINVAL);
748
749     if (dst->width > 0 && dst->height > 0)
750         return frame_copy_video(dst, src);
751     else if (dst->nb_samples > 0 && dst->channels > 0)
752         return frame_copy_audio(dst, src);
753
754     return AVERROR(EINVAL);
755 }
756
757 void av_frame_remove_side_data(AVFrame *frame, enum AVFrameSideDataType type)
758 {
759     int i;
760
761     for (i = 0; i < frame->nb_side_data; i++) {
762         AVFrameSideData *sd = frame->side_data[i];
763         if (sd->type == type) {
764             free_side_data(&frame->side_data[i]);
765             frame->side_data[i] = frame->side_data[frame->nb_side_data - 1];
766             frame->nb_side_data--;
767         }
768     }
769 }
770
771 const char *av_frame_side_data_name(enum AVFrameSideDataType type)
772 {
773     switch(type) {
774     case AV_FRAME_DATA_PANSCAN:         return "AVPanScan";
775     case AV_FRAME_DATA_A53_CC:          return "ATSC A53 Part 4 Closed Captions";
776     case AV_FRAME_DATA_STEREO3D:        return "Stereoscopic 3d metadata";
777     case AV_FRAME_DATA_MATRIXENCODING:  return "AVMatrixEncoding";
778     case AV_FRAME_DATA_DOWNMIX_INFO:    return "Metadata relevant to a downmix procedure";
779     case AV_FRAME_DATA_REPLAYGAIN:      return "AVReplayGain";
780     case AV_FRAME_DATA_DISPLAYMATRIX:   return "3x3 displaymatrix";
781     case AV_FRAME_DATA_AFD:             return "Active format description";
782     case AV_FRAME_DATA_MOTION_VECTORS:  return "Motion vectors";
783     case AV_FRAME_DATA_SKIP_SAMPLES:    return "Skip samples";
784     case AV_FRAME_DATA_AUDIO_SERVICE_TYPE:          return "Audio service type";
785     case AV_FRAME_DATA_MASTERING_DISPLAY_METADATA:  return "Mastering display metadata";
786     case AV_FRAME_DATA_CONTENT_LIGHT_LEVEL:         return "Content light level metadata";
787     case AV_FRAME_DATA_GOP_TIMECODE:                return "GOP timecode";
788     case AV_FRAME_DATA_ICC_PROFILE:                 return "ICC profile";
789     }
790     return NULL;
791 }
792
793 static int calc_cropping_offsets(size_t offsets[4], const AVFrame *frame,
794                                  const AVPixFmtDescriptor *desc)
795 {
796     int i, j;
797
798     for (i = 0; frame->data[i]; i++) {
799         const AVComponentDescriptor *comp = NULL;
800         int shift_x = (i == 1 || i == 2) ? desc->log2_chroma_w : 0;
801         int shift_y = (i == 1 || i == 2) ? desc->log2_chroma_h : 0;
802
803         if (desc->flags & (AV_PIX_FMT_FLAG_PAL | AV_PIX_FMT_FLAG_PSEUDOPAL) && i == 1) {
804             offsets[i] = 0;
805             break;
806         }
807
808         /* find any component descriptor for this plane */
809         for (j = 0; j < desc->nb_components; j++) {
810             if (desc->comp[j].plane == i) {
811                 comp = &desc->comp[j];
812                 break;
813             }
814         }
815         if (!comp)
816             return AVERROR_BUG;
817
818         offsets[i] = (frame->crop_top  >> shift_y) * frame->linesize[i] +
819                      (frame->crop_left >> shift_x) * comp->step;
820     }
821
822     return 0;
823 }
824
825 int av_frame_apply_cropping(AVFrame *frame, int flags)
826 {
827     const AVPixFmtDescriptor *desc;
828     size_t offsets[4];
829     int i;
830
831     if (!(frame->width > 0 && frame->height > 0))
832         return AVERROR(EINVAL);
833
834     if (frame->crop_left >= INT_MAX - frame->crop_right        ||
835         frame->crop_top  >= INT_MAX - frame->crop_bottom       ||
836         (frame->crop_left + frame->crop_right) >= frame->width ||
837         (frame->crop_top + frame->crop_bottom) >= frame->height)
838         return AVERROR(ERANGE);
839
840     desc = av_pix_fmt_desc_get(frame->format);
841     if (!desc)
842         return AVERROR_BUG;
843
844     /* Apply just the right/bottom cropping for hwaccel formats. Bitstream
845      * formats cannot be easily handled here either (and corresponding decoders
846      * should not export any cropping anyway), so do the same for those as well.
847      * */
848     if (desc->flags & (AV_PIX_FMT_FLAG_BITSTREAM | AV_PIX_FMT_FLAG_HWACCEL)) {
849         frame->width      -= frame->crop_right;
850         frame->height     -= frame->crop_bottom;
851         frame->crop_right  = 0;
852         frame->crop_bottom = 0;
853         return 0;
854     }
855
856     /* calculate the offsets for each plane */
857     calc_cropping_offsets(offsets, frame, desc);
858
859     /* adjust the offsets to avoid breaking alignment */
860     if (!(flags & AV_FRAME_CROP_UNALIGNED)) {
861         int log2_crop_align = frame->crop_left ? ff_ctz(frame->crop_left) : INT_MAX;
862         int min_log2_align = INT_MAX;
863
864         for (i = 0; frame->data[i]; i++) {
865             int log2_align = offsets[i] ? ff_ctz(offsets[i]) : INT_MAX;
866             min_log2_align = FFMIN(log2_align, min_log2_align);
867         }
868
869         /* we assume, and it should always be true, that the data alignment is
870          * related to the cropping alignment by a constant power-of-2 factor */
871         if (log2_crop_align < min_log2_align)
872             return AVERROR_BUG;
873
874         if (min_log2_align < 5) {
875             frame->crop_left &= ~((1 << (5 + log2_crop_align - min_log2_align)) - 1);
876             calc_cropping_offsets(offsets, frame, desc);
877         }
878     }
879
880     for (i = 0; frame->data[i]; i++)
881         frame->data[i] += offsets[i];
882
883     frame->width      -= (frame->crop_left + frame->crop_right);
884     frame->height     -= (frame->crop_top  + frame->crop_bottom);
885     frame->crop_left   = 0;
886     frame->crop_right  = 0;
887     frame->crop_top    = 0;
888     frame->crop_bottom = 0;
889
890     return 0;
891 }