videoscale: Don't copy scaled metas
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-base / gst / videoconvertscale / gstvideoconvertscale.c
1 /* GStreamer
2  * Copyright (C) <1999> Erik Walthinsen <omega@cse.ogi.edu>
3  * Copyright (C) 2003 Ronald Bultje <rbultje@ronald.bitfreak.net>
4  * Copyright (C) 2005-2012 David Schleef <ds@schleef.org>
5  * Copyright (C) 2022 Thibault Saunier <tsaunier@igalia.com>
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
20  * Boston, MA 02110-1301, USA.
21  */
22
23 /**
24  * SECTION:element-videoconvertscale
25  * @title: videoconvertscale
26  *
27  * This element resizes video frames and allows changing colorspace. By default
28  * the element will try to negotiate to the same size on the source and sinkpad
29  * so that no scaling is needed. It is therefore safe to insert this element in
30  * a pipeline to get more robust behaviour without any cost if no scaling is
31  * needed.
32  *
33  * This element supports a wide range of color spaces including various YUV and
34  * RGB formats and is therefore generally able to operate anywhere in a
35  * pipeline.
36  *
37  * ## Example pipelines
38  * |[
39  * gst-launch-1.0 -v filesrc location=videotestsrc.ogg ! oggdemux ! theoradec ! videoconvertscale ! autovideosink
40  * ]|
41  *  Decode an Ogg/Theora and display the video. If the video sink chosen
42  * cannot perform scaling, the video scaling will be performed by videoconvertscale
43  * when you resize the video window.
44  * To create the test Ogg/Theora file refer to the documentation of theoraenc.
45  * |[
46  * gst-launch-1.0 -v filesrc location=videotestsrc.ogg ! oggdemux ! theoradec ! videoconvertscale ! video/x-raw,width=100 ! autovideosink
47  * ]|
48  *  Decode an Ogg/Theora and display the video with a width of 100.
49  *
50  * Since: 1.22
51  */
52
53 /*
54  * Formulas for PAR, DAR, width and height relations:
55  *
56  * dar_n   w   par_n
57  * ----- = - * -----
58  * dar_d   h   par_d
59  *
60  * par_n    h   dar_n
61  * ----- =  - * -----
62  * par_d    w   dar_d
63  *
64  *         dar_n   par_d
65  * w = h * ----- * -----
66  *         dar_d   par_n
67  *
68  *         dar_d   par_n
69  * h = w * ----- * -----
70  *         dar_n   par_d
71  */
72
73 #ifdef HAVE_CONFIG_H
74 #include "config.h"
75 #endif
76
77 #include <string.h>
78
79 #include <math.h>
80
81 #include <gst/video/gstvideometa.h>
82 #include <gst/video/gstvideopool.h>
83
84 #include "gstvideoconvertscale.h"
85
86 typedef struct
87 {
88   /* properties */
89   GstVideoScaleMethod method;
90   gboolean add_borders;
91   double sharpness;
92   double sharpen;
93   int submethod;
94   double envelope;
95   gint n_threads;
96   GstVideoDitherMethod dither;
97   guint dither_quantization;
98   GstVideoResamplerMethod chroma_resampler;
99   GstVideoAlphaMode alpha_mode;
100   GstVideoChromaMode chroma_mode;
101   GstVideoMatrixMode matrix_mode;
102   GstVideoGammaMode gamma_mode;
103   GstVideoPrimariesMode primaries_mode;
104   gdouble alpha_value;
105
106   GstVideoConverter *convert;
107
108   gint borders_h;
109   gint borders_w;
110
111   gboolean scales;
112   gboolean converts;
113 } GstVideoConvertScalePrivate;
114
115 #define gst_video_convert_scale_parent_class parent_class
116 G_DEFINE_TYPE_WITH_PRIVATE (GstVideoConvertScale, gst_video_convert_scale,
117     GST_TYPE_VIDEO_FILTER);
118 GST_ELEMENT_REGISTER_DEFINE (videoconvertscale, "videoconvertscale",
119     GST_RANK_SECONDARY, GST_TYPE_VIDEO_CONVERT_SCALE);
120
121 #define PRIV(self) ((GstVideoConvertScalePrivate*)gst_video_convert_scale_get_instance_private(((GstVideoConvertScale*) self)))
122
123 #define GST_CAT_DEFAULT video_convertscale_debug
124 GST_DEBUG_CATEGORY_STATIC (video_convertscale_debug);
125 GST_DEBUG_CATEGORY_STATIC (CAT_PERFORMANCE);
126
127 #define DEFAULT_PROP_METHOD       GST_VIDEO_SCALE_BILINEAR
128 #define DEFAULT_PROP_ADD_BORDERS  TRUE
129 #define DEFAULT_PROP_SHARPNESS    1.0
130 #define DEFAULT_PROP_SHARPEN      0.0
131 #define DEFAULT_PROP_DITHER      GST_VIDEO_DITHER_BAYER
132 #define DEFAULT_PROP_ENVELOPE     2.0
133 #define DEFAULT_PROP_DITHER_QUANTIZATION 1
134 #define DEFAULT_PROP_CHROMA_RESAMPLER   GST_VIDEO_RESAMPLER_METHOD_LINEAR
135 #define DEFAULT_PROP_ALPHA_MODE GST_VIDEO_ALPHA_MODE_COPY
136 #define DEFAULT_PROP_ALPHA_VALUE 1.0
137 #define DEFAULT_PROP_CHROMA_MODE GST_VIDEO_CHROMA_MODE_FULL
138 #define DEFAULT_PROP_MATRIX_MODE GST_VIDEO_MATRIX_MODE_FULL
139 #define DEFAULT_PROP_GAMMA_MODE GST_VIDEO_GAMMA_MODE_NONE
140 #define DEFAULT_PROP_PRIMARIES_MODE GST_VIDEO_PRIMARIES_MODE_NONE
141 #define DEFAULT_PROP_N_THREADS 1
142
143 static GQuark _colorspace_quark;
144
145 enum
146 {
147   PROP_0,
148   PROP_METHOD,
149   PROP_ADD_BORDERS,
150   PROP_SHARPNESS,
151   PROP_SHARPEN,
152   PROP_DITHER,
153   PROP_SUBMETHOD,
154   PROP_ENVELOPE,
155   PROP_N_THREADS,
156   PROP_DITHER_QUANTIZATION,
157   PROP_CHROMA_RESAMPLER,
158   PROP_ALPHA_MODE,
159   PROP_ALPHA_VALUE,
160   PROP_CHROMA_MODE,
161   PROP_MATRIX_MODE,
162   PROP_GAMMA_MODE,
163   PROP_PRIMARIES_MODE,
164 };
165
166 #undef GST_VIDEO_SIZE_RANGE
167 #define GST_VIDEO_SIZE_RANGE "(int) [ 1, 32767]"
168
169 /* FIXME: add v210 support
170  * FIXME: add v216 support
171  * FIXME: add UYVP support
172  * FIXME: add A420 support
173  * FIXME: add YUV9 support
174  * FIXME: add YVU9 support
175  * FIXME: add IYU1 support
176  * FIXME: add r210 support
177  */
178
179 #define GST_VIDEO_FORMATS GST_VIDEO_FORMATS_ALL
180
181 static GstStaticCaps gst_video_convert_scale_format_caps =
182     GST_STATIC_CAPS (GST_VIDEO_CAPS_MAKE (GST_VIDEO_FORMATS) ";"
183     GST_VIDEO_CAPS_MAKE_WITH_FEATURES ("ANY", GST_VIDEO_FORMATS));
184
185 static GQuark _size_quark;
186 static GQuark _scale_quark;
187
188 #define GST_TYPE_VIDEO_SCALE_METHOD (gst_video_scale_method_get_type())
189 static GType
190 gst_video_scale_method_get_type (void)
191 {
192   static GType video_scale_method_type = 0;
193
194   static const GEnumValue video_scale_methods[] = {
195     {GST_VIDEO_SCALE_NEAREST, "Nearest Neighbour", "nearest-neighbour"},
196     {GST_VIDEO_SCALE_BILINEAR, "Bilinear (2-tap)", "bilinear"},
197     {GST_VIDEO_SCALE_4TAP, "4-tap Sinc", "4-tap"},
198     {GST_VIDEO_SCALE_LANCZOS, "Lanczos", "lanczos"},
199     {GST_VIDEO_SCALE_BILINEAR2, "Bilinear (multi-tap)", "bilinear2"},
200     {GST_VIDEO_SCALE_SINC, "Sinc (multi-tap)", "sinc"},
201     {GST_VIDEO_SCALE_HERMITE, "Hermite (multi-tap)", "hermite"},
202     {GST_VIDEO_SCALE_SPLINE, "Spline (multi-tap)", "spline"},
203     {GST_VIDEO_SCALE_CATROM, "Catmull-Rom (multi-tap)", "catrom"},
204     {GST_VIDEO_SCALE_MITCHELL, "Mitchell (multi-tap)", "mitchell"},
205     {0, NULL, NULL},
206   };
207
208   if (!video_scale_method_type) {
209     video_scale_method_type =
210         g_enum_register_static ("GstVideoScaleMethod", video_scale_methods);
211   }
212   return video_scale_method_type;
213 }
214
215 static GstCaps *
216 gst_video_convert_scale_get_capslist (void)
217 {
218   static GstCaps *caps = NULL;
219   static gsize inited = 0;
220
221   if (g_once_init_enter (&inited)) {
222     caps = gst_static_caps_get (&gst_video_convert_scale_format_caps);
223     g_once_init_leave (&inited, 1);
224   }
225   return caps;
226 }
227
228 static GstPadTemplate *
229 gst_video_convert_scale_src_template_factory (void)
230 {
231   return gst_pad_template_new ("src", GST_PAD_SRC, GST_PAD_ALWAYS,
232       gst_video_convert_scale_get_capslist ());
233 }
234
235 static GstPadTemplate *
236 gst_video_convert_scale_sink_template_factory (void)
237 {
238   return gst_pad_template_new ("sink", GST_PAD_SINK, GST_PAD_ALWAYS,
239       gst_video_convert_scale_get_capslist ());
240 }
241
242
243 static void gst_video_convert_scale_finalize (GstVideoConvertScale * self);
244 static gboolean gst_video_convert_scale_src_event (GstBaseTransform * trans,
245     GstEvent * event);
246
247 /* base transform vmethods */
248 static GstCaps *gst_video_convert_scale_transform_caps (GstBaseTransform *
249     trans, GstPadDirection direction, GstCaps * caps, GstCaps * filter);
250 static GstCaps *gst_video_convert_scale_fixate_caps (GstBaseTransform * base,
251     GstPadDirection direction, GstCaps * caps, GstCaps * othercaps);
252 static gboolean gst_video_convert_scale_transform_meta (GstBaseTransform *
253     trans, GstBuffer * outbuf, GstMeta * meta, GstBuffer * inbuf);
254
255 static gboolean gst_video_convert_scale_set_info (GstVideoFilter * filter,
256     GstCaps * in, GstVideoInfo * in_info, GstCaps * out,
257     GstVideoInfo * out_info);
258 static GstFlowReturn gst_video_convert_scale_transform_frame (GstVideoFilter *
259     filter, GstVideoFrame * in, GstVideoFrame * out);
260
261 static void gst_video_convert_scale_set_property (GObject * object,
262     guint prop_id, const GValue * value, GParamSpec * pspec);
263 static void gst_video_convert_scale_get_property (GObject * object,
264     guint prop_id, GValue * value, GParamSpec * pspec);
265
266 static GstCapsFeatures *features_format_interlaced,
267     *features_format_interlaced_sysmem;
268
269 static gboolean
270 gst_video_convert_scale_filter_meta (GstBaseTransform * trans, GstQuery * query,
271     GType api, const GstStructure * params)
272 {
273   /* This element cannot passthrough the crop meta, because it would convert the
274    * wrong sub-region of the image, and worst, our output image may not be large
275    * enough for the crop to be applied later */
276   if (api == GST_VIDEO_CROP_META_API_TYPE)
277     return FALSE;
278
279   /* propose all other metadata upstream */
280   return TRUE;
281 }
282
283 static void
284 gst_video_convert_scale_class_init (GstVideoConvertScaleClass * klass)
285 {
286   GObjectClass *gobject_class = (GObjectClass *) klass;
287   GstElementClass *element_class = (GstElementClass *) klass;
288   GstBaseTransformClass *trans_class = (GstBaseTransformClass *) klass;
289   GstVideoFilterClass *filter_class = (GstVideoFilterClass *) klass;
290
291   GST_DEBUG_CATEGORY_INIT (video_convertscale_debug, "videoconvertscale", 0,
292       "videoconvertscale element");
293   GST_DEBUG_CATEGORY_GET (CAT_PERFORMANCE, "GST_PERFORMANCE");
294
295   features_format_interlaced =
296       gst_caps_features_new (GST_CAPS_FEATURE_FORMAT_INTERLACED, NULL);
297   features_format_interlaced_sysmem =
298       gst_caps_features_copy (features_format_interlaced);
299   gst_caps_features_add (features_format_interlaced_sysmem,
300       GST_CAPS_FEATURE_MEMORY_SYSTEM_MEMORY);
301
302   _colorspace_quark = g_quark_from_static_string ("colorspace");
303
304   gobject_class->finalize =
305       (GObjectFinalizeFunc) gst_video_convert_scale_finalize;
306   gobject_class->set_property = gst_video_convert_scale_set_property;
307   gobject_class->get_property = gst_video_convert_scale_get_property;
308
309   g_object_class_install_property (gobject_class, PROP_METHOD,
310       g_param_spec_enum ("method", "method", "method",
311           GST_TYPE_VIDEO_SCALE_METHOD, DEFAULT_PROP_METHOD,
312           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
313
314   g_object_class_install_property (gobject_class, PROP_ADD_BORDERS,
315       g_param_spec_boolean ("add-borders", "Add Borders",
316           "Add black borders if necessary to keep the display aspect ratio",
317           DEFAULT_PROP_ADD_BORDERS,
318           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
319
320   g_object_class_install_property (gobject_class, PROP_SHARPNESS,
321       g_param_spec_double ("sharpness", "Sharpness",
322           "Sharpness of filter", 0.5, 1.5, DEFAULT_PROP_SHARPNESS,
323           G_PARAM_CONSTRUCT | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
324
325   g_object_class_install_property (gobject_class, PROP_SHARPEN,
326       g_param_spec_double ("sharpen", "Sharpen",
327           "Sharpening", 0.0, 1.0, DEFAULT_PROP_SHARPEN,
328           G_PARAM_CONSTRUCT | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
329
330   g_object_class_install_property (gobject_class, PROP_DITHER,
331       g_param_spec_enum ("dither", "Dither", "Apply dithering while converting",
332           gst_video_dither_method_get_type (), DEFAULT_PROP_DITHER,
333           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
334   g_object_class_install_property (gobject_class, PROP_ENVELOPE,
335       g_param_spec_double ("envelope", "Envelope",
336           "Size of filter envelope", 1.0, 5.0, DEFAULT_PROP_ENVELOPE,
337           G_PARAM_CONSTRUCT | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
338
339   g_object_class_install_property (gobject_class, PROP_N_THREADS,
340       g_param_spec_uint ("n-threads", "Threads",
341           "Maximum number of threads to use", 0, G_MAXUINT,
342           DEFAULT_PROP_N_THREADS,
343           G_PARAM_CONSTRUCT | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
344
345   g_object_class_install_property (gobject_class, PROP_DITHER_QUANTIZATION,
346       g_param_spec_uint ("dither-quantization", "Dither Quantize",
347           "Quantizer to use", 0, G_MAXUINT, DEFAULT_PROP_DITHER_QUANTIZATION,
348           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
349   g_object_class_install_property (gobject_class, PROP_CHROMA_RESAMPLER,
350       g_param_spec_enum ("chroma-resampler", "Chroma resampler",
351           "Chroma resampler method", gst_video_resampler_method_get_type (),
352           DEFAULT_PROP_CHROMA_RESAMPLER,
353           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
354   g_object_class_install_property (gobject_class, PROP_ALPHA_MODE,
355       g_param_spec_enum ("alpha-mode", "Alpha Mode",
356           "Alpha Mode to use", gst_video_alpha_mode_get_type (),
357           DEFAULT_PROP_ALPHA_MODE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
358   g_object_class_install_property (gobject_class, PROP_ALPHA_VALUE,
359       g_param_spec_double ("alpha-value", "Alpha Value",
360           "Alpha Value to use", 0.0, 1.0,
361           DEFAULT_PROP_ALPHA_VALUE,
362           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
363   g_object_class_install_property (gobject_class, PROP_CHROMA_MODE,
364       g_param_spec_enum ("chroma-mode", "Chroma Mode", "Chroma Resampling Mode",
365           gst_video_chroma_mode_get_type (), DEFAULT_PROP_CHROMA_MODE,
366           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
367   g_object_class_install_property (gobject_class, PROP_MATRIX_MODE,
368       g_param_spec_enum ("matrix-mode", "Matrix Mode", "Matrix Conversion Mode",
369           gst_video_matrix_mode_get_type (), DEFAULT_PROP_MATRIX_MODE,
370           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
371   g_object_class_install_property (gobject_class, PROP_GAMMA_MODE,
372       g_param_spec_enum ("gamma-mode", "Gamma Mode", "Gamma Conversion Mode",
373           gst_video_gamma_mode_get_type (), DEFAULT_PROP_GAMMA_MODE,
374           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
375   g_object_class_install_property (gobject_class, PROP_PRIMARIES_MODE,
376       g_param_spec_enum ("primaries-mode", "Primaries Mode",
377           "Primaries Conversion Mode", gst_video_primaries_mode_get_type (),
378           DEFAULT_PROP_PRIMARIES_MODE,
379           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
380
381   gst_element_class_set_static_metadata (element_class,
382       "Video colorspace converter and scaler",
383       "Filter/Converter/Video/Scaler/Colorspace",
384       "Resizes video and allow color conversion",
385       "Wim Taymans <wim.taymans@gmail.com>");
386
387   gst_element_class_add_pad_template (element_class,
388       gst_video_convert_scale_sink_template_factory ());
389   gst_element_class_add_pad_template (element_class,
390       gst_video_convert_scale_src_template_factory ());
391
392   _size_quark = g_quark_from_static_string (GST_META_TAG_VIDEO_SIZE_STR);
393   _scale_quark = gst_video_meta_transform_scale_get_quark ();
394
395   gst_type_mark_as_plugin_api (GST_TYPE_VIDEO_SCALE_METHOD, 0);
396   trans_class->transform_caps =
397       GST_DEBUG_FUNCPTR (gst_video_convert_scale_transform_caps);
398   trans_class->fixate_caps =
399       GST_DEBUG_FUNCPTR (gst_video_convert_scale_fixate_caps);
400   trans_class->filter_meta =
401       GST_DEBUG_FUNCPTR (gst_video_convert_scale_filter_meta);
402   trans_class->src_event =
403       GST_DEBUG_FUNCPTR (gst_video_convert_scale_src_event);
404   trans_class->transform_meta =
405       GST_DEBUG_FUNCPTR (gst_video_convert_scale_transform_meta);
406
407   filter_class->set_info = GST_DEBUG_FUNCPTR (gst_video_convert_scale_set_info);
408   filter_class->transform_frame =
409       GST_DEBUG_FUNCPTR (gst_video_convert_scale_transform_frame);
410 }
411
412 static void
413 gst_video_convert_scale_init (GstVideoConvertScale * self)
414 {
415   GstVideoConvertScalePrivate *priv = PRIV (self);
416
417   priv->method = DEFAULT_PROP_METHOD;
418   priv->add_borders = DEFAULT_PROP_ADD_BORDERS;
419   priv->sharpness = DEFAULT_PROP_SHARPNESS;
420   priv->sharpen = DEFAULT_PROP_SHARPEN;
421   priv->envelope = DEFAULT_PROP_ENVELOPE;
422   priv->n_threads = DEFAULT_PROP_N_THREADS;
423   priv->dither = DEFAULT_PROP_DITHER;
424   priv->dither_quantization = DEFAULT_PROP_DITHER_QUANTIZATION;
425   priv->chroma_resampler = DEFAULT_PROP_CHROMA_RESAMPLER;
426   priv->alpha_mode = DEFAULT_PROP_ALPHA_MODE;
427   priv->alpha_value = DEFAULT_PROP_ALPHA_VALUE;
428   priv->chroma_mode = DEFAULT_PROP_CHROMA_MODE;
429   priv->matrix_mode = DEFAULT_PROP_MATRIX_MODE;
430   priv->gamma_mode = DEFAULT_PROP_GAMMA_MODE;
431   priv->primaries_mode = DEFAULT_PROP_PRIMARIES_MODE;
432   priv->scales = TRUE;
433   priv->converts = TRUE;
434 }
435
436 static void
437 gst_video_convert_scale_finalize (GstVideoConvertScale * self)
438 {
439   GstVideoConvertScalePrivate *priv = PRIV (self);
440
441   if (priv->convert)
442     gst_video_converter_free (priv->convert);
443
444   G_OBJECT_CLASS (parent_class)->finalize (G_OBJECT (self));
445 }
446
447 static void
448 gst_video_convert_scale_set_property (GObject * object, guint prop_id,
449     const GValue * value, GParamSpec * pspec)
450 {
451   GstVideoConvertScalePrivate *priv = PRIV (object);
452
453   GST_OBJECT_LOCK (object);
454   switch (prop_id) {
455     case PROP_METHOD:
456       priv->method = g_value_get_enum (value);
457       break;
458     case PROP_ADD_BORDERS:
459       priv->add_borders = g_value_get_boolean (value);
460       GST_OBJECT_UNLOCK (object);
461
462       gst_base_transform_reconfigure_src (GST_BASE_TRANSFORM_CAST (object));
463       return;
464     case PROP_SHARPNESS:
465       priv->sharpness = g_value_get_double (value);
466       break;
467     case PROP_SHARPEN:
468       priv->sharpen = g_value_get_double (value);
469       break;
470     case PROP_SUBMETHOD:
471       priv->submethod = g_value_get_int (value);
472       break;
473     case PROP_ENVELOPE:
474       priv->envelope = g_value_get_double (value);
475       break;
476     case PROP_N_THREADS:
477       priv->n_threads = g_value_get_uint (value);
478       break;
479     case PROP_DITHER:
480       priv->dither = g_value_get_enum (value);
481       break;
482     case PROP_CHROMA_RESAMPLER:
483       priv->chroma_resampler = g_value_get_enum (value);
484       break;
485     case PROP_ALPHA_MODE:
486       priv->alpha_mode = g_value_get_enum (value);
487       break;
488     case PROP_ALPHA_VALUE:
489       priv->alpha_value = g_value_get_double (value);
490       break;
491     case PROP_CHROMA_MODE:
492       priv->chroma_mode = g_value_get_enum (value);
493       break;
494     case PROP_MATRIX_MODE:
495       priv->matrix_mode = g_value_get_enum (value);
496       break;
497     case PROP_GAMMA_MODE:
498       priv->gamma_mode = g_value_get_enum (value);
499       break;
500     case PROP_PRIMARIES_MODE:
501       priv->primaries_mode = g_value_get_enum (value);
502       break;
503     case PROP_DITHER_QUANTIZATION:
504       priv->dither_quantization = g_value_get_uint (value);
505       break;
506     default:
507       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
508       break;
509   }
510   GST_OBJECT_UNLOCK (object);
511 }
512
513 static void
514 gst_video_convert_scale_get_property (GObject * object, guint prop_id,
515     GValue * value, GParamSpec * pspec)
516 {
517   GstVideoConvertScalePrivate *priv = PRIV (object);
518
519   GST_OBJECT_LOCK (object);
520   switch (prop_id) {
521     case PROP_METHOD:
522       g_value_set_enum (value, priv->method);
523       break;
524     case PROP_ADD_BORDERS:
525       g_value_set_boolean (value, priv->add_borders);
526       break;
527     case PROP_SHARPNESS:
528       g_value_set_double (value, priv->sharpness);
529       break;
530     case PROP_SHARPEN:
531       g_value_set_double (value, priv->sharpen);
532       break;
533     case PROP_SUBMETHOD:
534       g_value_set_int (value, priv->submethod);
535       break;
536     case PROP_ENVELOPE:
537       g_value_set_double (value, priv->envelope);
538       break;
539     case PROP_N_THREADS:
540       g_value_set_uint (value, priv->n_threads);
541       break;
542     case PROP_DITHER:
543       g_value_set_enum (value, priv->dither);
544       break;
545     case PROP_CHROMA_RESAMPLER:
546       g_value_set_enum (value, priv->chroma_resampler);
547       break;
548     case PROP_ALPHA_MODE:
549       g_value_set_enum (value, priv->alpha_mode);
550       break;
551     case PROP_ALPHA_VALUE:
552       g_value_set_double (value, priv->alpha_value);
553       break;
554     case PROP_CHROMA_MODE:
555       g_value_set_enum (value, priv->chroma_mode);
556       break;
557     case PROP_MATRIX_MODE:
558       g_value_set_enum (value, priv->matrix_mode);
559       break;
560     case PROP_GAMMA_MODE:
561       g_value_set_enum (value, priv->gamma_mode);
562       break;
563     case PROP_PRIMARIES_MODE:
564       g_value_set_enum (value, priv->primaries_mode);
565       break;
566     case PROP_DITHER_QUANTIZATION:
567       g_value_set_uint (value, priv->dither_quantization);
568       break;
569     default:
570       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
571       break;
572   }
573   GST_OBJECT_UNLOCK (object);
574 }
575
576 static GstCaps *
577 gst_video_convert_caps_remove_format_and_rangify_size_info (GstVideoConvertScale
578     * self, GstCaps * caps)
579 {
580   GstCaps *ret;
581   GstStructure *structure;
582   GstCapsFeatures *features;
583   gint i, n;
584   GstVideoConvertScalePrivate *priv = PRIV (self);
585
586   ret = gst_caps_new_empty ();
587
588   n = gst_caps_get_size (caps);
589   for (i = 0; i < n; i++) {
590     structure = gst_caps_get_structure (caps, i);
591     features = gst_caps_get_features (caps, i);
592
593     /* If this is already expressed by the existing caps
594      * skip this structure */
595     if (i > 0 && gst_caps_is_subset_structure_full (ret, structure, features))
596       continue;
597
598     structure = gst_structure_copy (structure);
599     /* Only remove format info for the cases when we can actually convert */
600     if (!gst_caps_features_is_any (features)
601         && (gst_caps_features_is_equal (features,
602                 GST_CAPS_FEATURES_MEMORY_SYSTEM_MEMORY)
603             || gst_caps_features_is_equal (features, features_format_interlaced)
604             || gst_caps_features_is_equal (features,
605                 features_format_interlaced_sysmem))) {
606
607       if (priv->scales) {
608         gst_structure_set (structure, "width", GST_TYPE_INT_RANGE, 1, G_MAXINT,
609             "height", GST_TYPE_INT_RANGE, 1, G_MAXINT, NULL);
610         /* if pixel aspect ratio, make a range of it */
611         if (gst_structure_has_field (structure, "pixel-aspect-ratio")) {
612           gst_structure_set (structure, "pixel-aspect-ratio",
613               GST_TYPE_FRACTION_RANGE, 1, G_MAXINT, G_MAXINT, 1, NULL);
614         }
615       }
616
617       if (priv->converts) {
618         gst_structure_remove_fields (structure, "format", "colorimetry",
619             "chroma-site", NULL);
620       }
621     }
622     gst_caps_append_structure_full (ret, structure,
623         gst_caps_features_copy (features));
624   }
625
626   return ret;
627 }
628
629 static GstCaps *
630 gst_video_convert_scale_transform_caps (GstBaseTransform * trans,
631     GstPadDirection direction, GstCaps * caps, GstCaps * filter)
632 {
633   gint i;
634   GstCaps *ret;
635   GstVideoConvertScale *self = GST_VIDEO_CONVERT_SCALE (trans);
636
637   GST_DEBUG_OBJECT (trans,
638       "Transforming caps %" GST_PTR_FORMAT " in direction %s", caps,
639       (direction == GST_PAD_SINK) ? "sink" : "src");
640
641   ret = gst_video_convert_caps_remove_format_and_rangify_size_info (self, caps);
642   if (filter) {
643     GstCaps *intersection;
644
645     intersection =
646         gst_caps_intersect_full (filter, ret, GST_CAPS_INTERSECT_FIRST);
647     gst_caps_unref (ret);
648     ret = intersection;
649   }
650
651   if (GST_VIDEO_CONVERT_SCALE_GET_CLASS (trans)->any_memory)
652     return ret;
653
654   for (i = 0; i < gst_caps_get_size (ret); i++) {
655     gint j;
656     GstCapsFeatures *f = gst_caps_get_features (ret, i);
657
658     if (!f || gst_caps_features_is_any (f) ||
659         gst_caps_features_is_equal (f, GST_CAPS_FEATURES_MEMORY_SYSTEM_MEMORY))
660       continue;
661
662     for (j = 0; j < gst_caps_features_get_size (f); j++) {
663       const gchar *feature = gst_caps_features_get_nth (f, j);
664
665       if (g_str_has_prefix (feature, "memory:")) {
666         GST_DEBUG_OBJECT (trans, "Can not work with memory `%s`", feature);
667         gst_caps_remove_structure (ret, i);
668         break;
669       }
670     }
671   }
672
673   GST_DEBUG_OBJECT (trans, "returning caps: %" GST_PTR_FORMAT, ret);
674
675   return ret;
676 }
677
678 static gboolean
679 gst_video_convert_scale_transform_meta (GstBaseTransform * trans,
680     GstBuffer * outbuf, GstMeta * meta, GstBuffer * inbuf)
681 {
682   GstVideoFilter *videofilter = GST_VIDEO_FILTER (trans);
683   const GstMetaInfo *info = meta->info;
684   const gchar *const *tags;
685   const gchar *const *curr = NULL;
686   gboolean should_copy = TRUE;
687   const gchar *const valid_tags[] = {
688     GST_META_TAG_VIDEO_STR,
689     GST_META_TAG_VIDEO_ORIENTATION_STR,
690     GST_META_TAG_VIDEO_SIZE_STR,
691   };
692
693   tags = gst_meta_api_type_get_tags (info->api);
694
695   /* No specific tags, we are good to copy */
696   if (!tags) {
697     return TRUE;
698   }
699
700   if (gst_meta_api_type_has_tag (info->api, _colorspace_quark)) {
701     /* don't copy colorspace specific metadata, FIXME, we need a MetaTransform
702      * for the colorspace metadata. */
703     return FALSE;
704   }
705
706   /* We are only changing size, we can preserve other metas tagged as
707      orientation and colorspace */
708   for (curr = tags; *curr; ++curr) {
709
710     /* We dont handle any other tag */
711     if (!g_strv_contains (valid_tags, *curr)) {
712       should_copy = FALSE;
713       break;
714     }
715   }
716
717   /* Cant handle the tags in this meta, let the parent class handle it */
718   if (!should_copy) {
719     return GST_BASE_TRANSFORM_CLASS (parent_class)->transform_meta (trans,
720         outbuf, meta, inbuf);
721   }
722
723   /* This meta is size sensitive, try to transform it accordingly */
724   if (gst_meta_api_type_has_tag (info->api, _size_quark)) {
725     GstVideoMetaTransform trans =
726         { &videofilter->in_info, &videofilter->out_info };
727
728     if (info->transform_func)
729       info->transform_func (outbuf, meta, inbuf, _scale_quark, &trans);
730     return FALSE;
731   }
732
733   /* No need to transform, we can safely copy this meta */
734   return TRUE;
735 }
736
737 static gboolean
738 gst_video_convert_scale_set_info (GstVideoFilter * filter, GstCaps * in,
739     GstVideoInfo * in_info, GstCaps * out, GstVideoInfo * out_info)
740 {
741   GstVideoConvertScale *self = GST_VIDEO_CONVERT_SCALE (filter);
742   GstVideoConvertScalePrivate *priv = PRIV (self);
743   gint from_dar_n, from_dar_d, to_dar_n, to_dar_d;
744   GstVideoInfo tmp_info;
745
746   if (priv->convert) {
747     gst_video_converter_free (priv->convert);
748     priv->convert = NULL;
749   }
750
751   if (!gst_util_fraction_multiply (in_info->width,
752           in_info->height, in_info->par_n, in_info->par_d, &from_dar_n,
753           &from_dar_d)) {
754     from_dar_n = from_dar_d = -1;
755   }
756
757   if (!gst_util_fraction_multiply (out_info->width,
758           out_info->height, out_info->par_n, out_info->par_d, &to_dar_n,
759           &to_dar_d)) {
760     to_dar_n = to_dar_d = -1;
761   }
762
763   priv->borders_w = priv->borders_h = 0;
764   if (to_dar_n != from_dar_n || to_dar_d != from_dar_d) {
765     if (priv->add_borders) {
766       gint n, d, to_h, to_w;
767
768       if (from_dar_n != -1 && from_dar_d != -1
769           && gst_util_fraction_multiply (from_dar_n, from_dar_d,
770               out_info->par_d, out_info->par_n, &n, &d)) {
771         to_h = gst_util_uint64_scale_int (out_info->width, d, n);
772         if (to_h <= out_info->height) {
773           priv->borders_h = out_info->height - to_h;
774           priv->borders_w = 0;
775         } else {
776           to_w = gst_util_uint64_scale_int (out_info->height, n, d);
777           g_assert (to_w <= out_info->width);
778           priv->borders_h = 0;
779           priv->borders_w = out_info->width - to_w;
780         }
781       } else {
782         GST_WARNING_OBJECT (self, "Can't calculate borders");
783       }
784     } else {
785       GST_WARNING_OBJECT (self, "Can't keep DAR!");
786     }
787   }
788
789   /* if present, these must match */
790   if (in_info->interlace_mode != out_info->interlace_mode)
791     goto format_mismatch;
792
793   /* if the only thing different in the caps is the transfer function, and
794    * we're converting between equivalent transfer functions, do passthrough */
795   tmp_info = *in_info;
796   tmp_info.colorimetry.transfer = out_info->colorimetry.transfer;
797   if (gst_video_info_is_equal (&tmp_info, out_info)) {
798     if (gst_video_transfer_function_is_equivalent (in_info->
799             colorimetry.transfer, in_info->finfo->bits,
800             out_info->colorimetry.transfer, out_info->finfo->bits)) {
801       gst_base_transform_set_passthrough (GST_BASE_TRANSFORM (filter), TRUE);
802     }
803   } else {
804     GstStructure *options;
805     GST_CAT_DEBUG_OBJECT (CAT_PERFORMANCE, filter, "setup videoscaling");
806     gst_base_transform_set_passthrough (GST_BASE_TRANSFORM (filter), FALSE);
807
808     options = gst_structure_new_empty ("videoconvertscale");
809
810     switch (priv->method) {
811       case GST_VIDEO_SCALE_NEAREST:
812         gst_structure_set (options,
813             GST_VIDEO_CONVERTER_OPT_RESAMPLER_METHOD,
814             GST_TYPE_VIDEO_RESAMPLER_METHOD, GST_VIDEO_RESAMPLER_METHOD_NEAREST,
815             NULL);
816         break;
817       case GST_VIDEO_SCALE_BILINEAR:
818         gst_structure_set (options,
819             GST_VIDEO_CONVERTER_OPT_RESAMPLER_METHOD,
820             GST_TYPE_VIDEO_RESAMPLER_METHOD, GST_VIDEO_RESAMPLER_METHOD_LINEAR,
821             GST_VIDEO_RESAMPLER_OPT_MAX_TAPS, G_TYPE_INT, 2, NULL);
822         break;
823       case GST_VIDEO_SCALE_4TAP:
824         gst_structure_set (options,
825             GST_VIDEO_CONVERTER_OPT_RESAMPLER_METHOD,
826             GST_TYPE_VIDEO_RESAMPLER_METHOD, GST_VIDEO_RESAMPLER_METHOD_SINC,
827             GST_VIDEO_RESAMPLER_OPT_MAX_TAPS, G_TYPE_INT, 4, NULL);
828         break;
829       case GST_VIDEO_SCALE_LANCZOS:
830         gst_structure_set (options,
831             GST_VIDEO_CONVERTER_OPT_RESAMPLER_METHOD,
832             GST_TYPE_VIDEO_RESAMPLER_METHOD, GST_VIDEO_RESAMPLER_METHOD_LANCZOS,
833             NULL);
834         break;
835       case GST_VIDEO_SCALE_BILINEAR2:
836         gst_structure_set (options,
837             GST_VIDEO_CONVERTER_OPT_RESAMPLER_METHOD,
838             GST_TYPE_VIDEO_RESAMPLER_METHOD, GST_VIDEO_RESAMPLER_METHOD_LINEAR,
839             NULL);
840         break;
841       case GST_VIDEO_SCALE_SINC:
842         gst_structure_set (options,
843             GST_VIDEO_CONVERTER_OPT_RESAMPLER_METHOD,
844             GST_TYPE_VIDEO_RESAMPLER_METHOD, GST_VIDEO_RESAMPLER_METHOD_SINC,
845             NULL);
846         break;
847       case GST_VIDEO_SCALE_HERMITE:
848         gst_structure_set (options,
849             GST_VIDEO_CONVERTER_OPT_RESAMPLER_METHOD,
850             GST_TYPE_VIDEO_RESAMPLER_METHOD, GST_VIDEO_RESAMPLER_METHOD_CUBIC,
851             GST_VIDEO_RESAMPLER_OPT_CUBIC_B, G_TYPE_DOUBLE, (gdouble) 0.0,
852             GST_VIDEO_RESAMPLER_OPT_CUBIC_C, G_TYPE_DOUBLE, (gdouble) 0.0,
853             NULL);
854         break;
855       case GST_VIDEO_SCALE_SPLINE:
856         gst_structure_set (options,
857             GST_VIDEO_CONVERTER_OPT_RESAMPLER_METHOD,
858             GST_TYPE_VIDEO_RESAMPLER_METHOD, GST_VIDEO_RESAMPLER_METHOD_CUBIC,
859             GST_VIDEO_RESAMPLER_OPT_CUBIC_B, G_TYPE_DOUBLE, (gdouble) 1.0,
860             GST_VIDEO_RESAMPLER_OPT_CUBIC_C, G_TYPE_DOUBLE, (gdouble) 0.0,
861             NULL);
862         break;
863       case GST_VIDEO_SCALE_CATROM:
864         gst_structure_set (options,
865             GST_VIDEO_CONVERTER_OPT_RESAMPLER_METHOD,
866             GST_TYPE_VIDEO_RESAMPLER_METHOD, GST_VIDEO_RESAMPLER_METHOD_CUBIC,
867             GST_VIDEO_RESAMPLER_OPT_CUBIC_B, G_TYPE_DOUBLE, (gdouble) 0.0,
868             GST_VIDEO_RESAMPLER_OPT_CUBIC_C, G_TYPE_DOUBLE, (gdouble) 0.5,
869             NULL);
870         break;
871       case GST_VIDEO_SCALE_MITCHELL:
872         gst_structure_set (options,
873             GST_VIDEO_CONVERTER_OPT_RESAMPLER_METHOD,
874             GST_TYPE_VIDEO_RESAMPLER_METHOD, GST_VIDEO_RESAMPLER_METHOD_CUBIC,
875             GST_VIDEO_RESAMPLER_OPT_CUBIC_B, G_TYPE_DOUBLE, (gdouble) 1.0 / 3.0,
876             GST_VIDEO_RESAMPLER_OPT_CUBIC_C, G_TYPE_DOUBLE, (gdouble) 1.0 / 3.0,
877             NULL);
878         break;
879     }
880     gst_structure_set (options,
881         GST_VIDEO_RESAMPLER_OPT_ENVELOPE, G_TYPE_DOUBLE, priv->envelope,
882         GST_VIDEO_RESAMPLER_OPT_SHARPNESS, G_TYPE_DOUBLE, priv->sharpness,
883         GST_VIDEO_RESAMPLER_OPT_SHARPEN, G_TYPE_DOUBLE, priv->sharpen,
884         GST_VIDEO_CONVERTER_OPT_DEST_X, G_TYPE_INT, priv->borders_w / 2,
885         GST_VIDEO_CONVERTER_OPT_DEST_Y, G_TYPE_INT, priv->borders_h / 2,
886         GST_VIDEO_CONVERTER_OPT_DEST_WIDTH, G_TYPE_INT,
887         out_info->width - priv->borders_w, GST_VIDEO_CONVERTER_OPT_DEST_HEIGHT,
888         G_TYPE_INT, out_info->height - priv->borders_h,
889         GST_VIDEO_CONVERTER_OPT_DITHER_METHOD, GST_TYPE_VIDEO_DITHER_METHOD,
890         priv->dither, GST_VIDEO_CONVERTER_OPT_DITHER_QUANTIZATION, G_TYPE_UINT,
891         priv->dither_quantization,
892         GST_VIDEO_CONVERTER_OPT_CHROMA_RESAMPLER_METHOD,
893         GST_TYPE_VIDEO_RESAMPLER_METHOD, priv->chroma_resampler,
894         GST_VIDEO_CONVERTER_OPT_ALPHA_MODE, GST_TYPE_VIDEO_ALPHA_MODE,
895         priv->alpha_mode, GST_VIDEO_CONVERTER_OPT_ALPHA_VALUE, G_TYPE_DOUBLE,
896         priv->alpha_value, GST_VIDEO_CONVERTER_OPT_CHROMA_MODE,
897         GST_TYPE_VIDEO_CHROMA_MODE, priv->chroma_mode,
898         GST_VIDEO_CONVERTER_OPT_MATRIX_MODE, GST_TYPE_VIDEO_MATRIX_MODE,
899         priv->matrix_mode, GST_VIDEO_CONVERTER_OPT_GAMMA_MODE,
900         GST_TYPE_VIDEO_GAMMA_MODE, priv->gamma_mode,
901         GST_VIDEO_CONVERTER_OPT_PRIMARIES_MODE, GST_TYPE_VIDEO_PRIMARIES_MODE,
902         priv->primaries_mode, GST_VIDEO_CONVERTER_OPT_THREADS, G_TYPE_UINT,
903         priv->n_threads, NULL);
904
905     priv->convert = gst_video_converter_new (in_info, out_info, options);
906     if (priv->convert == NULL)
907       goto no_convert;
908   }
909
910   GST_DEBUG_OBJECT (filter, "converting format %s -> %s",
911       gst_video_format_to_string (GST_VIDEO_INFO_FORMAT (in_info)),
912       gst_video_format_to_string (GST_VIDEO_INFO_FORMAT (out_info)));
913   GST_DEBUG_OBJECT (self, "from=%dx%d (par=%d/%d dar=%d/%d), size %"
914       G_GSIZE_FORMAT " -> to=%dx%d (par=%d/%d dar=%d/%d borders=%d:%d), "
915       "size %" G_GSIZE_FORMAT,
916       in_info->width, in_info->height, in_info->par_n, in_info->par_d,
917       from_dar_n, from_dar_d, in_info->size, out_info->width,
918       out_info->height, out_info->par_n, out_info->par_d, to_dar_n, to_dar_d,
919       priv->borders_w, priv->borders_h, out_info->size);
920
921   return TRUE;
922
923   /* ERRORS */
924 format_mismatch:
925   {
926     GST_ERROR_OBJECT (self, "input and output formats do not match");
927     return FALSE;
928   }
929 no_convert:
930   {
931     GST_ERROR_OBJECT (self, "could not create converter");
932     return FALSE;
933   }
934 }
935
936 /*
937  * This is an incomplete matrix of in formats and a score for the preferred output
938  * format.
939  *
940  *         out: RGB24   RGB16  ARGB  AYUV  YUV444  YUV422 YUV420 YUV411 YUV410  PAL  GRAY
941  *  in
942  * RGB24          0      2       1     2     2       3      4      5      6      7    8
943  * RGB16          1      0       1     2     2       3      4      5      6      7    8
944  * ARGB           2      3       0     1     4       5      6      7      8      9    10
945  * AYUV           3      4       1     0     2       5      6      7      8      9    10
946  * YUV444         2      4       3     1     0       5      6      7      8      9    10
947  * YUV422         3      5       4     2     1       0      6      7      8      9    10
948  * YUV420         4      6       5     3     2       1      0      7      8      9    10
949  * YUV411         4      6       5     3     2       1      7      0      8      9    10
950  * YUV410         6      8       7     5     4       3      2      1      0      9    10
951  * PAL            1      3       2     6     4       6      7      8      9      0    10
952  * GRAY           1      4       3     2     1       5      6      7      8      9    0
953  *
954  * PAL or GRAY are never preferred, if we can we would convert to PAL instead
955  * of GRAY, though
956  * less subsampling is preferred and if any, preferably horizontal
957  * We would like to keep the alpha, even if we would need to to colorspace conversion
958  * or lose depth.
959  */
960 #define SCORE_FORMAT_CHANGE       1
961 #define SCORE_DEPTH_CHANGE        1
962 #define SCORE_ALPHA_CHANGE        1
963 #define SCORE_CHROMA_W_CHANGE     1
964 #define SCORE_CHROMA_H_CHANGE     1
965 #define SCORE_PALETTE_CHANGE      1
966
967 #define SCORE_COLORSPACE_LOSS     2     /* RGB <-> YUV */
968 #define SCORE_DEPTH_LOSS          4     /* change bit depth */
969 #define SCORE_ALPHA_LOSS          8     /* lose the alpha channel */
970 #define SCORE_CHROMA_W_LOSS      16     /* vertical subsample */
971 #define SCORE_CHROMA_H_LOSS      32     /* horizontal subsample */
972 #define SCORE_PALETTE_LOSS       64     /* convert to palette format */
973 #define SCORE_COLOR_LOSS        128     /* convert to GRAY */
974
975 #define COLORSPACE_MASK (GST_VIDEO_FORMAT_FLAG_YUV | \
976                          GST_VIDEO_FORMAT_FLAG_RGB | GST_VIDEO_FORMAT_FLAG_GRAY)
977 #define ALPHA_MASK      (GST_VIDEO_FORMAT_FLAG_ALPHA)
978 #define PALETTE_MASK    (GST_VIDEO_FORMAT_FLAG_PALETTE)
979
980 /* calculate how much loss a conversion would be */
981 static void
982 score_value (GstBaseTransform * base, const GstVideoFormatInfo * in_info,
983     const GValue * val, gint * min_loss, const GstVideoFormatInfo ** out_info)
984 {
985   const gchar *fname;
986   const GstVideoFormatInfo *t_info;
987   GstVideoFormatFlags in_flags, t_flags;
988   gint loss;
989
990   fname = g_value_get_string (val);
991   t_info = gst_video_format_get_info (gst_video_format_from_string (fname));
992   if (!t_info || t_info->format == GST_VIDEO_FORMAT_UNKNOWN)
993     return;
994
995   /* accept input format immediately without loss */
996   if (in_info == t_info) {
997     *min_loss = 0;
998     *out_info = t_info;
999     return;
1000   }
1001
1002   loss = SCORE_FORMAT_CHANGE;
1003
1004   in_flags = GST_VIDEO_FORMAT_INFO_FLAGS (in_info);
1005   in_flags &= ~GST_VIDEO_FORMAT_FLAG_LE;
1006   in_flags &= ~GST_VIDEO_FORMAT_FLAG_COMPLEX;
1007   in_flags &= ~GST_VIDEO_FORMAT_FLAG_UNPACK;
1008
1009   t_flags = GST_VIDEO_FORMAT_INFO_FLAGS (t_info);
1010   t_flags &= ~GST_VIDEO_FORMAT_FLAG_LE;
1011   t_flags &= ~GST_VIDEO_FORMAT_FLAG_COMPLEX;
1012   t_flags &= ~GST_VIDEO_FORMAT_FLAG_UNPACK;
1013
1014   if ((t_flags & PALETTE_MASK) != (in_flags & PALETTE_MASK)) {
1015     loss += SCORE_PALETTE_CHANGE;
1016     if (t_flags & PALETTE_MASK)
1017       loss += SCORE_PALETTE_LOSS;
1018   }
1019
1020   if ((t_flags & COLORSPACE_MASK) != (in_flags & COLORSPACE_MASK)) {
1021     loss += SCORE_COLORSPACE_LOSS;
1022     if (t_flags & GST_VIDEO_FORMAT_FLAG_GRAY)
1023       loss += SCORE_COLOR_LOSS;
1024   }
1025
1026   if ((t_flags & ALPHA_MASK) != (in_flags & ALPHA_MASK)) {
1027     loss += SCORE_ALPHA_CHANGE;
1028     if (in_flags & ALPHA_MASK)
1029       loss += SCORE_ALPHA_LOSS;
1030   }
1031
1032   if ((in_info->h_sub[1]) != (t_info->h_sub[1])) {
1033     loss += SCORE_CHROMA_H_CHANGE;
1034     if ((in_info->h_sub[1]) < (t_info->h_sub[1]))
1035       loss += SCORE_CHROMA_H_LOSS;
1036   }
1037   if ((in_info->w_sub[1]) != (t_info->w_sub[1])) {
1038     loss += SCORE_CHROMA_W_CHANGE;
1039     if ((in_info->w_sub[1]) < (t_info->w_sub[1]))
1040       loss += SCORE_CHROMA_W_LOSS;
1041   }
1042
1043   if ((in_info->bits) != (t_info->bits)) {
1044     loss += SCORE_DEPTH_CHANGE;
1045     if ((in_info->bits) > (t_info->bits))
1046       loss += SCORE_DEPTH_LOSS;
1047   }
1048
1049   GST_DEBUG_OBJECT (base, "score %s -> %s = %d",
1050       GST_VIDEO_FORMAT_INFO_NAME (in_info),
1051       GST_VIDEO_FORMAT_INFO_NAME (t_info), loss);
1052
1053   if (loss < *min_loss) {
1054     GST_DEBUG_OBJECT (base, "found new best %d", loss);
1055     *out_info = t_info;
1056     *min_loss = loss;
1057   }
1058 }
1059
1060 static void
1061 gst_video_convert_scale_fixate_format (GstBaseTransform * base, GstCaps * caps,
1062     GstCaps * result)
1063 {
1064   GstStructure *ins, *outs;
1065   const gchar *in_format;
1066   const GstVideoFormatInfo *in_info, *out_info = NULL;
1067   gint min_loss = G_MAXINT;
1068   guint i, capslen;
1069
1070   ins = gst_caps_get_structure (caps, 0);
1071   in_format = gst_structure_get_string (ins, "format");
1072   if (!in_format)
1073     return;
1074
1075   GST_DEBUG_OBJECT (base, "source format %s", in_format);
1076
1077   in_info =
1078       gst_video_format_get_info (gst_video_format_from_string (in_format));
1079   if (!in_info)
1080     return;
1081
1082   outs = gst_caps_get_structure (result, 0);
1083
1084   capslen = gst_caps_get_size (result);
1085   GST_DEBUG_OBJECT (base, "iterate %d structures", capslen);
1086   for (i = 0; i < capslen; i++) {
1087     GstStructure *tests;
1088     const GValue *format;
1089
1090     tests = gst_caps_get_structure (result, i);
1091     format = gst_structure_get_value (tests, "format");
1092     gst_structure_remove_fields (tests, "height", "width", "pixel-aspect-ratio",
1093         "display-aspect-ratio", NULL);
1094     /* should not happen */
1095     if (format == NULL)
1096       continue;
1097
1098     if (GST_VALUE_HOLDS_LIST (format)) {
1099       gint j, len;
1100
1101       len = gst_value_list_get_size (format);
1102       GST_DEBUG_OBJECT (base, "have %d formats", len);
1103       for (j = 0; j < len; j++) {
1104         const GValue *val;
1105
1106         val = gst_value_list_get_value (format, j);
1107         if (G_VALUE_HOLDS_STRING (val)) {
1108           score_value (base, in_info, val, &min_loss, &out_info);
1109           if (min_loss == 0)
1110             break;
1111         }
1112       }
1113     } else if (G_VALUE_HOLDS_STRING (format)) {
1114       score_value (base, in_info, format, &min_loss, &out_info);
1115     }
1116   }
1117   if (out_info)
1118     gst_structure_set (outs, "format", G_TYPE_STRING,
1119         GST_VIDEO_FORMAT_INFO_NAME (out_info), NULL);
1120 }
1121
1122 static gboolean
1123 subsampling_unchanged (GstVideoInfo * in_info, GstVideoInfo * out_info)
1124 {
1125   gint i;
1126   const GstVideoFormatInfo *in_format, *out_format;
1127
1128   if (GST_VIDEO_INFO_N_COMPONENTS (in_info) !=
1129       GST_VIDEO_INFO_N_COMPONENTS (out_info))
1130     return FALSE;
1131
1132   in_format = in_info->finfo;
1133   out_format = out_info->finfo;
1134
1135   for (i = 0; i < GST_VIDEO_INFO_N_COMPONENTS (in_info); i++) {
1136     if (GST_VIDEO_FORMAT_INFO_W_SUB (in_format,
1137             i) != GST_VIDEO_FORMAT_INFO_W_SUB (out_format, i))
1138       return FALSE;
1139     if (GST_VIDEO_FORMAT_INFO_H_SUB (in_format,
1140             i) != GST_VIDEO_FORMAT_INFO_H_SUB (out_format, i))
1141       return FALSE;
1142   }
1143
1144   return TRUE;
1145 }
1146
1147 static void
1148 transfer_colorimetry_from_input (GstBaseTransform * trans, GstCaps * in_caps,
1149     GstCaps * out_caps)
1150 {
1151   GstStructure *out_caps_s = gst_caps_get_structure (out_caps, 0);
1152   GstStructure *in_caps_s = gst_caps_get_structure (in_caps, 0);
1153   gboolean have_colorimetry =
1154       gst_structure_has_field (out_caps_s, "colorimetry");
1155   gboolean have_chroma_site =
1156       gst_structure_has_field (out_caps_s, "chroma-site");
1157
1158   /* If the output already has colorimetry and chroma-site, stop,
1159    * otherwise try and transfer what we can from the input caps */
1160   if (have_colorimetry && have_chroma_site)
1161     return;
1162
1163   {
1164     GstVideoInfo in_info, out_info;
1165     const GValue *in_colorimetry =
1166         gst_structure_get_value (in_caps_s, "colorimetry");
1167
1168     if (!gst_video_info_from_caps (&in_info, in_caps)) {
1169       GST_WARNING_OBJECT (trans,
1170           "Failed to convert sink pad caps to video info");
1171       return;
1172     }
1173     if (!gst_video_info_from_caps (&out_info, out_caps)) {
1174       GST_WARNING_OBJECT (trans,
1175           "Failed to convert src pad caps to video info");
1176       return;
1177     }
1178
1179     if (!have_colorimetry && in_colorimetry != NULL) {
1180       if ((GST_VIDEO_INFO_IS_YUV (&out_info)
1181               && GST_VIDEO_INFO_IS_YUV (&in_info))
1182           || (GST_VIDEO_INFO_IS_RGB (&out_info)
1183               && GST_VIDEO_INFO_IS_RGB (&in_info))
1184           || (GST_VIDEO_INFO_IS_GRAY (&out_info)
1185               && GST_VIDEO_INFO_IS_GRAY (&in_info))) {
1186         /* Can transfer the colorimetry intact from the input if it has it */
1187         gst_structure_set_value (out_caps_s, "colorimetry", in_colorimetry);
1188       } else {
1189         gchar *colorimetry_str;
1190
1191         /* Changing between YUV/RGB - forward primaries and transfer function, but use
1192          * default range and matrix.
1193          * the primaries is used for conversion between RGB and XYZ (CIE 1931 coordinate).
1194          * the transfer function could be another reference (e.g., HDR)
1195          */
1196         out_info.colorimetry.primaries = in_info.colorimetry.primaries;
1197         out_info.colorimetry.transfer = in_info.colorimetry.transfer;
1198
1199         colorimetry_str =
1200             gst_video_colorimetry_to_string (&out_info.colorimetry);
1201         gst_caps_set_simple (out_caps, "colorimetry", G_TYPE_STRING,
1202             colorimetry_str, NULL);
1203         g_free (colorimetry_str);
1204       }
1205     }
1206
1207     /* Only YUV output needs chroma-site. If the input was also YUV and had the same chroma
1208      * subsampling, transfer the siting. If the sub-sampling is changing, then the planes get
1209      * scaled anyway so there's no real reason to prefer the input siting. */
1210     if (!have_chroma_site && GST_VIDEO_INFO_IS_YUV (&out_info)) {
1211       if (GST_VIDEO_INFO_IS_YUV (&in_info)) {
1212         const GValue *in_chroma_site =
1213             gst_structure_get_value (in_caps_s, "chroma-site");
1214         if (in_chroma_site != NULL
1215             && subsampling_unchanged (&in_info, &out_info))
1216           gst_structure_set_value (out_caps_s, "chroma-site", in_chroma_site);
1217       }
1218     }
1219   }
1220 }
1221
1222
1223 static GstCaps *
1224 gst_video_convert_scale_get_fixed_format (GstBaseTransform * trans,
1225     GstPadDirection direction, GstCaps * caps, GstCaps * othercaps)
1226 {
1227   GstCaps *result;
1228
1229   result = gst_caps_intersect (othercaps, caps);
1230   if (gst_caps_is_empty (result)) {
1231     gst_caps_unref (result);
1232     result = gst_caps_copy (othercaps);
1233   }
1234
1235   gst_video_convert_scale_fixate_format (trans, caps, result);
1236
1237   /* fixate remaining fields */
1238   result = gst_caps_fixate (result);
1239
1240   if (direction == GST_PAD_SINK) {
1241     if (gst_caps_is_subset (caps, result)) {
1242       gst_caps_replace (&result, caps);
1243     } else {
1244       /* Try and preserve input colorimetry / chroma information */
1245       transfer_colorimetry_from_input (trans, caps, result);
1246     }
1247   }
1248
1249   return result;
1250 }
1251
1252 static GstCaps *
1253 gst_video_convert_scale_fixate_size (GstBaseTransform * base,
1254     GstPadDirection direction, GstCaps * caps, GstCaps * othercaps)
1255 {
1256   GstStructure *ins, *outs;
1257   const GValue *from_par, *to_par;
1258   GValue fpar = { 0, };
1259   GValue tpar = { 0, };
1260
1261   othercaps = gst_caps_truncate (othercaps);
1262   othercaps = gst_caps_make_writable (othercaps);
1263   ins = gst_caps_get_structure (caps, 0);
1264   outs = gst_caps_get_structure (othercaps, 0);
1265
1266   from_par = gst_structure_get_value (ins, "pixel-aspect-ratio");
1267   to_par = gst_structure_get_value (outs, "pixel-aspect-ratio");
1268
1269   /* If we're fixating from the sinkpad we always set the PAR and
1270    * assume that missing PAR on the sinkpad means 1/1 and
1271    * missing PAR on the srcpad means undefined
1272    */
1273   if (direction == GST_PAD_SINK) {
1274     if (!from_par) {
1275       g_value_init (&fpar, GST_TYPE_FRACTION);
1276       gst_value_set_fraction (&fpar, 1, 1);
1277       from_par = &fpar;
1278     }
1279     if (!to_par) {
1280       g_value_init (&tpar, GST_TYPE_FRACTION_RANGE);
1281       gst_value_set_fraction_range_full (&tpar, 1, G_MAXINT, G_MAXINT, 1);
1282       to_par = &tpar;
1283     }
1284   } else {
1285     if (!to_par) {
1286       g_value_init (&tpar, GST_TYPE_FRACTION);
1287       gst_value_set_fraction (&tpar, 1, 1);
1288       to_par = &tpar;
1289
1290       gst_structure_set (outs, "pixel-aspect-ratio", GST_TYPE_FRACTION, 1, 1,
1291           NULL);
1292     }
1293     if (!from_par) {
1294       g_value_init (&fpar, GST_TYPE_FRACTION);
1295       gst_value_set_fraction (&fpar, 1, 1);
1296       from_par = &fpar;
1297     }
1298   }
1299
1300   /* we have both PAR but they might not be fixated */
1301   {
1302     gint from_w, from_h, from_par_n, from_par_d, to_par_n, to_par_d;
1303     gint w = 0, h = 0;
1304     gint from_dar_n, from_dar_d;
1305     gint num, den;
1306
1307     /* from_par should be fixed */
1308     g_return_val_if_fail (gst_value_is_fixed (from_par), othercaps);
1309
1310     from_par_n = gst_value_get_fraction_numerator (from_par);
1311     from_par_d = gst_value_get_fraction_denominator (from_par);
1312
1313     gst_structure_get_int (ins, "width", &from_w);
1314     gst_structure_get_int (ins, "height", &from_h);
1315
1316     gst_structure_get_int (outs, "width", &w);
1317     gst_structure_get_int (outs, "height", &h);
1318
1319     /* if both width and height are already fixed, we can't do anything
1320      * about it anymore */
1321     if (w && h) {
1322       guint n, d;
1323
1324       GST_DEBUG_OBJECT (base, "dimensions already set to %dx%d, not fixating",
1325           w, h);
1326       if (!gst_value_is_fixed (to_par)) {
1327         if (gst_video_calculate_display_ratio (&n, &d, from_w, from_h,
1328                 from_par_n, from_par_d, w, h)) {
1329           GST_DEBUG_OBJECT (base, "fixating to_par to %dx%d", n, d);
1330           if (gst_structure_has_field (outs, "pixel-aspect-ratio"))
1331             gst_structure_fixate_field_nearest_fraction (outs,
1332                 "pixel-aspect-ratio", n, d);
1333           else if (n != d)
1334             gst_structure_set (outs, "pixel-aspect-ratio", GST_TYPE_FRACTION,
1335                 n, d, NULL);
1336         }
1337       }
1338       goto done;
1339     }
1340
1341     /* Calculate input DAR */
1342     if (!gst_util_fraction_multiply (from_w, from_h, from_par_n, from_par_d,
1343             &from_dar_n, &from_dar_d)) {
1344       GST_ELEMENT_ERROR (base, CORE, NEGOTIATION, (NULL),
1345           ("Error calculating the output scaled size - integer overflow"));
1346       goto done;
1347     }
1348
1349     GST_DEBUG_OBJECT (base, "Input DAR is %d/%d", from_dar_n, from_dar_d);
1350
1351     /* If either width or height are fixed there's not much we
1352      * can do either except choosing a height or width and PAR
1353      * that matches the DAR as good as possible
1354      */
1355     if (h) {
1356       GstStructure *tmp;
1357       gint set_w, set_par_n, set_par_d;
1358
1359       GST_DEBUG_OBJECT (base, "height is fixed (%d)", h);
1360
1361       /* If the PAR is fixed too, there's not much to do
1362        * except choosing the width that is nearest to the
1363        * width with the same DAR */
1364       if (gst_value_is_fixed (to_par)) {
1365         to_par_n = gst_value_get_fraction_numerator (to_par);
1366         to_par_d = gst_value_get_fraction_denominator (to_par);
1367
1368         GST_DEBUG_OBJECT (base, "PAR is fixed %d/%d", to_par_n, to_par_d);
1369
1370         if (!gst_util_fraction_multiply (from_dar_n, from_dar_d, to_par_d,
1371                 to_par_n, &num, &den)) {
1372           GST_ELEMENT_ERROR (base, CORE, NEGOTIATION, (NULL),
1373               ("Error calculating the output scaled size - integer overflow"));
1374           goto done;
1375         }
1376
1377         w = (guint) gst_util_uint64_scale_int_round (h, num, den);
1378         gst_structure_fixate_field_nearest_int (outs, "width", w);
1379
1380         goto done;
1381       }
1382
1383       /* The PAR is not fixed and it's quite likely that we can set
1384        * an arbitrary PAR. */
1385
1386       /* Check if we can keep the input width */
1387       tmp = gst_structure_copy (outs);
1388       gst_structure_fixate_field_nearest_int (tmp, "width", from_w);
1389       gst_structure_get_int (tmp, "width", &set_w);
1390
1391       /* Might have failed but try to keep the DAR nonetheless by
1392        * adjusting the PAR */
1393       if (!gst_util_fraction_multiply (from_dar_n, from_dar_d, h, set_w,
1394               &to_par_n, &to_par_d)) {
1395         GST_ELEMENT_ERROR (base, CORE, NEGOTIATION, (NULL),
1396             ("Error calculating the output scaled size - integer overflow"));
1397         gst_structure_free (tmp);
1398         goto done;
1399       }
1400
1401       if (!gst_structure_has_field (tmp, "pixel-aspect-ratio"))
1402         gst_structure_set_value (tmp, "pixel-aspect-ratio", to_par);
1403       gst_structure_fixate_field_nearest_fraction (tmp, "pixel-aspect-ratio",
1404           to_par_n, to_par_d);
1405       gst_structure_get_fraction (tmp, "pixel-aspect-ratio", &set_par_n,
1406           &set_par_d);
1407       gst_structure_free (tmp);
1408
1409       /* Check if the adjusted PAR is accepted */
1410       if (set_par_n == to_par_n && set_par_d == to_par_d) {
1411         if (gst_structure_has_field (outs, "pixel-aspect-ratio") ||
1412             set_par_n != set_par_d)
1413           gst_structure_set (outs, "width", G_TYPE_INT, set_w,
1414               "pixel-aspect-ratio", GST_TYPE_FRACTION, set_par_n, set_par_d,
1415               NULL);
1416         goto done;
1417       }
1418
1419       /* Otherwise scale the width to the new PAR and check if the
1420        * adjusted with is accepted. If all that fails we can't keep
1421        * the DAR */
1422       if (!gst_util_fraction_multiply (from_dar_n, from_dar_d, set_par_d,
1423               set_par_n, &num, &den)) {
1424         GST_ELEMENT_ERROR (base, CORE, NEGOTIATION, (NULL),
1425             ("Error calculating the output scaled size - integer overflow"));
1426         goto done;
1427       }
1428
1429       w = (guint) gst_util_uint64_scale_int_round (h, num, den);
1430       gst_structure_fixate_field_nearest_int (outs, "width", w);
1431       if (gst_structure_has_field (outs, "pixel-aspect-ratio") ||
1432           set_par_n != set_par_d)
1433         gst_structure_set (outs, "pixel-aspect-ratio", GST_TYPE_FRACTION,
1434             set_par_n, set_par_d, NULL);
1435
1436       goto done;
1437     } else if (w) {
1438       GstStructure *tmp;
1439       gint set_h, set_par_n, set_par_d;
1440
1441       GST_DEBUG_OBJECT (base, "width is fixed (%d)", w);
1442
1443       /* If the PAR is fixed too, there's not much to do
1444        * except choosing the height that is nearest to the
1445        * height with the same DAR */
1446       if (gst_value_is_fixed (to_par)) {
1447         to_par_n = gst_value_get_fraction_numerator (to_par);
1448         to_par_d = gst_value_get_fraction_denominator (to_par);
1449
1450         GST_DEBUG_OBJECT (base, "PAR is fixed %d/%d", to_par_n, to_par_d);
1451
1452         if (!gst_util_fraction_multiply (from_dar_n, from_dar_d, to_par_d,
1453                 to_par_n, &num, &den)) {
1454           GST_ELEMENT_ERROR (base, CORE, NEGOTIATION, (NULL),
1455               ("Error calculating the output scaled size - integer overflow"));
1456           goto done;
1457         }
1458
1459         h = (guint) gst_util_uint64_scale_int_round (w, den, num);
1460         gst_structure_fixate_field_nearest_int (outs, "height", h);
1461
1462         goto done;
1463       }
1464
1465       /* The PAR is not fixed and it's quite likely that we can set
1466        * an arbitrary PAR. */
1467
1468       /* Check if we can keep the input height */
1469       tmp = gst_structure_copy (outs);
1470       gst_structure_fixate_field_nearest_int (tmp, "height", from_h);
1471       gst_structure_get_int (tmp, "height", &set_h);
1472
1473       /* Might have failed but try to keep the DAR nonetheless by
1474        * adjusting the PAR */
1475       if (!gst_util_fraction_multiply (from_dar_n, from_dar_d, set_h, w,
1476               &to_par_n, &to_par_d)) {
1477         GST_ELEMENT_ERROR (base, CORE, NEGOTIATION, (NULL),
1478             ("Error calculating the output scaled size - integer overflow"));
1479         gst_structure_free (tmp);
1480         goto done;
1481       }
1482       if (!gst_structure_has_field (tmp, "pixel-aspect-ratio"))
1483         gst_structure_set_value (tmp, "pixel-aspect-ratio", to_par);
1484       gst_structure_fixate_field_nearest_fraction (tmp, "pixel-aspect-ratio",
1485           to_par_n, to_par_d);
1486       gst_structure_get_fraction (tmp, "pixel-aspect-ratio", &set_par_n,
1487           &set_par_d);
1488       gst_structure_free (tmp);
1489
1490       /* Check if the adjusted PAR is accepted */
1491       if (set_par_n == to_par_n && set_par_d == to_par_d) {
1492         if (gst_structure_has_field (outs, "pixel-aspect-ratio") ||
1493             set_par_n != set_par_d)
1494           gst_structure_set (outs, "height", G_TYPE_INT, set_h,
1495               "pixel-aspect-ratio", GST_TYPE_FRACTION, set_par_n, set_par_d,
1496               NULL);
1497         goto done;
1498       }
1499
1500       /* Otherwise scale the height to the new PAR and check if the
1501        * adjusted with is accepted. If all that fails we can't keep
1502        * the DAR */
1503       if (!gst_util_fraction_multiply (from_dar_n, from_dar_d, set_par_d,
1504               set_par_n, &num, &den)) {
1505         GST_ELEMENT_ERROR (base, CORE, NEGOTIATION, (NULL),
1506             ("Error calculating the output scaled size - integer overflow"));
1507         goto done;
1508       }
1509
1510       h = (guint) gst_util_uint64_scale_int_round (w, den, num);
1511       gst_structure_fixate_field_nearest_int (outs, "height", h);
1512       if (gst_structure_has_field (outs, "pixel-aspect-ratio") ||
1513           set_par_n != set_par_d)
1514         gst_structure_set (outs, "pixel-aspect-ratio", GST_TYPE_FRACTION,
1515             set_par_n, set_par_d, NULL);
1516
1517       goto done;
1518     } else if (gst_value_is_fixed (to_par)) {
1519       GstStructure *tmp;
1520       gint set_h, set_w, f_h, f_w;
1521
1522       to_par_n = gst_value_get_fraction_numerator (to_par);
1523       to_par_d = gst_value_get_fraction_denominator (to_par);
1524
1525       /* Calculate scale factor for the PAR change */
1526       if (!gst_util_fraction_multiply (from_dar_n, from_dar_d, to_par_n,
1527               to_par_d, &num, &den)) {
1528         GST_ELEMENT_ERROR (base, CORE, NEGOTIATION, (NULL),
1529             ("Error calculating the output scaled size - integer overflow"));
1530         goto done;
1531       }
1532
1533       /* Try to keep the input height (because of interlacing) */
1534       tmp = gst_structure_copy (outs);
1535       gst_structure_fixate_field_nearest_int (tmp, "height", from_h);
1536       gst_structure_get_int (tmp, "height", &set_h);
1537
1538       /* This might have failed but try to scale the width
1539        * to keep the DAR nonetheless */
1540       w = (guint) gst_util_uint64_scale_int_round (set_h, num, den);
1541       gst_structure_fixate_field_nearest_int (tmp, "width", w);
1542       gst_structure_get_int (tmp, "width", &set_w);
1543       gst_structure_free (tmp);
1544
1545       /* We kept the DAR and the height is nearest to the original height */
1546       if (set_w == w) {
1547         gst_structure_set (outs, "width", G_TYPE_INT, set_w, "height",
1548             G_TYPE_INT, set_h, NULL);
1549         goto done;
1550       }
1551
1552       f_h = set_h;
1553       f_w = set_w;
1554
1555       /* If the former failed, try to keep the input width at least */
1556       tmp = gst_structure_copy (outs);
1557       gst_structure_fixate_field_nearest_int (tmp, "width", from_w);
1558       gst_structure_get_int (tmp, "width", &set_w);
1559
1560       /* This might have failed but try to scale the width
1561        * to keep the DAR nonetheless */
1562       h = (guint) gst_util_uint64_scale_int_round (set_w, den, num);
1563       gst_structure_fixate_field_nearest_int (tmp, "height", h);
1564       gst_structure_get_int (tmp, "height", &set_h);
1565       gst_structure_free (tmp);
1566
1567       /* We kept the DAR and the width is nearest to the original width */
1568       if (set_h == h) {
1569         gst_structure_set (outs, "width", G_TYPE_INT, set_w, "height",
1570             G_TYPE_INT, set_h, NULL);
1571         goto done;
1572       }
1573
1574       /* If all this failed, keep the dimensions with the DAR that was closest
1575        * to the correct DAR. This changes the DAR but there's not much else to
1576        * do here.
1577        */
1578       if (set_w * ABS (set_h - h) < ABS (f_w - w) * f_h) {
1579         f_h = set_h;
1580         f_w = set_w;
1581       }
1582       gst_structure_set (outs, "width", G_TYPE_INT, f_w, "height", G_TYPE_INT,
1583           f_h, NULL);
1584       goto done;
1585     } else {
1586       GstStructure *tmp;
1587       gint set_h, set_w, set_par_n, set_par_d, tmp2;
1588
1589       /* width, height and PAR are not fixed but passthrough is not possible */
1590
1591       /* First try to keep the height and width as good as possible
1592        * and scale PAR */
1593       tmp = gst_structure_copy (outs);
1594       gst_structure_fixate_field_nearest_int (tmp, "height", from_h);
1595       gst_structure_get_int (tmp, "height", &set_h);
1596       gst_structure_fixate_field_nearest_int (tmp, "width", from_w);
1597       gst_structure_get_int (tmp, "width", &set_w);
1598
1599       if (!gst_util_fraction_multiply (from_dar_n, from_dar_d, set_h, set_w,
1600               &to_par_n, &to_par_d)) {
1601         GST_ELEMENT_ERROR (base, CORE, NEGOTIATION, (NULL),
1602             ("Error calculating the output scaled size - integer overflow"));
1603         gst_structure_free (tmp);
1604         goto done;
1605       }
1606
1607       if (!gst_structure_has_field (tmp, "pixel-aspect-ratio"))
1608         gst_structure_set_value (tmp, "pixel-aspect-ratio", to_par);
1609       gst_structure_fixate_field_nearest_fraction (tmp, "pixel-aspect-ratio",
1610           to_par_n, to_par_d);
1611       gst_structure_get_fraction (tmp, "pixel-aspect-ratio", &set_par_n,
1612           &set_par_d);
1613       gst_structure_free (tmp);
1614
1615       if (set_par_n == to_par_n && set_par_d == to_par_d) {
1616         gst_structure_set (outs, "width", G_TYPE_INT, set_w, "height",
1617             G_TYPE_INT, set_h, NULL);
1618
1619         if (gst_structure_has_field (outs, "pixel-aspect-ratio") ||
1620             set_par_n != set_par_d)
1621           gst_structure_set (outs, "pixel-aspect-ratio", GST_TYPE_FRACTION,
1622               set_par_n, set_par_d, NULL);
1623         goto done;
1624       }
1625
1626       /* Otherwise try to scale width to keep the DAR with the set
1627        * PAR and height */
1628       if (!gst_util_fraction_multiply (from_dar_n, from_dar_d, set_par_d,
1629               set_par_n, &num, &den)) {
1630         GST_ELEMENT_ERROR (base, CORE, NEGOTIATION, (NULL),
1631             ("Error calculating the output scaled size - integer overflow"));
1632         goto done;
1633       }
1634
1635       w = (guint) gst_util_uint64_scale_int_round (set_h, num, den);
1636       tmp = gst_structure_copy (outs);
1637       gst_structure_fixate_field_nearest_int (tmp, "width", w);
1638       gst_structure_get_int (tmp, "width", &tmp2);
1639       gst_structure_free (tmp);
1640
1641       if (tmp2 == w) {
1642         gst_structure_set (outs, "width", G_TYPE_INT, tmp2, "height",
1643             G_TYPE_INT, set_h, NULL);
1644         if (gst_structure_has_field (outs, "pixel-aspect-ratio") ||
1645             set_par_n != set_par_d)
1646           gst_structure_set (outs, "pixel-aspect-ratio", GST_TYPE_FRACTION,
1647               set_par_n, set_par_d, NULL);
1648         goto done;
1649       }
1650
1651       /* ... or try the same with the height */
1652       h = (guint) gst_util_uint64_scale_int_round (set_w, den, num);
1653       tmp = gst_structure_copy (outs);
1654       gst_structure_fixate_field_nearest_int (tmp, "height", h);
1655       gst_structure_get_int (tmp, "height", &tmp2);
1656       gst_structure_free (tmp);
1657
1658       if (tmp2 == h) {
1659         gst_structure_set (outs, "width", G_TYPE_INT, set_w, "height",
1660             G_TYPE_INT, tmp2, NULL);
1661         if (gst_structure_has_field (outs, "pixel-aspect-ratio") ||
1662             set_par_n != set_par_d)
1663           gst_structure_set (outs, "pixel-aspect-ratio", GST_TYPE_FRACTION,
1664               set_par_n, set_par_d, NULL);
1665         goto done;
1666       }
1667
1668       /* If all fails we can't keep the DAR and take the nearest values
1669        * for everything from the first try */
1670       gst_structure_set (outs, "width", G_TYPE_INT, set_w, "height",
1671           G_TYPE_INT, set_h, NULL);
1672       if (gst_structure_has_field (outs, "pixel-aspect-ratio") ||
1673           set_par_n != set_par_d)
1674         gst_structure_set (outs, "pixel-aspect-ratio", GST_TYPE_FRACTION,
1675             set_par_n, set_par_d, NULL);
1676     }
1677   }
1678
1679 done:
1680   othercaps = gst_caps_fixate (othercaps);
1681
1682   GST_DEBUG_OBJECT (base, "fixated othercaps to %" GST_PTR_FORMAT, othercaps);
1683
1684   if (from_par == &fpar)
1685     g_value_unset (&fpar);
1686   if (to_par == &tpar)
1687     g_value_unset (&tpar);
1688
1689   return othercaps;
1690 }
1691
1692 static GstCaps *
1693 gst_video_convert_scale_fixate_caps (GstBaseTransform * base,
1694     GstPadDirection direction, GstCaps * caps, GstCaps * othercaps)
1695 {
1696   GstCaps *format;
1697
1698   GST_DEBUG_OBJECT (base,
1699       "trying to fixate othercaps %" GST_PTR_FORMAT " based on caps %"
1700       GST_PTR_FORMAT, othercaps, caps);
1701
1702   format = gst_video_convert_scale_get_fixed_format (base, direction, caps,
1703       othercaps);
1704
1705   if (gst_caps_is_empty (format)) {
1706     GST_ERROR_OBJECT (base, "Could not convert formats");
1707     return format;
1708   }
1709
1710   othercaps =
1711       gst_video_convert_scale_fixate_size (base, direction, caps, othercaps);
1712   if (gst_caps_get_size (othercaps) == 1) {
1713     gint i;
1714     const gchar *format_fields[] = { "format", "colorimetry", "chroma-site" };
1715     GstStructure *format_struct = gst_caps_get_structure (format, 0);
1716     GstStructure *fixated_struct;
1717
1718     othercaps = gst_caps_make_writable (othercaps);
1719     fixated_struct = gst_caps_get_structure (othercaps, 0);
1720
1721     for (i = 0; i < G_N_ELEMENTS (format_fields); i++) {
1722       if (gst_structure_has_field (format_struct, format_fields[i])) {
1723         gst_structure_set (fixated_struct, format_fields[i], G_TYPE_STRING,
1724             gst_structure_get_string (format_struct, format_fields[i]), NULL);
1725       } else {
1726         gst_structure_remove_field (fixated_struct, format_fields[i]);
1727       }
1728     }
1729   }
1730   gst_caps_unref (format);
1731
1732   GST_DEBUG_OBJECT (base, "fixated othercaps to %" GST_PTR_FORMAT, othercaps);
1733
1734   return othercaps;
1735 }
1736
1737 #define GET_LINE(frame, line) \
1738     (gpointer)(((guint8*)(GST_VIDEO_FRAME_PLANE_DATA (frame, 0))) + \
1739      GST_VIDEO_FRAME_PLANE_STRIDE (frame, 0) * (line))
1740
1741 static GstFlowReturn
1742 gst_video_convert_scale_transform_frame (GstVideoFilter * filter,
1743     GstVideoFrame * in_frame, GstVideoFrame * out_frame)
1744 {
1745   GstVideoConvertScalePrivate *priv = PRIV (filter);
1746   GstFlowReturn ret = GST_FLOW_OK;
1747
1748   GST_CAT_DEBUG_OBJECT (CAT_PERFORMANCE, filter, "doing video scaling");
1749
1750   gst_video_converter_frame (priv->convert, in_frame, out_frame);
1751
1752   return ret;
1753 }
1754
1755 static gboolean
1756 gst_video_convert_scale_src_event (GstBaseTransform * trans, GstEvent * event)
1757 {
1758   GstVideoConvertScale *self = GST_VIDEO_CONVERT_SCALE_CAST (trans);
1759   GstVideoFilter *filter = GST_VIDEO_FILTER_CAST (trans);
1760   gboolean ret;
1761   gdouble x, y;
1762
1763   GST_DEBUG_OBJECT (self, "handling %s event", GST_EVENT_TYPE_NAME (event));
1764
1765   switch (GST_EVENT_TYPE (event)) {
1766     case GST_EVENT_NAVIGATION:
1767       if (filter->in_info.width != filter->out_info.width ||
1768           filter->in_info.height != filter->out_info.height) {
1769         event = gst_event_make_writable (event);
1770
1771         if (gst_navigation_event_get_coordinates (event, &x, &y)) {
1772           gst_navigation_event_set_coordinates (event,
1773               x * filter->in_info.width / filter->out_info.width,
1774               y * filter->in_info.height / filter->out_info.height);
1775         }
1776       }
1777       break;
1778     default:
1779       break;
1780   }
1781
1782   ret = GST_BASE_TRANSFORM_CLASS (parent_class)->src_event (trans, event);
1783
1784   return ret;
1785 }
1786
1787 void
1788 gst_video_convert_scale_set_scales (GstVideoConvertScale * self,
1789     gboolean scales)
1790 {
1791   GstVideoConvertScalePrivate *priv = PRIV (self);
1792
1793   if (!scales)
1794     g_assert (priv->converts);
1795
1796   priv->scales = scales;
1797 }
1798
1799 void
1800 gst_video_convert_scale_set_converts (GstVideoConvertScale * self,
1801     gboolean converts)
1802 {
1803   GstVideoConvertScalePrivate *priv = PRIV (self);
1804
1805   if (!converts)
1806     g_assert (priv->scales);
1807
1808   priv->converts = converts;
1809 }
1810
1811 gboolean
1812 gst_video_convert_scale_get_scales (GstVideoConvertScale * self)
1813 {
1814   return PRIV (self)->scales;
1815 }
1816
1817 gboolean
1818 gst_video_convert_scale_get_converts (GstVideoConvertScale * self)
1819 {
1820   return PRIV (self)->converts;
1821 }