weston: Add gst-recorder in weston 2.0.0
[AGL/meta-agl-devel.git] / meta-gstrecorder-rcar-gen3 / recipes-graphics / wayland / weston / 0002-Add-gst-recorder-for-h264-output-streaming.patch
1 From b1aa1e32e6a88ae2c3b1335ab63fa2d8f7e008c0 Mon Sep 17 00:00:00 2001
2 From: Harunobu Kurokawa <harunobu.kurokawa.dn@renesas.com>
3 Date: Thu, 10 Aug 2017 15:49:14 +0900
4 Subject: [PATCH 2/4] Add gst-recorder for h264 output streaming
5
6 This patch is ported to weston 2.0.0.
7 --------
8 Author: Damian Hobson-Garcia <dhobsong@igel.co.jp>
9 Date:   Thu Apr 27 16:47:00 2017 +0900
10
11   Following patch ported to Weston 1.11 with minor updates
12   --------
13   To use gst-recorder run weston with arg --gst-record. Add
14   recorder=true property to output section of one of the outputs
15   (real or virtual). Use properties ip, port to set host of RTP
16   stream. Use property bitrate to set desirable maximum h264 bitrate.
17   --------
18 ---
19  Makefile.am                         |   17 +
20  compositor/main.c                   |    4 +-
21  configure.ac                        |   13 +
22  libweston/compositor-drm.c          |  202 +++++-
23  libweston/compositor-drm.h          |    1 +
24  libweston/gst-recorder.c            | 1213 +++++++++++++++++++++++++++++++++++
25  libweston/gst-recorder.h            |   58 ++
26  libweston/media-ctl/libmediactl.c   |  955 +++++++++++++++++++++++++++
27  libweston/media-ctl/libv4l2subdev.c |  759 ++++++++++++++++++++++
28  libweston/media-ctl/mediactl-priv.h |   64 ++
29  libweston/media-ctl/mediactl.h      |  423 ++++++++++++
30  libweston/media-ctl/tools.h         |   32 +
31  libweston/media-ctl/v4l2subdev.h    |  258 ++++++++
32  13 files changed, 3997 insertions(+), 2 deletions(-)
33  create mode 100644 libweston/gst-recorder.c
34  create mode 100644 libweston/gst-recorder.h
35  create mode 100644 libweston/media-ctl/libmediactl.c
36  create mode 100644 libweston/media-ctl/libv4l2subdev.c
37  create mode 100644 libweston/media-ctl/mediactl-priv.h
38  create mode 100644 libweston/media-ctl/mediactl.h
39  create mode 100644 libweston/media-ctl/tools.h
40  create mode 100644 libweston/media-ctl/v4l2subdev.h
41
42 diff --git a/Makefile.am b/Makefile.am
43 index 36cb859..8139466 100644
44 --- a/Makefile.am
45 +++ b/Makefile.am
46 @@ -411,6 +411,23 @@ drm_backend_la_LIBADD += $(LIBVA_LIBS)
47  drm_backend_la_LDFLAGS += -pthread
48  drm_backend_la_CFLAGS += $(LIBVA_CFLAGS)
49  endif
50 +
51 +if ENABLE_GST_RECORDER
52 +drm_backend_la_SOURCES +=                      \
53 +       libweston/gst-recorder.c                        \
54 +       libweston/gst-recorder.h                        \
55 +       libweston/v4l2-device.h                 \
56 +       libweston/media-ctl/libmediactl.c               \
57 +       libweston/media-ctl/libv4l2subdev.c             \
58 +       libweston/media-ctl/mediactl-priv.h             \
59 +       libweston/media-ctl/mediactl.h          \
60 +       libweston/media-ctl/tools.h                     \
61 +       libweston/media-ctl/v4l2subdev.h
62 +drm_backend_la_LIBADD += $(LIBVA_LIBS)                 \
63 +       -lgstallocators-1.0                     \
64 +       -lgstvideo-1.0
65 +drm_backend_la_CFLAGS += $(LIBVA_CFLAGS)
66 +endif
67  endif
68  
69  if ENABLE_WAYLAND_COMPOSITOR
70 diff --git a/compositor/main.c b/compositor/main.c
71 index 4c0f8c9..fc57074 100644
72 --- a/compositor/main.c
73 +++ b/compositor/main.c
74 @@ -567,7 +567,8 @@ usage(int error_code)
75                 "  --tty=TTY\t\tThe tty to use\n"
76                 "  --use-pixman\t\tUse the pixman (CPU) renderer\n"
77                 "  --use-v4l2\t\tUse the v4l2 renderer\n"
78 -               "  --current-mode\tPrefer current KMS mode over EDID preferred mode\n\n");
79 +               "  --current-mode\tPrefer current KMS mode over EDID preferred mode\n"
80 +               "  --gst-record\t\tEnable GStreamer recording\n\n");
81  #endif
82  
83  #if defined(BUILD_FBDEV_COMPOSITOR)
84 @@ -1229,6 +1230,7 @@ load_drm_backend(struct weston_compositor *c,
85                 { WESTON_OPTION_BOOLEAN, "current-mode", 0, &wet->drm_use_current_mode },
86                 { WESTON_OPTION_BOOLEAN, "use-pixman", 0, &config.use_pixman },
87                 { WESTON_OPTION_BOOLEAN, "use-v4l2", 0, &config.use_v4l2 },
88 +               { WESTON_OPTION_BOOLEAN, "gst-record", 0, &config.enable_recorder },
89         };
90  
91         parse_options(options, ARRAY_LENGTH(options), argc, argv);
92 diff --git a/configure.ac b/configure.ac
93 index c2ebe4c..67a61b9 100644
94 --- a/configure.ac
95 +++ b/configure.ac
96 @@ -265,6 +265,18 @@ if test x$enable_headless_compositor = xyes; then
97  fi
98  
99  
100 +AC_ARG_ENABLE(gst-recorder, [  --enable-gst-recorder],,
101 +             enable_gst_recorder=yes)
102 +if test x$enable_gst_recorder != xno; then
103 +  AC_DEFINE([BUILD_GST_RECORDER], [1], [Build the gst recorder])
104 +  PKG_CHECK_MODULES(GSTREAMER, [gstreamer-1.0 >= 1.0])
105 +
106 +  CPPFLAGS="$CPPFLAGS $GSTREAMER_CFLAGS"
107 +  LIBS="$LIBS $GSTREAMER_LIBS -lgstapp-1.0"
108 +fi
109 +AM_CONDITIONAL(ENABLE_GST_RECORDER, test "x$enable_gst_recorder" != xno)
110 +
111 +
112  AC_ARG_ENABLE([fbdev-compositor], [  --enable-fbdev-compositor],,
113                enable_fbdev_compositor=yes)
114  AM_CONDITIONAL([ENABLE_FBDEV_COMPOSITOR],
115 @@ -752,4 +764,5 @@ AC_MSG_RESULT([
116         libwebp Support                 ${have_webp}
117         libunwind Support               ${have_libunwind}
118         VA H.264 encoding Support       ${have_libva}
119 +       GStreamer H.264 enc. Support    ${enable_gst_recorder}
120  ])
121 diff --git a/libweston/compositor-drm.c b/libweston/compositor-drm.c
122 index 3b97232..0706e5b 100644
123 --- a/libweston/compositor-drm.c
124 +++ b/libweston/compositor-drm.c
125 @@ -59,9 +59,11 @@
126  #include "v4l2-renderer.h"
127  #include "launcher-util.h"
128  #include "vaapi-recorder.h"
129 +#include "gst-recorder.h"
130  #include "presentation-time-server-protocol.h"
131  #include "linux-dmabuf.h"
132  #include "linux-dmabuf-unstable-v1-server-protocol.h"
133 +#include "compositor/weston.h"
134  
135  #ifndef DRM_CAP_TIMESTAMP_MONOTONIC
136  #define DRM_CAP_TIMESTAMP_MONOTONIC 0x6
137 @@ -117,6 +119,7 @@ struct drm_backend {
138         int use_v4l2;
139  
140         struct v4l2_renderer_config v4l2_config;
141 +       int enable_recorder;
142  
143         struct udev_input input;
144  
145 @@ -189,7 +192,12 @@ struct drm_output {
146         int current_image;
147         pixman_region32_t previous_damage;
148  
149 +#ifdef BUILD_VAAPI_RECORDER
150         struct vaapi_recorder *recorder;
151 +#endif
152 +#ifdef BUILD_GST_RECORDER
153 +       struct gst_recorder *recorder;
154 +#endif
155         struct wl_listener recorder_frame_listener;
156  
157         /* not real output device */
158 @@ -249,6 +257,9 @@ drm_output_set_cursor(struct drm_output *output);
159  static void
160  drm_output_update_msc(struct drm_output *output, unsigned int seq);
161  
162 +static void
163 +recorders_enable(struct drm_backend *b);
164 +
165  static int
166  drm_sprite_crtc_supported(struct drm_output *output, struct drm_sprite *sprite)
167  {
168 @@ -2411,6 +2422,23 @@ parse_modeline(const char *s, drmModeModeInfo *mode)
169         return 0;
170  }
171  
172 +static int parse_crop_rect(const char *s, struct v4l2_rect* crop)
173 +{
174 +       crop->left = 0;
175 +       crop->top = 0;
176 +       crop->width = 0;
177 +       crop->height = 0;
178 +
179 +       if (sscanf(s, "%dx%d@%dx%d",
180 +                  &crop->width,
181 +                  &crop->height,
182 +                  &crop->top,
183 +                  &crop->left) != 4)
184 +               return -1;
185 +
186 +       return 0;
187 +}
188 +
189  static void
190  setup_output_seat_constraint(struct drm_backend *b,
191                              struct weston_output *output,
192 @@ -3678,7 +3706,173 @@ recorder_binding(struct weston_keyboard *keyboard, uint32_t time, uint32_t key,
193                 recorder_destroy(output);
194         }
195  }
196 -#else
197 +#endif
198 +
199 +#ifdef BUILD_GST_RECORDER
200 +static void
201 +recorder_destroy(struct drm_output *output)
202 +{
203 +       wl_list_remove(&output->recorder_frame_listener.link);
204 +
205 +       gst_recorder_destroy(output->recorder);
206 +       output->recorder = NULL;
207 +
208 +       output->base.disable_planes--;
209 +
210 +       weston_log("[gst recorder] done\n");
211 +}
212 +
213 +static void
214 +recorder_frame_notify(struct wl_listener *listener, void *data)
215 +{
216 +       int ret = 0;
217 +       struct drm_output *output;
218 +       struct drm_backend *b;
219 +       int fd;
220 +
221 +       output = container_of(listener, struct drm_output,
222 +                             recorder_frame_listener);
223 +       b = to_drm_backend(output->base.compositor);
224 +
225 +       if (!output->recorder) {
226 +               weston_log("%s: output have no recorder enabled\n",
227 +                       output->base.name);
228 +               return;
229 +       }
230 +
231 +       if (!output->current) {
232 +               weston_log("%s: frame notify while current frame == NULL\n",
233 +                          output->base.name);
234 +               return;
235 +       }
236 +
237 +       ret = drmPrimeHandleToFD(b->drm.fd, output->current->handle,
238 +                                DRM_CLOEXEC, &fd);
239 +       if (!ret) {
240 +               ret = gst_recorder_frame_dmafd(output->recorder, fd,
241 +                                              output->current->stride);
242 +       }
243 +
244 +       if (ret < 0) {
245 +               weston_log("[gst recorder] aborted: %m\n");
246 +               recorder_destroy(output);
247 +       }
248 +}
249 +
250 +static int
251 +recorder_enable(struct drm_backend *b, struct drm_output *output)
252 +{
253 +       int enable_recorder = 0;
254 +       struct gst_recorder_settings *settings;
255 +       struct weston_config_section *section;
256 +       struct weston_config *config = wet_get_config(b->compositor);
257 +       char* s;
258 +       struct v4l2_rect crop = { .width = output->base.current_mode->width,
259 +                                 .height = output->base.current_mode->height,
260 +                                 .top = 0,
261 +                                 .left = 0 };
262 +
263 +       if (output->recorder)
264 +               return -1;
265 +
266 +       section = weston_config_get_section(config, "output", "name",
267 +                                           output->base.name);
268 +
269 +       weston_config_section_get_bool(section, "recorder", &enable_recorder, 0);
270 +
271 +       if (!enable_recorder)
272 +               return 0;
273 +
274 +       /* TODO: add support for NV16 or NV12 */
275 +       if (output->gbm_format != GBM_FORMAT_XRGB8888) {
276 +               weston_log("[gst recorder] %s: "
277 +                          "output format not supported\n", output->base.name);
278 +               return -1;
279 +       }
280 +
281 +       settings = malloc(sizeof(* settings));
282 +       weston_config_section_get_string(section, "ip", &settings->ip, NULL);
283 +       if (!settings->ip)
284 +               goto err;
285 +       weston_config_section_get_int(section, "port", &settings->port, -1);
286 +       /* default gives about 16 Mbit/s at 1280x720@60FPS */
287 +       weston_config_section_get_int(section, "bitrate", &settings->bitrate, 300000);
288 +
289 +       settings->width = output->base.current_mode->width;
290 +       settings->height = output->base.current_mode->height;
291 +
292 +       settings->crop = crop;
293 +
294 +       weston_config_section_get_string(section, "crop", &s, NULL);
295 +       if (s) {
296 +               if (parse_crop_rect(s, &settings->crop)) {
297 +                       weston_log("[gst recorder] %s:"
298 +                                  " failed to parse crop parameter\n",
299 +                                  output->base.name);
300 +                       goto err;
301 +               }
302 +       }
303 +
304 +
305 +       output->recorder =
306 +               gst_recorder_create(settings);
307 +       if (!output->recorder) {
308 +               weston_log("[gst recorder] %s:"
309 +                       " failed to create gst recorder\n",
310 +                       output->base.name);
311 +               goto err;
312 +       }
313 +
314 +       output->base.disable_planes++;
315 +
316 +       output->recorder_frame_listener.notify = recorder_frame_notify;
317 +       wl_signal_add(&output->base.frame_signal,
318 +                     &output->recorder_frame_listener);
319 +
320 +       weston_output_schedule_repaint(&output->base);
321 +
322 +       weston_log("[gst recorder] %s:"
323 +               " recorder initialized\n",
324 +               output->base.name);
325 +
326 +       return 0;
327 +err:
328 +       weston_log("[gst recorder] %s:"
329 +               " invalid settings\n",
330 +               output->base.name);
331 +       free(settings);
332 +       return -1;
333 +}
334 +
335 +static void
336 +recorders_enable(struct drm_backend *b)
337 +{
338 +       struct drm_output *output;
339 +
340 +       wl_list_for_each(output, &b->compositor->output_list, base.link) {
341 +               recorder_enable(b, output);
342 +       }
343 +}
344 +
345 +static void
346 +recorder_binding(struct weston_keyboard *keyboard, uint32_t time, uint32_t key,
347 +                void *data)
348 +{
349 +       struct drm_backend *b = data;
350 +       struct drm_output *output;
351 +
352 +       /* fix this */
353 +       wl_list_for_each(output, &b->compositor->output_list, base.link) {
354 +               if (!output->recorder)
355 +                       recorder_enable(b, output);
356 +               else
357 +                       recorder_destroy(output);
358 +       }
359 +}
360 +#endif
361 +
362 +#if !defined(BUILD_VAAPI_RECORDER) && !defined(BUILD_GST_RECORDER)
363 +
364  static void
365  recorder_binding(struct weston_keyboard *keyboard, uint32_t time, uint32_t key,
366                  void *data)
367 @@ -3801,6 +3995,7 @@ drm_backend_create(struct weston_compositor *compositor,
368                 b_cfg->max_compose = config->v4l2ops.max_compose;
369                 b_cfg->scaler_enable = config->v4l2ops.scaler_enable;
370         }
371 +       b->enable_recorder = config->enable_recorder;
372  
373         if (parse_gbm_format(config->gbm_format, GBM_FORMAT_XRGB8888, &b->gbm_format) < 0)
374                 goto err_compositor;
375 @@ -3855,6 +4050,11 @@ drm_backend_create(struct weston_compositor *compositor,
376                 }
377         }
378  
379 +#ifdef BUILD_GST_RECORDER
380 +       if (b->enable_recorder)
381 +               gst_recorder_init();
382 +#endif
383 +
384         b->base.destroy = drm_destroy;
385         b->base.restore = drm_restore;
386  
387 diff --git a/libweston/compositor-drm.h b/libweston/compositor-drm.h
388 index bba4c6a..bb9bd5b 100644
389 --- a/libweston/compositor-drm.h
390 +++ b/libweston/compositor-drm.h
391 @@ -126,6 +126,7 @@ struct weston_drm_backend_config {
392                 char *scaler_device;
393                 bool scaler_enable;
394         } v4l2ops;
395 +       bool enable_recorder;
396  
397         /** The seat to be used for input and output.
398          *
399 diff --git a/libweston/gst-recorder.c b/libweston/gst-recorder.c
400 new file mode 100644
401 index 0000000..d46d4f0
402 --- /dev/null
403 +++ b/libweston/gst-recorder.c
404 @@ -0,0 +1,1213 @@
405 +/*
406 + * Copyright Â© 2016 Cogent Embedded Inc
407 + *
408 + * Permission to use, copy, modify, distribute, and sell this software and
409 + * its documentation for any purpose is hereby granted without fee, provided
410 + * that the above copyright notice appear in all copies and that both that
411 + * copyright notice and this permission notice appear in supporting
412 + * documentation, and that the name of the copyright holders not be used in
413 + * advertising or publicity pertaining to distribution of the software
414 + * without specific, written prior permission.  The copyright holders make
415 + * no representations about the suitability of this software for any
416 + * purpose.  It is provided "as is" without express or implied warranty.
417 + *
418 + * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
419 + * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
420 + * FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
421 + * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
422 + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
423 + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
424 + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
425 + */
426 +
427 +/*
428 + * TODO:
429 + * 1) Add format parameter to virtual display to render in another format
430 + * with v4l2-renderer
431 + * 2) Add capability to use already NV12 rendered frame
432 + */
433 +#include "config.h"
434 +
435 +#include <stdlib.h>
436 +#include <stdint.h>
437 +#include <string.h>
438 +#include <unistd.h>
439 +#include <assert.h>
440 +#include <errno.h>
441 +
442 +#include <sys/types.h>
443 +#include <sys/stat.h>
444 +#include <sys/mman.h>
445 +#include <sys/ioctl.h>
446 +#include <fcntl.h>
447 +
448 +#include <pthread.h>
449 +
450 +#include "compositor.h"
451 +#include "gst-recorder.h"
452 +
453 +/* Gstreamer includes */
454 +#include <gst/gst.h>
455 +#include <gst/app/gstappsrc.h>
456 +#include <gst/rtp/gstrtpbuffer.h>
457 +
458 +#include <gst/video/video.h>
459 +#include <gst/video/gstvideometa.h>
460 +#include <gst/video/gstvideopool.h>
461 +#include <gst/allocators/gstdmabuf.h>
462 +
463 +struct vsp_data;
464 +
465 +#define DEFAULT_FPS            60
466 +
467 +typedef enum _vsp_port_n {
468 +       VSP_PORT_INPUT  = 0,
469 +       VSP_PORT_INPUT0 = VSP_PORT_INPUT,
470 +       VSP_PORT_INPUT1,
471 +       VSP_PORT_INPUT2,
472 +       VSP_PORT_INPUT3,
473 +       VSP_PORT_OUTPUT
474 +} vsp_port_n;
475 +
476 +struct gst_recorder {
477 +       struct gst_recorder_settings *set;
478 +       int frame_count;
479 +       int input_count;
480 +
481 +       int error;
482 +       int destroying;
483 +       pthread_t worker_thread;
484 +       pthread_mutex_t mutex;
485 +       pthread_cond_t input_cond;
486 +
487 +       struct {
488 +               int valid;
489 +               int prime_fd, stride;
490 +       } input;
491 +
492 +       /* GLib */
493 +       GMainContext *gcontext;
494 +       /* Gstreamer stuff */
495 +       GstElement *pipeline;
496 +       /* AppSrc */
497 +       GstAppSrc *appsrc;
498 +       /* ...and source pad */
499 +       GstPad *appsrc_pad;
500 +       /* OMX encoder buffer pool */
501 +       GstBufferPool *omx_pool;
502 +       /* bus */
503 +       GstBus *bus;
504 +       /* timestamp */
505 +       GstClock   *clock;
506 +       GstClockTime timestamp;
507 +       GstClockTime ts_last_frame;
508 +       /* to be removed */
509 +       guint callback_tag;
510 +
511 +       struct vsp_data *vsp;
512 +};
513 +
514 +/*******************************************************************************
515 + * VSP related code
516 + ******************************************************************************/
517 +
518 +#define VSP_OUTPUT_BUFFERS_PLANE       2
519 +
520 +/* #define VSP_OUTPUT_NV16                     1 */
521 +
522 +/* ...number of input/output pads (WPF1-3 are not implemented) */
523 +#define VSP_PADS_NUM                    1
524 +
525 +/*******************************************************************************
526 + * Local types definition
527 + ******************************************************************************/
528 +
529 +struct vsp_media_pad
530 +{
531 +       struct media_pad           *infmt_pad;
532 +       struct media_pad           *outfmt_pad;
533 +       struct media_entity        *entity;
534 +       int                     fd;
535 +};
536 +
537 +typedef struct vsp_media_pad vsp_media_pad_t;
538 +
539 +struct vsp_data
540 +{
541 +       /* ...media device */
542 +       struct media_device *media;
543 +
544 +       /* ...VSP input/output pads */
545 +       vsp_media_pad_t input, output;
546 +
547 +       /* mutex */
548 +       pthread_mutex_t mutex;
549 +
550 +       /* user count */
551 +       int users;
552 +};
553 +
554 +struct vsp_data *vsp_g = NULL;
555 +
556 +/* ...type declarations */
557 +typedef struct vsp_data vsp_data_t;
558 +
559 +static int
560 +gst_recorder_process_dmafd(struct gst_recorder *r, int fd, int stride);
561 +
562 +/* ...module initialization (a bit of salami) */
563 +static vsp_data_t *
564 +vsp_init(const char *devname)
565 +{
566 +       vsp_data_t                     *vsp;
567 +       struct media_device            *media;
568 +       const struct media_device_info *info;
569 +       const char                     *dev;
570 +       char                            buf[256];
571 +       char                           *endp, *p;
572 +       struct media_entity            *entity;
573 +
574 +       /* ...create data structure */
575 +       if ((vsp = malloc(sizeof(*vsp))) == NULL)
576 +       {
577 +               weston_log("failed to allocate memory\n");
578 +               errno = ENOMEM;
579 +               return NULL;
580 +       }
581 +       memset(vsp, 0, sizeof(*vsp));
582 +
583 +       pthread_mutex_init(&vsp->mutex, NULL);
584 +
585 +       /* ...create media device */
586 +       if ((vsp->media = media = media_device_new(devname)) == NULL)
587 +       {
588 +               weston_log("failed to open device '%s'\n", devname);
589 +               goto error;
590 +       }
591 +       else if ((errno = -media_device_enumerate(media)) != 0)
592 +       {
593 +               weston_log("failed to enumerate device '%s'\n", devname);
594 +               goto error_media;
595 +       }
596 +       else if ((info = media_get_info(media)) == NULL)
597 +       {
598 +               weston_log("failed to get media info data\n");
599 +               goto error_media;
600 +       }
601 +       else
602 +       {
603 +               dev = ((p = strchr(info->bus_info, ':')) ? p + 1 : info->bus_info);
604 +               weston_log("open media device: %s (%s)\n", info->bus_info, dev);
605 +       }
606 +
607 +       /* ...reset links */
608 +       if (media_reset_links(media) != 0)
609 +       {
610 +               weston_log("failed to reset media device\n");
611 +               goto error_media;
612 +       }
613 +
614 +       /* ...setup RPF.0:1 -> WPF.0:0 link */
615 +       snprintf(buf, sizeof(buf), "'%s rpf.0':1 -> '%s wpf.0':0 [1]", dev, dev);
616 +       if (media_parse_setup_link(media, buf, &endp) != 0)
617 +       {
618 +               weston_log("failed to setup link '%s'\n", buf);
619 +               errno = EINVAL;
620 +               goto error_media;
621 +       }
622 +
623 +       /* ...setup WPF.0:1 -> WPF.0 output link */
624 +       snprintf(buf, sizeof(buf), "'%s wpf.0':1 -> '%s wpf.0 output':0 [1]", dev, dev);
625 +       if (media_parse_setup_link(media, buf, &endp) != 0)
626 +       {
627 +               weston_log("failed to setup link '%s'\n", buf);
628 +               errno = EINVAL;
629 +               goto error_media;
630 +       }
631 +
632 +       /* ...specify input/output-format of RPF pad */
633 +       snprintf(buf, sizeof(buf), "'%s rpf.0':0", dev);
634 +       if ((vsp->input.infmt_pad = media_parse_pad(media, buf, NULL)) == NULL)
635 +       {
636 +               weston_log("failed to parse pad '%s'\n", buf);
637 +               errno = EINVAL;
638 +               goto error_media;
639 +       }
640 +
641 +       snprintf(buf, sizeof(buf), "'%s rpf.0':1", dev);
642 +       if ((vsp->input.outfmt_pad = media_parse_pad(media, buf, NULL)) == NULL)
643 +       {
644 +               weston_log("failed to parse pad '%s'\n", buf);
645 +               errno = EINVAL;
646 +               goto error_media;
647 +       }
648 +
649 +       snprintf(buf, sizeof(buf), "%s rpf.0", dev);
650 +       if ((vsp->input.entity = media_get_entity_by_name(media, buf, strlen(buf))) == NULL)
651 +       {
652 +               weston_log("failed to parse entity '%s'\n", buf);
653 +               errno = EINVAL;
654 +               goto error_media;
655 +       }
656 +
657 +       /* ...get input file-descriptor */
658 +       snprintf(buf, sizeof(buf), "%s rpf.0 input", dev);
659 +       if ((entity = media_get_entity_by_name(media, buf, strlen(buf))) == NULL)
660 +       {
661 +               weston_log("entity '%s' not found\n", buf);
662 +               errno = EINVAL;
663 +               goto error_media;
664 +       }
665 +       else if (v4l2_subdev_open(entity) != 0)
666 +       {
667 +               weston_log("failed to open subdev '%s'\n", buf);
668 +               goto error_media;
669 +       }
670 +       else if ((vsp->input.fd = open(media_entity_get_devname(entity), O_RDWR/* | O_NONBLOCK*/)) < 0)
671 +       {
672 +               weston_log("failed to open device '%s'\n", media_entity_get_devname(entity));
673 +               goto error_media;
674 +       }
675 +       else
676 +       {
677 +               weston_log("input pad setup ('%s':'%s')\n", buf, media_entity_get_devname(entity));
678 +       }
679 +
680 +       /* ...specify input/output formats of WPF pad */
681 +       snprintf(buf, sizeof(buf), "'%s wpf.0':0", dev);
682 +       if ((vsp->output.infmt_pad = media_parse_pad(media, buf, NULL)) == NULL)
683 +       {
684 +               weston_log("failed to parse pad '%s'\n", buf);
685 +               errno = EINVAL;
686 +               goto error_media;
687 +       }
688 +
689 +       snprintf(buf, sizeof(buf), "'%s wpf.0':1", dev);
690 +       if ((vsp->output.outfmt_pad = media_parse_pad(media, buf, NULL)) == NULL)
691 +       {
692 +               weston_log("failed to parse pad '%s'\n", buf);
693 +               errno = EINVAL;
694 +               goto error_media;
695 +       }
696 +
697 +       snprintf(buf, sizeof(buf), "%s wpf.0", dev);
698 +       if ((vsp->output.entity = media_get_entity_by_name(media, buf, strlen(buf))) == NULL)
699 +       {
700 +               weston_log("failed to parse entity '%s'\n", buf);
701 +               errno = EINVAL;
702 +               goto error_media;
703 +       }
704 +
705 +       /* ...get a file descriptor for the output */
706 +       snprintf(buf, sizeof(buf), "%s wpf.0 output", dev);
707 +       if ((entity = media_get_entity_by_name(media, buf, strlen(buf))) == NULL)
708 +       {
709 +               weston_log("failed to get entity '%s'\n", buf);
710 +               errno = EINVAL;
711 +               goto error_media;
712 +       }
713 +       else if (v4l2_subdev_open(entity) != 0)
714 +       {
715 +               weston_log("failed to open subdev '%s'\n", buf);
716 +               goto error_media;
717 +       }
718 +       else if ((vsp->output.fd = open(media_entity_get_devname(entity), O_RDWR | O_NONBLOCK)) < 0)
719 +       {
720 +               weston_log("failed to open device '%s'\n", media_entity_get_devname(entity));
721 +               goto error_media;
722 +       }
723 +       else
724 +       {
725 +               weston_log("output pad setup (%s:%s)\n", buf, media_entity_get_devname(entity));
726 +       }
727 +
728 +       weston_log("vsp-device '%s' created\n", devname);
729 +
730 +       return vsp;
731 +
732 +error_media:
733 +       /* ...destroy media device and all associated structures */
734 +       media_device_unref(vsp->media);
735 +
736 +error:
737 +       /* ...destroy data structure */
738 +       free(vsp);
739 +       return NULL;
740 +}
741 +
742 +static void
743 +vsp_deinit(vsp_data_t *vsp)
744 +{
745 +       /* ...destroy media device and all associated structures */
746 +       media_device_unref(vsp->media);
747 +
748 +       /* ...destroy data structure */
749 +       free(vsp);
750 +}
751 +
752 +/* ...set V4L2 device format */
753 +static int
754 +vsp_set_format(int fd, struct v4l2_format *fmt)
755 +{
756 +       /* ...set format */
757 +       if (ioctl(fd, VIDIOC_S_FMT, fmt) < 0) {
758 +               weston_log("format set (fd=%d) failed: %d\n",
759 +                       fd, errno);
760 +       }
761 +
762 +       return 0;
763 +}
764 +
765 +/* ...start streaming on specific V4L2 device */
766 +static int
767 +vsp_streaming_enable(vsp_data_t *vsp, vsp_port_n port, int enable)
768 +{
769 +       vsp_media_pad_t *pad = (port == VSP_PORT_INPUT) ? &vsp->input : &vsp->output;
770 +       int fd = pad->fd;
771 +       int type = (port == VSP_PORT_INPUT) ?
772 +               V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE : V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
773 +
774 +       return ioctl(fd, (enable ? VIDIOC_STREAMON : VIDIOC_STREAMOFF), &type);
775 +}
776 +
777 +/* ...prepare VSP filter for operation */
778 +static int
779 +vsp_set_formats(vsp_data_t *vsp, int width, int height, struct v4l2_rect* crop)
780 +{
781 +       vsp_media_pad_t *input = &vsp->input, *output = &vsp->output;
782 +       struct v4l2_mbus_framefmt mfmt = { .width = width, .height = height };
783 +       struct v4l2_format format;
784 +
785 +       /* ...configure RPF input pads; specify pixel format and size (one of YUV variants) */
786 +       mfmt.width = width;
787 +       mfmt.height = height;
788 +       mfmt.code = V4L2_MBUS_FMT_ARGB8888_1X32;
789 +       if (v4l2_subdev_set_format(input->infmt_pad->entity,
790 +               &mfmt, input->infmt_pad->index, V4L2_SUBDEV_FORMAT_ACTIVE) < 0) {
791 +               weston_log("VSP: input pad in format set failed: %d\n", errno);
792 +               return -1;
793 +       }
794 +
795 +        /* set a crop paramters */
796 +       if (v4l2_subdev_set_selection(input->infmt_pad->entity, crop, input->infmt_pad->index,
797 +                                     V4L2_SEL_TGT_CROP, V4L2_SUBDEV_FORMAT_ACTIVE)) {
798 +               weston_log("set crop parameter failed: %dx%d@(%d,%d).\n",
799 +                          crop->width, crop->height, crop->left, crop->top);
800 +               return -1;
801 +       }
802 +
803 +       /* ...output is NV12 or NV16 or I420*/
804 +       mfmt.width = crop->width;
805 +       mfmt.height = crop->height;
806 +       mfmt.code = V4L2_MBUS_FMT_AYUV8_1X32;
807 +       if (v4l2_subdev_set_format(input->outfmt_pad->entity,
808 +               &mfmt, input->outfmt_pad->index, V4L2_SUBDEV_FORMAT_ACTIVE) < 0) {
809 +               weston_log("VSP: input pad out format set failed: %d\n", errno);
810 +               return -1;
811 +       }
812 +
813 +       /* ...specify input format */
814 +       memset(&format, 0, sizeof(format));
815 +       format.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
816 +       format.fmt.pix_mp.width = /* crop-> */width;
817 +       format.fmt.pix_mp.height = /* crop-> */height;
818 +       format.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_ABGR32;
819 +       format.fmt.pix_mp.num_planes = 1;
820 +       /* ...set input port format */
821 +       if (vsp_set_format(input->fd, &format) < 0) {
822 +               weston_log("VSP: input set format failed: %d\n", errno);
823 +               return -1;
824 +       }
825 +
826 +       /* ...both input and output are ARGB8888 always (now effective) */
827 +       if (v4l2_subdev_set_format(output->infmt_pad->entity,
828 +               &mfmt, output->infmt_pad->index, V4L2_SUBDEV_FORMAT_ACTIVE) < 0) {
829 +               weston_log("VSP: output pad in format set failed: %d\n", errno);
830 +               return -1;
831 +       }
832 +
833 +       /* ...specify cropping area, probably? - tbd */
834 +       if (v4l2_subdev_set_format(output->outfmt_pad->entity,
835 +               &mfmt, output->outfmt_pad->index, V4L2_SUBDEV_FORMAT_ACTIVE) < 0) {
836 +               weston_log("VSP: output pad in format set failed: %d\n", errno);
837 +               return -1;
838 +       }
839 +
840 +       /* ...setup output pads */
841 +       memset(&format, 0, sizeof(format));
842 +       format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
843 +       format.fmt.pix_mp.width = crop->width;
844 +       format.fmt.pix_mp.height = crop->height;
845 +#ifdef VSP_OUTPUT_NV16
846 +       format.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_NV16M;
847 +#else
848 +       format.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_NV12M;
849 +#endif
850 +       format.fmt.pix_mp.num_planes = VSP_OUTPUT_BUFFERS_PLANE;
851 +       /* ...set output buffer format */
852 +       if (vsp_set_format(output->fd, &format) < 0) {
853 +               weston_log("VSP: output set format failed: %d\n", errno);
854 +               return -1;
855 +       }
856 +
857 +       return 0;
858 +}
859 +
860 +static int
861 +vsp_request_buffers(vsp_data_t *vsp, vsp_port_n port, unsigned int num)
862 +{
863 +       vsp_media_pad_t *pad = (port == VSP_PORT_INPUT) ? &vsp->input : &vsp->output;
864 +       struct v4l2_requestbuffers reqbuf;
865 +       int fd = pad->fd;
866 +
867 +       /* ...input buffers are DMA-fd, output buffers allocated by kernel */
868 +       memset(&reqbuf, 0, sizeof(reqbuf));
869 +       reqbuf.type = (port == VSP_PORT_INPUT) ?
870 +               V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE : V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
871 +       reqbuf.memory = V4L2_MEMORY_DMABUF;
872 +       reqbuf.count = num;
873 +       if (ioctl(fd, VIDIOC_REQBUFS, &reqbuf) < 0) {
874 +               weston_log("VSP: %s REQBUFS failed: %d\n",
875 +                       (port == VSP_PORT_INPUT) ? "input" : "output", errno);
876 +               return -1;
877 +       }
878 +
879 +       if (reqbuf.count != num) {
880 +               weston_log("VSP: %s failed to request %d (!= %d) bufs\n",
881 +                       (port == VSP_PORT_INPUT) ? "input" : "output", num, reqbuf.count);
882 +               return -1;
883 +       }
884 +       return 0;
885 +}
886 +
887 +
888 +/* ...enqueue dmafd buffer */
889 +static int
890 +vsp_input_buffer_queue_dmafd(vsp_data_t *vsp, int i, int dmafd)
891 +{
892 +       vsp_media_pad_t    *pad = &vsp->input;
893 +       struct v4l2_buffer  buf;
894 +       struct v4l2_plane   planes[1];
895 +
896 +       /* ...set buffer parameters */
897 +       memset(&buf, 0, sizeof(buf));
898 +       memset(planes, 0, sizeof(planes));
899 +       buf.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
900 +       buf.memory = V4L2_MEMORY_DMABUF;
901 +       buf.index = i;
902 +       buf.m.planes = planes;
903 +       buf.length = 1;
904 +       buf.m.planes[0].m.fd = dmafd;
905 +
906 +       /* ...submit buffer */
907 +       if (ioctl(pad->fd, VIDIOC_QBUF, &buf) < 0) {
908 +               weston_log("VSP: input dmafd (%d) buffer (%i) queue failed: %d\n",
909 +                       dmafd, i, errno);
910 +               return -1;
911 +       }
912 +
913 +       return 0;
914 +}
915 +
916 +/* ...dequeue dmafd buffer */
917 +static int
918 +vsp_input_buffer_dequeue_dmafd(vsp_data_t *vsp)
919 +{
920 +       vsp_media_pad_t    *pad = &vsp->input;
921 +       struct v4l2_buffer  buf;
922 +       struct v4l2_plane   planes[1];
923 +
924 +       /* ...set buffer parameters */
925 +       memset(&buf, 0, sizeof(buf));
926 +       memset(planes, 0, sizeof(planes));
927 +       buf.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
928 +       buf.memory = V4L2_MEMORY_DMABUF;
929 +       buf.m.planes = planes;
930 +       buf.length = 1;
931 +
932 +       if (ioctl(pad->fd, VIDIOC_DQBUF, &buf) < 0) {
933 +               weston_log("VSP: input dmafd buffer de-queue failed: %d\n", errno);
934 +               return -1;
935 +       }
936 +
937 +       /* ...return buffer index */
938 +       return buf.index;
939 +}
940 +
941 +/* ...enqueue output buffer */
942 +static int
943 +vsp_output_buffer_queue_dmafd(vsp_data_t *vsp, int i, int dmafd[])
944 +{
945 +       vsp_media_pad_t    *pad = &vsp->output;
946 +       struct v4l2_plane   planes[2];
947 +       struct v4l2_buffer  buf;
948 +
949 +       /* ...set buffer parameters (single-plane ARGB always) */
950 +       memset(&buf, 0, sizeof(buf));
951 +       memset(planes, 0, sizeof(planes));
952 +       buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
953 +       buf.memory = V4L2_MEMORY_DMABUF;
954 +       buf.index = i;
955 +       buf.m.planes = planes;
956 +       buf.length = VSP_OUTPUT_BUFFERS_PLANE;
957 +       buf.m.planes[0].m.fd = dmafd[0];
958 +       buf.m.planes[1].m.fd = dmafd[1];
959 +
960 +       /* ...submit buffer */
961 +       if (ioctl(pad->fd, VIDIOC_QBUF, &buf) < 0) {
962 +               weston_log("VSP: output dmafd queue failed: %d\n", errno);
963 +               return -1;
964 +       }
965 +
966 +       return 0;
967 +}
968 +
969 +/* ...dequeue output buffer */
970 +static int
971 +vsp_output_buffer_dequeue_dmafd(vsp_data_t *vsp)
972 +{
973 +       vsp_media_pad_t    *pad = &vsp->output;
974 +       struct v4l2_buffer  buf;
975 +       struct v4l2_plane   planes[2];
976 +
977 +       /* ...set buffer parameters */
978 +       memset(&buf, 0, sizeof(buf));
979 +       memset(planes, 0, sizeof(planes));
980 +       buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
981 +       buf.memory = V4L2_MEMORY_DMABUF;
982 +       buf.m.planes = planes;
983 +       buf.length = VSP_OUTPUT_BUFFERS_PLANE;
984 +
985 +       if (ioctl(pad->fd, VIDIOC_DQBUF, &buf) < 0) {
986 +               weston_log("VSP: output dmafd de-queue failed: %d\n", errno);
987 +               return -1;
988 +       }
989 +
990 +       /* ...return dequeue buffer index */
991 +       return buf.index;
992 +}
993 +
994 +/* ...get capturing interface file descriptor */
995 +static int
996 +vsp_capture_fd(vsp_data_t *vsp)
997 +{
998 +       return vsp->output.fd;
999 +}
1000 +
1001 +/*******************************************************************************
1002 + * Gstreamer stuff
1003 + ******************************************************************************/
1004 +
1005 +static void
1006 +print_one_tag (const GstTagList * list, const gchar * tag, gpointer user_data)
1007 +{
1008 +       int i, num;
1009 +
1010 +       num = gst_tag_list_get_tag_size (list, tag);
1011 +       for (i = 0; i < num; ++i) {
1012 +               const GValue *val;
1013 +
1014 +               /* Note: when looking for specific tags, use the gst_tag_list_get_xyz() API,
1015 +                * we only use the GValue approach here because it is more generic */
1016 +               val = gst_tag_list_get_value_index (list, tag, i);
1017 +               if (G_VALUE_HOLDS_STRING (val)) {
1018 +                       weston_log("\t%20s : %s\n", tag, g_value_get_string (val));
1019 +               } else if (G_VALUE_HOLDS_UINT (val)) {
1020 +                       weston_log("\t%20s : %u\n", tag, g_value_get_uint (val));
1021 +               } else if (G_VALUE_HOLDS_DOUBLE (val)) {
1022 +                       weston_log("\t%20s : %g\n", tag, g_value_get_double (val));
1023 +               } else if (G_VALUE_HOLDS_BOOLEAN (val)) {
1024 +                       weston_log("\t%20s : %s\n", tag,
1025 +                                       (g_value_get_boolean (val)) ? "true" : "false");
1026 +               } else if (GST_VALUE_HOLDS_BUFFER (val)) {
1027 +                       GstBuffer *buf = gst_value_get_buffer (val);
1028 +                       guint buffer_size = gst_buffer_get_size (buf);
1029 +
1030 +                       weston_log("\t%20s : buffer of size %u\n", tag, buffer_size);
1031 +               } else if (GST_VALUE_HOLDS_DATE_TIME (val)) {
1032 +                       GstDateTime *dt = g_value_get_boxed (val);
1033 +                       gchar *dt_str = gst_date_time_to_iso8601_string (dt);
1034 +
1035 +                       weston_log("\t%20s : %s\n", tag, dt_str);
1036 +                       g_free (dt_str);
1037 +               } else {
1038 +                       weston_log("\t%20s : tag of type '%s'\n", tag, G_VALUE_TYPE_NAME (val));
1039 +               }
1040 +       }
1041 +}
1042 +
1043 +static gboolean
1044 +gst_bus_callback(GstBus *bus, GstMessage *message, gpointer user_data)
1045 +{
1046 +       GTimeVal time;
1047 +       struct gst_recorder *r = user_data;
1048 +
1049 +       if (!r->pipeline) {
1050 +               weston_log("gst_pipeline: unexpected gst bus callback event, while pipeline==null\n");
1051 +               return TRUE;
1052 +       }
1053 +
1054 +       g_get_current_time(&time);
1055 +
1056 +       switch (GST_MESSAGE_TYPE(message))
1057 +       {
1058 +               case GST_MESSAGE_QOS:
1059 +                       {
1060 +                               GstFormat format;
1061 +                               guint64 processed;
1062 +                               guint64 dropped;
1063 +
1064 +                               gst_message_parse_qos_stats (message, &format, &processed, &dropped);
1065 +                               weston_log("gst_pipeline: qos from: %s processed %lud, dropped %lud\n",
1066 +                                       GST_OBJECT_NAME (message->src),
1067 +                                       processed, dropped);
1068 +                       }
1069 +               break;
1070 +               case GST_MESSAGE_STREAM_STATUS:
1071 +                       {
1072 +                               const GValue *val;
1073 +
1074 +                               val = gst_message_get_stream_status_object (message);
1075 +                               weston_log("gst_pipeline: stream status type %s, value %p\n",
1076 +                                       G_VALUE_TYPE_NAME(val),
1077 +                                       g_value_get_object(val));
1078 +                       }
1079 +               break;
1080 +               case GST_MESSAGE_TAG:
1081 +                       {
1082 +                               GstTagList *tags = NULL;
1083 +
1084 +                               gst_message_parse_tag (message, &tags);
1085 +                               weston_log("gst_pipeline: tag from element %s:\n",
1086 +                                       GST_OBJECT_NAME (message->src));
1087 +                               gst_tag_list_foreach (tags, print_one_tag, NULL);
1088 +                               weston_log("\n");
1089 +                       }
1090 +               break;
1091 +               case GST_MESSAGE_STATE_CHANGED:
1092 +                       {
1093 +                               GstState oldstate, newstate;
1094 +
1095 +                               gst_message_parse_state_changed(message, &oldstate, &newstate, NULL);
1096 +                               weston_log("gst_pipeline: element %s changed state from %s to %s.\n",
1097 +                                       GST_OBJECT_NAME (message->src),
1098 +                                       gst_element_state_get_name (oldstate),
1099 +                                       gst_element_state_get_name (newstate));
1100 +
1101 +                               /* if gstreamer become ready */
1102 +                               if ((GST_MESSAGE_SRC(message) == GST_OBJECT(r->appsrc)) &&
1103 +                                       (newstate == GST_STATE_PAUSED)) {
1104 +                                       weston_log("gst_pipeline: pipeline ready\n");
1105 +                               }
1106 +                       }
1107 +               break;
1108 +               case GST_MESSAGE_ERROR:
1109 +                       {
1110 +                               GError *err;
1111 +                               gchar *debug_info;
1112 +                               gst_message_parse_error(message, &err, &debug_info);
1113 +                               weston_log("gst_pipeline: error received from element %s: %s\n",
1114 +                                       GST_OBJECT_NAME(message->src), err->message);
1115 +                               weston_log("gst_pipeline: debugging information: %s\n",
1116 +                                       debug_info ? debug_info : "none");
1117 +                               g_clear_error (&err);
1118 +                               g_free (debug_info);
1119 +                       }
1120 +               break;
1121 +               case GST_MESSAGE_WARNING:
1122 +                       {
1123 +                               GError *err;
1124 +                               gchar *debug_info;
1125 +                               gst_message_parse_warning(message, &err, &debug_info);
1126 +                               weston_log("gst_pipeline: warning received from element %s: %s\n",
1127 +                                       GST_OBJECT_NAME(message->src), err->message);
1128 +                               weston_log("gst_pipeline: debugging information: %s\n",
1129 +                                       debug_info ? debug_info : "none");
1130 +                               g_clear_error (&err);
1131 +                               g_free (debug_info);
1132 +                       }
1133 +               break;
1134 +               default:
1135 +                       weston_log("gst_pipeline: %s from %s\n",
1136 +                               GST_MESSAGE_TYPE_NAME(message), GST_OBJECT_NAME (message->src));
1137 +               break;
1138 +       }
1139 +       return TRUE;
1140 +}
1141 +
1142 +static void *
1143 +worker_thread_function(void *data)
1144 +{
1145 +       GstMessage *msg;
1146 +       struct gst_recorder *r = data;
1147 +
1148 +       pthread_mutex_lock(&r->mutex);
1149 +
1150 +       while (!r->destroying) {
1151 +               if (!r->input.valid)
1152 +                       pthread_cond_wait(&r->input_cond, &r->mutex);
1153 +
1154 +               /* If the thread is awaken by destroy_worker_thread(),
1155 +                * there might not be valid input */
1156 +               if (!r->input.valid)
1157 +                       continue;
1158 +
1159 +               /* TODO: move it to separate thread? */
1160 +               g_main_context_iteration(r->gcontext, FALSE);
1161 +
1162 +               do {
1163 +                       msg = gst_bus_pop_filtered(r->bus,
1164 +                                                  GST_MESSAGE_ANY);
1165 +                       if (msg) {
1166 +                               gst_bus_callback(r->bus, msg, r);
1167 +                       }
1168 +               } while (msg);
1169 +
1170 +               /* check input */
1171 +               gst_recorder_process_dmafd(r, r->input.prime_fd, r->input.stride);
1172 +
1173 +               r->input.valid = 0;
1174 +       }
1175 +
1176 +       pthread_mutex_unlock(&r->mutex);
1177 +
1178 +       return NULL;
1179 +}
1180 +
1181 +static int
1182 +setup_worker_thread(struct gst_recorder *r)
1183 +{
1184 +       r->gcontext = g_main_context_new();
1185 +       pthread_mutex_init(&r->mutex, NULL);
1186 +       pthread_cond_init(&r->input_cond, NULL);
1187 +       pthread_create(&r->worker_thread, NULL, worker_thread_function, r);
1188 +
1189 +       return 1;
1190 +}
1191 +
1192 +static void
1193 +destroy_worker_thread(struct gst_recorder *r)
1194 +{
1195 +       /* Make sure the worker thread finishes */
1196 +       r->destroying = 1;
1197 +
1198 +       pthread_cond_signal(&r->input_cond);
1199 +
1200 +       pthread_join(r->worker_thread, NULL);
1201 +
1202 +       pthread_mutex_destroy(&r->mutex);
1203 +       pthread_cond_destroy(&r->input_cond);
1204 +}
1205 +
1206 +void weston_debug_function(GstDebugCategory* category, GstDebugLevel level,
1207 +                          const gchar* file, const char* function,
1208 +                          gint line, GObject* object, GstDebugMessage* message,
1209 +                          gpointer data)
1210 +{
1211 +       weston_log("[GST]:%s %s:%d %s\n", file, function, line, gst_debug_message_get(message));
1212 +}
1213 +
1214 +void
1215 +gst_recorder_init(void)
1216 +{
1217 +       gst_init(NULL, 0);
1218 +
1219 +       /* VSP init */
1220 +       vsp_g = vsp_init("/dev/media0");
1221 +       if (!vsp_g)
1222 +               weston_log("[gst recorder] VSP init failed\n");
1223 +}
1224 +
1225 +static int
1226 +gst_recorder_find_omx_pool(struct gst_recorder *r)
1227 +{
1228 +       int ret = 0;
1229 +       GstCaps *caps;
1230 +       GstQuery *query;
1231 +       GstBufferPool *pool;
1232 +       GstStructure *config;
1233 +       guint size, min, max;
1234 +
1235 +       caps = gst_caps_new_simple (    "video/x-raw",
1236 +#ifdef VSP_OUTPUT_NV16
1237 +                                       "format", G_TYPE_STRING, "NV16",
1238 +#else
1239 +                                       "format", G_TYPE_STRING, "NV12",
1240 +#endif
1241 +                                       "width", G_TYPE_INT, r->set->crop.width,
1242 +                                       "height", G_TYPE_INT, r->set->crop.height,
1243 +                                       "framerate", GST_TYPE_FRACTION, 0, DEFAULT_FPS,
1244 +                                       NULL);
1245 +
1246 +       /* find a pool for the negotiated caps now */
1247 +       query = gst_query_new_allocation (caps, TRUE);
1248 +
1249 +       if (!gst_pad_peer_query (r->appsrc_pad, query)) {
1250 +               /* query failed, not a problem, we use the query defaults */
1251 +               weston_log("allocation query failed\n");
1252 +               ret = -1;
1253 +               goto err;
1254 +       }
1255 +
1256 +       weston_log("goot %d pools\n", gst_query_get_n_allocation_pools (query));
1257 +       if (gst_query_get_n_allocation_pools (query) > 0) {
1258 +               /* we got configuration from our peer, parse them */
1259 +               gst_query_parse_nth_allocation_pool (query, 0, &pool, &size, &min, &max);
1260 +               weston_log(" pool settings size %d, min %d, max %d\n", size, min, max);
1261 +       } else {
1262 +               weston_log("no pool queried\n");
1263 +               ret = -1;
1264 +               goto err;
1265 +       }
1266 +
1267 +       config = gst_buffer_pool_get_config (pool);
1268 +       gst_buffer_pool_config_add_option (config, GST_BUFFER_POOL_OPTION_VIDEO_META);
1269 +       gst_buffer_pool_config_set_params (config, caps, size, min, max);
1270 +       gst_buffer_pool_set_config (pool, config);
1271 +
1272 +       /* and activate */
1273 +       gst_buffer_pool_set_active (pool, TRUE);
1274 +
1275 +       r->omx_pool = pool;
1276 +
1277 +err:
1278 +       gst_query_unref (query);
1279 +       return ret;
1280 +}
1281 +
1282 +static int
1283 +gst_recorder_omx_buffer_acquire(struct gst_recorder *r, GstBuffer **ret_buf, int fd[])
1284 +{
1285 +       unsigned int i;
1286 +       GstFlowReturn ret;
1287 +       GstBuffer *buf;
1288 +       guint n_mem;
1289 +       GstMemory *mem;
1290 +
1291 +       ret = gst_buffer_pool_acquire_buffer(r->omx_pool, &buf, NULL);
1292 +       if (ret != GST_FLOW_OK) {
1293 +               weston_log("OMX buffer acquire failed\n");
1294 +               return -1;
1295 +       }
1296 +
1297 +       n_mem = gst_buffer_n_memory(buf);
1298 +       if (n_mem < 1) {
1299 +               weston_log("Buffer with no mem!\n");
1300 +               goto err_release;
1301 +       }
1302 +
1303 +       for (i = 0; i < n_mem; i++) {
1304 +               mem = gst_buffer_peek_memory (buf, i);
1305 +               if (!gst_is_dmabuf_memory (mem)) {
1306 +                       weston_log("Mem not dmabuf\n");
1307 +                       goto err_release;
1308 +               }
1309 +               fd[i] = gst_dmabuf_memory_get_fd (mem);
1310 +       }
1311 +
1312 +       *ret_buf = buf;
1313 +
1314 +       return 0;
1315 +err_release:
1316 +       gst_buffer_pool_release_buffer(r->omx_pool, buf);
1317 +       return -1;
1318 +}
1319 +
1320 +static int
1321 +gst_recorder_omx_buffer_release(struct gst_recorder *r, GstBuffer *buf)
1322 +{
1323 +       gst_buffer_pool_release_buffer(r->omx_pool, buf);
1324 +
1325 +       return 0;
1326 +}
1327 +
1328 +struct gst_recorder *
1329 +gst_recorder_create(struct gst_recorder_settings *settings)
1330 +{
1331 +       struct gst_recorder *r;
1332 +       char gst_pipe[1024];
1333 +       char *ptr = gst_pipe;
1334 +       GError *perror = NULL;
1335 +
1336 +       weston_log("gst_recorder_create (%dx%d) crop %dx%d at %d,%d\n",
1337 +                  settings->width, settings->height, settings->crop.width,
1338 +                  settings->crop.height, settings->crop.top, settings->crop.left);
1339 +
1340 +       if (!vsp_g) {
1341 +               weston_log("gst_recorder_create: no VSP\n");
1342 +               return NULL;
1343 +       }
1344 +
1345 +       r = calloc(1, sizeof *r);
1346 +       if (!r)
1347 +               return NULL;
1348 +       memset(r, 0, sizeof *r);
1349 +
1350 +       r->set = settings;
1351 +       r->timestamp = 0;
1352 +
1353 +       r->vsp = vsp_g;
1354 +       vsp_g->users++;
1355 +
1356 +       /* GST init */
1357 +       /* source (GST_FORMAT_BYTES) */
1358 +       ptr += sprintf(ptr,
1359 +               "appsrc name=src ! ");
1360 +
1361 +       /* omx */
1362 +       ptr += sprintf(ptr,
1363 +               "omxh264enc target-bitrate=%d control-rate=2 name=my_encoder ! "
1364 +               "video/x-h264,width=%d,height=%d ! ",
1365 +               r->set->bitrate, r->set->crop.width, r->set->crop.height);
1366 +
1367 +       /* rtp payloader */
1368 +       ptr += sprintf(ptr,
1369 +               "rtph264pay config-interval=1 name=my_h264pay ! queue  ! ");
1370 +
1371 +       /* usp sink */
1372 +       ptr += sprintf(ptr,
1373 +               "udpsink host=%s ", r->set->ip);
1374 +       if (r->set->port > 0)
1375 +               ptr += sprintf(ptr,
1376 +                       " port=%d name=my_udpsink", r->set->port);
1377 +
1378 +       weston_log("gst_pipeline: starting: %s\n", gst_pipe);
1379 +
1380 +       /* launch */
1381 +       r->pipeline = gst_parse_launch (gst_pipe, &perror);
1382 +       if (!r->pipeline) {
1383 +               weston_log("gst_pipeline: can not start pipeline: %s\n", perror->message);
1384 +               goto err_gst;
1385 +       }
1386 +
1387 +       /* get appsrc */
1388 +       r->appsrc = gst_bin_get_by_name(GST_BIN (r->pipeline), "src");
1389 +       if (!r->appsrc) {
1390 +               weston_log("gst_pipeline: can not get appsrc\n");
1391 +               goto err_gst;
1392 +       }
1393 +
1394 +       /* get bus */
1395 +       r->bus = gst_pipeline_get_bus (GST_PIPELINE(r->pipeline));
1396 +       if (!r->bus) {
1397 +               weston_log("gst_pipeline: can not get bus\n");
1398 +               goto err_gst;
1399 +       }
1400 +
1401 +       setup_worker_thread(r);
1402 +
1403 +       /* setup caps */
1404 +       g_object_set(G_OBJECT(r->appsrc), "caps",
1405 +               gst_caps_new_simple (   "video/x-raw",
1406 +#ifdef VSP_OUTPUT_NV16
1407 +                                       "format", G_TYPE_STRING, "NV16",
1408 +#else
1409 +                                       "format", G_TYPE_STRING, "NV12",
1410 +#endif
1411 +                                       "width", G_TYPE_INT, r->set->crop.width,
1412 +                                       "height", G_TYPE_INT, r->set->crop.height,
1413 +                                       "framerate", GST_TYPE_FRACTION, 0, DEFAULT_FPS,
1414 +                                       NULL), NULL);
1415 +
1416 +       r->appsrc_pad = gst_element_get_static_pad(GST_ELEMENT_CAST(r->appsrc), "src");
1417 +       if (!r->appsrc_pad)
1418 +               weston_log("Failed to get src0 pad of appsrc\n");
1419 +
1420 +       /* set playing */
1421 +       if (gst_element_set_state (r->pipeline, GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE) {
1422 +               weston_log("gst_pipeline: can not change state to PLAYING\n");
1423 +               goto err_gst;
1424 +       }
1425 +
1426 +       if (gst_recorder_find_omx_pool(r) != 0) {
1427 +               weston_log("failed to find OMX buffer pool\n");
1428 +               goto err_gst_stop;
1429 +       }
1430 +
1431 +       /* set clock time */
1432 +       r->clock = gst_element_get_clock (GST_ELEMENT_CAST (r->appsrc));
1433 +
1434 +       weston_log("gst_recorder_create done\n");
1435 +
1436 +       return r;
1437 +
1438 +err_gst_stop:
1439 +       gst_element_set_state (r->pipeline, GST_STATE_NULL);
1440 +       destroy_worker_thread(r);
1441 +err_gst:
1442 +       free(r->pipeline);
1443 +       free(r);
1444 +
1445 +       return NULL;
1446 +}
1447 +
1448 +void
1449 +gst_recorder_destroy(struct gst_recorder *r)
1450 +{
1451 +       r->vsp->users--;
1452 +
1453 +       if (r->pipeline) {
1454 +               gst_element_set_state (r->pipeline, GST_STATE_NULL);
1455 +               gst_object_unref(r->omx_pool);
1456 +
1457 +               destroy_worker_thread(r);
1458 +
1459 +               gst_object_unref(GST_OBJECT(r->bus));
1460 +               gst_object_unref (r->pipeline);
1461 +               r->pipeline = NULL;
1462 +       }
1463 +       free(r);
1464 +}
1465 +
1466 +static int
1467 +gst_recorder_set_timestamp(struct gst_recorder *r, GstBuffer *buffer)
1468 +{
1469 +       GstClockTime cur_time = gst_clock_get_time(r->clock);
1470 +
1471 +       if (r->timestamp == 0) {
1472 +               /* first frame assume around DEFAULT_FPS FPS */
1473 +               GST_BUFFER_DURATION(buffer) = gst_util_uint64_scale_int(1, GST_SECOND, DEFAULT_FPS);
1474 +       } else {
1475 +               GstClockTime delta = cur_time - r->ts_last_frame;
1476 +               /* delta in nS */
1477 +               GST_BUFFER_DURATION(buffer) = delta;
1478 +       }
1479 +
1480 +       r->timestamp += GST_BUFFER_DURATION(buffer);
1481 +       GST_BUFFER_PTS(buffer) = r->timestamp;
1482 +       GST_BUFFER_DTS(buffer) = r->timestamp;
1483 +
1484 +       r->ts_last_frame = cur_time;
1485 +
1486 +       return 0;
1487 +}
1488 +
1489 +
1490 +static int
1491 +gst_recorder_process_dmafd(struct gst_recorder *r, int fd, int stride)
1492 +{
1493 +       int ret;
1494 +       GstBuffer *buf;
1495 +       int omx_fd[2];
1496 +
1497 +        /* get GST buffer */
1498 +       if (gst_recorder_omx_buffer_acquire(r, &buf, omx_fd) < 0) {
1499 +               weston_log("VSP: can not acquire GST buffer, dropping frame\n");
1500 +               return 0;
1501 +       }
1502 +
1503 +       pthread_mutex_lock(&r->vsp->mutex);
1504 +       /* setup vsp */
1505 +       if (vsp_set_formats(r->vsp, r->set->width, r->set->height, &r->set->crop) < 0) {
1506 +               weston_log("VSP: format set failed\n");
1507 +               goto err;
1508 +       }
1509 +
1510 +       /* input */
1511 +       if (vsp_request_buffers(r->vsp, VSP_PORT_INPUT, 1) < 0) {
1512 +               weston_log("VSP: input buffer allocation failed\n");
1513 +               goto err_vsp;
1514 +       }
1515 +
1516 +       /* output */
1517 +       if (vsp_request_buffers(r->vsp, VSP_PORT_OUTPUT, 1) < 0) {
1518 +               weston_log("VSP: output buffer allocation failed\n");
1519 +               goto err_vsp;
1520 +       }
1521 +
1522 +       /* queue output biffer */
1523 +       if (vsp_output_buffer_queue_dmafd(r->vsp, 0, omx_fd) < 0) {
1524 +               weston_log("can not queue OMX buffer %d to VSP\n", 0);
1525 +               gst_recorder_omx_buffer_release(r, buf);
1526 +               goto err_vsp;
1527 +       }
1528 +
1529 +       /* queue input vsp buffer */
1530 +       if (vsp_input_buffer_queue_dmafd(r->vsp, 0, fd) < 0) {
1531 +               weston_log("VSP: failed to queue input buffer\n");
1532 +               goto err_vsp;
1533 +       }
1534 +
1535 +       /* start input */
1536 +       if (vsp_streaming_enable(r->vsp, VSP_PORT_INPUT, 1) < 0) {
1537 +               weston_log("VSP: failed to start input\n");
1538 +               goto err_vsp;
1539 +       }
1540 +
1541 +       /* start output */
1542 +       if (vsp_streaming_enable(r->vsp, VSP_PORT_OUTPUT, 1) < 0) {
1543 +               weston_log("VSP: failed to start output\n");
1544 +               goto err_vsp;
1545 +       }
1546 +
1547 +       /* dequeue input (do we need this?) */
1548 +       if (vsp_input_buffer_dequeue_dmafd(r->vsp) < 0) {
1549 +               weston_log("VSP: failed to dequeue input buffer\n");
1550 +               /* don't care */
1551 +       }
1552 +
1553 +       /* dequeue output */
1554 +       if (vsp_output_buffer_dequeue_dmafd(r->vsp) < 0) {
1555 +               weston_log("VSP: failed to dequeu output buffer\n");
1556 +               gst_recorder_omx_buffer_release(r, buf);
1557 +               /* fall through */
1558 +       } else {
1559 +               /* set timestamp */
1560 +               gst_recorder_set_timestamp(r, buf);
1561 +
1562 +               ret = gst_app_src_push_buffer(r->appsrc, buf);
1563 +               r->frame_count++;
1564 +
1565 +               if (ret != GST_FLOW_OK) {
1566 +                       /* some error, stop sending data */
1567 +                       weston_log("gst_pipeline: some error %d\n", ret);
1568 +               }
1569 +
1570 +       }
1571 +       /* stop input */
1572 +       vsp_streaming_enable(r->vsp, VSP_PORT_INPUT, 0);
1573 +       /* stop output */
1574 +       vsp_streaming_enable(r->vsp, VSP_PORT_OUTPUT, 0);
1575 +
1576 +       /* deinit */
1577 +       vsp_request_buffers(r->vsp, VSP_PORT_INPUT, 0);
1578 +       vsp_request_buffers(r->vsp, VSP_PORT_OUTPUT, 0);
1579 +
1580 +       pthread_mutex_unlock(&r->vsp->mutex);
1581 +       return 0;
1582 +
1583 +err_vsp:
1584 +       /* drop gst buffer */
1585 +       /* finish vsp here */
1586 +err:
1587 +       pthread_mutex_unlock(&r->vsp->mutex);
1588 +       return -1;
1589 +}
1590 +
1591 +int
1592 +gst_recorder_frame_dmafd(struct gst_recorder *r, int fd, int stride)
1593 +{
1594 +       int ret = 0;
1595 +       
1596 +       pthread_mutex_lock(&r->mutex);
1597 +
1598 +       if (r->error) {
1599 +               errno = r->error;
1600 +               ret = -1;
1601 +               goto unlock;
1602 +       }
1603 +               
1604 +       /* The mutex is never released while encoding, so this point should
1605 +        * never be reached if input.valid is true. */
1606 +       assert(!r->input.valid);
1607 +
1608 +       r->input.prime_fd = fd;
1609 +       r->input.stride = stride;
1610 +       r->input.valid = 1;
1611 +       pthread_cond_signal(&r->input_cond);
1612 +
1613 +unlock:
1614 +       pthread_mutex_unlock(&r->mutex);
1615 +
1616 +       return 0;
1617 +}
1618 diff --git a/libweston/gst-recorder.h b/libweston/gst-recorder.h
1619 new file mode 100644
1620 index 0000000..78290c1
1621 --- /dev/null
1622 +++ b/libweston/gst-recorder.h
1623 @@ -0,0 +1,58 @@
1624 +/*
1625 + * Copyright Â© 2016 Cogent Embedded Inc
1626 + *
1627 + * Permission to use, copy, modify, distribute, and sell this software and
1628 + * its documentation for any purpose is hereby granted without fee, provided
1629 + * that the above copyright notice appear in all copies and that both that
1630 + * copyright notice and this permission notice appear in supporting
1631 + * documentation, and that the name of the copyright holders not be used in
1632 + * advertising or publicity pertaining to distribution of the software
1633 + * without specific, written prior permission.  The copyright holders make
1634 + * no representations about the suitability of this software for any
1635 + * purpose.  It is provided "as is" without express or implied warranty.
1636 + *
1637 + * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
1638 + * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
1639 + * FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
1640 + * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
1641 + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
1642 + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
1643 + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
1644 + */
1645 +
1646 +#ifndef _GST_RECORDER_H_
1647 +#define _GST_RECORDER_H_
1648 +
1649 +/* VSP includes */
1650 +#include <media-ctl/mediactl.h>
1651 +#include <media-ctl/v4l2subdev.h>
1652 +
1653 +struct gst_recorder;
1654 +
1655 +struct gst_recorder_settings {
1656 +       int width;
1657 +       int height;
1658 +       int bitrate;
1659 +       char *ip;
1660 +       int port;
1661 +       int latency_test;
1662 +       int refresh_ratio;
1663 +
1664 +       /* Cropping */
1665 +       struct v4l2_rect crop;
1666 +};
1667 +
1668 +void
1669 +gst_recorder_init(void);
1670 +struct gst_recorder *
1671 +gst_recorder_create(struct gst_recorder_settings *settings);
1672 +void
1673 +gst_recorder_destroy(struct gst_recorder *r);
1674 +int
1675 +gst_recorder_frame(struct gst_recorder *r, int fd, int stride);
1676 +int
1677 +gst_recorder_frame_mmap(struct gst_recorder *r, void *data, int stride);
1678 +int
1679 +gst_recorder_frame_dmafd(struct gst_recorder *r, int fd, int stride);
1680 +
1681 +#endif /* _GST_RECORDER_H_ */
1682 diff --git a/libweston/media-ctl/libmediactl.c b/libweston/media-ctl/libmediactl.c
1683 new file mode 100644
1684 index 0000000..f15b1a3
1685 --- /dev/null
1686 +++ b/libweston/media-ctl/libmediactl.c
1687 @@ -0,0 +1,955 @@
1688 +/*
1689 + * Media controller interface library
1690 + *
1691 + * Copyright (C) 2010-2014 Ideas on board SPRL
1692 + *
1693 + * Contact: Laurent Pinchart <laurent.pinchart@ideasonboard.com>
1694 + *
1695 + * This program is free software; you can redistribute it and/or modify
1696 + * it under the terms of the GNU Lesser General Public License as published
1697 + * by the Free Software Foundation; either version 2.1 of the License, or
1698 + * (at your option) any later version.
1699 + *
1700 + * This program is distributed in the hope that it will be useful,
1701 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
1702 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
1703 + * GNU Lesser General Public License for more details.
1704 + *
1705 + * You should have received a copy of the GNU Lesser General Public License
1706 + * along with this program. If not, see <http://www.gnu.org/licenses/>.
1707 + */
1708 +
1709 +#include "config.h"
1710 +
1711 +#include <sys/ioctl.h>
1712 +#include <sys/stat.h>
1713 +#include <sys/types.h>
1714 +
1715 +#include <ctype.h>
1716 +#include <errno.h>
1717 +#include <fcntl.h>
1718 +#include <stdbool.h>
1719 +#include <stdio.h>
1720 +#include <stdlib.h>
1721 +#include <string.h>
1722 +#include <unistd.h>
1723 +
1724 +#include <linux/media.h>
1725 +#include <linux/videodev2.h>
1726 +
1727 +#include "mediactl.h"
1728 +#include "mediactl-priv.h"
1729 +#include "tools.h"
1730 +
1731 +/* -----------------------------------------------------------------------------
1732 + * Graph access
1733 + */
1734 +
1735 +struct media_pad *media_entity_remote_source(struct media_pad *pad)
1736 +{
1737 +       unsigned int i;
1738 +
1739 +       if (!(pad->flags & MEDIA_PAD_FL_SINK))
1740 +               return NULL;
1741 +
1742 +       for (i = 0; i < pad->entity->num_links; ++i) {
1743 +               struct media_link *link = &pad->entity->links[i];
1744 +
1745 +               if (!(link->flags & MEDIA_LNK_FL_ENABLED))
1746 +                       continue;
1747 +
1748 +               if (link->sink == pad)
1749 +                       return link->source;
1750 +       }
1751 +
1752 +       return NULL;
1753 +}
1754 +
1755 +struct media_entity *media_get_entity_by_name(struct media_device *media,
1756 +                                             const char *name, size_t length)
1757 +{
1758 +       unsigned int i;
1759 +
1760 +       /* A match is impossible if the entity name is longer than the maximum
1761 +        * size we can get from the kernel.
1762 +        */
1763 +       if (length >= FIELD_SIZEOF(struct media_entity_desc, name))
1764 +               return NULL;
1765 +
1766 +       for (i = 0; i < media->entities_count; ++i) {
1767 +               struct media_entity *entity = &media->entities[i];
1768 +
1769 +               if (strncmp(entity->info.name, name, length) == 0 &&
1770 +                   entity->info.name[length] == '\0')
1771 +                       return entity;
1772 +       }
1773 +
1774 +       return NULL;
1775 +}
1776 +
1777 +struct media_entity *media_get_entity_by_id(struct media_device *media,
1778 +                                           __u32 id)
1779 +{
1780 +       bool next = id & MEDIA_ENT_ID_FLAG_NEXT;
1781 +       unsigned int i;
1782 +
1783 +       id &= ~MEDIA_ENT_ID_FLAG_NEXT;
1784 +
1785 +       for (i = 0; i < media->entities_count; ++i) {
1786 +               struct media_entity *entity = &media->entities[i];
1787 +
1788 +               if ((entity->info.id == id && !next) ||
1789 +                   (entity->info.id > id && next))
1790 +                       return entity;
1791 +       }
1792 +
1793 +       return NULL;
1794 +}
1795 +
1796 +unsigned int media_get_entities_count(struct media_device *media)
1797 +{
1798 +       return media->entities_count;
1799 +}
1800 +
1801 +struct media_entity *media_get_entity(struct media_device *media, unsigned int index)
1802 +{
1803 +       if (index >= media->entities_count)
1804 +               return NULL;
1805 +
1806 +       return &media->entities[index];
1807 +}
1808 +
1809 +const struct media_pad *media_entity_get_pad(struct media_entity *entity, unsigned int index)
1810 +{
1811 +       if (index >= entity->info.pads)
1812 +               return NULL;
1813 +
1814 +       return &entity->pads[index];
1815 +}
1816 +
1817 +unsigned int media_entity_get_links_count(struct media_entity *entity)
1818 +{
1819 +       return entity->num_links;
1820 +}
1821 +
1822 +const struct media_link *media_entity_get_link(struct media_entity *entity, unsigned int index)
1823 +{
1824 +       if (index >= entity->num_links)
1825 +               return NULL;
1826 +
1827 +       return &entity->links[index];
1828 +}
1829 +
1830 +const char *media_entity_get_devname(struct media_entity *entity)
1831 +{
1832 +       return entity->devname[0] ? entity->devname : NULL;
1833 +}
1834 +
1835 +struct media_entity *media_get_default_entity(struct media_device *media,
1836 +                                             unsigned int type)
1837 +{
1838 +       switch (type) {
1839 +       case MEDIA_ENT_T_DEVNODE_V4L:
1840 +               return media->def.v4l;
1841 +       case MEDIA_ENT_T_DEVNODE_FB:
1842 +               return media->def.fb;
1843 +       case MEDIA_ENT_T_DEVNODE_ALSA:
1844 +               return media->def.alsa;
1845 +       case MEDIA_ENT_T_DEVNODE_DVB:
1846 +               return media->def.dvb;
1847 +       }
1848 +
1849 +       return NULL;
1850 +}
1851 +
1852 +const struct media_device_info *media_get_info(struct media_device *media)
1853 +{
1854 +       return &media->info;
1855 +}
1856 +
1857 +const char *media_get_devnode(struct media_device *media)
1858 +{
1859 +       return media->devnode;
1860 +}
1861 +
1862 +const struct media_entity_desc *media_entity_get_info(struct media_entity *entity)
1863 +{
1864 +       return &entity->info;
1865 +}
1866 +
1867 +/* -----------------------------------------------------------------------------
1868 + * Open/close
1869 + */
1870 +
1871 +static int media_device_open(struct media_device *media)
1872 +{
1873 +       int ret;
1874 +
1875 +       if (media->fd != -1)
1876 +               return 0;
1877 +
1878 +       media_dbg(media, "Opening media device %s\n", media->devnode);
1879 +
1880 +       media->fd = open(media->devnode, O_RDWR);
1881 +       if (media->fd < 0) {
1882 +               ret = -errno;
1883 +               media_dbg(media, "%s: Can't open media device %s\n",
1884 +                         __func__, media->devnode);
1885 +               return ret;
1886 +       }
1887 +
1888 +       return 0;
1889 +}
1890 +
1891 +static void media_device_close(struct media_device *media)
1892 +{
1893 +       if (media->fd != -1) {
1894 +               close(media->fd);
1895 +               media->fd = -1;
1896 +       }
1897 +}
1898 +
1899 +/* -----------------------------------------------------------------------------
1900 + * Link setup
1901 + */
1902 +
1903 +int media_setup_link(struct media_device *media,
1904 +                    struct media_pad *source,
1905 +                    struct media_pad *sink,
1906 +                    __u32 flags)
1907 +{
1908 +       struct media_link *link;
1909 +       struct media_link_desc ulink;
1910 +       unsigned int i;
1911 +       int ret;
1912 +
1913 +       ret = media_device_open(media);
1914 +       if (ret < 0)
1915 +               goto done;
1916 +
1917 +       for (i = 0; i < source->entity->num_links; i++) {
1918 +               link = &source->entity->links[i];
1919 +
1920 +               if (link->source->entity == source->entity &&
1921 +                   link->source->index == source->index &&
1922 +                   link->sink->entity == sink->entity &&
1923 +                   link->sink->index == sink->index)
1924 +                       break;
1925 +       }
1926 +
1927 +       if (i == source->entity->num_links) {
1928 +               media_dbg(media, "%s: Link not found\n", __func__);
1929 +               ret = -ENOENT;
1930 +               goto done;
1931 +       }
1932 +
1933 +       /* source pad */
1934 +       ulink.source.entity = source->entity->info.id;
1935 +       ulink.source.index = source->index;
1936 +       ulink.source.flags = MEDIA_PAD_FL_SOURCE;
1937 +
1938 +       /* sink pad */
1939 +       ulink.sink.entity = sink->entity->info.id;
1940 +       ulink.sink.index = sink->index;
1941 +       ulink.sink.flags = MEDIA_PAD_FL_SINK;
1942 +
1943 +       ulink.flags = flags | (link->flags & MEDIA_LNK_FL_IMMUTABLE);
1944 +
1945 +       ret = ioctl(media->fd, MEDIA_IOC_SETUP_LINK, &ulink);
1946 +       if (ret == -1) {
1947 +               ret = -errno;
1948 +               media_dbg(media, "%s: Unable to setup link (%s)\n",
1949 +                         __func__, strerror(errno));
1950 +               goto done;
1951 +       }
1952 +
1953 +       link->flags = ulink.flags;
1954 +       link->twin->flags = ulink.flags;
1955 +
1956 +       ret = 0;
1957 +
1958 +done:
1959 +       return ret;
1960 +}
1961 +
1962 +int media_reset_links(struct media_device *media)
1963 +{
1964 +       unsigned int i, j;
1965 +       int ret;
1966 +
1967 +       for (i = 0; i < media->entities_count; ++i) {
1968 +               struct media_entity *entity = &media->entities[i];
1969 +
1970 +               for (j = 0; j < entity->num_links; j++) {
1971 +                       struct media_link *link = &entity->links[j];
1972 +
1973 +                       if (link->flags & MEDIA_LNK_FL_IMMUTABLE ||
1974 +                           link->source->entity != entity)
1975 +                               continue;
1976 +
1977 +                       ret = media_setup_link(media, link->source, link->sink,
1978 +                                              link->flags & ~MEDIA_LNK_FL_ENABLED);
1979 +                       if (ret < 0)
1980 +                               return ret;
1981 +               }
1982 +       }
1983 +
1984 +       return 0;
1985 +}
1986 +
1987 +/* -----------------------------------------------------------------------------
1988 + * Entities, pads and links enumeration
1989 + */
1990 +
1991 +static struct media_link *media_entity_add_link(struct media_entity *entity)
1992 +{
1993 +       if (entity->num_links >= entity->max_links) {
1994 +               struct media_link *links = entity->links;
1995 +               unsigned int max_links = entity->max_links * 2;
1996 +               unsigned int i;
1997 +
1998 +               links = realloc(links, max_links * sizeof *links);
1999 +               if (links == NULL)
2000 +                       return NULL;
2001 +
2002 +               for (i = 0; i < entity->num_links; ++i)
2003 +                       links[i].twin->twin = &links[i];
2004 +
2005 +               entity->max_links = max_links;
2006 +               entity->links = links;
2007 +       }
2008 +
2009 +       return &entity->links[entity->num_links++];
2010 +}
2011 +
2012 +static int media_enum_links(struct media_device *media)
2013 +{
2014 +       __u32 id;
2015 +       int ret = 0;
2016 +
2017 +       for (id = 1; id <= media->entities_count; id++) {
2018 +               struct media_entity *entity = &media->entities[id - 1];
2019 +               struct media_links_enum links;
2020 +               unsigned int i;
2021 +
2022 +               links.entity = entity->info.id;
2023 +               links.pads = calloc(entity->info.pads, sizeof(struct media_pad_desc));
2024 +               links.links = calloc(entity->info.links, sizeof(struct media_link_desc));
2025 +
2026 +               if (ioctl(media->fd, MEDIA_IOC_ENUM_LINKS, &links) < 0) {
2027 +                       ret = -errno;
2028 +                       media_dbg(media,
2029 +                                 "%s: Unable to enumerate pads and links (%s).\n",
2030 +                                 __func__, strerror(errno));
2031 +                       free(links.pads);
2032 +                       free(links.links);
2033 +                       return ret;
2034 +               }
2035 +
2036 +               for (i = 0; i < entity->info.pads; ++i) {
2037 +                       entity->pads[i].entity = entity;
2038 +                       entity->pads[i].index = links.pads[i].index;
2039 +                       entity->pads[i].flags = links.pads[i].flags;
2040 +               }
2041 +
2042 +               for (i = 0; i < entity->info.links; ++i) {
2043 +                       struct media_link_desc *link = &links.links[i];
2044 +                       struct media_link *fwdlink;
2045 +                       struct media_link *backlink;
2046 +                       struct media_entity *source;
2047 +                       struct media_entity *sink;
2048 +
2049 +                       source = media_get_entity_by_id(media, link->source.entity);
2050 +                       sink = media_get_entity_by_id(media, link->sink.entity);
2051 +
2052 +                       if (source == NULL || sink == NULL) {
2053 +                               media_dbg(media,
2054 +                                         "WARNING entity %u link %u from %u/%u to %u/%u is invalid!\n",
2055 +                                         id, i, link->source.entity,
2056 +                                         link->source.index,
2057 +                                         link->sink.entity,
2058 +                                         link->sink.index);
2059 +                               ret = -EINVAL;
2060 +                       } else {
2061 +                               fwdlink = media_entity_add_link(source);
2062 +                               fwdlink->source = &source->pads[link->source.index];
2063 +                               fwdlink->sink = &sink->pads[link->sink.index];
2064 +                               fwdlink->flags = link->flags;
2065 +
2066 +                               backlink = media_entity_add_link(sink);
2067 +                               backlink->source = &source->pads[link->source.index];
2068 +                               backlink->sink = &sink->pads[link->sink.index];
2069 +                               backlink->flags = link->flags;
2070 +
2071 +                               fwdlink->twin = backlink;
2072 +                               backlink->twin = fwdlink;
2073 +                       }
2074 +               }
2075 +
2076 +               free(links.pads);
2077 +               free(links.links);
2078 +       }
2079 +
2080 +       return ret;
2081 +}
2082 +
2083 +#ifdef HAVE_LIBUDEV
2084 +
2085 +#include <libudev.h>
2086 +
2087 +static inline int media_udev_open(struct udev **udev)
2088 +{
2089 +       *udev = udev_new();
2090 +       if (*udev == NULL)
2091 +               return -ENOMEM;
2092 +       return 0;
2093 +}
2094 +
2095 +static inline void media_udev_close(struct udev *udev)
2096 +{
2097 +       if (udev != NULL)
2098 +               udev_unref(udev);
2099 +}
2100 +
2101 +static int media_get_devname_udev(struct udev *udev,
2102 +               struct media_entity *entity)
2103 +{
2104 +       struct udev_device *device;
2105 +       dev_t devnum;
2106 +       const char *p;
2107 +       int ret = -ENODEV;
2108 +
2109 +       if (udev == NULL)
2110 +               return -EINVAL;
2111 +
2112 +       devnum = makedev(entity->info.v4l.major, entity->info.v4l.minor);
2113 +       media_dbg(entity->media, "looking up device: %u:%u\n",
2114 +                 major(devnum), minor(devnum));
2115 +       device = udev_device_new_from_devnum(udev, 'c', devnum);
2116 +       if (device) {
2117 +               p = udev_device_get_devnode(device);
2118 +               if (p) {
2119 +                       strncpy(entity->devname, p, sizeof(entity->devname));
2120 +                       entity->devname[sizeof(entity->devname) - 1] = '\0';
2121 +               }
2122 +               ret = 0;
2123 +       }
2124 +
2125 +       udev_device_unref(device);
2126 +
2127 +       return ret;
2128 +}
2129 +
2130 +#else  /* HAVE_LIBUDEV */
2131 +
2132 +struct udev;
2133 +
2134 +static inline int media_udev_open(struct udev **udev) { return 0; }
2135 +
2136 +static inline void media_udev_close(struct udev *udev) { }
2137 +
2138 +static inline int media_get_devname_udev(struct udev *udev,
2139 +               struct media_entity *entity)
2140 +{
2141 +       return -ENOTSUP;
2142 +}
2143 +
2144 +#endif /* HAVE_LIBUDEV */
2145 +
2146 +static int media_get_devname_sysfs(struct media_entity *entity)
2147 +{
2148 +       struct stat devstat;
2149 +       char devname[32];
2150 +       char sysname[32];
2151 +       char target[1024];
2152 +       char *p;
2153 +       int ret;
2154 +
2155 +       sprintf(sysname, "/sys/dev/char/%u:%u", entity->info.v4l.major,
2156 +               entity->info.v4l.minor);
2157 +       ret = readlink(sysname, target, sizeof(target) - 1);
2158 +       if (ret < 0)
2159 +               return -errno;
2160 +
2161 +       target[ret] = '\0';
2162 +       p = strrchr(target, '/');
2163 +       if (p == NULL)
2164 +               return -EINVAL;
2165 +
2166 +       sprintf(devname, "/dev/%s", p + 1);
2167 +       ret = stat(devname, &devstat);
2168 +       if (ret < 0)
2169 +               return -errno;
2170 +
2171 +       /* Sanity check: udev might have reordered the device nodes.
2172 +        * Make sure the major/minor match. We should really use
2173 +        * libudev.
2174 +        */
2175 +       if (major(devstat.st_rdev) == entity->info.v4l.major &&
2176 +           minor(devstat.st_rdev) == entity->info.v4l.minor)
2177 +               strcpy(entity->devname, devname);
2178 +
2179 +       return 0;
2180 +}
2181 +
2182 +static int media_enum_entities(struct media_device *media)
2183 +{
2184 +       struct media_entity *entity;
2185 +       struct udev *udev;
2186 +       unsigned int size;
2187 +       __u32 id;
2188 +       int ret;
2189 +
2190 +       ret = media_udev_open(&udev);
2191 +       if (ret < 0)
2192 +               media_dbg(media, "Can't get udev context\n");
2193 +
2194 +       for (id = 0, ret = 0; ; id = entity->info.id) {
2195 +               size = (media->entities_count + 1) * sizeof(*media->entities);
2196 +               media->entities = realloc(media->entities, size);
2197 +
2198 +               entity = &media->entities[media->entities_count];
2199 +               memset(entity, 0, sizeof(*entity));
2200 +               entity->fd = -1;
2201 +               entity->info.id = id | MEDIA_ENT_ID_FLAG_NEXT;
2202 +               entity->media = media;
2203 +
2204 +               ret = ioctl(media->fd, MEDIA_IOC_ENUM_ENTITIES, &entity->info);
2205 +               if (ret < 0) {
2206 +                       ret = errno != EINVAL ? -errno : 0;
2207 +                       break;
2208 +               }
2209 +
2210 +               /* Number of links (for outbound links) plus number of pads (for
2211 +                * inbound links) is a good safe initial estimate of the total
2212 +                * number of links.
2213 +                */
2214 +               entity->max_links = entity->info.pads + entity->info.links;
2215 +
2216 +               entity->pads = malloc(entity->info.pads * sizeof(*entity->pads));
2217 +               entity->links = malloc(entity->max_links * sizeof(*entity->links));
2218 +               if (entity->pads == NULL || entity->links == NULL) {
2219 +                       ret = -ENOMEM;
2220 +                       break;
2221 +               }
2222 +
2223 +               media->entities_count++;
2224 +
2225 +               if (entity->info.flags & MEDIA_ENT_FL_DEFAULT) {
2226 +                       switch (entity->info.type) {
2227 +                       case MEDIA_ENT_T_DEVNODE_V4L:
2228 +                               media->def.v4l = entity;
2229 +                               break;
2230 +                       case MEDIA_ENT_T_DEVNODE_FB:
2231 +                               media->def.fb = entity;
2232 +                               break;
2233 +                       case MEDIA_ENT_T_DEVNODE_ALSA:
2234 +                               media->def.alsa = entity;
2235 +                               break;
2236 +                       case MEDIA_ENT_T_DEVNODE_DVB:
2237 +                               media->def.dvb = entity;
2238 +                               break;
2239 +                       }
2240 +               }
2241 +
2242 +               /* Find the corresponding device name. */
2243 +               if (media_entity_type(entity) != MEDIA_ENT_T_DEVNODE &&
2244 +                   media_entity_type(entity) != MEDIA_ENT_T_V4L2_SUBDEV)
2245 +                       continue;
2246 +
2247 +               /* Try to get the device name via udev */
2248 +               if (!media_get_devname_udev(udev, entity))
2249 +                       continue;
2250 +
2251 +               /* Fall back to get the device name via sysfs */
2252 +               media_get_devname_sysfs(entity);
2253 +       }
2254 +
2255 +       media_udev_close(udev);
2256 +       return ret;
2257 +}
2258 +
2259 +int media_device_enumerate(struct media_device *media)
2260 +{
2261 +       int ret;
2262 +
2263 +       if (media->entities)
2264 +               return 0;
2265 +
2266 +       ret = media_device_open(media);
2267 +       if (ret < 0)
2268 +               return ret;
2269 +
2270 +       ret = ioctl(media->fd, MEDIA_IOC_DEVICE_INFO, &media->info);
2271 +       if (ret < 0) {
2272 +               ret = -errno;
2273 +               media_dbg(media, "%s: Unable to retrieve media device "
2274 +                         "information for device %s (%s)\n", __func__,
2275 +                         media->devnode, strerror(errno));
2276 +               goto done;
2277 +       }
2278 +
2279 +       media_dbg(media, "Enumerating entities\n");
2280 +
2281 +       ret = media_enum_entities(media);
2282 +       if (ret < 0) {
2283 +               media_dbg(media,
2284 +                         "%s: Unable to enumerate entities for device %s (%s)\n",
2285 +                         __func__, media->devnode, strerror(-ret));
2286 +               goto done;
2287 +       }
2288 +
2289 +       media_dbg(media, "Found %u entities\n", media->entities_count);
2290 +       media_dbg(media, "Enumerating pads and links\n");
2291 +
2292 +       ret = media_enum_links(media);
2293 +       if (ret < 0) {
2294 +               media_dbg(media,
2295 +                         "%s: Unable to enumerate pads and linksfor device %s\n",
2296 +                         __func__, media->devnode);
2297 +               goto done;
2298 +       }
2299 +
2300 +       ret = 0;
2301 +
2302 +done:
2303 +       return ret;
2304 +}
2305 +
2306 +/* -----------------------------------------------------------------------------
2307 + * Create/destroy
2308 + */
2309 +
2310 +static void media_debug_default(void *ptr, ...)
2311 +{
2312 +}
2313 +
2314 +void media_debug_set_handler(struct media_device *media,
2315 +                            void (*debug_handler)(void *, ...),
2316 +                            void *debug_priv)
2317 +{
2318 +       if (debug_handler) {
2319 +               media->debug_handler = debug_handler;
2320 +               media->debug_priv = debug_priv;
2321 +       } else {
2322 +               media->debug_handler = media_debug_default;
2323 +               media->debug_priv = NULL;
2324 +       }
2325 +}
2326 +
2327 +static struct media_device *__media_device_new(void)
2328 +{
2329 +       struct media_device *media;
2330 +
2331 +       media = calloc(1, sizeof(*media));
2332 +       if (media == NULL)
2333 +               return NULL;
2334 +
2335 +       media->fd = -1;
2336 +       media->refcount = 1;
2337 +
2338 +       media_debug_set_handler(media, NULL, NULL);
2339 +
2340 +       return media;
2341 +}
2342 +
2343 +struct media_device *media_device_new(const char *devnode)
2344 +{
2345 +       struct media_device *media;
2346 +
2347 +       media = __media_device_new();
2348 +       if (media == NULL)
2349 +               return NULL;
2350 +
2351 +       media->devnode = strdup(devnode);
2352 +       if (media->devnode == NULL) {
2353 +               media_device_unref(media);
2354 +               return NULL;
2355 +       }
2356 +
2357 +       return media;
2358 +}
2359 +
2360 +struct media_device *media_device_new_emulated(struct media_device_info *info)
2361 +{
2362 +       struct media_device *media;
2363 +
2364 +       media = __media_device_new();
2365 +       if (media == NULL)
2366 +               return NULL;
2367 +
2368 +       media->info = *info;
2369 +
2370 +       return media;
2371 +}
2372 +
2373 +struct media_device *media_device_ref(struct media_device *media)
2374 +{
2375 +       media->refcount++;
2376 +       return media;
2377 +}
2378 +
2379 +void media_device_unref(struct media_device *media)
2380 +{
2381 +       unsigned int i;
2382 +
2383 +       media->refcount--;
2384 +       if (media->refcount > 0)
2385 +               return;
2386 +
2387 +       for (i = 0; i < media->entities_count; ++i) {
2388 +               struct media_entity *entity = &media->entities[i];
2389 +
2390 +               free(entity->pads);
2391 +               free(entity->links);
2392 +               if (entity->fd != -1)
2393 +                       close(entity->fd);
2394 +       }
2395 +
2396 +       free(media->entities);
2397 +       free(media->devnode);
2398 +       free(media);
2399 +}
2400 +
2401 +int media_device_add_entity(struct media_device *media,
2402 +                           const struct media_entity_desc *desc,
2403 +                           const char *devnode)
2404 +{
2405 +       struct media_entity **defent = NULL;
2406 +       struct media_entity *entity;
2407 +       unsigned int size;
2408 +
2409 +       size = (media->entities_count + 1) * sizeof(*media->entities);
2410 +       entity = realloc(media->entities, size);
2411 +       if (entity == NULL)
2412 +               return -ENOMEM;
2413 +
2414 +       media->entities = entity;
2415 +       media->entities_count++;
2416 +
2417 +       entity = &media->entities[media->entities_count - 1];
2418 +       memset(entity, 0, sizeof *entity);
2419 +
2420 +       entity->fd = -1;
2421 +       entity->media = media;
2422 +       strncpy(entity->devname, devnode, sizeof entity->devname);
2423 +       entity->devname[sizeof entity->devname - 1] = '\0';
2424 +
2425 +       entity->info.id = 0;
2426 +       entity->info.type = desc->type;
2427 +       entity->info.flags = 0;
2428 +       memcpy(entity->info.name, desc->name, sizeof entity->info.name);
2429 +
2430 +       switch (entity->info.type) {
2431 +       case MEDIA_ENT_T_DEVNODE_V4L:
2432 +               defent = &media->def.v4l;
2433 +               entity->info.v4l = desc->v4l;
2434 +               break;
2435 +       case MEDIA_ENT_T_DEVNODE_FB:
2436 +               defent = &media->def.fb;
2437 +               entity->info.fb = desc->fb;
2438 +               break;
2439 +       case MEDIA_ENT_T_DEVNODE_ALSA:
2440 +               defent = &media->def.alsa;
2441 +               entity->info.alsa = desc->alsa;
2442 +               break;
2443 +       case MEDIA_ENT_T_DEVNODE_DVB:
2444 +               defent = &media->def.dvb;
2445 +               entity->info.dvb = desc->dvb;
2446 +               break;
2447 +       }
2448 +
2449 +       if (desc->flags & MEDIA_ENT_FL_DEFAULT) {
2450 +               entity->info.flags |= MEDIA_ENT_FL_DEFAULT;
2451 +               if (defent)
2452 +                       *defent = entity;
2453 +       }
2454 +
2455 +       return 0;
2456 +}
2457 +
2458 +struct media_pad *media_parse_pad(struct media_device *media,
2459 +                                 const char *p, char **endp)
2460 +{
2461 +       unsigned int entity_id, pad;
2462 +       struct media_entity *entity;
2463 +       char *end;
2464 +
2465 +       /* endp can be NULL. To avoid spreading NULL checks across the function,
2466 +        * set endp to &end in that case.
2467 +        */
2468 +       if (endp == NULL)
2469 +               endp = &end;
2470 +
2471 +       for (; isspace(*p); ++p);
2472 +
2473 +       if (*p == '"' || *p == '\'') {
2474 +               for (end = (char *)p + 1; *end && *end != '"' && *end != '\''; ++end);
2475 +               if (*end != '"' && *end != '\'') {
2476 +                       media_dbg(media, "missing matching '\"'\n");
2477 +                       *endp = end;
2478 +                       return NULL;
2479 +               }
2480 +
2481 +               entity = media_get_entity_by_name(media, p + 1, end - p - 1);
2482 +               if (entity == NULL) {
2483 +                       media_dbg(media, "no such entity \"%.*s\"\n", end - p - 1, p + 1);
2484 +                       *endp = (char *)p + 1;
2485 +                       return NULL;
2486 +               }
2487 +
2488 +               ++end;
2489 +       } else {
2490 +               entity_id = strtoul(p, &end, 10);
2491 +               entity = media_get_entity_by_id(media, entity_id);
2492 +               if (entity == NULL) {
2493 +                       media_dbg(media, "no such entity %d\n", entity_id);
2494 +                       *endp = (char *)p;
2495 +                       return NULL;
2496 +               }
2497 +       }
2498 +       for (; isspace(*end); ++end);
2499 +
2500 +       if (*end != ':') {
2501 +               media_dbg(media, "Expected ':'\n", *end);
2502 +               *endp = end;
2503 +               return NULL;
2504 +       }
2505 +
2506 +       for (p = end + 1; isspace(*p); ++p);
2507 +
2508 +       pad = strtoul(p, &end, 10);
2509 +
2510 +       if (pad >= entity->info.pads) {
2511 +               media_dbg(media, "No pad '%d' on entity \"%s\". Maximum pad number is %d\n",
2512 +                               pad, entity->info.name, entity->info.pads - 1);
2513 +               *endp = (char *)p;
2514 +               return NULL;
2515 +       }
2516 +
2517 +       for (p = end; isspace(*p); ++p);
2518 +       *endp = (char *)p;
2519 +
2520 +       return &entity->pads[pad];
2521 +}
2522 +
2523 +struct media_link *media_parse_link(struct media_device *media,
2524 +                                   const char *p, char **endp)
2525 +{
2526 +       struct media_link *link;
2527 +       struct media_pad *source;
2528 +       struct media_pad *sink;
2529 +       unsigned int i;
2530 +       char *end;
2531 +
2532 +       source = media_parse_pad(media, p, &end);
2533 +       if (source == NULL) {
2534 +               *endp = end;
2535 +               return NULL;
2536 +       }
2537 +
2538 +       if (end[0] != '-' || end[1] != '>') {
2539 +               *endp = end;
2540 +               media_dbg(media, "Expected '->'\n");
2541 +               return NULL;
2542 +       }
2543 +
2544 +       p = end + 2;
2545 +
2546 +       sink = media_parse_pad(media, p, &end);
2547 +       if (sink == NULL) {
2548 +               *endp = end;
2549 +               return NULL;
2550 +       }
2551 +
2552 +       *endp = end;
2553 +
2554 +       for (i = 0; i < source->entity->num_links; i++) {
2555 +               link = &source->entity->links[i];
2556 +
2557 +               if (link->source == source && link->sink == sink)
2558 +                       return link;
2559 +       }
2560 +
2561 +       media_dbg(media, "No link between \"%s\":%d and \"%s\":%d\n",
2562 +                       source->entity->info.name, source->index,
2563 +                       sink->entity->info.name, sink->index);
2564 +       return NULL;
2565 +}
2566 +
2567 +int media_parse_setup_link(struct media_device *media,
2568 +                          const char *p, char **endp)
2569 +{
2570 +       struct media_link *link;
2571 +       __u32 flags;
2572 +       char *end;
2573 +
2574 +       link = media_parse_link(media, p, &end);
2575 +       if (link == NULL) {
2576 +               media_dbg(media,
2577 +                         "%s: Unable to parse link\n", __func__);
2578 +               *endp = end;
2579 +               return -EINVAL;
2580 +       }
2581 +
2582 +       p = end;
2583 +       if (*p++ != '[') {
2584 +               media_dbg(media, "Unable to parse link flags: expected '['.\n");
2585 +               *endp = (char *)p - 1;
2586 +               return -EINVAL;
2587 +       }
2588 +
2589 +       flags = strtoul(p, &end, 10);
2590 +       for (p = end; isspace(*p); p++);
2591 +       if (*p++ != ']') {
2592 +               media_dbg(media, "Unable to parse link flags: expected ']'.\n");
2593 +               *endp = (char *)p - 1;
2594 +               return -EINVAL;
2595 +       }
2596 +
2597 +       for (; isspace(*p); p++);
2598 +       *endp = (char *)p;
2599 +
2600 +       media_dbg(media,
2601 +                 "Setting up link %u:%u -> %u:%u [%u]\n",
2602 +                 link->source->entity->info.id, link->source->index,
2603 +                 link->sink->entity->info.id, link->sink->index,
2604 +                 flags);
2605 +
2606 +       return media_setup_link(media, link->source, link->sink, flags);
2607 +}
2608 +
2609 +void media_print_streampos(struct media_device *media, const char *p,
2610 +                          const char *end)
2611 +{
2612 +       int pos;
2613 +
2614 +       pos = end - p + 1;
2615 +
2616 +       if (pos < 0)
2617 +               pos = 0;
2618 +       if (pos > strlen(p))
2619 +               pos = strlen(p);
2620 +
2621 +       media_dbg(media, "\n");
2622 +       media_dbg(media, " %s\n", p);
2623 +       media_dbg(media, " %*s\n", pos, "^");
2624 +}
2625 +
2626 +int media_parse_setup_links(struct media_device *media, const char *p)
2627 +{
2628 +       char *end;
2629 +       int ret;
2630 +
2631 +       do {
2632 +               ret = media_parse_setup_link(media, p, &end);
2633 +               if (ret < 0) {
2634 +                       media_print_streampos(media, p, end);
2635 +                       return ret;
2636 +               }
2637 +
2638 +               p = end + 1;
2639 +       } while (*end == ',');
2640 +
2641 +       return *end ? -EINVAL : 0;
2642 +}
2643 diff --git a/libweston/media-ctl/libv4l2subdev.c b/libweston/media-ctl/libv4l2subdev.c
2644 new file mode 100644
2645 index 0000000..4ede4fa
2646 --- /dev/null
2647 +++ b/libweston/media-ctl/libv4l2subdev.c
2648 @@ -0,0 +1,759 @@
2649 +/*
2650 + * V4L2 subdev interface library
2651 + *
2652 + * Copyright (C) 2010-2014 Ideas on board SPRL
2653 + *
2654 + * Contact: Laurent Pinchart <laurent.pinchart@ideasonboard.com>
2655 + *
2656 + * This program is free software; you can redistribute it and/or modify
2657 + * it under the terms of the GNU Lesser General Public License as published
2658 + * by the Free Software Foundation; either version 2.1 of the License, or
2659 + * (at your option) any later version.
2660 + *
2661 + * This program is distributed in the hope that it will be useful,
2662 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
2663 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
2664 + * GNU Lesser General Public License for more details.
2665 + *
2666 + * You should have received a copy of the GNU Lesser General Public License
2667 + * along with this program. If not, see <http://www.gnu.org/licenses/>.
2668 + */
2669 +
2670 +#include <sys/ioctl.h>
2671 +#include <sys/stat.h>
2672 +#include <sys/types.h>
2673 +
2674 +#include <ctype.h>
2675 +#include <errno.h>
2676 +#include <fcntl.h>
2677 +#include <stdbool.h>
2678 +#include <stdio.h>
2679 +#include <stdlib.h>
2680 +#include <string.h>
2681 +#include <unistd.h>
2682 +
2683 +#include <linux/v4l2-subdev.h>
2684 +
2685 +#include "mediactl.h"
2686 +#include "mediactl-priv.h"
2687 +#include "tools.h"
2688 +#include "v4l2subdev.h"
2689 +
2690 +int v4l2_subdev_open(struct media_entity *entity)
2691 +{
2692 +       if (entity->fd != -1)
2693 +               return 0;
2694 +
2695 +       entity->fd = open(entity->devname, O_RDWR);
2696 +       if (entity->fd == -1) {
2697 +               int ret = -errno;
2698 +               media_dbg(entity->media,
2699 +                         "%s: Failed to open subdev device node %s\n", __func__,
2700 +                         entity->devname);
2701 +               return ret;
2702 +       }
2703 +
2704 +       return 0;
2705 +}
2706 +
2707 +void v4l2_subdev_close(struct media_entity *entity)
2708 +{
2709 +       close(entity->fd);
2710 +       entity->fd = -1;
2711 +}
2712 +
2713 +int v4l2_subdev_get_format(struct media_entity *entity,
2714 +       struct v4l2_mbus_framefmt *format, unsigned int pad,
2715 +       enum v4l2_subdev_format_whence which)
2716 +{
2717 +       struct v4l2_subdev_format fmt;
2718 +       int ret;
2719 +
2720 +       ret = v4l2_subdev_open(entity);
2721 +       if (ret < 0)
2722 +               return ret;
2723 +
2724 +       memset(&fmt, 0, sizeof(fmt));
2725 +       fmt.pad = pad;
2726 +       fmt.which = which;
2727 +
2728 +       ret = ioctl(entity->fd, VIDIOC_SUBDEV_G_FMT, &fmt);
2729 +       if (ret < 0)
2730 +               return -errno;
2731 +
2732 +       *format = fmt.format;
2733 +       return 0;
2734 +}
2735 +
2736 +int v4l2_subdev_set_format(struct media_entity *entity,
2737 +       struct v4l2_mbus_framefmt *format, unsigned int pad,
2738 +       enum v4l2_subdev_format_whence which)
2739 +{
2740 +       struct v4l2_subdev_format fmt;
2741 +       int ret;
2742 +
2743 +       ret = v4l2_subdev_open(entity);
2744 +       if (ret < 0)
2745 +               return ret;
2746 +
2747 +       memset(&fmt, 0, sizeof(fmt));
2748 +       fmt.pad = pad;
2749 +       fmt.which = which;
2750 +       fmt.format = *format;
2751 +
2752 +       ret = ioctl(entity->fd, VIDIOC_SUBDEV_S_FMT, &fmt);
2753 +       if (ret < 0)
2754 +               return -errno;
2755 +
2756 +       *format = fmt.format;
2757 +       return 0;
2758 +}
2759 +
2760 +int v4l2_subdev_get_selection(struct media_entity *entity,
2761 +       struct v4l2_rect *rect, unsigned int pad, unsigned int target,
2762 +       enum v4l2_subdev_format_whence which)
2763 +{
2764 +       union {
2765 +               struct v4l2_subdev_selection sel;
2766 +               struct v4l2_subdev_crop crop;
2767 +       } u;
2768 +       int ret;
2769 +
2770 +       ret = v4l2_subdev_open(entity);
2771 +       if (ret < 0)
2772 +               return ret;
2773 +
2774 +       memset(&u.sel, 0, sizeof(u.sel));
2775 +       u.sel.pad = pad;
2776 +       u.sel.target = target;
2777 +       u.sel.which = which;
2778 +
2779 +       ret = ioctl(entity->fd, VIDIOC_SUBDEV_G_SELECTION, &u.sel);
2780 +       if (ret >= 0) {
2781 +               *rect = u.sel.r;
2782 +               return 0;
2783 +       }
2784 +       if (errno != ENOTTY || target != V4L2_SEL_TGT_CROP)
2785 +               return -errno;
2786 +
2787 +       memset(&u.crop, 0, sizeof(u.crop));
2788 +       u.crop.pad = pad;
2789 +       u.crop.which = which;
2790 +
2791 +       ret = ioctl(entity->fd, VIDIOC_SUBDEV_G_CROP, &u.crop);
2792 +       if (ret < 0)
2793 +               return -errno;
2794 +
2795 +       *rect = u.crop.rect;
2796 +       return 0;
2797 +}
2798 +
2799 +int v4l2_subdev_set_selection(struct media_entity *entity,
2800 +       struct v4l2_rect *rect, unsigned int pad, unsigned int target,
2801 +       enum v4l2_subdev_format_whence which)
2802 +{
2803 +       union {
2804 +               struct v4l2_subdev_selection sel;
2805 +               struct v4l2_subdev_crop crop;
2806 +       } u;
2807 +       int ret;
2808 +
2809 +       ret = v4l2_subdev_open(entity);
2810 +       if (ret < 0)
2811 +               return ret;
2812 +
2813 +       memset(&u.sel, 0, sizeof(u.sel));
2814 +       u.sel.pad = pad;
2815 +       u.sel.target = target;
2816 +       u.sel.which = which;
2817 +       u.sel.r = *rect;
2818 +
2819 +       ret = ioctl(entity->fd, VIDIOC_SUBDEV_S_SELECTION, &u.sel);
2820 +       if (ret >= 0) {
2821 +               *rect = u.sel.r;
2822 +               return 0;
2823 +       }
2824 +       if (errno != ENOTTY || target != V4L2_SEL_TGT_CROP)
2825 +               return -errno;
2826 +
2827 +       memset(&u.crop, 0, sizeof(u.crop));
2828 +       u.crop.pad = pad;
2829 +       u.crop.which = which;
2830 +       u.crop.rect = *rect;
2831 +
2832 +       ret = ioctl(entity->fd, VIDIOC_SUBDEV_S_CROP, &u.crop);
2833 +       if (ret < 0)
2834 +               return -errno;
2835 +
2836 +       *rect = u.crop.rect;
2837 +       return 0;
2838 +}
2839 +
2840 +#if 0
2841 +int v4l2_subdev_get_dv_timings_caps(struct media_entity *entity,
2842 +       struct v4l2_dv_timings_cap *caps)
2843 +{
2844 +       unsigned int pad = caps->pad;
2845 +       int ret;
2846 +
2847 +       ret = v4l2_subdev_open(entity);
2848 +       if (ret < 0)
2849 +               return ret;
2850 +
2851 +       memset(caps, 0, sizeof(*caps));
2852 +       caps->pad = pad;
2853 +
2854 +       ret = ioctl(entity->fd, VIDIOC_SUBDEV_DV_TIMINGS_CAP, caps);
2855 +       if (ret < 0)
2856 +               return -errno;
2857 +
2858 +       return 0;
2859 +}
2860 +
2861 +int v4l2_subdev_query_dv_timings(struct media_entity *entity,
2862 +       struct v4l2_dv_timings *timings)
2863 +{
2864 +       int ret;
2865 +
2866 +       ret = v4l2_subdev_open(entity);
2867 +       if (ret < 0)
2868 +               return ret;
2869 +
2870 +       memset(timings, 0, sizeof(*timings));
2871 +
2872 +       ret = ioctl(entity->fd, VIDIOC_SUBDEV_QUERY_DV_TIMINGS, timings);
2873 +       if (ret < 0)
2874 +               return -errno;
2875 +
2876 +       return 0;
2877 +}
2878 +
2879 +int v4l2_subdev_get_dv_timings(struct media_entity *entity,
2880 +       struct v4l2_dv_timings *timings)
2881 +{
2882 +       int ret;
2883 +
2884 +       ret = v4l2_subdev_open(entity);
2885 +       if (ret < 0)
2886 +               return ret;
2887 +
2888 +       memset(timings, 0, sizeof(*timings));
2889 +
2890 +       ret = ioctl(entity->fd, VIDIOC_SUBDEV_G_DV_TIMINGS, timings);
2891 +       if (ret < 0)
2892 +               return -errno;
2893 +
2894 +       return 0;
2895 +}
2896 +
2897 +int v4l2_subdev_set_dv_timings(struct media_entity *entity,
2898 +       struct v4l2_dv_timings *timings)
2899 +{
2900 +       int ret;
2901 +
2902 +       ret = v4l2_subdev_open(entity);
2903 +       if (ret < 0)
2904 +               return ret;
2905 +
2906 +       ret = ioctl(entity->fd, VIDIOC_SUBDEV_S_DV_TIMINGS, timings);
2907 +       if (ret < 0)
2908 +               return -errno;
2909 +
2910 +       return 0;
2911 +}
2912 +#endif
2913 +
2914 +int v4l2_subdev_get_frame_interval(struct media_entity *entity,
2915 +                                  struct v4l2_fract *interval)
2916 +{
2917 +       struct v4l2_subdev_frame_interval ival;
2918 +       int ret;
2919 +
2920 +       ret = v4l2_subdev_open(entity);
2921 +       if (ret < 0)
2922 +               return ret;
2923 +
2924 +       memset(&ival, 0, sizeof(ival));
2925 +
2926 +       ret = ioctl(entity->fd, VIDIOC_SUBDEV_G_FRAME_INTERVAL, &ival);
2927 +       if (ret < 0)
2928 +               return -errno;
2929 +
2930 +       *interval = ival.interval;
2931 +       return 0;
2932 +}
2933 +
2934 +int v4l2_subdev_set_frame_interval(struct media_entity *entity,
2935 +                                  struct v4l2_fract *interval)
2936 +{
2937 +       struct v4l2_subdev_frame_interval ival;
2938 +       int ret;
2939 +
2940 +       ret = v4l2_subdev_open(entity);
2941 +       if (ret < 0)
2942 +               return ret;
2943 +
2944 +       memset(&ival, 0, sizeof(ival));
2945 +       ival.interval = *interval;
2946 +
2947 +       ret = ioctl(entity->fd, VIDIOC_SUBDEV_S_FRAME_INTERVAL, &ival);
2948 +       if (ret < 0)
2949 +               return -errno;
2950 +
2951 +       *interval = ival.interval;
2952 +       return 0;
2953 +}
2954 +
2955 +static int v4l2_subdev_parse_format(struct media_device *media,
2956 +                                   struct v4l2_mbus_framefmt *format,
2957 +                                   const char *p, char **endp)
2958 +{
2959 +       enum v4l2_mbus_pixelcode code;
2960 +       unsigned int width, height;
2961 +       char *end;
2962 +
2963 +       /*
2964 +        * Compatibility with the old syntax: consider space as valid
2965 +        * separator between the media bus pixel code and the size.
2966 +        */
2967 +       for (; isspace(*p); ++p);
2968 +       for (end = (char *)p;
2969 +            *end != '/' && *end != ' ' && *end != '\0'; ++end);
2970 +
2971 +       code = v4l2_subdev_string_to_pixelcode(p, end - p);
2972 +       if (code == (enum v4l2_mbus_pixelcode)-1) {
2973 +               media_dbg(media, "Invalid pixel code '%.*s'\n", end - p, p);
2974 +               return -EINVAL;
2975 +       }
2976 +
2977 +       p = end + 1;
2978 +       width = strtoul(p, &end, 10);
2979 +       if (*end != 'x') {
2980 +               media_dbg(media, "Expected 'x'\n");
2981 +               return -EINVAL;
2982 +       }
2983 +
2984 +       p = end + 1;
2985 +       height = strtoul(p, &end, 10);
2986 +       *endp = end;
2987 +
2988 +       memset(format, 0, sizeof(*format));
2989 +       format->width = width;
2990 +       format->height = height;
2991 +       format->code = code;
2992 +
2993 +       return 0;
2994 +}
2995 +
2996 +static int v4l2_subdev_parse_rectangle(struct media_device *media,
2997 +                                      struct v4l2_rect *r, const char *p,
2998 +                                      char **endp)
2999 +{
3000 +       char *end;
3001 +
3002 +       if (*p++ != '(') {
3003 +               media_dbg(media, "Expected '('\n");
3004 +               *endp = (char *)p - 1;
3005 +               return -EINVAL;
3006 +       }
3007 +
3008 +       r->left = strtoul(p, &end, 10);
3009 +       if (*end != ',') {
3010 +               media_dbg(media, "Expected ','\n");
3011 +               *endp = end;
3012 +               return -EINVAL;
3013 +       }
3014 +
3015 +       p = end + 1;
3016 +       r->top = strtoul(p, &end, 10);
3017 +       if (*end++ != ')') {
3018 +               media_dbg(media, "Expected ')'\n");
3019 +               *endp = end - 1;
3020 +               return -EINVAL;
3021 +       }
3022 +       if (*end != '/') {
3023 +               media_dbg(media, "Expected '/'\n");
3024 +               *endp = end;
3025 +               return -EINVAL;
3026 +       }
3027 +
3028 +       p = end + 1;
3029 +       r->width = strtoul(p, &end, 10);
3030 +       if (*end != 'x') {
3031 +               media_dbg(media, "Expected 'x'\n");
3032 +               *endp = end;
3033 +               return -EINVAL;
3034 +       }
3035 +
3036 +       p = end + 1;
3037 +       r->height = strtoul(p, &end, 10);
3038 +       *endp = end;
3039 +
3040 +       return 0;
3041 +}
3042 +
3043 +static int v4l2_subdev_parse_frame_interval(struct media_device *media,
3044 +                                           struct v4l2_fract *interval,
3045 +                                           const char *p, char **endp)
3046 +{
3047 +       char *end;
3048 +
3049 +       for (; isspace(*p); ++p);
3050 +
3051 +       interval->numerator = strtoul(p, &end, 10);
3052 +
3053 +       for (p = end; isspace(*p); ++p);
3054 +       if (*p++ != '/') {
3055 +               media_dbg(media, "Expected '/'\n");
3056 +               *endp = (char *)p - 1;
3057 +               return -EINVAL;
3058 +       }
3059 +
3060 +       for (; isspace(*p); ++p);
3061 +       interval->denominator = strtoul(p, &end, 10);
3062 +
3063 +       *endp = end;
3064 +       return 0;
3065 +}
3066 +
3067 +/*
3068 + * The debate over whether this function should be named icanhasstr() instead
3069 + * has been strong and heated. If you feel like this would be an important
3070 + * change, patches are welcome (or not).
3071 + */
3072 +static bool strhazit(const char *str, const char **p)
3073 +{
3074 +       int len = strlen(str);
3075 +
3076 +       if (strncmp(str, *p, len))
3077 +               return false;
3078 +
3079 +       for (*p += len; isspace(**p); ++*p);
3080 +       return true;
3081 +}
3082 +
3083 +static struct media_pad *v4l2_subdev_parse_pad_format(
3084 +       struct media_device *media, struct v4l2_mbus_framefmt *format,
3085 +       struct v4l2_rect *crop, struct v4l2_rect *compose,
3086 +       struct v4l2_fract *interval, const char *p, char **endp)
3087 +{
3088 +       struct media_pad *pad;
3089 +       bool first;
3090 +       char *end;
3091 +       int ret;
3092 +
3093 +       for (; isspace(*p); ++p);
3094 +
3095 +       pad = media_parse_pad(media, p, &end);
3096 +       if (pad == NULL) {
3097 +               *endp = end;
3098 +               return NULL;
3099 +       }
3100 +
3101 +       for (p = end; isspace(*p); ++p);
3102 +       if (*p++ != '[') {
3103 +               media_dbg(media, "Expected '['\n");
3104 +               *endp = (char *)p - 1;
3105 +               return NULL;
3106 +       }
3107 +
3108 +       for (first = true; ; first = false) {
3109 +               for (; isspace(*p); p++);
3110 +
3111 +               /*
3112 +                * Backward compatibility: if the first property starts with an
3113 +                * uppercase later, process it as a format description.
3114 +                */
3115 +               if (strhazit("fmt:", &p) || (first && isupper(*p))) {
3116 +                       ret = v4l2_subdev_parse_format(media, format, p, &end);
3117 +                       if (ret < 0) {
3118 +                               *endp = end;
3119 +                               return NULL;
3120 +                       }
3121 +
3122 +                       p = end;
3123 +                       continue;
3124 +               }
3125 +
3126 +               /*
3127 +                * Backward compatibility: crop rectangles can be specified
3128 +                * implicitly without the 'crop:' property name.
3129 +                */
3130 +               if (strhazit("crop:", &p) || *p == '(') {
3131 +                       ret = v4l2_subdev_parse_rectangle(media, crop, p, &end);
3132 +                       if (ret < 0) {
3133 +                               *endp = end;
3134 +                               return NULL;
3135 +                       }
3136 +
3137 +                       p = end;
3138 +                       continue;
3139 +               }
3140 +
3141 +               if (strhazit("compose:", &p)) {
3142 +                       ret = v4l2_subdev_parse_rectangle(media, compose, p, &end);
3143 +                       if (ret < 0) {
3144 +                               *endp = end;
3145 +                               return NULL;
3146 +                       }
3147 +
3148 +                       for (p = end; isspace(*p); p++);
3149 +                       continue;
3150 +               }
3151 +
3152 +               if (*p == '@') {
3153 +                       ret = v4l2_subdev_parse_frame_interval(media, interval, ++p, &end);
3154 +                       if (ret < 0) {
3155 +                               *endp = end;
3156 +                               return NULL;
3157 +                       }
3158 +
3159 +                       p = end;
3160 +                       continue;
3161 +               }
3162 +
3163 +               break;
3164 +       }
3165 +
3166 +       if (*p != ']') {
3167 +               media_dbg(media, "Expected ']'\n");
3168 +               *endp = (char *)p;
3169 +               return NULL;
3170 +       }
3171 +
3172 +       *endp = (char *)p + 1;
3173 +       return pad;
3174 +}
3175 +
3176 +static int set_format(struct media_pad *pad,
3177 +                     struct v4l2_mbus_framefmt *format)
3178 +{
3179 +       int ret;
3180 +
3181 +       if (format->width == 0 || format->height == 0)
3182 +               return 0;
3183 +
3184 +       media_dbg(pad->entity->media,
3185 +                 "Setting up format %s %ux%u on pad %s/%u\n",
3186 +                 v4l2_subdev_pixelcode_to_string(format->code),
3187 +                 format->width, format->height,
3188 +                 pad->entity->info.name, pad->index);
3189 +
3190 +       ret = v4l2_subdev_set_format(pad->entity, format, pad->index,
3191 +                                    V4L2_SUBDEV_FORMAT_ACTIVE);
3192 +       if (ret < 0) {
3193 +               media_dbg(pad->entity->media,
3194 +                         "Unable to set format: %s (%d)\n",
3195 +                         strerror(-ret), ret);
3196 +               return ret;
3197 +       }
3198 +
3199 +       media_dbg(pad->entity->media,
3200 +                 "Format set: %s %ux%u\n",
3201 +                 v4l2_subdev_pixelcode_to_string(format->code),
3202 +                 format->width, format->height);
3203 +
3204 +       return 0;
3205 +}
3206 +
3207 +static int set_selection(struct media_pad *pad, unsigned int target,
3208 +                        struct v4l2_rect *rect)
3209 +{
3210 +       int ret;
3211 +
3212 +       if (rect->left == -1 || rect->top == -1)
3213 +               return 0;
3214 +
3215 +       media_dbg(pad->entity->media,
3216 +                 "Setting up selection target %u rectangle (%u,%u)/%ux%u on pad %s/%u\n",
3217 +                 target, rect->left, rect->top, rect->width, rect->height,
3218 +                 pad->entity->info.name, pad->index);
3219 +
3220 +       ret = v4l2_subdev_set_selection(pad->entity, rect, pad->index,
3221 +                                       target, V4L2_SUBDEV_FORMAT_ACTIVE);
3222 +       if (ret < 0) {
3223 +               media_dbg(pad->entity->media,
3224 +                         "Unable to set selection rectangle: %s (%d)\n",
3225 +                         strerror(-ret), ret);
3226 +               return ret;
3227 +       }
3228 +
3229 +       media_dbg(pad->entity->media,
3230 +                 "Selection rectangle set: (%u,%u)/%ux%u\n",
3231 +                 rect->left, rect->top, rect->width, rect->height);
3232 +
3233 +       return 0;
3234 +}
3235 +
3236 +static int set_frame_interval(struct media_entity *entity,
3237 +                             struct v4l2_fract *interval)
3238 +{
3239 +       int ret;
3240 +
3241 +       if (interval->numerator == 0)
3242 +               return 0;
3243 +
3244 +       media_dbg(entity->media,
3245 +                 "Setting up frame interval %u/%u on entity %s\n",
3246 +                 interval->numerator, interval->denominator,
3247 +                 entity->info.name);
3248 +
3249 +       ret = v4l2_subdev_set_frame_interval(entity, interval);
3250 +       if (ret < 0) {
3251 +               media_dbg(entity->media,
3252 +                         "Unable to set frame interval: %s (%d)",
3253 +                         strerror(-ret), ret);
3254 +               return ret;
3255 +       }
3256 +
3257 +       media_dbg(entity->media, "Frame interval set: %u/%u\n",
3258 +                 interval->numerator, interval->denominator);
3259 +
3260 +       return 0;
3261 +}
3262 +
3263 +
3264 +static int v4l2_subdev_parse_setup_format(struct media_device *media,
3265 +                                         const char *p, char **endp)
3266 +{
3267 +       struct v4l2_mbus_framefmt format = { 0, 0, 0 };
3268 +       struct media_pad *pad;
3269 +       struct v4l2_rect crop = { -1, -1, -1, -1 };
3270 +       struct v4l2_rect compose = crop;
3271 +       struct v4l2_fract interval = { 0, 0 };
3272 +       unsigned int i;
3273 +       char *end;
3274 +       int ret;
3275 +
3276 +       pad = v4l2_subdev_parse_pad_format(media, &format, &crop, &compose,
3277 +                                          &interval, p, &end);
3278 +       if (pad == NULL) {
3279 +               media_print_streampos(media, p, end);
3280 +               media_dbg(media, "Unable to parse format\n");
3281 +               return -EINVAL;
3282 +       }
3283 +
3284 +       if (pad->flags & MEDIA_PAD_FL_SINK) {
3285 +               ret = set_format(pad, &format);
3286 +               if (ret < 0)
3287 +                       return ret;
3288 +       }
3289 +
3290 +       ret = set_selection(pad, V4L2_SEL_TGT_CROP, &crop);
3291 +       if (ret < 0)
3292 +               return ret;
3293 +
3294 +       ret = set_selection(pad, V4L2_SEL_TGT_COMPOSE, &compose);
3295 +       if (ret < 0)
3296 +               return ret;
3297 +
3298 +       if (pad->flags & MEDIA_PAD_FL_SOURCE) {
3299 +               ret = set_format(pad, &format);
3300 +               if (ret < 0)
3301 +                       return ret;
3302 +       }
3303 +
3304 +       ret = set_frame_interval(pad->entity, &interval);
3305 +       if (ret < 0)
3306 +               return ret;
3307 +
3308 +
3309 +       /* If the pad is an output pad, automatically set the same format on
3310 +        * the remote subdev input pads, if any.
3311 +        */
3312 +       if (pad->flags & MEDIA_PAD_FL_SOURCE) {
3313 +               for (i = 0; i < pad->entity->num_links; ++i) {
3314 +                       struct media_link *link = &pad->entity->links[i];
3315 +                       struct v4l2_mbus_framefmt remote_format;
3316 +
3317 +                       if (!(link->flags & MEDIA_LNK_FL_ENABLED))
3318 +                               continue;
3319 +
3320 +                       if (link->source == pad &&
3321 +                           link->sink->entity->info.type == MEDIA_ENT_T_V4L2_SUBDEV) {
3322 +                               remote_format = format;
3323 +                               set_format(link->sink, &remote_format);
3324 +                       }
3325 +               }
3326 +       }
3327 +
3328 +       *endp = end;
3329 +       return 0;
3330 +}
3331 +
3332 +int v4l2_subdev_parse_setup_formats(struct media_device *media, const char *p)
3333 +{
3334 +       char *end;
3335 +       int ret;
3336 +
3337 +       do {
3338 +               ret = v4l2_subdev_parse_setup_format(media, p, &end);
3339 +               if (ret < 0)
3340 +                       return ret;
3341 +
3342 +               p = end + 1;
3343 +       } while (*end == ',');
3344 +
3345 +       return *end ? -EINVAL : 0;
3346 +}
3347 +
3348 +static struct {
3349 +       const char *name;
3350 +       enum v4l2_mbus_pixelcode code;
3351 +} mbus_formats[] = {
3352 +       { "Y8", V4L2_MBUS_FMT_Y8_1X8},
3353 +       { "Y10", V4L2_MBUS_FMT_Y10_1X10 },
3354 +       { "Y12", V4L2_MBUS_FMT_Y12_1X12 },
3355 +       { "YUYV", V4L2_MBUS_FMT_YUYV8_1X16 },
3356 +       { "YUYV1_5X8", V4L2_MBUS_FMT_YUYV8_1_5X8 },
3357 +       { "YUYV2X8", V4L2_MBUS_FMT_YUYV8_2X8 },
3358 +       { "UYVY", V4L2_MBUS_FMT_UYVY8_1X16 },
3359 +       { "UYVY1_5X8", V4L2_MBUS_FMT_UYVY8_1_5X8 },
3360 +       { "UYVY2X8", V4L2_MBUS_FMT_UYVY8_2X8 },
3361 +       { "SBGGR8", V4L2_MBUS_FMT_SBGGR8_1X8 },
3362 +       { "SGBRG8", V4L2_MBUS_FMT_SGBRG8_1X8 },
3363 +       { "SGRBG8", V4L2_MBUS_FMT_SGRBG8_1X8 },
3364 +       { "SRGGB8", V4L2_MBUS_FMT_SRGGB8_1X8 },
3365 +       { "SBGGR10", V4L2_MBUS_FMT_SBGGR10_1X10 },
3366 +       { "SGBRG10", V4L2_MBUS_FMT_SGBRG10_1X10 },
3367 +       { "SGRBG10", V4L2_MBUS_FMT_SGRBG10_1X10 },
3368 +       { "SRGGB10", V4L2_MBUS_FMT_SRGGB10_1X10 },
3369 +       { "SBGGR10_DPCM8", V4L2_MBUS_FMT_SBGGR10_DPCM8_1X8 },
3370 +       { "SGBRG10_DPCM8", V4L2_MBUS_FMT_SGBRG10_DPCM8_1X8 },
3371 +       { "SGRBG10_DPCM8", V4L2_MBUS_FMT_SGRBG10_DPCM8_1X8 },
3372 +       { "SRGGB10_DPCM8", V4L2_MBUS_FMT_SRGGB10_DPCM8_1X8 },
3373 +       { "SBGGR12", V4L2_MBUS_FMT_SBGGR12_1X12 },
3374 +       { "SGBRG12", V4L2_MBUS_FMT_SGBRG12_1X12 },
3375 +       { "SGRBG12", V4L2_MBUS_FMT_SGRBG12_1X12 },
3376 +       { "SRGGB12", V4L2_MBUS_FMT_SRGGB12_1X12 },
3377 +       { "AYUV32", V4L2_MBUS_FMT_AYUV8_1X32 },
3378 +       { "ARGB32", V4L2_MBUS_FMT_ARGB8888_1X32 },
3379 +};
3380 +
3381 +const char *v4l2_subdev_pixelcode_to_string(enum v4l2_mbus_pixelcode code)
3382 +{
3383 +       unsigned int i;
3384 +
3385 +       for (i = 0; i < ARRAY_SIZE(mbus_formats); ++i) {
3386 +               if (mbus_formats[i].code == code)
3387 +                       return mbus_formats[i].name;
3388 +       }
3389 +
3390 +       return "unknown";
3391 +}
3392 +
3393 +enum v4l2_mbus_pixelcode v4l2_subdev_string_to_pixelcode(const char *string,
3394 +                                                        unsigned int length)
3395 +{
3396 +       unsigned int i;
3397 +
3398 +       for (i = 0; i < ARRAY_SIZE(mbus_formats); ++i) {
3399 +               if (strncmp(mbus_formats[i].name, string, length) == 0)
3400 +                       break;
3401 +       }
3402 +
3403 +       if (i == ARRAY_SIZE(mbus_formats))
3404 +               return (enum v4l2_mbus_pixelcode)-1;
3405 +
3406 +       return mbus_formats[i].code;
3407 +}
3408 diff --git a/libweston/media-ctl/mediactl-priv.h b/libweston/media-ctl/mediactl-priv.h
3409 new file mode 100644
3410 index 0000000..a0d3a55
3411 --- /dev/null
3412 +++ b/libweston/media-ctl/mediactl-priv.h
3413 @@ -0,0 +1,64 @@
3414 +/*
3415 + * Media controller interface library
3416 + *
3417 + * Copyright (C) 2010-2014 Ideas on board SPRL
3418 + *
3419 + * Contact: Laurent Pinchart <laurent.pinchart@ideasonboard.com>
3420 + *
3421 + * This program is free software; you can redistribute it and/or modify
3422 + * it under the terms of the GNU Lesser General Public License as published
3423 + * by the Free Software Foundation; either version 2.1 of the License, or
3424 + * (at your option) any later version.
3425 + *
3426 + * This program is distributed in the hope that it will be useful,
3427 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
3428 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
3429 + * GNU Lesser General Public License for more details.
3430 + *
3431 + * You should have received a copy of the GNU Lesser General Public License
3432 + * along with this program. If not, see <http://www.gnu.org/licenses/>.
3433 + */
3434 +
3435 +#ifndef __MEDIA_PRIV_H__
3436 +#define __MEDIA_PRIV_H__
3437 +
3438 +#include <linux/media.h>
3439 +
3440 +#include "mediactl.h"
3441 +
3442 +struct media_entity {
3443 +       struct media_device *media;
3444 +       struct media_entity_desc info;
3445 +       struct media_pad *pads;
3446 +       struct media_link *links;
3447 +       unsigned int max_links;
3448 +       unsigned int num_links;
3449 +
3450 +       char devname[32];
3451 +       int fd;
3452 +};
3453 +
3454 +struct media_device {
3455 +       int fd;
3456 +       int refcount;
3457 +       char *devnode;
3458 +
3459 +       struct media_device_info info;
3460 +       struct media_entity *entities;
3461 +       unsigned int entities_count;
3462 +
3463 +       void (*debug_handler)(void *, ...);
3464 +       void *debug_priv;
3465 +
3466 +       struct {
3467 +               struct media_entity *v4l;
3468 +               struct media_entity *fb;
3469 +               struct media_entity *alsa;
3470 +               struct media_entity *dvb;
3471 +       } def;
3472 +};
3473 +
3474 +#define media_dbg(media, ...) \
3475 +       (media)->debug_handler((media)->debug_priv, __VA_ARGS__)
3476 +
3477 +#endif /* __MEDIA_PRIV_H__ */
3478 diff --git a/libweston/media-ctl/mediactl.h b/libweston/media-ctl/mediactl.h
3479 new file mode 100644
3480 index 0000000..77ac182
3481 --- /dev/null
3482 +++ b/libweston/media-ctl/mediactl.h
3483 @@ -0,0 +1,423 @@
3484 +/*
3485 + * Media controller interface library
3486 + *
3487 + * Copyright (C) 2010-2014 Ideas on board SPRL
3488 + *
3489 + * Contact: Laurent Pinchart <laurent.pinchart@ideasonboard.com>
3490 + *
3491 + * This program is free software; you can redistribute it and/or modify
3492 + * it under the terms of the GNU Lesser General Public License as published
3493 + * by the Free Software Foundation; either version 2.1 of the License, or
3494 + * (at your option) any later version.
3495 + *
3496 + * This program is distributed in the hope that it will be useful,
3497 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
3498 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
3499 + * GNU Lesser General Public License for more details.
3500 + *
3501 + * You should have received a copy of the GNU Lesser General Public License
3502 + * along with this program. If not, see <http://www.gnu.org/licenses/>.
3503 + */
3504 +
3505 +#ifndef __MEDIA_H__
3506 +#define __MEDIA_H__
3507 +
3508 +#include <linux/media.h>
3509 +
3510 +struct media_link {
3511 +       struct media_pad *source;
3512 +       struct media_pad *sink;
3513 +       struct media_link *twin;
3514 +       __u32 flags;
3515 +       __u32 padding[3];
3516 +};
3517 +
3518 +struct media_pad {
3519 +       struct media_entity *entity;
3520 +       __u32 index;
3521 +       __u32 flags;
3522 +       __u32 padding[3];
3523 +};
3524 +
3525 +struct media_device;
3526 +struct media_entity;
3527 +
3528 +/**
3529 + * @brief Create a new media device.
3530 + * @param devnode - device node path.
3531 + *
3532 + * Create a media device instance for the given device node and return it. The
3533 + * device node is not accessed by this function, device node access errors will
3534 + * not be caught and reported here. The media device needs to be enumerated
3535 + * before it can be accessed, see media_device_enumerate().
3536 + *
3537 + * Media devices are reference-counted, see media_device_ref() and
3538 + * media_device_unref() for more information.
3539 + *
3540 + * @return A pointer to the new media device or NULL if memory cannot be
3541 + * allocated.
3542 + */
3543 +struct media_device *media_device_new(const char *devnode);
3544 +
3545 +/**
3546 + * @brief Create a new emulated media device.
3547 + * @param info - device information.
3548 + *
3549 + * Emulated media devices are userspace-only objects not backed by a kernel
3550 + * media device. They are created for ALSA and V4L2 devices that are not
3551 + * associated with a media controller device.
3552 + *
3553 + * Only device query functions are available for media devices. Enumerating or
3554 + * setting up links is invalid.
3555 + *
3556 + * @return A pointer to the new media device or NULL if memory cannot be
3557 + * allocated.
3558 + */
3559 +struct media_device *media_device_new_emulated(struct media_device_info *info);
3560 +
3561 +/**
3562 + * @brief Take a reference to the device.
3563 + * @param media - device instance.
3564 + *
3565 + * Media devices are reference-counted. Taking a reference to a device prevents
3566 + * it from being freed until all references are released. The reference count is
3567 + * initialized to 1 when the device is created.
3568 + *
3569 + * @return A pointer to @a media.
3570 + */
3571 +struct media_device *media_device_ref(struct media_device *media);
3572 +
3573 +/**
3574 + * @brief Release a reference to the device.
3575 + * @param media - device instance.
3576 + *
3577 + * Release a reference to the media device. When the reference count reaches 0
3578 + * this function frees the device.
3579 + */
3580 +void media_device_unref(struct media_device *media);
3581 +
3582 +/**
3583 + * @brief Add an entity to an existing media device
3584 + * @param media - device instance.
3585 + * @param desc - description of the entity to be added
3586 + * @param devnode - device node corresponding to the entity
3587 + *
3588 + * Entities are usually created and added to media devices automatically when
3589 + * the media device is enumerated through the media controller API. However,
3590 + * when an emulated media device (thus not backed with a kernel-side media
3591 + * controller device) is created, entities need to be manually added.
3592 + *
3593 + * Entities can also be manually added to a successfully enumerated media device
3594 + * to group several functions provided by separate kernel devices. The most
3595 + * common use case is to group the audio and video functions of a USB webcam in
3596 + * a single media device. Those functions are exposed through separate USB
3597 + * interfaces and handled through unrelated kernel drivers, they must thus be
3598 + * manually added to the same media device.
3599 + *
3600 + * This function adds a new entity to the given media device and initializes it
3601 + * from the given entity description and device node name. Only the following
3602 + * fields of the description are copied over to the new entity:
3603 + *
3604 + * - type
3605 + * - flags (MEDIA_ENT_FL_DEFAULT only)
3606 + * - name
3607 + * - v4l, fb, alsa or dvb (depending on the device type)
3608 + *
3609 + * All other fields of the newly created entity id are initialized to 0,
3610 + * including the entity ID.
3611 + *
3612 + * @return Zero on success or -ENOMEM if memory cannot be allocated.
3613 + */
3614 +int media_device_add_entity(struct media_device *media,
3615 +                           const struct media_entity_desc *desc,
3616 +                           const char *devnode);
3617 +
3618 +/**
3619 + * @brief Set a handler for debug messages.
3620 + * @param media - device instance.
3621 + * @param debug_handler - debug message handler
3622 + * @param debug_priv - first argument to debug message handler
3623 + *
3624 + * Set a handler for debug messages that will be called whenever
3625 + * debugging information is to be printed. The handler expects an
3626 + * fprintf-like function.
3627 + */
3628 +void media_debug_set_handler(
3629 +       struct media_device *media, void (*debug_handler)(void *, ...),
3630 +       void *debug_priv);
3631 +
3632 +/**
3633 + * @brief Enumerate the device topology
3634 + * @param media - device instance.
3635 + *
3636 + * Enumerate the media device entities, pads and links. Calling this function is
3637 + * mandatory before accessing the media device contents.
3638 + *
3639 + * @return Zero on success or a negative error code on failure.
3640 + */
3641 +int media_device_enumerate(struct media_device *media);
3642 +
3643 +/**
3644 + * @brief Locate the pad at the other end of a link.
3645 + * @param pad - sink pad at one end of the link.
3646 + *
3647 + * Locate the source pad connected to @a pad through an enabled link. As only one
3648 + * link connected to a sink pad can be enabled at a time, the connected source
3649 + * pad is guaranteed to be unique.
3650 + *
3651 + * @return A pointer to the connected source pad, or NULL if all links connected
3652 + * to @a pad are disabled. Return NULL also if @a pad is not a sink pad.
3653 + */
3654 +struct media_pad *media_entity_remote_source(struct media_pad *pad);
3655 +
3656 +/**
3657 + * @brief Get information about a media entity
3658 + * @param entity - media entity.
3659 + *
3660 + * The information structure is owned by the media entity object and will be
3661 + * freed when the object is destroyed.
3662 + *
3663 + * @return A pointer to the media entity information
3664 + */
3665 +const struct media_entity_desc *media_entity_get_info(struct media_entity *entity);
3666 +
3667 +/**
3668 + * @brief Get an entity pad
3669 + * @param entity - media entity.
3670 + * @param index - pad index.
3671 + *
3672 + * This function returns a pointer to the pad object identified by its index
3673 + * for the given entity. If the pad index is out of bounds it will return NULL.
3674 + *
3675 + * @return A pointer to the pad
3676 + */
3677 +const struct media_pad *media_entity_get_pad(struct media_entity *entity,
3678 +                                            unsigned int index);
3679 +
3680 +/**
3681 + * @brief Get the number of links
3682 + * @param entity - media entity.
3683 + *
3684 + * This function returns the total number of links that originate from or arrive
3685 + * at the the media entity.
3686 + *
3687 + * @return The number of links for the entity
3688 + */
3689 +unsigned int media_entity_get_links_count(struct media_entity *entity);
3690 +
3691 +/**
3692 + * @brief Get an entity link
3693 + * @param entity - media entity.
3694 + * @param index - link index.
3695 + *
3696 + * This function returns a pointer to the link object identified by its index
3697 + * for the given entity. If the link index is out of bounds it will return NULL.
3698 + *
3699 + * @return A pointer to the link
3700 + */
3701 +const struct media_link *media_entity_get_link(struct media_entity *entity,
3702 +                                              unsigned int index);
3703 +
3704 +/**
3705 + * @brief Get the device node name for an entity
3706 + * @param entity - media entity.
3707 + *
3708 + * This function returns the full path and name to the device node corresponding
3709 + * to the given entity.
3710 + *
3711 + * @return A pointer to the device node name or NULL if the entity has no
3712 + * associated device node
3713 + */
3714 +const char *media_entity_get_devname(struct media_entity *entity);
3715 +
3716 +/**
3717 + * @brief Get the type of an entity.
3718 + * @param entity - the entity.
3719 + *
3720 + * @return The type of @a entity.
3721 + */
3722 +static inline unsigned int media_entity_type(struct media_entity *entity)
3723 +{
3724 +       return media_entity_get_info(entity)->type & MEDIA_ENT_TYPE_MASK;
3725 +}
3726 +
3727 +/**
3728 + * @brief Find an entity by its name.
3729 + * @param media - media device.
3730 + * @param name - entity name.
3731 + * @param length - size of @a name.
3732 + *
3733 + * Search for an entity with a name equal to @a name.
3734 + *
3735 + * @return A pointer to the entity if found, or NULL otherwise.
3736 + */
3737 +struct media_entity *media_get_entity_by_name(struct media_device *media,
3738 +       const char *name, size_t length);
3739 +
3740 +/**
3741 + * @brief Find an entity by its ID.
3742 + * @param media - media device.
3743 + * @param id - entity ID.
3744 + *
3745 + * This function searches for an entity based on its ID using an exact match or
3746 + * next ID method based on the given @a id. If @a id is ORed with
3747 + * MEDIA_ENT_ID_FLAG_NEXT, the function will return the entity with the smallest
3748 + * ID larger than @a id. Otherwise it will return the entity with an ID equal to
3749 + * @a id.
3750 + *
3751 + * @return A pointer to the entity if found, or NULL otherwise.
3752 + */
3753 +struct media_entity *media_get_entity_by_id(struct media_device *media,
3754 +       __u32 id);
3755 +
3756 +/**
3757 + * @brief Get the number of entities
3758 + * @param media - media device.
3759 + *
3760 + * This function returns the total number of entities in the media device. If
3761 + * entities haven't been enumerated yet it will return 0.
3762 + *
3763 + * @return The number of entities in the media device
3764 + */
3765 +unsigned int media_get_entities_count(struct media_device *media);
3766 +
3767 +/**
3768 + * @brief Get the entities
3769 + * @param media - media device.
3770 + *
3771 + * This function returns a pointer to the array of entities for the media
3772 + * device. If entities haven't been enumerated yet it will return NULL.
3773 + *
3774 + * The array of entities is owned by the media device object and will be freed
3775 + * when the media object is destroyed.
3776 + *
3777 + * @return A pointer to an array of entities
3778 + */
3779 +struct media_entity *media_get_entity(struct media_device *media, unsigned int index);
3780 +
3781 +/**
3782 + * @brief Get the default entity for a given type
3783 + * @param media - media device.
3784 + * @param type - entity type.
3785 + *
3786 + * This function returns the default entity of the requested type. @a type must
3787 + * be one of
3788 + *
3789 + *     MEDIA_ENT_T_DEVNODE_V4L
3790 + *     MEDIA_ENT_T_DEVNODE_FB
3791 + *     MEDIA_ENT_T_DEVNODE_ALSA
3792 + *     MEDIA_ENT_T_DEVNODE_DVB
3793 + *
3794 + * @return A pointer to the default entity for the type if it exists, or NULL
3795 + * otherwise.
3796 + */
3797 +struct media_entity *media_get_default_entity(struct media_device *media,
3798 +                                             unsigned int type);
3799 +
3800 +/**
3801 + * @brief Get the media device information
3802 + * @param media - media device.
3803 + *
3804 + * The information structure is owned by the media device object and will be freed
3805 + * when the media object is destroyed.
3806 + *
3807 + * @return A pointer to the media device information
3808 + */
3809 +const struct media_device_info *media_get_info(struct media_device *media);
3810 +
3811 +/**
3812 + * @brief Get the media device node name
3813 + * @param media - media device.
3814 + *
3815 + * The device node name string is owned by the media device object and will be
3816 + * freed when the media object is destroyed.
3817 + *
3818 + * @return A pointer to the media device node name
3819 + */
3820 +const char *media_get_devnode(struct media_device *media);
3821 +
3822 +/**
3823 + * @brief Configure a link.
3824 + * @param media - media device.
3825 + * @param source - source pad at the link origin.
3826 + * @param sink - sink pad at the link target.
3827 + * @param flags - configuration flags.
3828 + *
3829 + * Locate the link between @a source and @a sink, and configure it by applying
3830 + * the new @a flags.
3831 + *
3832 + * Only the MEDIA_LINK_FLAG_ENABLED flag is writable.
3833 + *
3834 + * @return 0 on success, -1 on failure:
3835 + *        -ENOENT: link not found
3836 + *        - other error codes returned by MEDIA_IOC_SETUP_LINK
3837 + */
3838 +int media_setup_link(struct media_device *media,
3839 +       struct media_pad *source, struct media_pad *sink,
3840 +       __u32 flags);
3841 +
3842 +/**
3843 + * @brief Reset all links to the disabled state.
3844 + * @param media - media device.
3845 + *
3846 + * Disable all links in the media device. This function is usually used after
3847 + * opening a media device to reset all links to a known state.
3848 + *
3849 + * @return 0 on success, or a negative error code on failure.
3850 + */
3851 +int media_reset_links(struct media_device *media);
3852 +
3853 +/**
3854 + * @brief Parse string to a pad on the media device.
3855 + * @param media - media device.
3856 + * @param p - input string
3857 + * @param endp - pointer to string where parsing ended
3858 + *
3859 + * Parse NULL terminated string describing a pad and return its struct
3860 + * media_pad instance.
3861 + *
3862 + * @return Pointer to struct media_pad on success, NULL on failure.
3863 + */
3864 +struct media_pad *media_parse_pad(struct media_device *media,
3865 +                                 const char *p, char **endp);
3866 +
3867 +/**
3868 + * @brief Parse string to a link on the media device.
3869 + * @param media - media device.
3870 + * @param p - input string
3871 + * @param endp - pointer to p where parsing ended
3872 + *
3873 + * Parse NULL terminated string p describing a link and return its struct
3874 + * media_link instance.
3875 + *
3876 + * @return Pointer to struct media_link on success, NULL on failure.
3877 + */
3878 +struct media_link *media_parse_link(struct media_device *media,
3879 +                                   const char *p, char **endp);
3880 +
3881 +/**
3882 + * @brief Parse string to a link on the media device and set it up.
3883 + * @param media - media device.
3884 + * @param p - input string
3885 + *
3886 + * Parse NULL terminated string p describing a link and its configuration
3887 + * and configure the link.
3888 + *
3889 + * @return 0 on success, or a negative error code on failure.
3890 + */
3891 +int media_parse_setup_link(struct media_device *media,
3892 +                          const char *p, char **endp);
3893 +
3894 +/**
3895 + * @brief Parse string to link(s) on the media device and set it up.
3896 + * @param media - media device.
3897 + * @param p - input string
3898 + *
3899 + * Parse NULL terminated string p describing link(s) separated by
3900 + * commas (,) and configure the link(s).
3901 + *
3902 + * @return 0 on success, or a negative error code on failure.
3903 + */
3904 +int media_parse_setup_links(struct media_device *media, const char *p);
3905 +
3906 +#endif
3907 diff --git a/libweston/media-ctl/tools.h b/libweston/media-ctl/tools.h
3908 new file mode 100644
3909 index 0000000..815534c
3910 --- /dev/null
3911 +++ b/libweston/media-ctl/tools.h
3912 @@ -0,0 +1,32 @@
3913 +/*
3914 + * Media controller test application
3915 + *
3916 + * Copyright (C) 2010-2014 Ideas on board SPRL
3917 + *
3918 + * Contact: Laurent Pinchart <laurent.pinchart@ideasonboard.com>
3919 + *
3920 + * This program is free software; you can redistribute it and/or modify
3921 + * it under the terms of the GNU Lesser General Public License as published
3922 + * by the Free Software Foundation; either version 2.1 of the License, or
3923 + * (at your option) any later version.
3924 + *
3925 + * This program is distributed in the hope that it will be useful,
3926 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
3927 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
3928 + * GNU Lesser General Public License for more details.
3929 + *
3930 + * You should have received a copy of the GNU Lesser General Public License
3931 + * along with this program. If not, see <http://www.gnu.org/licenses/>.
3932 + */
3933 +
3934 +#ifndef __TOOLS_H__
3935 +#define __TOOLS_H__
3936 +
3937 +#define ARRAY_SIZE(array)      (sizeof(array) / sizeof((array)[0]))
3938 +#define FIELD_SIZEOF(t, f)     (sizeof(((t*)0)->f))
3939 +
3940 +void media_print_streampos(struct media_device *media, const char *p,
3941 +                          const char *end);
3942 +
3943 +#endif /* __TOOLS_H__ */
3944 +
3945 diff --git a/libweston/media-ctl/v4l2subdev.h b/libweston/media-ctl/v4l2subdev.h
3946 new file mode 100644
3947 index 0000000..1cb53ff
3948 --- /dev/null
3949 +++ b/libweston/media-ctl/v4l2subdev.h
3950 @@ -0,0 +1,258 @@
3951 +/*
3952 + * V4L2 subdev interface library
3953 + *
3954 + * Copyright (C) 2010-2014 Ideas on board SPRL
3955 + *
3956 + * Contact: Laurent Pinchart <laurent.pinchart@ideasonboard.com>
3957 + *
3958 + * This program is free software; you can redistribute it and/or modify
3959 + * it under the terms of the GNU Lesser General Public License as published
3960 + * by the Free Software Foundation; either version 2.1 of the License, or
3961 + * (at your option) any later version.
3962 + *
3963 + * This program is distributed in the hope that it will be useful,
3964 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
3965 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
3966 + * GNU Lesser General Public License for more details.
3967 + *
3968 + * You should have received a copy of the GNU Lesser General Public License
3969 + * along with this program. If not, see <http://www.gnu.org/licenses/>.
3970 + */
3971 +
3972 +#ifndef __SUBDEV_H__
3973 +#define __SUBDEV_H__
3974 +
3975 +#include <linux/v4l2-subdev.h>
3976 +
3977 +struct media_entity;
3978 +
3979 +/**
3980 + * @brief Open a sub-device.
3981 + * @param entity - sub-device media entity.
3982 + *
3983 + * Open the V4L2 subdev device node associated with @a entity. The file
3984 + * descriptor is stored in the media_entity structure.
3985 + *
3986 + * @return 0 on success, or a negative error code on failure.
3987 + */
3988 +int v4l2_subdev_open(struct media_entity *entity);
3989 +
3990 +/**
3991 + * @brief Close a sub-device.
3992 + * @param entity - sub-device media entity.
3993 + *
3994 + * Close the V4L2 subdev device node associated with the @a entity and opened by
3995 + * a previous call to v4l2_subdev_open() (either explicit or implicit).
3996 + */
3997 +void v4l2_subdev_close(struct media_entity *entity);
3998 +
3999 +/**
4000 + * @brief Retrieve the format on a pad.
4001 + * @param entity - subdev-device media entity.
4002 + * @param format - format to be filled.
4003 + * @param pad - pad number.
4004 + * @param which - identifier of the format to get.
4005 + *
4006 + * Retrieve the current format on the @a entity @a pad and store it in the
4007 + * @a format structure.
4008 + *
4009 + * @a which is set to V4L2_SUBDEV_FORMAT_TRY to retrieve the try format stored
4010 + * in the file handle, of V4L2_SUBDEV_FORMAT_ACTIVE to retrieve the current
4011 + * active format.
4012 + *
4013 + * @return 0 on success, or a negative error code on failure.
4014 + */
4015 +int v4l2_subdev_get_format(struct media_entity *entity,
4016 +       struct v4l2_mbus_framefmt *format, unsigned int pad,
4017 +       enum v4l2_subdev_format_whence which);
4018 +
4019 +/**
4020 + * @brief Set the format on a pad.
4021 + * @param entity - subdev-device media entity.
4022 + * @param format - format.
4023 + * @param pad - pad number.
4024 + * @param which - identifier of the format to set.
4025 + *
4026 + * Set the format on the @a entity @a pad to @a format. The driver is allowed to
4027 + * modify the requested format, in which case @a format is updated with the
4028 + * modifications.
4029 + *
4030 + * @a which is set to V4L2_SUBDEV_FORMAT_TRY to set the try format stored in the
4031 + * file handle, of V4L2_SUBDEV_FORMAT_ACTIVE to configure the device with an
4032 + * active format.
4033 + *
4034 + * @return 0 on success, or a negative error code on failure.
4035 + */
4036 +int v4l2_subdev_set_format(struct media_entity *entity,
4037 +       struct v4l2_mbus_framefmt *format, unsigned int pad,
4038 +       enum v4l2_subdev_format_whence which);
4039 +
4040 +/**
4041 + * @brief Retrieve a selection rectangle on a pad.
4042 + * @param entity - subdev-device media entity.
4043 + * @param r - rectangle to be filled.
4044 + * @param pad - pad number.
4045 + * @param target - selection target
4046 + * @param which - identifier of the format to get.
4047 + *
4048 + * Retrieve the @a target selection rectangle on the @a entity @a pad
4049 + * and store it in the @a rect structure.
4050 + *
4051 + * @a which is set to V4L2_SUBDEV_FORMAT_TRY to retrieve the try
4052 + * selection rectangle stored in the file handle, or
4053 + * V4L2_SUBDEV_FORMAT_ACTIVE to retrieve the current active selection
4054 + * rectangle.
4055 + *
4056 + * @return 0 on success, or a negative error code on failure.
4057 + */
4058 +int v4l2_subdev_get_selection(struct media_entity *entity,
4059 +       struct v4l2_rect *rect, unsigned int pad, unsigned int target,
4060 +       enum v4l2_subdev_format_whence which);
4061 +
4062 +/**
4063 + * @brief Set a selection rectangle on a pad.
4064 + * @param entity - subdev-device media entity.
4065 + * @param rect - crop rectangle.
4066 + * @param pad - pad number.
4067 + * @param target - selection target
4068 + * @param which - identifier of the format to set.
4069 + *
4070 + * Set the @a target selection rectangle on the @a entity @a pad to @a
4071 + * rect. The driver is allowed to modify the requested rectangle, in
4072 + * which case @a rect is updated with the modifications.
4073 + *
4074 + * @a which is set to V4L2_SUBDEV_FORMAT_TRY to set the try crop rectangle
4075 + * stored in the file handle, of V4L2_SUBDEV_FORMAT_ACTIVE to configure the
4076 + * device with an active crop rectangle.
4077 + *
4078 + * @return 0 on success, or a negative error code on failure.
4079 + */
4080 +int v4l2_subdev_set_selection(struct media_entity *entity,
4081 +       struct v4l2_rect *rect, unsigned int pad, unsigned int target,
4082 +       enum v4l2_subdev_format_whence which);
4083 +
4084 +/**
4085 + * @brief Query the digital video capabilities of a pad.
4086 + * @param entity - subdev-device media entity.
4087 + * @param cap - capabilities to be filled.
4088 + *
4089 + * Retrieve the digital video capabilities of the @a entity pad specified by
4090 + * @a cap.pad and store it in the @a cap structure.
4091 + *
4092 + * @return 0 on success, or a negative error code on failure.
4093 + */
4094 +int v4l2_subdev_get_dv_timings_caps(struct media_entity *entity,
4095 +       struct v4l2_dv_timings_cap *caps);
4096 +
4097 +/**
4098 + * @brief Query the digital video timings of a sub-device
4099 + * @param entity - subdev-device media entity.
4100 + * @param timings timings to be filled.
4101 + *
4102 + * Retrieve the detected digital video timings for the currently selected input
4103 + * of @a entity and store them in the @a timings structure.
4104 + *
4105 + * @return 0 on success, or a negative error code on failure.
4106 + */
4107 +int v4l2_subdev_query_dv_timings(struct media_entity *entity,
4108 +       struct v4l2_dv_timings *timings);
4109 +
4110 +/**
4111 + * @brief Get the current digital video timings of a sub-device
4112 + * @param entity - subdev-device media entity.
4113 + * @param timings timings to be filled.
4114 + *
4115 + * Retrieve the current digital video timings for the currently selected input
4116 + * of @a entity and store them in the @a timings structure.
4117 + *
4118 + * @return 0 on success, or a negative error code on failure.
4119 + */
4120 +int v4l2_subdev_get_dv_timings(struct media_entity *entity,
4121 +       struct v4l2_dv_timings *timings);
4122 +
4123 +/**
4124 + * @brief Set the digital video timings of a sub-device
4125 + * @param entity - subdev-device media entity.
4126 + * @param timings timings to be set.
4127 + *
4128 + * Set the digital video timings of @a entity to @a timings. The driver is
4129 + * allowed to modify the requested format, in which case @a timings is updated
4130 + * with the modifications.
4131 + *
4132 + * @return 0 on success, or a negative error code on failure.
4133 + */
4134 +int v4l2_subdev_set_dv_timings(struct media_entity *entity,
4135 +       struct v4l2_dv_timings *timings);
4136 +
4137 +/**
4138 + * @brief Retrieve the frame interval on a sub-device.
4139 + * @param entity - subdev-device media entity.
4140 + * @param interval - frame interval to be filled.
4141 + *
4142 + * Retrieve the current frame interval on subdev @a entity and store it in the
4143 + * @a interval structure.
4144 + *
4145 + * Frame interval retrieving is usually supported only on devices at the
4146 + * beginning of video pipelines, such as sensors.
4147 + *
4148 + * @return 0 on success, or a negative error code on failure.
4149 + */
4150 +
4151 +int v4l2_subdev_get_frame_interval(struct media_entity *entity,
4152 +       struct v4l2_fract *interval);
4153 +
4154 +/**
4155 + * @brief Set the frame interval on a sub-device.
4156 + * @param entity - subdev-device media entity.
4157 + * @param interval - frame interval.
4158 + *
4159 + * Set the frame interval on subdev @a entity to @a interval. The driver is
4160 + * allowed to modify the requested frame interval, in which case @a interval is
4161 + * updated with the modifications.
4162 + *
4163 + * Frame interval setting is usually supported only on devices at the beginning
4164 + * of video pipelines, such as sensors.
4165 + *
4166 + * @return 0 on success, or a negative error code on failure.
4167 + */
4168 +int v4l2_subdev_set_frame_interval(struct media_entity *entity,
4169 +       struct v4l2_fract *interval);
4170 +
4171 +/**
4172 + * @brief Parse a string and apply format, crop and frame interval settings.
4173 + * @param media - media device.
4174 + * @param p - input string
4175 + * @param endp - pointer to string p where parsing ended (return)
4176 + *
4177 + * Parse string @a p and apply format, crop and frame interval settings to a
4178 + * subdev pad specified in @a p. @a endp will be written a pointer where
4179 + * parsing of @a p ended.
4180 + *
4181 + * Format strings are separeted by commas (,).
4182 + *
4183 + * @return 0 on success, or a negative error code on failure.
4184 + */
4185 +int v4l2_subdev_parse_setup_formats(struct media_device *media, const char *p);
4186 +
4187 +/**
4188 + * @brief Convert media bus pixel code to string.
4189 + * @param code - input string
4190 + *
4191 + * Convert media bus pixel code @a code to a human-readable string.
4192 + *
4193 + * @return A pointer to a string on success, NULL on failure.
4194 + */
4195 +const char *v4l2_subdev_pixelcode_to_string(enum v4l2_mbus_pixelcode code);
4196 +
4197 +/**
4198 + * @brief Parse string to media bus pixel code.
4199 + * @param string - input string
4200 + * @param lenght - length of the string
4201 + *
4202 + * Parse human readable string @a string to an media bus pixel code.
4203 + *
4204 + * @return media bus pixelcode on success, -1 on failure.
4205 + */
4206 +enum v4l2_mbus_pixelcode v4l2_subdev_string_to_pixelcode(const char *string,
4207 +                                                        unsigned int length);
4208 +#endif
4209 -- 
4210 2.9.2
4211