Introduce the videocolorscale element
[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   GstCaps *ret;
621
622   GST_DEBUG_OBJECT (trans,
623       "Transforming caps %" GST_PTR_FORMAT " in direction %s", caps,
624       (direction == GST_PAD_SINK) ? "sink" : "src");
625
626   ret = gst_video_convert_caps_remove_format_and_rangify_size_info (caps);
627   if (filter) {
628     GstCaps *intersection;
629
630     intersection =
631         gst_caps_intersect_full (filter, ret, GST_CAPS_INTERSECT_FIRST);
632     gst_caps_unref (ret);
633     ret = intersection;
634   }
635
636   GST_DEBUG_OBJECT (trans, "returning caps: %" GST_PTR_FORMAT, ret);
637
638   return ret;
639 }
640
641 static gboolean
642 gst_video_convert_scale_transform_meta (GstBaseTransform * trans,
643     GstBuffer * outbuf, GstMeta * meta, GstBuffer * inbuf)
644 {
645   GstVideoFilter *videofilter = GST_VIDEO_FILTER (trans);
646   const GstMetaInfo *info = meta->info;
647   const gchar *const *tags;
648   const gchar *const *curr = NULL;
649   gboolean should_copy = TRUE;
650   const gchar *const valid_tags[] = {
651     GST_META_TAG_VIDEO_STR,
652     GST_META_TAG_VIDEO_ORIENTATION_STR,
653     GST_META_TAG_VIDEO_SIZE_STR,
654   };
655
656   tags = gst_meta_api_type_get_tags (info->api);
657
658   /* No specific tags, we are good to copy */
659   if (!tags) {
660     return TRUE;
661   }
662
663   if (gst_meta_api_type_has_tag (info->api, _colorspace_quark)) {
664     /* don't copy colorspace specific metadata, FIXME, we need a MetaTransform
665      * for the colorspace metadata. */
666     return FALSE;
667   }
668
669   /* We are only changing size, we can preserve other metas tagged as
670      orientation and colorspace */
671   for (curr = tags; *curr; ++curr) {
672
673     /* We dont handle any other tag */
674     if (!g_strv_contains (valid_tags, *curr)) {
675       should_copy = FALSE;
676       break;
677     }
678   }
679
680   /* Cant handle the tags in this meta, let the parent class handle it */
681   if (!should_copy) {
682     return GST_BASE_TRANSFORM_CLASS (parent_class)->transform_meta (trans,
683         outbuf, meta, inbuf);
684   }
685
686   /* This meta is size sensitive, try to transform it accordingly */
687   if (gst_meta_api_type_has_tag (info->api, _size_quark)) {
688     GstVideoMetaTransform trans =
689         { &videofilter->in_info, &videofilter->out_info };
690
691     if (info->transform_func)
692       return info->transform_func (outbuf, meta, inbuf, _scale_quark, &trans);
693     return FALSE;
694   }
695
696   /* No need to transform, we can safely copy this meta */
697   return TRUE;
698 }
699
700 static gboolean
701 gst_video_convert_scale_set_info (GstVideoFilter * filter, GstCaps * in,
702     GstVideoInfo * in_info, GstCaps * out, GstVideoInfo * out_info)
703 {
704   GstVideoConvertScale *self = GST_VIDEO_CONVERT_SCALE (filter);
705   GstVideoConvertScalePrivate *priv = PRIV (self);
706   gint from_dar_n, from_dar_d, to_dar_n, to_dar_d;
707   GstVideoInfo tmp_info;
708
709   if (priv->convert) {
710     gst_video_converter_free (priv->convert);
711     priv->convert = NULL;
712   }
713
714   if (!gst_util_fraction_multiply (in_info->width,
715           in_info->height, in_info->par_n, in_info->par_d, &from_dar_n,
716           &from_dar_d)) {
717     from_dar_n = from_dar_d = -1;
718   }
719
720   if (!gst_util_fraction_multiply (out_info->width,
721           out_info->height, out_info->par_n, out_info->par_d, &to_dar_n,
722           &to_dar_d)) {
723     to_dar_n = to_dar_d = -1;
724   }
725
726   priv->borders_w = priv->borders_h = 0;
727   if (to_dar_n != from_dar_n || to_dar_d != from_dar_d) {
728     if (priv->add_borders) {
729       gint n, d, to_h, to_w;
730
731       if (from_dar_n != -1 && from_dar_d != -1
732           && gst_util_fraction_multiply (from_dar_n, from_dar_d,
733               out_info->par_d, out_info->par_n, &n, &d)) {
734         to_h = gst_util_uint64_scale_int (out_info->width, d, n);
735         if (to_h <= out_info->height) {
736           priv->borders_h = out_info->height - to_h;
737           priv->borders_w = 0;
738         } else {
739           to_w = gst_util_uint64_scale_int (out_info->height, n, d);
740           g_assert (to_w <= out_info->width);
741           priv->borders_h = 0;
742           priv->borders_w = out_info->width - to_w;
743         }
744       } else {
745         GST_WARNING_OBJECT (self, "Can't calculate borders");
746       }
747     } else {
748       GST_WARNING_OBJECT (self, "Can't keep DAR!");
749     }
750   }
751
752   /* if present, these must match */
753   if (in_info->interlace_mode != out_info->interlace_mode)
754     goto format_mismatch;
755
756   /* if the only thing different in the caps is the transfer function, and
757    * we're converting between equivalent transfer functions, do passthrough */
758   tmp_info = *in_info;
759   tmp_info.colorimetry.transfer = out_info->colorimetry.transfer;
760   if (gst_video_info_is_equal (&tmp_info, out_info)) {
761     if (gst_video_transfer_function_is_equivalent (in_info->
762             colorimetry.transfer, in_info->finfo->bits,
763             out_info->colorimetry.transfer, out_info->finfo->bits)) {
764       gst_base_transform_set_passthrough (GST_BASE_TRANSFORM (filter), TRUE);
765     }
766   } else {
767     GstStructure *options;
768     GST_CAT_DEBUG_OBJECT (CAT_PERFORMANCE, filter, "setup videoscaling");
769     gst_base_transform_set_passthrough (GST_BASE_TRANSFORM (filter), FALSE);
770
771     options = gst_structure_new_empty ("videoconvertscale");
772
773     switch (priv->method) {
774       case GST_VIDEO_SCALE_NEAREST:
775         gst_structure_set (options,
776             GST_VIDEO_CONVERTER_OPT_RESAMPLER_METHOD,
777             GST_TYPE_VIDEO_RESAMPLER_METHOD, GST_VIDEO_RESAMPLER_METHOD_NEAREST,
778             NULL);
779         break;
780       case GST_VIDEO_SCALE_BILINEAR:
781         gst_structure_set (options,
782             GST_VIDEO_CONVERTER_OPT_RESAMPLER_METHOD,
783             GST_TYPE_VIDEO_RESAMPLER_METHOD, GST_VIDEO_RESAMPLER_METHOD_LINEAR,
784             GST_VIDEO_RESAMPLER_OPT_MAX_TAPS, G_TYPE_INT, 2, NULL);
785         break;
786       case GST_VIDEO_SCALE_4TAP:
787         gst_structure_set (options,
788             GST_VIDEO_CONVERTER_OPT_RESAMPLER_METHOD,
789             GST_TYPE_VIDEO_RESAMPLER_METHOD, GST_VIDEO_RESAMPLER_METHOD_SINC,
790             GST_VIDEO_RESAMPLER_OPT_MAX_TAPS, G_TYPE_INT, 4, NULL);
791         break;
792       case GST_VIDEO_SCALE_LANCZOS:
793         gst_structure_set (options,
794             GST_VIDEO_CONVERTER_OPT_RESAMPLER_METHOD,
795             GST_TYPE_VIDEO_RESAMPLER_METHOD, GST_VIDEO_RESAMPLER_METHOD_LANCZOS,
796             NULL);
797         break;
798       case GST_VIDEO_SCALE_BILINEAR2:
799         gst_structure_set (options,
800             GST_VIDEO_CONVERTER_OPT_RESAMPLER_METHOD,
801             GST_TYPE_VIDEO_RESAMPLER_METHOD, GST_VIDEO_RESAMPLER_METHOD_LINEAR,
802             NULL);
803         break;
804       case GST_VIDEO_SCALE_SINC:
805         gst_structure_set (options,
806             GST_VIDEO_CONVERTER_OPT_RESAMPLER_METHOD,
807             GST_TYPE_VIDEO_RESAMPLER_METHOD, GST_VIDEO_RESAMPLER_METHOD_SINC,
808             NULL);
809         break;
810       case GST_VIDEO_SCALE_HERMITE:
811         gst_structure_set (options,
812             GST_VIDEO_CONVERTER_OPT_RESAMPLER_METHOD,
813             GST_TYPE_VIDEO_RESAMPLER_METHOD, GST_VIDEO_RESAMPLER_METHOD_CUBIC,
814             GST_VIDEO_RESAMPLER_OPT_CUBIC_B, G_TYPE_DOUBLE, (gdouble) 0.0,
815             GST_VIDEO_RESAMPLER_OPT_CUBIC_C, G_TYPE_DOUBLE, (gdouble) 0.0,
816             NULL);
817         break;
818       case GST_VIDEO_SCALE_SPLINE:
819         gst_structure_set (options,
820             GST_VIDEO_CONVERTER_OPT_RESAMPLER_METHOD,
821             GST_TYPE_VIDEO_RESAMPLER_METHOD, GST_VIDEO_RESAMPLER_METHOD_CUBIC,
822             GST_VIDEO_RESAMPLER_OPT_CUBIC_B, G_TYPE_DOUBLE, (gdouble) 1.0,
823             GST_VIDEO_RESAMPLER_OPT_CUBIC_C, G_TYPE_DOUBLE, (gdouble) 0.0,
824             NULL);
825         break;
826       case GST_VIDEO_SCALE_CATROM:
827         gst_structure_set (options,
828             GST_VIDEO_CONVERTER_OPT_RESAMPLER_METHOD,
829             GST_TYPE_VIDEO_RESAMPLER_METHOD, GST_VIDEO_RESAMPLER_METHOD_CUBIC,
830             GST_VIDEO_RESAMPLER_OPT_CUBIC_B, G_TYPE_DOUBLE, (gdouble) 0.0,
831             GST_VIDEO_RESAMPLER_OPT_CUBIC_C, G_TYPE_DOUBLE, (gdouble) 0.5,
832             NULL);
833         break;
834       case GST_VIDEO_SCALE_MITCHELL:
835         gst_structure_set (options,
836             GST_VIDEO_CONVERTER_OPT_RESAMPLER_METHOD,
837             GST_TYPE_VIDEO_RESAMPLER_METHOD, GST_VIDEO_RESAMPLER_METHOD_CUBIC,
838             GST_VIDEO_RESAMPLER_OPT_CUBIC_B, G_TYPE_DOUBLE, (gdouble) 1.0 / 3.0,
839             GST_VIDEO_RESAMPLER_OPT_CUBIC_C, G_TYPE_DOUBLE, (gdouble) 1.0 / 3.0,
840             NULL);
841         break;
842     }
843     gst_structure_set (options,
844         GST_VIDEO_RESAMPLER_OPT_ENVELOPE, G_TYPE_DOUBLE, priv->envelope,
845         GST_VIDEO_RESAMPLER_OPT_SHARPNESS, G_TYPE_DOUBLE, priv->sharpness,
846         GST_VIDEO_RESAMPLER_OPT_SHARPEN, G_TYPE_DOUBLE, priv->sharpen,
847         GST_VIDEO_CONVERTER_OPT_DEST_X, G_TYPE_INT, priv->borders_w / 2,
848         GST_VIDEO_CONVERTER_OPT_DEST_Y, G_TYPE_INT, priv->borders_h / 2,
849         GST_VIDEO_CONVERTER_OPT_DEST_WIDTH, G_TYPE_INT,
850         out_info->width - priv->borders_w, GST_VIDEO_CONVERTER_OPT_DEST_HEIGHT,
851         G_TYPE_INT, out_info->height - priv->borders_h,
852         GST_VIDEO_CONVERTER_OPT_DITHER_METHOD, GST_TYPE_VIDEO_DITHER_METHOD,
853         priv->dither, GST_VIDEO_CONVERTER_OPT_DITHER_QUANTIZATION, G_TYPE_UINT,
854         priv->dither_quantization,
855         GST_VIDEO_CONVERTER_OPT_CHROMA_RESAMPLER_METHOD,
856         GST_TYPE_VIDEO_RESAMPLER_METHOD, priv->chroma_resampler,
857         GST_VIDEO_CONVERTER_OPT_ALPHA_MODE, GST_TYPE_VIDEO_ALPHA_MODE,
858         priv->alpha_mode, GST_VIDEO_CONVERTER_OPT_ALPHA_VALUE, G_TYPE_DOUBLE,
859         priv->alpha_value, GST_VIDEO_CONVERTER_OPT_CHROMA_MODE,
860         GST_TYPE_VIDEO_CHROMA_MODE, priv->chroma_mode,
861         GST_VIDEO_CONVERTER_OPT_MATRIX_MODE, GST_TYPE_VIDEO_MATRIX_MODE,
862         priv->matrix_mode, GST_VIDEO_CONVERTER_OPT_GAMMA_MODE,
863         GST_TYPE_VIDEO_GAMMA_MODE, priv->gamma_mode,
864         GST_VIDEO_CONVERTER_OPT_PRIMARIES_MODE, GST_TYPE_VIDEO_PRIMARIES_MODE,
865         priv->primaries_mode, GST_VIDEO_CONVERTER_OPT_THREADS, G_TYPE_UINT,
866         priv->n_threads, NULL);
867
868     priv->convert = gst_video_converter_new (in_info, out_info, options);
869     if (priv->convert == NULL)
870       goto no_convert;
871   }
872
873   GST_DEBUG_OBJECT (filter, "converting format %s -> %s",
874       gst_video_format_to_string (GST_VIDEO_INFO_FORMAT (in_info)),
875       gst_video_format_to_string (GST_VIDEO_INFO_FORMAT (out_info)));
876   GST_DEBUG_OBJECT (self, "from=%dx%d (par=%d/%d dar=%d/%d), size %"
877       G_GSIZE_FORMAT " -> to=%dx%d (par=%d/%d dar=%d/%d borders=%d:%d), "
878       "size %" G_GSIZE_FORMAT,
879       in_info->width, in_info->height, in_info->par_n, in_info->par_d,
880       from_dar_n, from_dar_d, in_info->size, out_info->width,
881       out_info->height, out_info->par_n, out_info->par_d, to_dar_n, to_dar_d,
882       priv->borders_w, priv->borders_h, out_info->size);
883
884   return TRUE;
885
886   /* ERRORS */
887 format_mismatch:
888   {
889     GST_ERROR_OBJECT (self, "input and output formats do not match");
890     return FALSE;
891   }
892 no_convert:
893   {
894     GST_ERROR_OBJECT (self, "could not create converter");
895     return FALSE;
896   }
897 }
898
899 /*
900  * This is an incomplete matrix of in formats and a score for the preferred output
901  * format.
902  *
903  *         out: RGB24   RGB16  ARGB  AYUV  YUV444  YUV422 YUV420 YUV411 YUV410  PAL  GRAY
904  *  in
905  * RGB24          0      2       1     2     2       3      4      5      6      7    8
906  * RGB16          1      0       1     2     2       3      4      5      6      7    8
907  * ARGB           2      3       0     1     4       5      6      7      8      9    10
908  * AYUV           3      4       1     0     2       5      6      7      8      9    10
909  * YUV444         2      4       3     1     0       5      6      7      8      9    10
910  * YUV422         3      5       4     2     1       0      6      7      8      9    10
911  * YUV420         4      6       5     3     2       1      0      7      8      9    10
912  * YUV411         4      6       5     3     2       1      7      0      8      9    10
913  * YUV410         6      8       7     5     4       3      2      1      0      9    10
914  * PAL            1      3       2     6     4       6      7      8      9      0    10
915  * GRAY           1      4       3     2     1       5      6      7      8      9    0
916  *
917  * PAL or GRAY are never preferred, if we can we would convert to PAL instead
918  * of GRAY, though
919  * less subsampling is preferred and if any, preferably horizontal
920  * We would like to keep the alpha, even if we would need to to colorspace conversion
921  * or lose depth.
922  */
923 #define SCORE_FORMAT_CHANGE       1
924 #define SCORE_DEPTH_CHANGE        1
925 #define SCORE_ALPHA_CHANGE        1
926 #define SCORE_CHROMA_W_CHANGE     1
927 #define SCORE_CHROMA_H_CHANGE     1
928 #define SCORE_PALETTE_CHANGE      1
929
930 #define SCORE_COLORSPACE_LOSS     2     /* RGB <-> YUV */
931 #define SCORE_DEPTH_LOSS          4     /* change bit depth */
932 #define SCORE_ALPHA_LOSS          8     /* lose the alpha channel */
933 #define SCORE_CHROMA_W_LOSS      16     /* vertical subsample */
934 #define SCORE_CHROMA_H_LOSS      32     /* horizontal subsample */
935 #define SCORE_PALETTE_LOSS       64     /* convert to palette format */
936 #define SCORE_COLOR_LOSS        128     /* convert to GRAY */
937
938 #define COLORSPACE_MASK (GST_VIDEO_FORMAT_FLAG_YUV | \
939                          GST_VIDEO_FORMAT_FLAG_RGB | GST_VIDEO_FORMAT_FLAG_GRAY)
940 #define ALPHA_MASK      (GST_VIDEO_FORMAT_FLAG_ALPHA)
941 #define PALETTE_MASK    (GST_VIDEO_FORMAT_FLAG_PALETTE)
942
943 /* calculate how much loss a conversion would be */
944 static void
945 score_value (GstBaseTransform * base, const GstVideoFormatInfo * in_info,
946     const GValue * val, gint * min_loss, const GstVideoFormatInfo ** out_info)
947 {
948   const gchar *fname;
949   const GstVideoFormatInfo *t_info;
950   GstVideoFormatFlags in_flags, t_flags;
951   gint loss;
952
953   fname = g_value_get_string (val);
954   t_info = gst_video_format_get_info (gst_video_format_from_string (fname));
955   if (!t_info || t_info->format == GST_VIDEO_FORMAT_UNKNOWN)
956     return;
957
958   /* accept input format immediately without loss */
959   if (in_info == t_info) {
960     *min_loss = 0;
961     *out_info = t_info;
962     return;
963   }
964
965   loss = SCORE_FORMAT_CHANGE;
966
967   in_flags = GST_VIDEO_FORMAT_INFO_FLAGS (in_info);
968   in_flags &= ~GST_VIDEO_FORMAT_FLAG_LE;
969   in_flags &= ~GST_VIDEO_FORMAT_FLAG_COMPLEX;
970   in_flags &= ~GST_VIDEO_FORMAT_FLAG_UNPACK;
971
972   t_flags = GST_VIDEO_FORMAT_INFO_FLAGS (t_info);
973   t_flags &= ~GST_VIDEO_FORMAT_FLAG_LE;
974   t_flags &= ~GST_VIDEO_FORMAT_FLAG_COMPLEX;
975   t_flags &= ~GST_VIDEO_FORMAT_FLAG_UNPACK;
976
977   if ((t_flags & PALETTE_MASK) != (in_flags & PALETTE_MASK)) {
978     loss += SCORE_PALETTE_CHANGE;
979     if (t_flags & PALETTE_MASK)
980       loss += SCORE_PALETTE_LOSS;
981   }
982
983   if ((t_flags & COLORSPACE_MASK) != (in_flags & COLORSPACE_MASK)) {
984     loss += SCORE_COLORSPACE_LOSS;
985     if (t_flags & GST_VIDEO_FORMAT_FLAG_GRAY)
986       loss += SCORE_COLOR_LOSS;
987   }
988
989   if ((t_flags & ALPHA_MASK) != (in_flags & ALPHA_MASK)) {
990     loss += SCORE_ALPHA_CHANGE;
991     if (in_flags & ALPHA_MASK)
992       loss += SCORE_ALPHA_LOSS;
993   }
994
995   if ((in_info->h_sub[1]) != (t_info->h_sub[1])) {
996     loss += SCORE_CHROMA_H_CHANGE;
997     if ((in_info->h_sub[1]) < (t_info->h_sub[1]))
998       loss += SCORE_CHROMA_H_LOSS;
999   }
1000   if ((in_info->w_sub[1]) != (t_info->w_sub[1])) {
1001     loss += SCORE_CHROMA_W_CHANGE;
1002     if ((in_info->w_sub[1]) < (t_info->w_sub[1]))
1003       loss += SCORE_CHROMA_W_LOSS;
1004   }
1005
1006   if ((in_info->bits) != (t_info->bits)) {
1007     loss += SCORE_DEPTH_CHANGE;
1008     if ((in_info->bits) > (t_info->bits))
1009       loss += SCORE_DEPTH_LOSS;
1010   }
1011
1012   GST_DEBUG_OBJECT (base, "score %s -> %s = %d",
1013       GST_VIDEO_FORMAT_INFO_NAME (in_info),
1014       GST_VIDEO_FORMAT_INFO_NAME (t_info), loss);
1015
1016   if (loss < *min_loss) {
1017     GST_DEBUG_OBJECT (base, "found new best %d", loss);
1018     *out_info = t_info;
1019     *min_loss = loss;
1020   }
1021 }
1022
1023 static void
1024 gst_video_convert_scale_fixate_format (GstBaseTransform * base, GstCaps * caps,
1025     GstCaps * result)
1026 {
1027   GstStructure *ins, *outs;
1028   const gchar *in_format;
1029   const GstVideoFormatInfo *in_info, *out_info = NULL;
1030   gint min_loss = G_MAXINT;
1031   guint i, capslen;
1032
1033   ins = gst_caps_get_structure (caps, 0);
1034   in_format = gst_structure_get_string (ins, "format");
1035   if (!in_format)
1036     return;
1037
1038   GST_DEBUG_OBJECT (base, "source format %s", in_format);
1039
1040   in_info =
1041       gst_video_format_get_info (gst_video_format_from_string (in_format));
1042   if (!in_info)
1043     return;
1044
1045   outs = gst_caps_get_structure (result, 0);
1046
1047   capslen = gst_caps_get_size (result);
1048   GST_DEBUG_OBJECT (base, "iterate %d structures", capslen);
1049   for (i = 0; i < capslen; i++) {
1050     GstStructure *tests;
1051     const GValue *format;
1052
1053     tests = gst_caps_get_structure (result, i);
1054     format = gst_structure_get_value (tests, "format");
1055     gst_structure_remove_fields (tests, "height", "width", "pixel-aspect-ratio",
1056         "display-aspect-ratio", NULL);
1057     /* should not happen */
1058     if (format == NULL)
1059       continue;
1060
1061     if (GST_VALUE_HOLDS_LIST (format)) {
1062       gint j, len;
1063
1064       len = gst_value_list_get_size (format);
1065       GST_DEBUG_OBJECT (base, "have %d formats", len);
1066       for (j = 0; j < len; j++) {
1067         const GValue *val;
1068
1069         val = gst_value_list_get_value (format, j);
1070         if (G_VALUE_HOLDS_STRING (val)) {
1071           score_value (base, in_info, val, &min_loss, &out_info);
1072           if (min_loss == 0)
1073             break;
1074         }
1075       }
1076     } else if (G_VALUE_HOLDS_STRING (format)) {
1077       score_value (base, in_info, format, &min_loss, &out_info);
1078     }
1079   }
1080   if (out_info)
1081     gst_structure_set (outs, "format", G_TYPE_STRING,
1082         GST_VIDEO_FORMAT_INFO_NAME (out_info), NULL);
1083 }
1084
1085 static gboolean
1086 subsampling_unchanged (GstVideoInfo * in_info, GstVideoInfo * out_info)
1087 {
1088   gint i;
1089   const GstVideoFormatInfo *in_format, *out_format;
1090
1091   if (GST_VIDEO_INFO_N_COMPONENTS (in_info) !=
1092       GST_VIDEO_INFO_N_COMPONENTS (out_info))
1093     return FALSE;
1094
1095   in_format = in_info->finfo;
1096   out_format = out_info->finfo;
1097
1098   for (i = 0; i < GST_VIDEO_INFO_N_COMPONENTS (in_info); i++) {
1099     if (GST_VIDEO_FORMAT_INFO_W_SUB (in_format,
1100             i) != GST_VIDEO_FORMAT_INFO_W_SUB (out_format, i))
1101       return FALSE;
1102     if (GST_VIDEO_FORMAT_INFO_H_SUB (in_format,
1103             i) != GST_VIDEO_FORMAT_INFO_H_SUB (out_format, i))
1104       return FALSE;
1105   }
1106
1107   return TRUE;
1108 }
1109
1110 static void
1111 transfer_colorimetry_from_input (GstBaseTransform * trans, GstCaps * in_caps,
1112     GstCaps * out_caps)
1113 {
1114   GstStructure *out_caps_s = gst_caps_get_structure (out_caps, 0);
1115   GstStructure *in_caps_s = gst_caps_get_structure (in_caps, 0);
1116   gboolean have_colorimetry =
1117       gst_structure_has_field (out_caps_s, "colorimetry");
1118   gboolean have_chroma_site =
1119       gst_structure_has_field (out_caps_s, "chroma-site");
1120
1121   /* If the output already has colorimetry and chroma-site, stop,
1122    * otherwise try and transfer what we can from the input caps */
1123   if (have_colorimetry && have_chroma_site)
1124     return;
1125
1126   {
1127     GstVideoInfo in_info, out_info;
1128     const GValue *in_colorimetry =
1129         gst_structure_get_value (in_caps_s, "colorimetry");
1130
1131     if (!gst_video_info_from_caps (&in_info, in_caps)) {
1132       GST_WARNING_OBJECT (trans,
1133           "Failed to convert sink pad caps to video info");
1134       return;
1135     }
1136     if (!gst_video_info_from_caps (&out_info, out_caps)) {
1137       GST_WARNING_OBJECT (trans,
1138           "Failed to convert src pad caps to video info");
1139       return;
1140     }
1141
1142     if (!have_colorimetry && in_colorimetry != NULL) {
1143       if ((GST_VIDEO_INFO_IS_YUV (&out_info)
1144               && GST_VIDEO_INFO_IS_YUV (&in_info))
1145           || (GST_VIDEO_INFO_IS_RGB (&out_info)
1146               && GST_VIDEO_INFO_IS_RGB (&in_info))
1147           || (GST_VIDEO_INFO_IS_GRAY (&out_info)
1148               && GST_VIDEO_INFO_IS_GRAY (&in_info))) {
1149         /* Can transfer the colorimetry intact from the input if it has it */
1150         gst_structure_set_value (out_caps_s, "colorimetry", in_colorimetry);
1151       } else {
1152         gchar *colorimetry_str;
1153
1154         /* Changing between YUV/RGB - forward primaries and transfer function, but use
1155          * default range and matrix.
1156          * the primaries is used for conversion between RGB and XYZ (CIE 1931 coordinate).
1157          * the transfer function could be another reference (e.g., HDR)
1158          */
1159         out_info.colorimetry.primaries = in_info.colorimetry.primaries;
1160         out_info.colorimetry.transfer = in_info.colorimetry.transfer;
1161
1162         colorimetry_str =
1163             gst_video_colorimetry_to_string (&out_info.colorimetry);
1164         gst_caps_set_simple (out_caps, "colorimetry", G_TYPE_STRING,
1165             colorimetry_str, NULL);
1166         g_free (colorimetry_str);
1167       }
1168     }
1169
1170     /* Only YUV output needs chroma-site. If the input was also YUV and had the same chroma
1171      * subsampling, transfer the siting. If the sub-sampling is changing, then the planes get
1172      * scaled anyway so there's no real reason to prefer the input siting. */
1173     if (!have_chroma_site && GST_VIDEO_INFO_IS_YUV (&out_info)) {
1174       if (GST_VIDEO_INFO_IS_YUV (&in_info)) {
1175         const GValue *in_chroma_site =
1176             gst_structure_get_value (in_caps_s, "chroma-site");
1177         if (in_chroma_site != NULL
1178             && subsampling_unchanged (&in_info, &out_info))
1179           gst_structure_set_value (out_caps_s, "chroma-site", in_chroma_site);
1180       }
1181     }
1182   }
1183 }
1184
1185
1186 static GstCaps *
1187 gst_video_convert_scale_get_fixed_format (GstBaseTransform * trans,
1188     GstPadDirection direction, GstCaps * caps, GstCaps * othercaps)
1189 {
1190   GstCaps *result;
1191
1192   result = gst_caps_intersect (othercaps, caps);
1193   if (gst_caps_is_empty (result)) {
1194     gst_caps_unref (result);
1195     result = gst_caps_copy (othercaps);
1196   }
1197
1198   gst_video_convert_scale_fixate_format (trans, caps, result);
1199
1200   /* fixate remaining fields */
1201   result = gst_caps_fixate (result);
1202
1203   if (direction == GST_PAD_SINK) {
1204     if (gst_caps_is_subset (caps, result)) {
1205       gst_caps_replace (&result, caps);
1206     } else {
1207       /* Try and preserve input colorimetry / chroma information */
1208       transfer_colorimetry_from_input (trans, caps, result);
1209     }
1210   }
1211
1212   return result;
1213 }
1214
1215 static GstCaps *
1216 gst_video_convert_scale_fixate_size (GstBaseTransform * base,
1217     GstPadDirection direction, GstCaps * caps, GstCaps * othercaps)
1218 {
1219   GstStructure *ins, *outs;
1220   const GValue *from_par, *to_par;
1221   GValue fpar = { 0, };
1222   GValue tpar = { 0, };
1223
1224   othercaps = gst_caps_truncate (othercaps);
1225   othercaps = gst_caps_make_writable (othercaps);
1226   ins = gst_caps_get_structure (caps, 0);
1227   outs = gst_caps_get_structure (othercaps, 0);
1228
1229   from_par = gst_structure_get_value (ins, "pixel-aspect-ratio");
1230   to_par = gst_structure_get_value (outs, "pixel-aspect-ratio");
1231
1232   /* If we're fixating from the sinkpad we always set the PAR and
1233    * assume that missing PAR on the sinkpad means 1/1 and
1234    * missing PAR on the srcpad means undefined
1235    */
1236   if (direction == GST_PAD_SINK) {
1237     if (!from_par) {
1238       g_value_init (&fpar, GST_TYPE_FRACTION);
1239       gst_value_set_fraction (&fpar, 1, 1);
1240       from_par = &fpar;
1241     }
1242     if (!to_par) {
1243       g_value_init (&tpar, GST_TYPE_FRACTION_RANGE);
1244       gst_value_set_fraction_range_full (&tpar, 1, G_MAXINT, G_MAXINT, 1);
1245       to_par = &tpar;
1246     }
1247   } else {
1248     if (!to_par) {
1249       g_value_init (&tpar, GST_TYPE_FRACTION);
1250       gst_value_set_fraction (&tpar, 1, 1);
1251       to_par = &tpar;
1252
1253       gst_structure_set (outs, "pixel-aspect-ratio", GST_TYPE_FRACTION, 1, 1,
1254           NULL);
1255     }
1256     if (!from_par) {
1257       g_value_init (&fpar, GST_TYPE_FRACTION);
1258       gst_value_set_fraction (&fpar, 1, 1);
1259       from_par = &fpar;
1260     }
1261   }
1262
1263   /* we have both PAR but they might not be fixated */
1264   {
1265     gint from_w, from_h, from_par_n, from_par_d, to_par_n, to_par_d;
1266     gint w = 0, h = 0;
1267     gint from_dar_n, from_dar_d;
1268     gint num, den;
1269
1270     /* from_par should be fixed */
1271     g_return_val_if_fail (gst_value_is_fixed (from_par), othercaps);
1272
1273     from_par_n = gst_value_get_fraction_numerator (from_par);
1274     from_par_d = gst_value_get_fraction_denominator (from_par);
1275
1276     gst_structure_get_int (ins, "width", &from_w);
1277     gst_structure_get_int (ins, "height", &from_h);
1278
1279     gst_structure_get_int (outs, "width", &w);
1280     gst_structure_get_int (outs, "height", &h);
1281
1282     /* if both width and height are already fixed, we can't do anything
1283      * about it anymore */
1284     if (w && h) {
1285       guint n, d;
1286
1287       GST_DEBUG_OBJECT (base, "dimensions already set to %dx%d, not fixating",
1288           w, h);
1289       if (!gst_value_is_fixed (to_par)) {
1290         if (gst_video_calculate_display_ratio (&n, &d, from_w, from_h,
1291                 from_par_n, from_par_d, w, h)) {
1292           GST_DEBUG_OBJECT (base, "fixating to_par to %dx%d", n, d);
1293           if (gst_structure_has_field (outs, "pixel-aspect-ratio"))
1294             gst_structure_fixate_field_nearest_fraction (outs,
1295                 "pixel-aspect-ratio", n, d);
1296           else if (n != d)
1297             gst_structure_set (outs, "pixel-aspect-ratio", GST_TYPE_FRACTION,
1298                 n, d, NULL);
1299         }
1300       }
1301       goto done;
1302     }
1303
1304     /* Calculate input DAR */
1305     if (!gst_util_fraction_multiply (from_w, from_h, from_par_n, from_par_d,
1306             &from_dar_n, &from_dar_d)) {
1307       GST_ELEMENT_ERROR (base, CORE, NEGOTIATION, (NULL),
1308           ("Error calculating the output scaled size - integer overflow"));
1309       goto done;
1310     }
1311
1312     GST_DEBUG_OBJECT (base, "Input DAR is %d/%d", from_dar_n, from_dar_d);
1313
1314     /* If either width or height are fixed there's not much we
1315      * can do either except choosing a height or width and PAR
1316      * that matches the DAR as good as possible
1317      */
1318     if (h) {
1319       GstStructure *tmp;
1320       gint set_w, set_par_n, set_par_d;
1321
1322       GST_DEBUG_OBJECT (base, "height is fixed (%d)", h);
1323
1324       /* If the PAR is fixed too, there's not much to do
1325        * except choosing the width that is nearest to the
1326        * width with the same DAR */
1327       if (gst_value_is_fixed (to_par)) {
1328         to_par_n = gst_value_get_fraction_numerator (to_par);
1329         to_par_d = gst_value_get_fraction_denominator (to_par);
1330
1331         GST_DEBUG_OBJECT (base, "PAR is fixed %d/%d", to_par_n, to_par_d);
1332
1333         if (!gst_util_fraction_multiply (from_dar_n, from_dar_d, to_par_d,
1334                 to_par_n, &num, &den)) {
1335           GST_ELEMENT_ERROR (base, CORE, NEGOTIATION, (NULL),
1336               ("Error calculating the output scaled size - integer overflow"));
1337           goto done;
1338         }
1339
1340         w = (guint) gst_util_uint64_scale_int_round (h, num, den);
1341         gst_structure_fixate_field_nearest_int (outs, "width", w);
1342
1343         goto done;
1344       }
1345
1346       /* The PAR is not fixed and it's quite likely that we can set
1347        * an arbitrary PAR. */
1348
1349       /* Check if we can keep the input width */
1350       tmp = gst_structure_copy (outs);
1351       gst_structure_fixate_field_nearest_int (tmp, "width", from_w);
1352       gst_structure_get_int (tmp, "width", &set_w);
1353
1354       /* Might have failed but try to keep the DAR nonetheless by
1355        * adjusting the PAR */
1356       if (!gst_util_fraction_multiply (from_dar_n, from_dar_d, h, set_w,
1357               &to_par_n, &to_par_d)) {
1358         GST_ELEMENT_ERROR (base, CORE, NEGOTIATION, (NULL),
1359             ("Error calculating the output scaled size - integer overflow"));
1360         gst_structure_free (tmp);
1361         goto done;
1362       }
1363
1364       if (!gst_structure_has_field (tmp, "pixel-aspect-ratio"))
1365         gst_structure_set_value (tmp, "pixel-aspect-ratio", to_par);
1366       gst_structure_fixate_field_nearest_fraction (tmp, "pixel-aspect-ratio",
1367           to_par_n, to_par_d);
1368       gst_structure_get_fraction (tmp, "pixel-aspect-ratio", &set_par_n,
1369           &set_par_d);
1370       gst_structure_free (tmp);
1371
1372       /* Check if the adjusted PAR is accepted */
1373       if (set_par_n == to_par_n && set_par_d == to_par_d) {
1374         if (gst_structure_has_field (outs, "pixel-aspect-ratio") ||
1375             set_par_n != set_par_d)
1376           gst_structure_set (outs, "width", G_TYPE_INT, set_w,
1377               "pixel-aspect-ratio", GST_TYPE_FRACTION, set_par_n, set_par_d,
1378               NULL);
1379         goto done;
1380       }
1381
1382       /* Otherwise scale the width to the new PAR and check if the
1383        * adjusted with is accepted. If all that fails we can't keep
1384        * the DAR */
1385       if (!gst_util_fraction_multiply (from_dar_n, from_dar_d, set_par_d,
1386               set_par_n, &num, &den)) {
1387         GST_ELEMENT_ERROR (base, CORE, NEGOTIATION, (NULL),
1388             ("Error calculating the output scaled size - integer overflow"));
1389         goto done;
1390       }
1391
1392       w = (guint) gst_util_uint64_scale_int_round (h, num, den);
1393       gst_structure_fixate_field_nearest_int (outs, "width", w);
1394       if (gst_structure_has_field (outs, "pixel-aspect-ratio") ||
1395           set_par_n != set_par_d)
1396         gst_structure_set (outs, "pixel-aspect-ratio", GST_TYPE_FRACTION,
1397             set_par_n, set_par_d, NULL);
1398
1399       goto done;
1400     } else if (w) {
1401       GstStructure *tmp;
1402       gint set_h, set_par_n, set_par_d;
1403
1404       GST_DEBUG_OBJECT (base, "width is fixed (%d)", w);
1405
1406       /* If the PAR is fixed too, there's not much to do
1407        * except choosing the height that is nearest to the
1408        * height with the same DAR */
1409       if (gst_value_is_fixed (to_par)) {
1410         to_par_n = gst_value_get_fraction_numerator (to_par);
1411         to_par_d = gst_value_get_fraction_denominator (to_par);
1412
1413         GST_DEBUG_OBJECT (base, "PAR is fixed %d/%d", to_par_n, to_par_d);
1414
1415         if (!gst_util_fraction_multiply (from_dar_n, from_dar_d, to_par_d,
1416                 to_par_n, &num, &den)) {
1417           GST_ELEMENT_ERROR (base, CORE, NEGOTIATION, (NULL),
1418               ("Error calculating the output scaled size - integer overflow"));
1419           goto done;
1420         }
1421
1422         h = (guint) gst_util_uint64_scale_int_round (w, den, num);
1423         gst_structure_fixate_field_nearest_int (outs, "height", h);
1424
1425         goto done;
1426       }
1427
1428       /* The PAR is not fixed and it's quite likely that we can set
1429        * an arbitrary PAR. */
1430
1431       /* Check if we can keep the input height */
1432       tmp = gst_structure_copy (outs);
1433       gst_structure_fixate_field_nearest_int (tmp, "height", from_h);
1434       gst_structure_get_int (tmp, "height", &set_h);
1435
1436       /* Might have failed but try to keep the DAR nonetheless by
1437        * adjusting the PAR */
1438       if (!gst_util_fraction_multiply (from_dar_n, from_dar_d, set_h, w,
1439               &to_par_n, &to_par_d)) {
1440         GST_ELEMENT_ERROR (base, CORE, NEGOTIATION, (NULL),
1441             ("Error calculating the output scaled size - integer overflow"));
1442         gst_structure_free (tmp);
1443         goto done;
1444       }
1445       if (!gst_structure_has_field (tmp, "pixel-aspect-ratio"))
1446         gst_structure_set_value (tmp, "pixel-aspect-ratio", to_par);
1447       gst_structure_fixate_field_nearest_fraction (tmp, "pixel-aspect-ratio",
1448           to_par_n, to_par_d);
1449       gst_structure_get_fraction (tmp, "pixel-aspect-ratio", &set_par_n,
1450           &set_par_d);
1451       gst_structure_free (tmp);
1452
1453       /* Check if the adjusted PAR is accepted */
1454       if (set_par_n == to_par_n && set_par_d == to_par_d) {
1455         if (gst_structure_has_field (outs, "pixel-aspect-ratio") ||
1456             set_par_n != set_par_d)
1457           gst_structure_set (outs, "height", G_TYPE_INT, set_h,
1458               "pixel-aspect-ratio", GST_TYPE_FRACTION, set_par_n, set_par_d,
1459               NULL);
1460         goto done;
1461       }
1462
1463       /* Otherwise scale the height to the new PAR and check if the
1464        * adjusted with is accepted. If all that fails we can't keep
1465        * the DAR */
1466       if (!gst_util_fraction_multiply (from_dar_n, from_dar_d, set_par_d,
1467               set_par_n, &num, &den)) {
1468         GST_ELEMENT_ERROR (base, CORE, NEGOTIATION, (NULL),
1469             ("Error calculating the output scaled size - integer overflow"));
1470         goto done;
1471       }
1472
1473       h = (guint) gst_util_uint64_scale_int_round (w, den, num);
1474       gst_structure_fixate_field_nearest_int (outs, "height", h);
1475       if (gst_structure_has_field (outs, "pixel-aspect-ratio") ||
1476           set_par_n != set_par_d)
1477         gst_structure_set (outs, "pixel-aspect-ratio", GST_TYPE_FRACTION,
1478             set_par_n, set_par_d, NULL);
1479
1480       goto done;
1481     } else if (gst_value_is_fixed (to_par)) {
1482       GstStructure *tmp;
1483       gint set_h, set_w, f_h, f_w;
1484
1485       to_par_n = gst_value_get_fraction_numerator (to_par);
1486       to_par_d = gst_value_get_fraction_denominator (to_par);
1487
1488       /* Calculate scale factor for the PAR change */
1489       if (!gst_util_fraction_multiply (from_dar_n, from_dar_d, to_par_n,
1490               to_par_d, &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       /* Try to keep the input height (because of interlacing) */
1497       tmp = gst_structure_copy (outs);
1498       gst_structure_fixate_field_nearest_int (tmp, "height", from_h);
1499       gst_structure_get_int (tmp, "height", &set_h);
1500
1501       /* This might have failed but try to scale the width
1502        * to keep the DAR nonetheless */
1503       w = (guint) gst_util_uint64_scale_int_round (set_h, num, den);
1504       gst_structure_fixate_field_nearest_int (tmp, "width", w);
1505       gst_structure_get_int (tmp, "width", &set_w);
1506       gst_structure_free (tmp);
1507
1508       /* We kept the DAR and the height is nearest to the original height */
1509       if (set_w == w) {
1510         gst_structure_set (outs, "width", G_TYPE_INT, set_w, "height",
1511             G_TYPE_INT, set_h, NULL);
1512         goto done;
1513       }
1514
1515       f_h = set_h;
1516       f_w = set_w;
1517
1518       /* If the former failed, try to keep the input width at least */
1519       tmp = gst_structure_copy (outs);
1520       gst_structure_fixate_field_nearest_int (tmp, "width", from_w);
1521       gst_structure_get_int (tmp, "width", &set_w);
1522
1523       /* This might have failed but try to scale the width
1524        * to keep the DAR nonetheless */
1525       h = (guint) gst_util_uint64_scale_int_round (set_w, den, num);
1526       gst_structure_fixate_field_nearest_int (tmp, "height", h);
1527       gst_structure_get_int (tmp, "height", &set_h);
1528       gst_structure_free (tmp);
1529
1530       /* We kept the DAR and the width is nearest to the original width */
1531       if (set_h == h) {
1532         gst_structure_set (outs, "width", G_TYPE_INT, set_w, "height",
1533             G_TYPE_INT, set_h, NULL);
1534         goto done;
1535       }
1536
1537       /* If all this failed, keep the dimensions with the DAR that was closest
1538        * to the correct DAR. This changes the DAR but there's not much else to
1539        * do here.
1540        */
1541       if (set_w * ABS (set_h - h) < ABS (f_w - w) * f_h) {
1542         f_h = set_h;
1543         f_w = set_w;
1544       }
1545       gst_structure_set (outs, "width", G_TYPE_INT, f_w, "height", G_TYPE_INT,
1546           f_h, NULL);
1547       goto done;
1548     } else {
1549       GstStructure *tmp;
1550       gint set_h, set_w, set_par_n, set_par_d, tmp2;
1551
1552       /* width, height and PAR are not fixed but passthrough is not possible */
1553
1554       /* First try to keep the height and width as good as possible
1555        * and scale PAR */
1556       tmp = gst_structure_copy (outs);
1557       gst_structure_fixate_field_nearest_int (tmp, "height", from_h);
1558       gst_structure_get_int (tmp, "height", &set_h);
1559       gst_structure_fixate_field_nearest_int (tmp, "width", from_w);
1560       gst_structure_get_int (tmp, "width", &set_w);
1561
1562       if (!gst_util_fraction_multiply (from_dar_n, from_dar_d, set_h, set_w,
1563               &to_par_n, &to_par_d)) {
1564         GST_ELEMENT_ERROR (base, CORE, NEGOTIATION, (NULL),
1565             ("Error calculating the output scaled size - integer overflow"));
1566         gst_structure_free (tmp);
1567         goto done;
1568       }
1569
1570       if (!gst_structure_has_field (tmp, "pixel-aspect-ratio"))
1571         gst_structure_set_value (tmp, "pixel-aspect-ratio", to_par);
1572       gst_structure_fixate_field_nearest_fraction (tmp, "pixel-aspect-ratio",
1573           to_par_n, to_par_d);
1574       gst_structure_get_fraction (tmp, "pixel-aspect-ratio", &set_par_n,
1575           &set_par_d);
1576       gst_structure_free (tmp);
1577
1578       if (set_par_n == to_par_n && set_par_d == to_par_d) {
1579         gst_structure_set (outs, "width", G_TYPE_INT, set_w, "height",
1580             G_TYPE_INT, set_h, NULL);
1581
1582         if (gst_structure_has_field (outs, "pixel-aspect-ratio") ||
1583             set_par_n != set_par_d)
1584           gst_structure_set (outs, "pixel-aspect-ratio", GST_TYPE_FRACTION,
1585               set_par_n, set_par_d, NULL);
1586         goto done;
1587       }
1588
1589       /* Otherwise try to scale width to keep the DAR with the set
1590        * PAR and height */
1591       if (!gst_util_fraction_multiply (from_dar_n, from_dar_d, set_par_d,
1592               set_par_n, &num, &den)) {
1593         GST_ELEMENT_ERROR (base, CORE, NEGOTIATION, (NULL),
1594             ("Error calculating the output scaled size - integer overflow"));
1595         goto done;
1596       }
1597
1598       w = (guint) gst_util_uint64_scale_int_round (set_h, num, den);
1599       tmp = gst_structure_copy (outs);
1600       gst_structure_fixate_field_nearest_int (tmp, "width", w);
1601       gst_structure_get_int (tmp, "width", &tmp2);
1602       gst_structure_free (tmp);
1603
1604       if (tmp2 == w) {
1605         gst_structure_set (outs, "width", G_TYPE_INT, tmp2, "height",
1606             G_TYPE_INT, set_h, NULL);
1607         if (gst_structure_has_field (outs, "pixel-aspect-ratio") ||
1608             set_par_n != set_par_d)
1609           gst_structure_set (outs, "pixel-aspect-ratio", GST_TYPE_FRACTION,
1610               set_par_n, set_par_d, NULL);
1611         goto done;
1612       }
1613
1614       /* ... or try the same with the height */
1615       h = (guint) gst_util_uint64_scale_int_round (set_w, den, num);
1616       tmp = gst_structure_copy (outs);
1617       gst_structure_fixate_field_nearest_int (tmp, "height", h);
1618       gst_structure_get_int (tmp, "height", &tmp2);
1619       gst_structure_free (tmp);
1620
1621       if (tmp2 == h) {
1622         gst_structure_set (outs, "width", G_TYPE_INT, set_w, "height",
1623             G_TYPE_INT, tmp2, NULL);
1624         if (gst_structure_has_field (outs, "pixel-aspect-ratio") ||
1625             set_par_n != set_par_d)
1626           gst_structure_set (outs, "pixel-aspect-ratio", GST_TYPE_FRACTION,
1627               set_par_n, set_par_d, NULL);
1628         goto done;
1629       }
1630
1631       /* If all fails we can't keep the DAR and take the nearest values
1632        * for everything from the first try */
1633       gst_structure_set (outs, "width", G_TYPE_INT, set_w, "height",
1634           G_TYPE_INT, set_h, NULL);
1635       if (gst_structure_has_field (outs, "pixel-aspect-ratio") ||
1636           set_par_n != set_par_d)
1637         gst_structure_set (outs, "pixel-aspect-ratio", GST_TYPE_FRACTION,
1638             set_par_n, set_par_d, NULL);
1639     }
1640   }
1641
1642 done:
1643   othercaps = gst_caps_fixate (othercaps);
1644
1645   GST_DEBUG_OBJECT (base, "fixated othercaps to %" GST_PTR_FORMAT, othercaps);
1646
1647   if (from_par == &fpar)
1648     g_value_unset (&fpar);
1649   if (to_par == &tpar)
1650     g_value_unset (&tpar);
1651
1652   return othercaps;
1653 }
1654
1655 static GstCaps *
1656 gst_video_convert_scale_fixate_caps (GstBaseTransform * base,
1657     GstPadDirection direction, GstCaps * caps, GstCaps * othercaps)
1658 {
1659   GstCaps *format;
1660
1661   GST_DEBUG_OBJECT (base,
1662       "trying to fixate othercaps %" GST_PTR_FORMAT " based on caps %"
1663       GST_PTR_FORMAT, othercaps, caps);
1664
1665   format = gst_video_convert_scale_get_fixed_format (base, direction, caps,
1666       othercaps);
1667
1668   if (gst_caps_is_empty (format)) {
1669     GST_ERROR_OBJECT (base, "Could not convert formats");
1670     return format;
1671   }
1672
1673   othercaps =
1674       gst_video_convert_scale_fixate_size (base, direction, caps, othercaps);
1675   if (gst_caps_get_size (othercaps) == 1) {
1676     gint i;
1677     const gchar *format_fields[] = { "format", "colorimetry", "chroma-site" };
1678     GstStructure *format_struct = gst_caps_get_structure (format, 0);
1679     GstStructure *fixated_struct;
1680
1681     othercaps = gst_caps_make_writable (othercaps);
1682     fixated_struct = gst_caps_get_structure (othercaps, 0);
1683
1684     for (i = 0; i < G_N_ELEMENTS (format_fields); i++) {
1685       if (gst_structure_has_field (format_struct, format_fields[i])) {
1686         gst_structure_set (fixated_struct, format_fields[i], G_TYPE_STRING,
1687             gst_structure_get_string (format_struct, format_fields[i]), NULL);
1688       } else {
1689         gst_structure_remove_field (fixated_struct, format_fields[i]);
1690       }
1691     }
1692   }
1693   gst_caps_unref (format);
1694
1695   GST_DEBUG_OBJECT (base, "fixated othercaps to %" GST_PTR_FORMAT, othercaps);
1696
1697   return othercaps;
1698 }
1699
1700 #define GET_LINE(frame, line) \
1701     (gpointer)(((guint8*)(GST_VIDEO_FRAME_PLANE_DATA (frame, 0))) + \
1702      GST_VIDEO_FRAME_PLANE_STRIDE (frame, 0) * (line))
1703
1704 static GstFlowReturn
1705 gst_video_convert_scale_transform_frame (GstVideoFilter * filter,
1706     GstVideoFrame * in_frame, GstVideoFrame * out_frame)
1707 {
1708   GstVideoConvertScalePrivate *priv = PRIV (filter);
1709   GstFlowReturn ret = GST_FLOW_OK;
1710
1711   GST_CAT_DEBUG_OBJECT (CAT_PERFORMANCE, filter, "doing video scaling");
1712
1713   gst_video_converter_frame (priv->convert, in_frame, out_frame);
1714
1715   return ret;
1716 }
1717
1718 static gboolean
1719 gst_video_convert_scale_src_event (GstBaseTransform * trans, GstEvent * event)
1720 {
1721   GstVideoConvertScale *self = GST_VIDEO_CONVERT_SCALE_CAST (trans);
1722   GstVideoFilter *filter = GST_VIDEO_FILTER_CAST (trans);
1723   gboolean ret;
1724   gdouble x, y;
1725
1726   GST_DEBUG_OBJECT (self, "handling %s event", GST_EVENT_TYPE_NAME (event));
1727
1728   switch (GST_EVENT_TYPE (event)) {
1729     case GST_EVENT_NAVIGATION:
1730       if (filter->in_info.width != filter->out_info.width ||
1731           filter->in_info.height != filter->out_info.height) {
1732         event = gst_event_make_writable (event);
1733
1734         if (gst_navigation_event_get_coordinates (event, &x, &y)) {
1735           gst_navigation_event_set_coordinates (event,
1736               x * filter->in_info.width / filter->out_info.width,
1737               y * filter->in_info.height / filter->out_info.height);
1738         }
1739       }
1740       break;
1741     default:
1742       break;
1743   }
1744
1745   ret = GST_BASE_TRANSFORM_CLASS (parent_class)->src_event (trans, event);
1746
1747   return ret;
1748 }