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