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