v4l2: Add initial support for alignment and cropping
[platform/upstream/gst-plugins-good.git] / sys / v4l2 / gstv4l2bufferpool.c
1 /* GStreamer
2  *
3  * Copyright (C) 2001-2002 Ronald Bultje <rbultje@ronald.bitfreak.net>
4  *               2006 Edgard Lima <edgard.lima@indt.org.br>
5  *               2009 Texas Instruments, Inc - http://www.ti.com/
6  *
7  * gstv4l2bufferpool.c V4L2 buffer pool class
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public
20  * License along with this library; if not, write to the
21  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
22  * Boston, MA 02110-1301, USA.
23  */
24
25 #ifdef HAVE_CONFIG_H
26 #  include <config.h>
27 #endif
28
29 #ifndef _GNU_SOURCE
30 # define _GNU_SOURCE            /* O_CLOEXEC */
31 #endif
32 #include <fcntl.h>
33
34 #include <sys/mman.h>
35 #include <string.h>
36 #include <unistd.h>
37
38 #include "gst/video/video.h"
39 #include "gst/video/gstvideometa.h"
40 #include "gst/video/gstvideopool.h"
41 #include "gst/allocators/gstdmabuf.h"
42
43 #include <gstv4l2bufferpool.h>
44
45 #include "v4l2_calls.h"
46 #include "gst/gst-i18n-plugin.h"
47 #include <gst/glib-compat-private.h>
48
49 GST_DEBUG_CATEGORY_EXTERN (v4l2_debug);
50 #define GST_CAT_DEFAULT v4l2_debug
51
52 /*
53  * GstV4l2Buffer:
54  */
55 GType
56 gst_v4l2_meta_api_get_type (void)
57 {
58   static volatile GType type;
59   static const gchar *tags[] =
60       { GST_META_TAG_VIDEO_STR, GST_META_TAG_MEMORY_STR, NULL };
61
62   if (g_once_init_enter (&type)) {
63     GType _type = gst_meta_api_type_register ("GstV4l2MetaAPI", tags);
64     g_once_init_leave (&type, _type);
65   }
66   return type;
67 }
68
69 const GstMetaInfo *
70 gst_v4l2_meta_get_info (void)
71 {
72   static const GstMetaInfo *meta_info = NULL;
73
74   if (g_once_init_enter (&meta_info)) {
75     const GstMetaInfo *meta =
76         gst_meta_register (gst_v4l2_meta_api_get_type (), "GstV4l2Meta",
77         sizeof (GstV4l2Meta), (GstMetaInitFunction) NULL,
78         (GstMetaFreeFunction) NULL, (GstMetaTransformFunction) NULL);
79     g_once_init_leave (&meta_info, meta);
80   }
81   return meta_info;
82 }
83
84 /*
85  * GstV4l2BufferPool:
86  */
87 #define gst_v4l2_buffer_pool_parent_class parent_class
88 G_DEFINE_TYPE (GstV4l2BufferPool, gst_v4l2_buffer_pool, GST_TYPE_BUFFER_POOL);
89
90 static void gst_v4l2_buffer_pool_release_buffer (GstBufferPool * bpool,
91     GstBuffer * buffer);
92
93 static void
94 gst_v4l2_buffer_pool_free_buffer (GstBufferPool * bpool, GstBuffer * buffer)
95 {
96   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
97   GstV4l2Object *obj;
98
99   obj = pool->obj;
100
101   switch (obj->mode) {
102     case GST_V4L2_IO_RW:
103     case GST_V4L2_IO_DMABUF:
104       break;
105     case GST_V4L2_IO_MMAP:
106     {
107       GstV4l2Meta *meta;
108       gint index;
109       gint i = 0;
110
111       meta = GST_V4L2_META_GET (buffer);
112       g_assert (meta != NULL);
113
114       index = meta->vbuffer.index;
115
116       for (i = 0; i < meta->n_planes; i++) {
117         GST_LOG_OBJECT (pool,
118             "unmap multiplanar buffer %p idx %d (data %p, len %u, plane %u)",
119             buffer, index, meta->mem[i], meta->vplanes[i].length, i);
120
121         v4l2_munmap (meta->mem[i], meta->vplanes[i].length);
122       }
123
124       pool->buffers[index] = NULL;
125       break;
126     }
127     case GST_V4L2_IO_USERPTR:
128     default:
129       g_assert_not_reached ();
130       break;
131   }
132   gst_buffer_unref (buffer);
133 }
134
135 static GstFlowReturn
136 gst_v4l2_buffer_pool_alloc_buffer (GstBufferPool * bpool, GstBuffer ** buffer,
137     GstBufferPoolAcquireParams * params)
138 {
139   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
140   GstBuffer *newbuf;
141   GstV4l2Meta *meta;
142   GstV4l2Object *obj;
143   GstVideoInfo *info;
144   GstVideoAlignment *align;
145   guint index;
146   gint i;
147
148   obj = pool->obj;
149   info = &obj->info;
150   align = &obj->align;
151
152   switch (obj->mode) {
153     case GST_V4L2_IO_RW:
154     {
155       newbuf =
156           gst_buffer_new_allocate (pool->allocator, pool->size, &pool->params);
157       break;
158     }
159     case GST_V4L2_IO_MMAP:
160     case GST_V4L2_IO_DMABUF:
161     {
162       if (pool->num_allocated == pool->num_buffers) {
163         struct v4l2_create_buffers create_bufs;
164
165         memset (&create_bufs, 0, sizeof (struct v4l2_create_buffers));
166         create_bufs.count = 1;
167         create_bufs.memory = V4L2_MEMORY_MMAP;
168         create_bufs.format.type = obj->type;
169
170         if (v4l2_ioctl (pool->video_fd, VIDIOC_G_FMT, &create_bufs.format) < 0)
171           goto g_fmt_failed;
172
173         if (v4l2_ioctl (pool->video_fd, VIDIOC_CREATE_BUFS, &create_bufs) < 0)
174           goto create_bufs_failed;
175
176         GST_LOG_OBJECT (pool, "created buffer with index: %u",
177             create_bufs.index);
178         pool->num_buffers++;
179         pool->buffers = g_renew (GstBuffer *, pool->buffers, pool->num_buffers);
180         pool->buffers[pool->num_buffers - 1] = NULL;
181       }
182
183       newbuf = gst_buffer_new ();
184       meta = GST_V4L2_META_ADD (newbuf);
185
186       index = pool->num_allocated;
187
188       GST_LOG_OBJECT (pool, "creating buffer %u, %p", index, newbuf);
189
190       /* prepare the buffer */
191       memset (&meta->vbuffer, 0x0, sizeof (struct v4l2_buffer));
192       meta->vbuffer.index = index;
193       meta->vbuffer.type = obj->type;
194       meta->vbuffer.memory = V4L2_MEMORY_MMAP;
195
196       /* main information */
197       meta->n_planes = obj->n_v4l2_planes;
198
199       /* prepare the planes of the buffer */
200       if (V4L2_TYPE_IS_MULTIPLANAR (obj->type)) {
201         /* length is the number of elements in the
202          * vplanes array */
203         meta->vbuffer.length = obj->n_v4l2_planes;
204         meta->vbuffer.m.planes = meta->vplanes;
205       }
206
207       /* the buffer is prepared, now fill in it with meaningful values */
208       if (v4l2_ioctl (pool->video_fd, VIDIOC_QUERYBUF, &meta->vbuffer) < 0)
209         goto querybuf_failed;
210
211       /* in non MPLANE mode we emulate one plane in order to
212        * factorize the code */
213       if (!V4L2_TYPE_IS_MULTIPLANAR (obj->type)) {
214         /* here meta->n_planes == 1 */
215         meta->vplanes[0].length = meta->vbuffer.length;
216         meta->vplanes[0].bytesused = meta->vbuffer.bytesused;
217         meta->vplanes[0].m.mem_offset = meta->vbuffer.m.offset;
218         meta->vplanes[0].data_offset = 0;
219       }
220
221       GST_LOG_OBJECT (pool, "  index:     %u", meta->vbuffer.index);
222       GST_LOG_OBJECT (pool, "  type:      %d", meta->vbuffer.type);
223       GST_LOG_OBJECT (pool, "  flags:     %08x", meta->vbuffer.flags);
224       GST_LOG_OBJECT (pool, "  field:     %d", meta->vbuffer.field);
225       GST_LOG_OBJECT (pool, "  memory:    %d", meta->vbuffer.memory);
226       GST_LOG_OBJECT (pool, "  planes:    %d", meta->n_planes);
227
228 #ifndef GST_DISABLE_GST_DEBUG
229       if (meta->vbuffer.memory == V4L2_MEMORY_MMAP) {
230         for (i = 0; i < meta->n_planes; i++) {
231           GST_LOG_OBJECT (pool, "  bytesused: %u, plane: %u",
232               meta->vplanes[i].bytesused, i);
233           GST_LOG_OBJECT (pool, "  MMAP offset:  %u, plane: %u",
234               meta->vplanes[i].m.mem_offset, i);
235         }
236       }
237 #endif
238
239       if (obj->mode == GST_V4L2_IO_MMAP) {
240         /* append one gstmemory for each plane */
241         for (i = 0; i < meta->n_planes; i++) {
242           meta->mem[i] = v4l2_mmap (0, meta->vplanes[i].length,
243               PROT_READ | PROT_WRITE, MAP_SHARED, pool->video_fd,
244               meta->vplanes[i].m.mem_offset);
245           if (meta->mem[i] == MAP_FAILED)
246             goto mmap_failed;
247
248           GST_LOG_OBJECT (pool, "  buffer length %d, data offset %d, plane %d",
249               meta->vplanes[i].length, meta->vplanes[i].data_offset, i);
250
251           gst_buffer_append_memory (newbuf,
252               gst_memory_new_wrapped (GST_MEMORY_FLAG_NO_SHARE,
253                   meta->mem[i], meta->vplanes[i].length,
254                   meta->vplanes[i].data_offset,
255                   meta->vplanes[i].length, NULL, NULL));
256         }
257       }
258
259       if (obj->mode == GST_V4L2_IO_DMABUF) {
260         struct v4l2_exportbuffer expbuf;
261
262         memset (&expbuf, 0, sizeof (struct v4l2_exportbuffer));
263         expbuf.type = meta->vbuffer.type;
264         expbuf.index = meta->vbuffer.index;
265         expbuf.flags = O_CLOEXEC;
266
267         for (i = 0; i < meta->n_planes; i++) {
268           expbuf.plane = i;
269
270           if (v4l2_ioctl (pool->video_fd, VIDIOC_EXPBUF, &expbuf) < 0)
271             goto expbuf_failed;
272
273           gst_buffer_append_memory (newbuf,
274               gst_dmabuf_allocator_alloc (pool->allocator, expbuf.fd,
275                   meta->vplanes[i].length));
276         }
277
278         meta->vbuffer.memory = V4L2_MEMORY_DMABUF;
279
280         /* in non-MPLANE mode our meta is not automatically updated
281          * because the plane is emulated (not referenced by
282          * meta->vbuffer) */
283         if (!V4L2_TYPE_IS_MULTIPLANAR (obj->type))
284           meta->vplanes[0].m.fd = meta->vbuffer.m.fd;
285       }
286
287       /* add metadata to raw video buffers */
288       if (pool->add_videometa && info->finfo) {
289         const GstVideoFormatInfo *finfo = info->finfo;
290         gsize offset[GST_VIDEO_MAX_PLANES];
291         gint width, height, n_gst_planes, offs, i, stride[GST_VIDEO_MAX_PLANES];
292
293         width = GST_VIDEO_INFO_WIDTH (info);
294         height = GST_VIDEO_INFO_HEIGHT (info);
295
296         /* n_gst_planes is the number of planes
297          * (RGB: 1, YUY2: 1, NV12: 2, I420: 3)
298          * It's greater or equal than the number of v4l2 planes. */
299         n_gst_planes = GST_VIDEO_INFO_N_PLANES (info);
300
301         /* the basic are common between MPLANE mode and non MPLANE mode
302          * except a special case inside the loop at the end
303          */
304         offs = 0;
305         for (i = 0; i < n_gst_planes; i++) {
306           GST_DEBUG_OBJECT (pool, "adding video meta, bytesperline %d",
307               obj->bytesperline[i]);
308
309           offset[i] = offs;
310
311           if (GST_VIDEO_FORMAT_INFO_IS_TILED (finfo)) {
312             guint x_tiles, y_tiles, ws, hs, tile_height;
313
314             ws = GST_VIDEO_FORMAT_INFO_TILE_WS (finfo);
315             hs = GST_VIDEO_FORMAT_INFO_TILE_HS (finfo);
316             tile_height = 1 << hs;
317
318             x_tiles = obj->bytesperline[i] >> ws;
319             y_tiles = GST_VIDEO_FORMAT_INFO_SCALE_HEIGHT (finfo, i,
320                 GST_ROUND_UP_N (height, tile_height) >> hs);
321             stride[i] = GST_VIDEO_TILE_MAKE_STRIDE (x_tiles, y_tiles);
322           } else {
323             stride[i] = obj->bytesperline[i];
324           }
325
326           /* when using multiplanar mode and if there is more then one v4l
327            * plane for each gst plane
328            */
329           if (V4L2_TYPE_IS_MULTIPLANAR (obj->type) && meta->n_planes > 1)
330             /* non_contiguous case here so we have to make sure that gst goes to the
331              * next plane (using default gstvideometa.c::default_map).
332              * And the next plane is after length bytes of the previous one from
333              * the gst buffer point of view. */
334             offs += meta->vplanes[i].length;
335           else
336             offs += obj->bytesperline[i] *
337                 GST_VIDEO_FORMAT_INFO_SCALE_HEIGHT (finfo, i, height);
338         }
339
340         gst_buffer_add_video_meta_full (newbuf, GST_VIDEO_FRAME_FLAG_NONE,
341             GST_VIDEO_INFO_FORMAT (info), width, height, n_gst_planes,
342             offset, stride);
343       }
344
345       if (pool->add_cropmeta) {
346         GstVideoCropMeta *crop;
347         crop = gst_buffer_add_video_crop_meta (newbuf);
348         crop->x = align->padding_left;
349         crop->y = align->padding_top;
350         crop->width = info->width;
351         crop->width = info->height;
352       }
353       break;
354     }
355     case GST_V4L2_IO_USERPTR:
356     default:
357       newbuf = NULL;
358       g_assert_not_reached ();
359   }
360
361   pool->num_allocated++;
362
363   *buffer = newbuf;
364
365   return GST_FLOW_OK;
366
367   /* ERRORS */
368 g_fmt_failed:
369   {
370     gint errnosave = errno;
371
372     GST_WARNING ("Failed G_FMT: %s", g_strerror (errnosave));
373     errno = errnosave;
374     return GST_FLOW_ERROR;
375   }
376 create_bufs_failed:
377   {
378     gint errnosave = errno;
379
380     GST_WARNING ("Failed CREATE_BUFS: %s", g_strerror (errnosave));
381     errno = errnosave;
382     return GST_FLOW_ERROR;
383   }
384 querybuf_failed:
385   {
386     gint errnosave = errno;
387
388     GST_WARNING ("Failed QUERYBUF: %s", g_strerror (errnosave));
389     gst_buffer_unref (newbuf);
390     errno = errnosave;
391     return GST_FLOW_ERROR;
392   }
393 mmap_failed:
394   {
395     gint errnosave = errno;
396
397     GST_WARNING ("Failed to mmap: %s", g_strerror (errnosave));
398     gst_buffer_unref (newbuf);
399     errno = errnosave;
400     return GST_FLOW_ERROR;
401   }
402 expbuf_failed:
403   {
404     gint errnosave = errno;
405
406     GST_WARNING ("Failed EXPBUF: %s", g_strerror (errnosave));
407     gst_buffer_unref (newbuf);
408     errno = errnosave;
409     return GST_FLOW_ERROR;
410   }
411 }
412
413 static gboolean
414 gst_v4l2_buffer_pool_set_config (GstBufferPool * bpool, GstStructure * config)
415 {
416   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
417   GstV4l2Object *obj = pool->obj;
418   GstCaps *caps;
419   guint size, min_buffers, max_buffers;
420   GstAllocator *allocator;
421   GstAllocationParams params;
422
423   GST_DEBUG_OBJECT (pool, "set config");
424
425   pool->add_videometa =
426       gst_buffer_pool_config_has_option (config,
427       GST_BUFFER_POOL_OPTION_VIDEO_META);
428
429   if (!pool->add_videometa &&
430       GST_VIDEO_INFO_FORMAT (&obj->info) != GST_VIDEO_FORMAT_ENCODED) {
431     /* in non MPLANE mode, there is only one  bytesperline field */
432     gint nb_checked_planes =
433         V4L2_TYPE_IS_MULTIPLANAR (obj->type) ? GST_VIDEO_INFO_N_PLANES (&obj->
434         info) : 1;
435     gint stride = 0;
436     gint i = 0;
437     for (i = 0; i < nb_checked_planes; i++) {
438       /* we don't have video metadata, and we are dealing with raw video,
439        * see if the strides are compatible */
440       stride = GST_VIDEO_INFO_PLANE_STRIDE (&obj->info, i);
441
442       if (GST_VIDEO_FORMAT_INFO_IS_TILED (obj->info.finfo)) {
443         stride = GST_VIDEO_TILE_X_TILES (stride) <<
444             GST_VIDEO_FORMAT_INFO_TILE_WS ((obj->info.finfo));
445       }
446
447       GST_DEBUG_OBJECT (pool, "no videometadata, checking strides %d and %u",
448           stride, obj->bytesperline[i]);
449
450       if (stride != obj->bytesperline[i])
451         goto missing_video_api;
452     }
453   }
454
455   /* parse the config and keep around */
456   if (!gst_buffer_pool_config_get_params (config, &caps, &size, &min_buffers,
457           &max_buffers))
458     goto wrong_config;
459
460   /* FIXME Check alignement, and S_FMT with new size if different */
461
462   if (!gst_buffer_pool_config_get_allocator (config, &allocator, &params))
463     goto wrong_config;
464
465   GST_DEBUG_OBJECT (pool, "config %" GST_PTR_FORMAT, config);
466
467   if (obj->mode == GST_V4L2_IO_DMABUF)
468     allocator = gst_dmabuf_allocator_new ();
469   else if (allocator)
470     gst_object_ref (allocator);
471
472   if (pool->allocator)
473     gst_object_unref (pool->allocator);
474   pool->allocator = allocator;
475
476   pool->params = params;
477
478   gst_buffer_pool_config_set_params (config, caps, size, min_buffers,
479       max_buffers);
480
481   return GST_BUFFER_POOL_CLASS (parent_class)->set_config (bpool, config);
482
483   /* ERRORS */
484 missing_video_api:
485   {
486     GST_ERROR_OBJECT (pool, "missing GstMetaVideo API in config, "
487         "default stride: %d, wanted stride %u",
488         GST_VIDEO_INFO_PLANE_STRIDE (&obj->info, 0), obj->bytesperline[0]);
489     return FALSE;
490   }
491 wrong_config:
492   {
493     GST_ERROR_OBJECT (pool, "invalid config %" GST_PTR_FORMAT, config);
494     return FALSE;
495   }
496 }
497
498 static gboolean
499 start_streaming (GstV4l2BufferPool * pool)
500 {
501   GstV4l2Object *obj = pool->obj;
502
503   switch (obj->mode) {
504     case GST_V4L2_IO_RW:
505       break;
506     case GST_V4L2_IO_MMAP:
507     case GST_V4L2_IO_USERPTR:
508     case GST_V4L2_IO_DMABUF:
509       GST_DEBUG_OBJECT (pool, "STREAMON");
510       if (v4l2_ioctl (pool->video_fd, VIDIOC_STREAMON, &obj->type) < 0)
511         goto start_failed;
512       break;
513     default:
514       g_assert_not_reached ();
515       break;
516   }
517
518   pool->streaming = TRUE;
519
520   return TRUE;
521
522   /* ERRORS */
523 start_failed:
524   {
525     GST_ERROR_OBJECT (pool, "error with STREAMON %d (%s)", errno,
526         g_strerror (errno));
527     return FALSE;
528   }
529 }
530
531 static gboolean
532 gst_v4l2_buffer_pool_start (GstBufferPool * bpool)
533 {
534   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
535   GstV4l2Object *obj = pool->obj;
536   GstStructure *config;
537   GstCaps *caps;
538   guint size, num_buffers, min_buffers, max_buffers, copy_threshold;
539   struct v4l2_requestbuffers breq;
540
541   config = gst_buffer_pool_get_config (bpool);
542   if (!gst_buffer_pool_config_get_params (config, &caps, &size, &min_buffers,
543           &max_buffers))
544     goto wrong_config;
545
546   switch (obj->mode) {
547     case GST_V4L2_IO_RW:
548       /* we preallocate 1 buffer, this value also instructs the latency
549        * calculation to have 1 frame latency max */
550       num_buffers = 1;
551       copy_threshold = 0;
552       break;
553     case GST_V4L2_IO_DMABUF:
554     case GST_V4L2_IO_MMAP:
555     {
556       /* request a reasonable number of buffers when no max specified. We will
557        * copy when we run out of buffers */
558       if (max_buffers == 0)
559         num_buffers = MAX (4, min_buffers);
560       else
561         num_buffers = max_buffers;
562
563       /* first, lets request buffers, and see how many we can get: */
564       GST_DEBUG_OBJECT (pool, "starting, requesting %d MMAP buffers",
565           num_buffers);
566
567       memset (&breq, 0, sizeof (struct v4l2_requestbuffers));
568       breq.type = obj->type;
569       breq.count = num_buffers;
570       breq.memory = V4L2_MEMORY_MMAP;
571
572       if (v4l2_ioctl (pool->video_fd, VIDIOC_REQBUFS, &breq) < 0)
573         goto reqbufs_failed;
574
575       GST_LOG_OBJECT (pool, " count:  %u", breq.count);
576       GST_LOG_OBJECT (pool, " type:   %d", breq.type);
577       GST_LOG_OBJECT (pool, " memory: %d", breq.memory);
578
579       if (breq.count < GST_V4L2_MIN_BUFFERS)
580         goto no_buffers;
581
582       if (num_buffers != breq.count) {
583         GST_WARNING_OBJECT (pool, "using %u buffers instead", breq.count);
584         num_buffers = breq.count;
585       }
586       /* update min buffers with the amount of buffers we just reserved. We need
587        * to configure this value in the bufferpool so that the default start
588        * implementation calls our allocate function */
589       min_buffers = breq.count;
590
591       if (max_buffers == 0 || num_buffers < max_buffers) {
592         /* if we are asked to provide more buffers than we have allocated, start
593          * copying buffers when we only have 2 buffers left in the pool */
594         copy_threshold = 2;
595       } else {
596         /* we are certain that we have enough buffers so we don't need to
597          * copy */
598         copy_threshold = 0;
599       }
600
601       /* FIXME try to call CREATEBUFS with count 0 to check if max shall
602        * remain 0 */
603       break;
604     }
605     case GST_V4L2_IO_USERPTR:
606     default:
607       num_buffers = 0;
608       copy_threshold = 0;
609       g_assert_not_reached ();
610       break;
611   }
612
613   pool->size = size;
614   pool->num_buffers = num_buffers;
615   pool->copy_threshold = copy_threshold;
616
617   gst_buffer_pool_config_set_params (config, caps, size, min_buffers,
618       max_buffers);
619   GST_BUFFER_POOL_CLASS (parent_class)->set_config (bpool, config);
620
621   pool->obj = obj;
622   pool->buffers = g_new0 (GstBuffer *, pool->num_buffers);
623   pool->num_allocated = 0;
624
625   /* now, allocate the buffers: */
626   if (!GST_BUFFER_POOL_CLASS (parent_class)->start (bpool))
627     goto start_failed;
628
629   /* we can start capturing now, we wait for the playback case until we queued
630    * the first buffer */
631   if (!V4L2_TYPE_IS_OUTPUT (obj->type))
632     if (!start_streaming (pool))
633       goto start_failed;
634
635   gst_poll_set_flushing (obj->poll, FALSE);
636
637   return TRUE;
638
639   /* ERRORS */
640 wrong_config:
641   {
642     GST_ERROR_OBJECT (pool, "invalid config %" GST_PTR_FORMAT, config);
643     return FALSE;
644   }
645 reqbufs_failed:
646   {
647     GST_ERROR_OBJECT (pool,
648         "error requesting %d buffers: %s", num_buffers, g_strerror (errno));
649     return FALSE;
650   }
651 no_buffers:
652   {
653     GST_ERROR_OBJECT (pool,
654         "we received %d from device '%s', we want at least %d",
655         breq.count, obj->videodev, GST_V4L2_MIN_BUFFERS);
656     return FALSE;
657   }
658 start_failed:
659   {
660     GST_ERROR_OBJECT (pool, "failed to start streaming");
661     return FALSE;
662   }
663 }
664
665 static void
666 gst_v4l2_buffer_pool_free_buffers (GstV4l2BufferPool * pool)
667 {
668   if (pool->num_buffers > 0) {
669     struct v4l2_requestbuffers breq;
670     memset (&breq, 0, sizeof (struct v4l2_requestbuffers));
671     breq.type = pool->obj->type;
672     breq.count = 0;
673     breq.memory = V4L2_MEMORY_MMAP;
674     if (v4l2_ioctl (pool->video_fd, VIDIOC_REQBUFS, &breq) < 0) {
675       GST_ERROR_OBJECT (pool, "error releasing buffers: %s",
676           g_strerror (errno));
677     }
678     pool->num_buffers = 0;
679   }
680 }
681
682 static gboolean
683 stop_streaming (GstV4l2BufferPool * pool)
684 {
685   GstV4l2Object *obj = pool->obj;
686
687   GST_DEBUG_OBJECT (pool, "stopping stream");
688
689   gst_poll_set_flushing (obj->poll, TRUE);
690
691   if (!pool->streaming) {
692     /* it avoid error: STREAMOFF 22 (Invalid argument) when
693      * attempting to stop a stream not previously started */
694     GST_DEBUG_OBJECT (pool, "no need to stop, was not previously started");
695     return TRUE;
696   }
697
698   switch (obj->mode) {
699     case GST_V4L2_IO_RW:
700       break;
701     case GST_V4L2_IO_MMAP:
702     case GST_V4L2_IO_USERPTR:
703     case GST_V4L2_IO_DMABUF:
704       GST_DEBUG_OBJECT (pool, "STREAMOFF");
705       if (v4l2_ioctl (pool->video_fd, VIDIOC_STREAMOFF, &obj->type) < 0)
706         goto stop_failed;
707       break;
708     default:
709       g_assert_not_reached ();
710       break;
711   }
712
713   pool->streaming = FALSE;
714
715   return TRUE;
716
717   /* ERRORS */
718 stop_failed:
719   {
720     GST_ERROR_OBJECT (pool, "error with STREAMOFF %d (%s)", errno,
721         g_strerror (errno));
722     return FALSE;
723   }
724 }
725
726 static gboolean
727 gst_v4l2_buffer_pool_stop (GstBufferPool * bpool)
728 {
729   gboolean ret;
730   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
731   GstV4l2Object *obj = pool->obj;
732   guint n;
733
734   GST_DEBUG_OBJECT (pool, "stopping pool");
735
736   gst_poll_set_flushing (obj->poll, TRUE);
737
738   if (pool->streaming) {
739     switch (obj->mode) {
740       case GST_V4L2_IO_RW:
741         break;
742       case GST_V4L2_IO_MMAP:
743       case GST_V4L2_IO_USERPTR:
744       case GST_V4L2_IO_DMABUF:
745         /* we actually need to sync on all queued buffers but not
746          * on the non-queued ones */
747         GST_DEBUG_OBJECT (pool, "STREAMOFF");
748         if (v4l2_ioctl (pool->video_fd, VIDIOC_STREAMOFF, &obj->type) < 0)
749           goto stop_failed;
750         break;
751       default:
752         g_assert_not_reached ();
753         break;
754     }
755     pool->streaming = FALSE;
756   }
757
758   /* first free the buffers in the queue */
759   ret = GST_BUFFER_POOL_CLASS (parent_class)->stop (bpool);
760
761   /* then free the remaining buffers */
762   for (n = 0; n < pool->num_buffers; n++) {
763     if (pool->buffers[n])
764       gst_v4l2_buffer_pool_free_buffer (bpool, pool->buffers[n]);
765   }
766   pool->num_queued = 0;
767   g_free (pool->buffers);
768   pool->buffers = NULL;
769
770   gst_v4l2_buffer_pool_free_buffers (pool);
771
772   return ret;
773
774   /* ERRORS */
775 stop_failed:
776   {
777     GST_ERROR_OBJECT (pool, "error with STREAMOFF %d (%s)", errno,
778         g_strerror (errno));
779     return FALSE;
780   }
781 }
782
783 static GstFlowReturn
784 gst_v4l2_object_poll (GstV4l2Object * v4l2object)
785 {
786   gint ret;
787
788   if (v4l2object->can_poll_device) {
789     GST_LOG_OBJECT (v4l2object->element, "polling device");
790     ret = gst_poll_wait (v4l2object->poll, GST_CLOCK_TIME_NONE);
791     if (G_UNLIKELY (ret < 0)) {
792       if (errno == EBUSY)
793         goto stopped;
794       if (errno == ENXIO) {
795         GST_WARNING_OBJECT (v4l2object->element,
796             "v4l2 device doesn't support polling. Disabling");
797         v4l2object->can_poll_device = FALSE;
798       } else {
799         if (errno != EAGAIN && errno != EINTR)
800           goto select_error;
801       }
802     }
803   }
804   return GST_FLOW_OK;
805
806   /* ERRORS */
807 stopped:
808   {
809     GST_DEBUG ("stop called");
810     return GST_FLOW_FLUSHING;
811   }
812 select_error:
813   {
814     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, READ, (NULL),
815         ("poll error %d: %s (%d)", ret, g_strerror (errno), errno));
816     return GST_FLOW_ERROR;
817   }
818 }
819
820 static GstFlowReturn
821 gst_v4l2_buffer_pool_qbuf (GstV4l2BufferPool * pool, GstBuffer * buf)
822 {
823   GstV4l2Meta *meta;
824   gint index;
825   gint i = 0;
826
827   meta = GST_V4L2_META_GET (buf);
828   if (meta == NULL) {
829     GST_LOG_OBJECT (pool, "unref copied buffer %p", buf);
830     /* no meta, it was a copied buffer that we can unref */
831     gst_buffer_unref (buf);
832     return GST_FLOW_OK;
833   }
834
835   index = meta->vbuffer.index;
836
837   /* this field is common to MPLANE and not MPLANE */
838   meta->vbuffer.bytesused = gst_buffer_get_size (buf);
839
840   for (i = 0; i < meta->n_planes; i++) {
841     meta->vplanes[i].bytesused =
842         gst_buffer_get_sizes_range (buf, i, 1, NULL, NULL);
843
844     GST_LOG_OBJECT (pool,
845         "enqueue buffer %p, index:%d, queued:%d, flags:%08x mem:%p used:%d, plane:%d",
846         buf, index, pool->num_queued, meta->vbuffer.flags,
847         meta->mem[i], meta->vplanes[i].bytesused, i);
848   }
849
850   if (pool->buffers[index] != NULL)
851     goto already_queued;
852
853   GST_LOG_OBJECT (pool, "doing QBUF");
854   if (v4l2_ioctl (pool->video_fd, VIDIOC_QBUF, &meta->vbuffer) < 0)
855     goto queue_failed;
856
857   pool->buffers[index] = buf;
858   pool->num_queued++;
859
860   return GST_FLOW_OK;
861
862   /* ERRORS */
863 already_queued:
864   {
865     GST_WARNING_OBJECT (pool, "the buffer was already queued");
866     return GST_FLOW_ERROR;
867   }
868 queue_failed:
869   {
870     GST_WARNING_OBJECT (pool, "could not queue a buffer %d (%s)", errno,
871         g_strerror (errno));
872     return GST_FLOW_ERROR;
873   }
874 }
875
876 static GstFlowReturn
877 gst_v4l2_buffer_pool_dqbuf (GstV4l2BufferPool * pool, GstBuffer ** buffer)
878 {
879   GstFlowReturn res;
880   GstBuffer *outbuf;
881   struct v4l2_buffer vbuffer;
882   struct v4l2_plane vplanes[GST_VIDEO_MAX_PLANES];
883   GstV4l2Object *obj = pool->obj;
884   GstClockTime timestamp;
885   GstV4l2Meta *meta;
886   gint i;
887
888   if ((res = gst_v4l2_object_poll (obj)) != GST_FLOW_OK)
889     goto poll_error;
890
891   /* prepare the buffer */
892   memset (&vbuffer, 0x00, sizeof (vbuffer));
893   vbuffer.type = obj->type;
894
895   if (obj->mode == GST_V4L2_IO_DMABUF)
896     vbuffer.memory = V4L2_MEMORY_DMABUF;
897   else
898     vbuffer.memory = V4L2_MEMORY_MMAP;
899
900   /* prepare the planes of the buffer */
901   if (V4L2_TYPE_IS_MULTIPLANAR (obj->type)) {
902     /* length is the number of elements in the
903      * vplanes array */
904     vbuffer.length = obj->n_v4l2_planes;
905     vbuffer.m.planes = vplanes;
906   }
907
908   /* the buffer is prepared, now fill in it with meaningful values */
909   GST_LOG_OBJECT (pool, "doing DQBUF");
910   if (v4l2_ioctl (pool->video_fd, VIDIOC_DQBUF, &vbuffer) < 0)
911     goto error;
912
913   /* get our GstBuffer with that index from the pool, if the buffer was
914    * outstanding we have a serious problem.
915    */
916   outbuf = pool->buffers[vbuffer.index];
917   if (outbuf == NULL)
918     goto no_buffer;
919
920   /* mark the buffer outstanding */
921   pool->buffers[vbuffer.index] = NULL;
922   pool->num_queued--;
923
924   timestamp = GST_TIMEVAL_TO_TIME (vbuffer.timestamp);
925
926   meta = GST_V4L2_META_GET (outbuf);
927   g_assert (meta != NULL);
928
929   /* The size can change at every frame, esp. with jpeg. The GstMemory
930    * inside the GstBuffer could have been changed by some other
931    * element. So update our meta */
932   if (obj->type == V4L2_BUF_TYPE_VIDEO_CAPTURE
933       || obj->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
934
935     /* this field is common to MPLANE and not MPLANE */
936     meta->vbuffer.length = vbuffer.length;
937     meta->vbuffer.bytesused = vbuffer.bytesused;
938
939     if (obj->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
940       for (i = 0; i < meta->n_planes; i++) {
941         /* the following also update meta->vbuffer.m.planes[i].length */
942         meta->vplanes[i].length = vbuffer.m.planes[i].length;
943         /* the following also update meta->vbuffer.m.planes[i].bytesused */
944         meta->vplanes[i].bytesused = vbuffer.m.planes[i].bytesused;
945         /* the following also update meta->vbuffer.m.planes[i].data_offset */
946         meta->vplanes[i].data_offset = vbuffer.m.planes[i].data_offset;
947       }
948     } else {
949       meta->vplanes[0].length = vbuffer.length;
950       meta->vplanes[0].bytesused = vbuffer.bytesused;
951       meta->vplanes[0].data_offset = 0;
952     }
953   }
954 #ifndef GST_DISABLE_GST_DEBUG
955   for (i = 0; i < meta->n_planes; i++) {
956     GST_LOG_OBJECT (pool,
957         "dequeued buffer %p seq:%d (ix=%d), mem %p used %d, plane=%d, flags %08x, ts %"
958         GST_TIME_FORMAT ", pool-queued=%d, buffer=%p", outbuf,
959         vbuffer.sequence, vbuffer.index, meta->mem[i],
960         meta->vplanes[i].bytesused, i, vbuffer.flags,
961         GST_TIME_ARGS (timestamp), pool->num_queued, outbuf);
962   }
963 #endif
964
965   /* set top/bottom field first if v4l2_buffer has the information */
966   if (vbuffer.field == V4L2_FIELD_INTERLACED_TB) {
967     GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_INTERLACED);
968     GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
969   } else if (vbuffer.field == V4L2_FIELD_INTERLACED_BT) {
970     GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_INTERLACED);
971     GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
972   } else {
973     GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_FLAG_INTERLACED);
974     GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
975   }
976
977   if (GST_VIDEO_INFO_FORMAT (&obj->info) == GST_VIDEO_FORMAT_ENCODED) {
978     if (vbuffer.flags & V4L2_BUF_FLAG_KEYFRAME)
979       GST_BUFFER_FLAG_UNSET (outbuf, GST_BUFFER_FLAG_DELTA_UNIT);
980     else
981       GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DELTA_UNIT);
982   }
983
984   /* The size can change at every frame, esp. with jpeg. The GstMemory
985    * inside the GstBuffer could have been changed by some other
986    * element, so just put back the original one. We always set it as
987    * no share, so if it's not there, it's not used at all.
988    */
989   if (obj->type == V4L2_BUF_TYPE_VIDEO_CAPTURE
990       || obj->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
991     gst_buffer_remove_all_memory (outbuf);
992     for (i = 0; i < meta->n_planes; i++) {
993       gst_buffer_append_memory (outbuf,
994           gst_memory_new_wrapped (GST_MEMORY_FLAG_NO_SHARE,
995               meta->mem[i], meta->vplanes[i].length,
996               meta->vplanes[i].data_offset,
997               meta->vplanes[i].bytesused, NULL, NULL));
998     }
999   }
1000
1001   GST_BUFFER_TIMESTAMP (outbuf) = timestamp;
1002
1003   *buffer = outbuf;
1004
1005   return GST_FLOW_OK;
1006
1007   /* ERRORS */
1008 poll_error:
1009   {
1010     GST_DEBUG_OBJECT (pool, "poll error %s", gst_flow_get_name (res));
1011     return res;
1012   }
1013 error:
1014   {
1015     GST_WARNING_OBJECT (pool,
1016         "problem dequeuing frame %d (ix=%d), pool-ct=%d, buf.flags=%d",
1017         vbuffer.sequence, vbuffer.index,
1018         GST_MINI_OBJECT_REFCOUNT (pool), vbuffer.flags);
1019
1020     switch (errno) {
1021       case EAGAIN:
1022         GST_WARNING_OBJECT (pool,
1023             "Non-blocking I/O has been selected using O_NONBLOCK and"
1024             " no buffer was in the outgoing queue. device %s", obj->videodev);
1025         break;
1026       case EINVAL:
1027         GST_ERROR_OBJECT (pool,
1028             "The buffer type is not supported, or the index is out of bounds, "
1029             "or no buffers have been allocated yet, or the userptr "
1030             "or length are invalid. device %s", obj->videodev);
1031         break;
1032       case ENOMEM:
1033         GST_ERROR_OBJECT (pool,
1034             "insufficient memory to enqueue a user pointer buffer");
1035         break;
1036       case EIO:
1037         GST_INFO_OBJECT (pool,
1038             "VIDIOC_DQBUF failed due to an internal error."
1039             " Can also indicate temporary problems like signal loss."
1040             " Note the driver might dequeue an (empty) buffer despite"
1041             " returning an error, or even stop capturing."
1042             " device %s", obj->videodev);
1043         /* have we de-queued a buffer ? */
1044         if (!(vbuffer.flags & (V4L2_BUF_FLAG_QUEUED | V4L2_BUF_FLAG_DONE))) {
1045           GST_DEBUG_OBJECT (pool, "reenqueing buffer");
1046           /* FIXME ... should we do something here? */
1047         }
1048         break;
1049       case EINTR:
1050         GST_WARNING_OBJECT (pool,
1051             "could not sync on a buffer on device %s", obj->videodev);
1052         break;
1053       default:
1054         GST_WARNING_OBJECT (pool,
1055             "Grabbing frame got interrupted on %s unexpectedly. %d: %s.",
1056             obj->videodev, errno, g_strerror (errno));
1057         break;
1058     }
1059     return GST_FLOW_ERROR;
1060   }
1061 no_buffer:
1062   {
1063     GST_ERROR_OBJECT (pool, "No free buffer found in the pool at index %d.",
1064         vbuffer.index);
1065     return GST_FLOW_ERROR;
1066   }
1067 }
1068
1069 static GstFlowReturn
1070 gst_v4l2_buffer_pool_acquire_buffer (GstBufferPool * bpool, GstBuffer ** buffer,
1071     GstBufferPoolAcquireParams * params)
1072 {
1073   GstFlowReturn ret;
1074   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
1075   GstV4l2Object *obj = pool->obj;
1076
1077   GST_DEBUG_OBJECT (pool, "acquire");
1078
1079   if (GST_BUFFER_POOL_IS_FLUSHING (bpool))
1080     goto flushing;
1081
1082   switch (obj->type) {
1083     case V4L2_BUF_TYPE_VIDEO_CAPTURE:
1084     case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE:
1085       /* capture, This function should return a buffer with new captured data */
1086       switch (obj->mode) {
1087         case GST_V4L2_IO_RW:
1088           /* take empty buffer from the pool */
1089           ret = GST_BUFFER_POOL_CLASS (parent_class)->acquire_buffer (bpool,
1090               buffer, params);
1091           break;
1092         case GST_V4L2_IO_DMABUF:
1093         case GST_V4L2_IO_MMAP:
1094           /* just dequeue a buffer, we basically use the queue of v4l2 as the
1095            * storage for our buffers. This function does poll first so we can
1096            * interrupt it fine. */
1097           ret = gst_v4l2_buffer_pool_dqbuf (pool, buffer);
1098           if (G_UNLIKELY (ret != GST_FLOW_OK))
1099             goto done;
1100
1101           /* start copying buffers when we are running low on buffers */
1102           if (pool->num_queued < pool->copy_threshold) {
1103             GstBuffer *copy;
1104
1105             if (pool->can_alloc) {
1106               if (GST_BUFFER_POOL_CLASS (parent_class)->acquire_buffer (bpool,
1107                       &copy, params) == GST_FLOW_OK) {
1108                 gst_v4l2_buffer_pool_release_buffer (bpool, copy);
1109                 break;
1110               } else {
1111                 pool->can_alloc = FALSE;
1112               }
1113             }
1114
1115             /* copy the buffer */
1116             copy = gst_buffer_copy_region (*buffer,
1117                 GST_BUFFER_COPY_ALL | GST_BUFFER_COPY_DEEP, 0, -1);
1118             GST_LOG_OBJECT (pool, "copy buffer %p->%p", *buffer, copy);
1119
1120             /* and requeue so that we can continue capturing */
1121             ret = gst_v4l2_buffer_pool_qbuf (pool, *buffer);
1122             *buffer = copy;
1123           }
1124           break;
1125
1126         case GST_V4L2_IO_USERPTR:
1127         default:
1128           ret = GST_FLOW_ERROR;
1129           g_assert_not_reached ();
1130           break;
1131       }
1132       break;
1133
1134     case V4L2_BUF_TYPE_VIDEO_OUTPUT:
1135     case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE:
1136       /* playback, This function should return an empty buffer */
1137       switch (obj->mode) {
1138         case GST_V4L2_IO_RW:
1139           /* get an empty buffer */
1140           ret = GST_BUFFER_POOL_CLASS (parent_class)->acquire_buffer (bpool,
1141               buffer, params);
1142           break;
1143
1144         case GST_V4L2_IO_MMAP:
1145           /* get a free unqueued buffer */
1146           ret = GST_BUFFER_POOL_CLASS (parent_class)->acquire_buffer (bpool,
1147               buffer, params);
1148           break;
1149
1150         case GST_V4L2_IO_USERPTR:
1151         default:
1152           ret = GST_FLOW_ERROR;
1153           g_assert_not_reached ();
1154           break;
1155       }
1156       break;
1157
1158     default:
1159       ret = GST_FLOW_ERROR;
1160       g_assert_not_reached ();
1161       break;
1162   }
1163 done:
1164   return ret;
1165
1166   /* ERRORS */
1167 flushing:
1168   {
1169     GST_DEBUG_OBJECT (pool, "We are flushing");
1170     return GST_FLOW_FLUSHING;
1171   }
1172 }
1173
1174 static void
1175 gst_v4l2_buffer_pool_release_buffer (GstBufferPool * bpool, GstBuffer * buffer)
1176 {
1177   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
1178   GstV4l2Object *obj = pool->obj;
1179
1180   GST_DEBUG_OBJECT (pool, "release buffer %p", buffer);
1181
1182   switch (obj->type) {
1183     case V4L2_BUF_TYPE_VIDEO_CAPTURE:
1184     case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE:
1185       /* capture, put the buffer back in the queue so that we can refill it
1186        * later. */
1187       switch (obj->mode) {
1188         case GST_V4L2_IO_RW:
1189           /* release back in the pool */
1190           GST_BUFFER_POOL_CLASS (parent_class)->release_buffer (bpool, buffer);
1191           break;
1192
1193         case GST_V4L2_IO_DMABUF:
1194         case GST_V4L2_IO_MMAP:
1195           /* queue back in the device */
1196           gst_v4l2_buffer_pool_qbuf (pool, buffer);
1197           break;
1198
1199         case GST_V4L2_IO_USERPTR:
1200         default:
1201           g_assert_not_reached ();
1202           break;
1203       }
1204       break;
1205
1206     case V4L2_BUF_TYPE_VIDEO_OUTPUT:
1207     case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE:
1208       switch (obj->mode) {
1209         case GST_V4L2_IO_RW:
1210           /* release back in the pool */
1211           GST_BUFFER_POOL_CLASS (parent_class)->release_buffer (bpool, buffer);
1212           break;
1213
1214         case GST_V4L2_IO_MMAP:
1215         {
1216           GstV4l2Meta *meta;
1217           guint index;
1218
1219           meta = GST_V4L2_META_GET (buffer);
1220           g_assert (meta != NULL);
1221
1222           index = meta->vbuffer.index;
1223
1224           if (pool->buffers[index] == NULL) {
1225             GST_LOG_OBJECT (pool, "buffer %u not queued, putting on free list",
1226                 index);
1227
1228             /* reset to the full length, in case it was changed */
1229             if (V4L2_TYPE_IS_MULTIPLANAR (obj->type)) {
1230               gint i = 0;
1231               gint total_length = 0;
1232               for (i = 0; i < meta->n_planes; i++)
1233                 total_length += meta->vplanes[i].length;
1234
1235               if (total_length != gst_buffer_get_size (buffer) &&
1236                   obj->info.finfo->n_planes > 1) {
1237                 /* FIXME if the lengths has actually changed it may require
1238                  * to restore the sizes of the individual memories and
1239                  * re-add them */
1240                 GST_WARNING_OBJECT (pool,
1241                     "lengths changed, more work required");
1242               }
1243
1244               gst_buffer_resize (buffer, 0, total_length);
1245             } else {
1246               gst_buffer_resize (buffer, 0, meta->vbuffer.length);
1247             }
1248
1249             /* playback, put the buffer back in the queue to refill later. */
1250             GST_BUFFER_POOL_CLASS (parent_class)->release_buffer (bpool,
1251                 buffer);
1252           } else {
1253             /* the buffer is queued in the device but maybe not played yet. We just
1254              * leave it there and not make it available for future calls to acquire
1255              * for now. The buffer will be dequeued and reused later. */
1256             GST_LOG_OBJECT (pool, "buffer %u is queued", index);
1257           }
1258           break;
1259         }
1260
1261         case GST_V4L2_IO_USERPTR:
1262         default:
1263           g_assert_not_reached ();
1264           break;
1265       }
1266       break;
1267
1268     default:
1269       g_assert_not_reached ();
1270       break;
1271   }
1272 }
1273
1274 static void
1275 gst_v4l2_buffer_pool_finalize (GObject * object)
1276 {
1277   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (object);
1278
1279   gst_v4l2_buffer_pool_free_buffers (pool);
1280
1281   if (pool->video_fd >= 0)
1282     v4l2_close (pool->video_fd);
1283   if (pool->allocator)
1284     gst_object_unref (pool->allocator);
1285   g_free (pool->buffers);
1286
1287   gst_object_unref (pool->obj->element);
1288
1289   G_OBJECT_CLASS (parent_class)->finalize (object);
1290 }
1291
1292 static void
1293 gst_v4l2_buffer_pool_init (GstV4l2BufferPool * pool)
1294 {
1295 }
1296
1297 static void
1298 gst_v4l2_buffer_pool_class_init (GstV4l2BufferPoolClass * klass)
1299 {
1300   GObjectClass *object_class = G_OBJECT_CLASS (klass);
1301   GstBufferPoolClass *bufferpool_class = GST_BUFFER_POOL_CLASS (klass);
1302
1303   object_class->finalize = gst_v4l2_buffer_pool_finalize;
1304
1305   bufferpool_class->start = gst_v4l2_buffer_pool_start;
1306   bufferpool_class->stop = gst_v4l2_buffer_pool_stop;
1307   bufferpool_class->set_config = gst_v4l2_buffer_pool_set_config;
1308   bufferpool_class->alloc_buffer = gst_v4l2_buffer_pool_alloc_buffer;
1309   bufferpool_class->acquire_buffer = gst_v4l2_buffer_pool_acquire_buffer;
1310   bufferpool_class->release_buffer = gst_v4l2_buffer_pool_release_buffer;
1311   bufferpool_class->free_buffer = gst_v4l2_buffer_pool_free_buffer;
1312 }
1313
1314 /**
1315  * gst_v4l2_buffer_pool_new:
1316  * @obj:  the v4l2 object owning the pool
1317  *
1318  * Construct a new buffer pool.
1319  *
1320  * Returns: the new pool, use gst_object_unref() to free resources
1321  */
1322 GstBufferPool *
1323 gst_v4l2_buffer_pool_new (GstV4l2Object * obj, GstCaps * caps)
1324 {
1325   GstV4l2BufferPool *pool;
1326   GstStructure *config;
1327   gboolean res = FALSE;
1328   gint fd;
1329
1330   fd = v4l2_dup (obj->video_fd);
1331   if (fd < 0)
1332     goto dup_failed;
1333
1334   pool = (GstV4l2BufferPool *) g_object_new (GST_TYPE_V4L2_BUFFER_POOL, NULL);
1335   pool->video_fd = fd;
1336   pool->obj = obj;
1337   pool->can_alloc = TRUE;
1338
1339   config = gst_buffer_pool_get_config (GST_BUFFER_POOL_CAST (pool));
1340   gst_buffer_pool_config_set_params (config, caps, obj->sizeimage, 2, 0);
1341
1342   res = gst_buffer_pool_set_config (GST_BUFFER_POOL_CAST (pool), config);
1343   if (!res)
1344     goto config_failed;
1345
1346   gst_object_ref (obj->element);
1347
1348   return GST_BUFFER_POOL (pool);
1349
1350   /* ERRORS */
1351 dup_failed:
1352   {
1353     GST_DEBUG ("failed to dup fd %d (%s)", errno, g_strerror (errno));
1354     return NULL;
1355   }
1356 config_failed:
1357   {
1358     GST_WARNING ("failed to set pool config");
1359     return NULL;
1360   }
1361 }
1362
1363 static GstFlowReturn
1364 gst_v4l2_do_read (GstV4l2BufferPool * pool, GstBuffer * buf)
1365 {
1366   GstFlowReturn res;
1367   GstV4l2Object *obj = pool->obj;
1368   gint amount;
1369   GstMapInfo map;
1370   gint toread;
1371
1372   toread = obj->sizeimage;
1373
1374   GST_LOG_OBJECT (pool, "reading %d bytes into buffer %p", toread, buf);
1375
1376   gst_buffer_map (buf, &map, GST_MAP_WRITE);
1377
1378   do {
1379     if ((res = gst_v4l2_object_poll (obj)) != GST_FLOW_OK)
1380       goto poll_error;
1381
1382     amount = v4l2_read (obj->video_fd, map.data, toread);
1383
1384     if (amount == toread) {
1385       break;
1386     } else if (amount == -1) {
1387       if (errno == EAGAIN || errno == EINTR) {
1388         continue;
1389       } else
1390         goto read_error;
1391     } else {
1392       /* short reads can happen if a signal interrupts the read */
1393       continue;
1394     }
1395   } while (TRUE);
1396
1397   GST_LOG_OBJECT (pool, "read %d bytes", amount);
1398   gst_buffer_unmap (buf, &map);
1399   gst_buffer_resize (buf, 0, amount);
1400
1401   return GST_FLOW_OK;
1402
1403   /* ERRORS */
1404 poll_error:
1405   {
1406     GST_DEBUG ("poll error %s", gst_flow_get_name (res));
1407     goto cleanup;
1408   }
1409 read_error:
1410   {
1411     GST_ELEMENT_ERROR (obj->element, RESOURCE, READ,
1412         (_("Error reading %d bytes from device '%s'."),
1413             toread, obj->videodev), GST_ERROR_SYSTEM);
1414     res = GST_FLOW_ERROR;
1415     goto cleanup;
1416   }
1417 cleanup:
1418   {
1419     gst_buffer_unmap (buf, &map);
1420     gst_buffer_resize (buf, 0, 0);
1421     return res;
1422   }
1423 }
1424
1425 /**
1426  * gst_v4l2_buffer_pool_process:
1427  * @bpool: a #GstBufferPool
1428  * @buf: a #GstBuffer
1429  *
1430  * Process @buf in @bpool. For capture devices, this functions fills @buf with
1431  * data from the device. For output devices, this functions send the contents of
1432  * @buf to the device for playback.
1433  *
1434  * Returns: %GST_FLOW_OK on success.
1435  */
1436 GstFlowReturn
1437 gst_v4l2_buffer_pool_process (GstV4l2BufferPool * pool, GstBuffer * buf)
1438 {
1439   GstFlowReturn ret = GST_FLOW_OK;
1440   GstBufferPool *bpool = GST_BUFFER_POOL_CAST (pool);
1441   GstV4l2Object *obj = pool->obj;
1442
1443   GST_DEBUG_OBJECT (pool, "process buffer %p", buf);
1444
1445   switch (obj->type) {
1446     case V4L2_BUF_TYPE_VIDEO_CAPTURE:
1447     case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE:
1448       /* capture */
1449       switch (obj->mode) {
1450         case GST_V4L2_IO_RW:
1451           /* capture into the buffer */
1452           ret = gst_v4l2_do_read (pool, buf);
1453           break;
1454
1455         case GST_V4L2_IO_MMAP:
1456         {
1457           GstBuffer *tmp;
1458
1459           if (buf->pool == bpool)
1460             /* nothing, data was inside the buffer when we did _acquire() */
1461             goto done;
1462
1463           /* buffer not from our pool, grab a frame and copy it into the target */
1464           if ((ret = gst_v4l2_buffer_pool_dqbuf (pool, &tmp)) != GST_FLOW_OK)
1465             goto done;
1466
1467           if (!gst_v4l2_object_copy (obj, buf, tmp))
1468             goto copy_failed;
1469
1470           /* an queue the buffer again after the copy */
1471           if ((ret = gst_v4l2_buffer_pool_qbuf (pool, tmp)) != GST_FLOW_OK)
1472             goto done;
1473           break;
1474         }
1475
1476         case GST_V4L2_IO_USERPTR:
1477         default:
1478           g_assert_not_reached ();
1479           break;
1480       }
1481       break;
1482
1483     case V4L2_BUF_TYPE_VIDEO_OUTPUT:
1484     case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE:
1485       /* playback */
1486       switch (obj->mode) {
1487         case GST_V4L2_IO_RW:
1488           /* FIXME, do write() */
1489           GST_WARNING_OBJECT (pool, "implement write()");
1490           break;
1491         case GST_V4L2_IO_DMABUF:
1492         case GST_V4L2_IO_MMAP:
1493         {
1494           GstBuffer *to_queue;
1495
1496           if (buf->pool == bpool) {
1497             /* nothing, we can queue directly */
1498             to_queue = gst_buffer_ref (buf);
1499             GST_LOG_OBJECT (pool, "processing buffer from our pool");
1500           } else {
1501             GST_LOG_OBJECT (pool, "alloc buffer from our pool");
1502             if (!gst_buffer_pool_is_active (bpool)) {
1503               GstStructure *config;
1504
1505               /* this pool was not activated, configure and activate */
1506               GST_DEBUG_OBJECT (pool, "activating pool");
1507
1508               config = gst_buffer_pool_get_config (bpool);
1509               gst_buffer_pool_config_add_option (config,
1510                   GST_BUFFER_POOL_OPTION_VIDEO_META);
1511               gst_buffer_pool_set_config (bpool, config);
1512
1513               if (!gst_buffer_pool_set_active (bpool, TRUE))
1514                 goto activate_failed;
1515             }
1516
1517             /* this can block if all buffers are outstanding which would be
1518              * strange because we would expect the upstream element to have
1519              * allocated them and returned to us.. */
1520             ret = gst_buffer_pool_acquire_buffer (bpool, &to_queue, NULL);
1521             if (ret != GST_FLOW_OK)
1522               goto acquire_failed;
1523
1524             /* copy into it and queue */
1525             if (!gst_v4l2_object_copy (obj, to_queue, buf))
1526               goto copy_failed;
1527           }
1528
1529           if ((ret = gst_v4l2_buffer_pool_qbuf (pool, to_queue)) != GST_FLOW_OK)
1530             goto done;
1531
1532           /* if we are not streaming yet (this is the first buffer, start
1533            * streaming now */
1534           if (!pool->streaming)
1535             if (!start_streaming (pool))
1536               goto start_failed;
1537
1538           if (pool->num_queued == pool->num_allocated) {
1539             GstBuffer *out;
1540             /* all buffers are queued, try to dequeue one and release it back
1541              * into the pool so that _acquire can get to it again. */
1542             ret = gst_v4l2_buffer_pool_dqbuf (pool, &out);
1543             if (ret != GST_FLOW_OK) {
1544               gst_buffer_unref (to_queue);
1545               goto done;
1546             }
1547
1548             /* release the rendered buffer back into the pool. This wakes up any
1549              * thread waiting for a buffer in _acquire(). If the buffer still has
1550              * a pool then this will happen when the refcount reaches 0 */
1551             if (!out->pool)
1552               gst_v4l2_buffer_pool_release_buffer (bpool, out);
1553           }
1554           gst_buffer_unref (to_queue);
1555           break;
1556         }
1557
1558         case GST_V4L2_IO_USERPTR:
1559         default:
1560           g_assert_not_reached ();
1561           break;
1562       }
1563       break;
1564     default:
1565       g_assert_not_reached ();
1566       break;
1567   }
1568 done:
1569   return ret;
1570
1571   /* ERRORS */
1572 activate_failed:
1573   {
1574     GST_ERROR_OBJECT (obj->element, "failed to activate pool");
1575     return GST_FLOW_ERROR;
1576   }
1577 acquire_failed:
1578   {
1579     GST_WARNING_OBJECT (obj->element, "failed to acquire a buffer: %s",
1580         gst_flow_get_name (ret));
1581     return ret;
1582   }
1583 copy_failed:
1584   {
1585     GST_ERROR_OBJECT (obj->element, "failed to copy data");
1586     return GST_FLOW_ERROR;
1587   }
1588 start_failed:
1589   {
1590     GST_ERROR_OBJECT (obj->element, "failed to start streaming");
1591     return GST_FLOW_ERROR;
1592   }
1593 }
1594
1595
1596 /**
1597  * gst_v4l2_buffer_pool_flush:
1598  * @bpool: a #GstBufferPool
1599  *
1600  * First, set obj->poll to be flushing
1601  * Call STREAMOFF to clear QUEUED flag on every driver buffers.
1602  * Then release all buffers that are in pool->buffers array.
1603  * Finally call STREAMON if CAPTURE type
1604  * The caller is responsible to unset flushing on obj->pool
1605  * 
1606  * Returns: TRUE on success.
1607  */
1608 gboolean
1609 gst_v4l2_buffer_pool_flush (GstV4l2BufferPool * pool)
1610 {
1611   GstBufferPool *bpool = GST_BUFFER_POOL_CAST (pool);
1612   GstV4l2Object *obj = pool->obj;
1613   gint i = 0;
1614
1615   GST_DEBUG_OBJECT (pool, "flush");
1616
1617   stop_streaming (pool);
1618
1619   switch (obj->type) {
1620     case V4L2_BUF_TYPE_VIDEO_CAPTURE:
1621     case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE:
1622     case V4L2_BUF_TYPE_VIDEO_OUTPUT:
1623     case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE:
1624       switch (obj->mode) {
1625         case GST_V4L2_IO_RW:
1626           break;
1627         case GST_V4L2_IO_MMAP:
1628         case GST_V4L2_IO_USERPTR:
1629         case GST_V4L2_IO_DMABUF:
1630         {
1631           for (i = 0; i < pool->num_buffers; i++) {
1632             GstBuffer *buf = pool->buffers[i];
1633             if (buf) {
1634               /* it's necessary to set to NULL before to call
1635                * gst_v4l2_buffer_pool_release_buffer
1636                * otherwise it won't go back to the pool */
1637               pool->buffers[i] = NULL;
1638
1639               /* dicrease counter */
1640               pool->num_queued--;
1641
1642               /* in CAPTURE mode the pool->num_queued will be re-incremented
1643                * because the buffers are queued when released */
1644               if (buf->pool)
1645                 gst_buffer_unref (buf);
1646               else
1647                 gst_v4l2_buffer_pool_release_buffer (bpool, buf);
1648             }
1649           }
1650
1651           /* do not set pool->num_queued to 0 because
1652            * the buffers are queued when released */
1653           break;
1654         }
1655
1656         default:
1657           g_assert_not_reached ();
1658           break;
1659       }
1660       break;
1661     default:
1662       g_assert_not_reached ();
1663       break;
1664   }
1665   /* we can start capturing now, we wait for the playback
1666    * case until we queued the first buffer */
1667   if (!V4L2_TYPE_IS_OUTPUT (obj->type))
1668     if (!start_streaming (pool))
1669       goto start_failed;
1670
1671   return TRUE;
1672
1673   /* ERRORS */
1674 start_failed:
1675   {
1676     GST_ERROR_OBJECT (pool, "failed to start streaming");
1677     return FALSE;
1678   }
1679 }
1680
1681 void
1682 gst_v4l2_buffer_pool_add_crop_meta (GstV4l2BufferPool * bpool, gboolean add)
1683 {
1684   bpool->add_cropmeta = add;
1685 }