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