V4L/DVB: V4L2: add a generic function to find the nearest discrete format to the required one

Many video drivers implement a fixed set of frame formats and thus face a task
of finding the best match for a user-requested format. Implementing this in a
generic function has also an advantage, that different drivers with similar
supported format sets will select the same format for the user, which improves
consistency across drivers.

Signed-off-by: Guennadi Liakhovetski <g.liakhovetski@gmx.de>
Signed-off-by: Mauro Carvalho Chehab <mchehab@redhat.com>
diff --git a/drivers/media/video/v4l2-common.c b/drivers/media/video/v4l2-common.c
index 8ee1179..31ae1a1 100644
--- a/drivers/media/video/v4l2-common.c
+++ b/drivers/media/video/v4l2-common.c
@@ -676,3 +676,27 @@
 	return 0;
 }
 EXPORT_SYMBOL_GPL(v4l_fill_dv_preset_info);
+
+struct v4l2_frmsize_discrete *v4l2_find_nearest_format(struct v4l2_discrete_probe *probe,
+						       s32 width, s32 height)
+{
+	int i;
+	u32 error, min_error = UINT_MAX;
+	struct v4l2_frmsize_discrete *size, *best = NULL;
+
+	if (!probe)
+		return best;
+
+	for (i = 0, size = probe->sizes; i < probe->num_sizes; i++, size++) {
+		error = abs(size->width - width) + abs(size->height - height);
+		if (error < min_error) {
+			min_error = error;
+			best = size;
+		}
+		if (!error)
+			break;
+	}
+
+	return best;
+}
+EXPORT_SYMBOL_GPL(v4l2_find_nearest_format);
diff --git a/include/linux/videodev2.h b/include/linux/videodev2.h
index b06479f..957d5b0 100644
--- a/include/linux/videodev2.h
+++ b/include/linux/videodev2.h
@@ -397,6 +397,14 @@
 	__u32			height;		/* Frame height [pixel] */
 };
 
+struct v4l2_discrete_probe {
+	const struct v4l2_frmsize_discrete	*sizes;
+	int					num_sizes;
+};
+
+struct v4l2_frmsize_discrete *v4l2_find_nearest_format(struct v4l2_discrete_probe *probe,
+						       s32 width, s32 height);
+
 struct v4l2_frmsize_stepwise {
 	__u32			min_width;	/* Minimum frame width [pixel] */
 	__u32			max_width;	/* Maximum frame width [pixel] */