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