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