v4l2allocator: Fix libv4l2 support
[platform/upstream/gst-plugins-good.git] / sys / v4l2 / gstv4l2allocator.c
1 /*
2  * Copyright (C) 2014 Collabora Ltd.
3  *     Author: Nicolas Dufresne <nicolas.dufresne@collabora.com>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
18  * Boston, MA 02110-1301, USA.
19  *
20  */
21
22 #include "config.h"
23
24 #include "ext/videodev2.h"
25 #include "gstv4l2allocator.h"
26 #include "v4l2_calls.h"
27
28 #include <gst/allocators/gstdmabuf.h>
29
30 #include <fcntl.h>
31 #include <string.h>
32 #include <sys/stat.h>
33 #include <sys/types.h>
34 #include <sys/mman.h>
35
36 #define GST_V4L2_MEMORY_TYPE "V4l2Memory"
37
38 #define gst_v4l2_allocator_parent_class parent_class
39 G_DEFINE_TYPE (GstV4l2Allocator, gst_v4l2_allocator, GST_TYPE_ALLOCATOR);
40
41 GST_DEBUG_CATEGORY_STATIC (v4l2allocator_debug);
42 #define GST_CAT_DEFAULT v4l2allocator_debug
43
44 #define UNSET_QUEUED(buffer) \
45     ((buffer).flags &= ~(V4L2_BUF_FLAG_QUEUED | V4L2_BUF_FLAG_DONE))
46
47 #define SET_QUEUED(buffer) ((buffer).flags |= V4L2_BUF_FLAG_QUEUED)
48
49 #define IS_QUEUED(buffer) \
50     ((buffer).flags & (V4L2_BUF_FLAG_QUEUED | V4L2_BUF_FLAG_DONE))
51
52 enum
53 {
54   GROUP_RELEASED,
55   LAST_SIGNAL
56 };
57
58 static guint gst_v4l2_allocator_signals[LAST_SIGNAL] = { 0 };
59
60 static void gst_v4l2_allocator_release (GstV4l2Allocator * allocator,
61     GstV4l2Memory * mem);
62
63 static const gchar *
64 memory_type_to_str (guint32 memory)
65 {
66   switch (memory) {
67     case V4L2_MEMORY_MMAP:
68       return "mmap";
69     case V4L2_MEMORY_USERPTR:
70       return "userptr";
71     case V4L2_MEMORY_DMABUF:
72       return "dmabuf";
73     default:
74       return "unknown";
75   }
76 }
77
78 /*************************************/
79 /* GstV4lMemory implementation */
80 /*************************************/
81
82 static gpointer
83 _v4l2mem_map (GstV4l2Memory * mem, gsize maxsize, GstMapFlags flags)
84 {
85   gpointer data = NULL;
86
87   switch (mem->group->buffer.memory) {
88     case V4L2_MEMORY_MMAP:
89     case V4L2_MEMORY_USERPTR:
90       data = mem->data;
91       break;
92     case V4L2_MEMORY_DMABUF:
93       /* v4l2 dmabuf memory are not shared with downstream */
94       g_assert_not_reached ();
95       break;
96     default:
97       GST_WARNING ("Unknown memory type %i", mem->group->buffer.memory);
98       break;
99   }
100   return data;
101 }
102
103 static gboolean
104 _v4l2mem_unmap (GstV4l2Memory * mem)
105 {
106   gboolean ret = FALSE;
107
108   switch (mem->group->buffer.memory) {
109     case V4L2_MEMORY_MMAP:
110     case V4L2_MEMORY_USERPTR:
111       ret = TRUE;
112       break;
113     case V4L2_MEMORY_DMABUF:
114       /* v4l2 dmabuf memory are not share with downstream */
115       g_assert_not_reached ();
116       break;
117     default:
118       GST_WARNING ("Unknown memory type %i", mem->group->buffer.memory);
119       break;
120   }
121   return ret;
122 }
123
124 static gboolean
125 _v4l2mem_dispose (GstV4l2Memory * mem)
126 {
127   GstV4l2Allocator *allocator = (GstV4l2Allocator *) mem->mem.allocator;
128   GstV4l2MemoryGroup *group = mem->group;
129   gboolean ret;
130
131   if (group->mem[mem->plane]) {
132     /* We may have a dmabuf, replace it with returned original memory */
133     group->mem[mem->plane] = gst_memory_ref ((GstMemory *) mem);
134     gst_v4l2_allocator_release (allocator, mem);
135     ret = FALSE;
136   } else {
137     gst_object_ref (allocator);
138     ret = TRUE;
139   }
140
141   return ret;
142 }
143
144 static void
145 _v4l2mem_free (GstV4l2Memory * mem)
146 {
147   if (mem->dmafd >= 0)
148     close (mem->dmafd);
149   g_slice_free (GstV4l2Memory, mem);
150 }
151
152 static inline GstV4l2Memory *
153 _v4l2mem_new (GstMemoryFlags flags, GstAllocator * allocator,
154     GstMemory * parent, gsize maxsize, gsize align, gsize offset, gsize size,
155     gint plane, gpointer data, int dmafd, GstV4l2MemoryGroup * group)
156 {
157   GstV4l2Memory *mem;
158
159   mem = g_slice_new0 (GstV4l2Memory);
160   gst_memory_init (GST_MEMORY_CAST (mem),
161       flags, allocator, parent, maxsize, align, offset, size);
162
163   if (parent == NULL)
164     mem->mem.mini_object.dispose =
165         (GstMiniObjectDisposeFunction) _v4l2mem_dispose;
166
167   mem->plane = plane;
168   mem->data = data;
169   mem->dmafd = dmafd;
170   mem->group = group;
171
172   return mem;
173 }
174
175 static GstV4l2Memory *
176 _v4l2mem_share (GstV4l2Memory * mem, gssize offset, gsize size)
177 {
178   GstV4l2Memory *sub;
179   GstMemory *parent;
180
181   /* find the real parent */
182   if ((parent = mem->mem.parent) == NULL)
183     parent = (GstMemory *) mem;
184
185   if (size == -1)
186     size = mem->mem.size - offset;
187
188   /* the shared memory is always readonly */
189   sub = _v4l2mem_new (GST_MINI_OBJECT_FLAGS (parent) |
190       GST_MINI_OBJECT_FLAG_LOCK_READONLY, mem->mem.allocator, parent,
191       mem->mem.maxsize, mem->mem.align, offset, size, mem->plane, mem->data,
192       -1, mem->group);
193
194   return sub;
195 }
196
197 static gboolean
198 _v4l2mem_is_span (GstV4l2Memory * mem1, GstV4l2Memory * mem2, gsize * offset)
199 {
200   if (offset)
201     *offset = mem1->mem.offset - mem1->mem.parent->offset;
202
203   /* and memory is contiguous */
204   return mem1->mem.offset + mem1->mem.size == mem2->mem.offset;
205 }
206
207 static void
208 _v4l2mem_parent_to_dmabuf (GstV4l2Memory * mem, GstMemory * dma_mem)
209 {
210   gst_memory_lock (&mem->mem, GST_LOCK_FLAG_EXCLUSIVE);
211   dma_mem->parent = gst_memory_ref (&mem->mem);
212 }
213
214 gboolean
215 gst_is_v4l2_memory (GstMemory * mem)
216 {
217   return gst_memory_is_type (mem, GST_V4L2_MEMORY_TYPE);
218 }
219
220
221 /*************************************/
222 /* GstV4l2MemoryGroup implementation */
223 /*************************************/
224
225 static void
226 gst_v4l2_memory_group_free (GstV4l2MemoryGroup * group)
227 {
228   gint i;
229
230   for (i = 0; i < group->n_mem; i++) {
231     GstMemory *mem = group->mem[i];
232     group->mem[i] = NULL;
233     if (mem)
234       gst_memory_unref (mem);
235   }
236
237   g_slice_free (GstV4l2MemoryGroup, group);
238 }
239
240 static GstV4l2MemoryGroup *
241 gst_v4l2_memory_group_new (GstV4l2Allocator * allocator, guint32 index)
242 {
243   gint video_fd = allocator->video_fd;
244   guint32 memory = allocator->memory;
245   struct v4l2_format *format = &allocator->format;
246   GstV4l2MemoryGroup *group;
247   gsize img_size, buf_size;
248
249   group = g_slice_new0 (GstV4l2MemoryGroup);
250
251   group->buffer.type = format->type;
252   group->buffer.index = index;
253   group->buffer.memory = memory;
254
255   if (V4L2_TYPE_IS_MULTIPLANAR (format->type)) {
256     group->n_mem = group->buffer.length = format->fmt.pix_mp.num_planes;
257     group->buffer.m.planes = group->planes;
258   } else {
259     group->n_mem = 1;
260   }
261
262   if (v4l2_ioctl (video_fd, VIDIOC_QUERYBUF, &group->buffer) < 0)
263     goto querybuf_failed;
264
265   /* Check that provided size matches the format we have negotiation. Failing
266    * there usually means a driver of libv4l bug. */
267   if (V4L2_TYPE_IS_MULTIPLANAR (allocator->type)) {
268     gint i;
269
270     for (i = 0; i < group->n_mem; i++) {
271       img_size = allocator->format.fmt.pix_mp.plane_fmt[i].sizeimage;
272       buf_size = group->planes[i].length;
273       if (buf_size < img_size)
274         goto buffer_too_short;
275     }
276   } else {
277     img_size = allocator->format.fmt.pix.sizeimage;
278     buf_size = group->buffer.length;
279     if (buf_size < img_size)
280       goto buffer_too_short;
281   }
282
283   /* We save non planar buffer information into the multi-planar plane array
284    * to avoid duplicating the code later */
285   if (!V4L2_TYPE_IS_MULTIPLANAR (format->type)) {
286     group->planes[0].bytesused = group->buffer.bytesused;
287     group->planes[0].length = group->buffer.length;
288     g_assert (sizeof (group->planes[0].m) == sizeof (group->buffer.m));
289     memcpy (&group->planes[0].m, &group->buffer.m, sizeof (group->buffer.m));
290   }
291
292   GST_LOG_OBJECT (allocator, "Got %s buffer", memory_type_to_str (memory));
293   GST_LOG_OBJECT (allocator, "  index:     %u", group->buffer.index);
294   GST_LOG_OBJECT (allocator, "  type:      %d", group->buffer.type);
295   GST_LOG_OBJECT (allocator, "  flags:     %08x", group->buffer.flags);
296   GST_LOG_OBJECT (allocator, "  field:     %d", group->buffer.field);
297   GST_LOG_OBJECT (allocator, "  memory:    %d", group->buffer.memory);
298   GST_LOG_OBJECT (allocator, "  planes:    %d", group->n_mem);
299
300 #ifndef GST_DISABLE_GST_DEBUG
301   if (memory == V4L2_MEMORY_MMAP) {
302     gint i;
303     for (i = 0; i < group->n_mem; i++) {
304       GST_LOG_OBJECT (allocator, "  [%u] bytesused: %u, length: %u", i,
305           group->planes[i].bytesused, group->planes[i].length);
306       GST_LOG_OBJECT (allocator, "  [%u] MMAP offset:  %u", i,
307           group->planes[i].m.mem_offset);
308     }
309   }
310 #endif
311
312   return group;
313
314 querybuf_failed:
315   {
316     GST_ERROR ("error querying buffer %d: %s", index, g_strerror (errno));
317     goto failed;
318   }
319 buffer_too_short:
320   {
321     GST_ERROR ("buffer size %" G_GSIZE_FORMAT
322         " is smaller then negotiated size %" G_GSIZE_FORMAT
323         ", this is usually the result of a bug in the v4l2 driver or libv4l.",
324         buf_size, img_size);
325     goto failed;
326   }
327 failed:
328   gst_v4l2_memory_group_free (group);
329   return NULL;
330 }
331
332
333 /*************************************/
334 /* GstV4lAllocator implementation    */
335 /*************************************/
336
337 static void
338 gst_v4l2_allocator_release (GstV4l2Allocator * allocator, GstV4l2Memory * mem)
339 {
340   GstV4l2MemoryGroup *group = mem->group;
341
342   GST_LOG_OBJECT (allocator, "plane %i of buffer %u released",
343       mem->plane, group->buffer.index);
344
345   switch (allocator->memory) {
346     case V4L2_MEMORY_DMABUF:
347       close (mem->dmafd);
348       mem->dmafd = -1;
349       break;
350     case V4L2_MEMORY_USERPTR:
351       mem->data = NULL;
352       break;
353     default:
354       break;
355   }
356
357   /* When all memory are back, put the group back in the free queue */
358   if (g_atomic_int_dec_and_test (&group->mems_allocated)) {
359     GST_LOG_OBJECT (allocator, "buffer %u released", group->buffer.index);
360     gst_atomic_queue_push (allocator->free_queue, group);
361     g_signal_emit (allocator, gst_v4l2_allocator_signals[GROUP_RELEASED], 0);
362   }
363
364   /* Keep last, allocator may be freed after this call */
365   g_object_unref (allocator);
366 }
367
368 static void
369 gst_v4l2_allocator_free (GstAllocator * gallocator, GstMemory * gmem)
370 {
371   GstV4l2Allocator *allocator = (GstV4l2Allocator *) gallocator;
372   GstV4l2Memory *mem = (GstV4l2Memory *) gmem;
373   GstV4l2MemoryGroup *group = mem->group;
374
375   GST_LOG_OBJECT (allocator, "freeing plane %i of buffer %u",
376       mem->plane, group->buffer.index);
377
378   switch (allocator->memory) {
379     case V4L2_MEMORY_MMAP:
380       if (mem->data) {
381         v4l2_munmap (mem->data, group->planes[mem->plane].length);
382       } else if (group->planes[mem->plane].m.fd > 0) {
383         close (group->planes[mem->plane].m.fd);
384       }
385       break;
386     default:
387       /* Nothing to do */
388       break;
389   }
390
391   _v4l2mem_free (mem);
392 }
393
394 static void
395 gst_v4l2_allocator_dispose (GObject * obj)
396 {
397   GstV4l2Allocator *allocator = (GstV4l2Allocator *) obj;
398   gint i;
399
400   GST_LOG_OBJECT (obj, "called");
401
402   for (i = 0; i < allocator->count; i++) {
403     GstV4l2MemoryGroup *group = allocator->groups[i];
404     allocator->groups[i] = NULL;
405     if (group)
406       gst_v4l2_memory_group_free (group);
407   }
408
409   G_OBJECT_CLASS (parent_class)->dispose (obj);
410 }
411
412 static void
413 gst_v4l2_allocator_finalize (GObject * obj)
414 {
415   GstV4l2Allocator *allocator = (GstV4l2Allocator *) obj;
416
417   GST_LOG_OBJECT (obj, "called");
418
419   v4l2_close (allocator->video_fd);
420   gst_atomic_queue_unref (allocator->free_queue);
421
422   G_OBJECT_CLASS (parent_class)->finalize (obj);
423 }
424
425 static void
426 gst_v4l2_allocator_class_init (GstV4l2AllocatorClass * klass)
427 {
428   GObjectClass *object_class;
429   GstAllocatorClass *allocator_class;
430
431   allocator_class = (GstAllocatorClass *) klass;
432   object_class = (GObjectClass *) klass;
433
434   allocator_class->alloc = NULL;
435   allocator_class->free = gst_v4l2_allocator_free;
436
437   object_class->dispose = gst_v4l2_allocator_dispose;
438   object_class->finalize = gst_v4l2_allocator_finalize;
439
440   gst_v4l2_allocator_signals[GROUP_RELEASED] = g_signal_new ("group-released",
441       G_TYPE_FROM_CLASS (object_class), G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL,
442       G_TYPE_NONE, 0);
443
444   GST_DEBUG_CATEGORY_INIT (v4l2allocator_debug, "v4l2allocator", 0,
445       "V4L2 Allocator");
446 }
447
448 static void
449 gst_v4l2_allocator_init (GstV4l2Allocator * allocator)
450 {
451   GstAllocator *alloc = GST_ALLOCATOR_CAST (allocator);
452
453   alloc->mem_type = GST_V4L2_MEMORY_TYPE;
454   alloc->mem_map = (GstMemoryMapFunction) _v4l2mem_map;
455   alloc->mem_unmap = (GstMemoryUnmapFunction) _v4l2mem_unmap;
456   alloc->mem_share = (GstMemoryShareFunction) _v4l2mem_share;
457   alloc->mem_is_span = (GstMemoryIsSpanFunction) _v4l2mem_is_span;
458   /* Use the default, fallback copy function */
459
460   allocator->free_queue = gst_atomic_queue_new (VIDEO_MAX_FRAME);
461
462   GST_OBJECT_FLAG_SET (allocator, GST_ALLOCATOR_FLAG_CUSTOM_ALLOC);
463 }
464
465 #define GST_V4L2_ALLOCATOR_PROBE(obj,type) \
466     gst_v4l2_allocator_probe ((obj), V4L2_MEMORY_ ## type, \
467         GST_V4L2_ALLOCATOR_FLAG_ ## type ## _REQBUFS, \
468         GST_V4L2_ALLOCATOR_FLAG_ ## type ## _CREATE_BUFS)
469 static guint32
470 gst_v4l2_allocator_probe (GstV4l2Allocator * allocator, guint32 memory,
471     guint32 breq_flag, guint32 bcreate_flag)
472 {
473   struct v4l2_requestbuffers breq = { 0 };
474   guint32 flags = 0;
475
476   breq.type = allocator->type;
477   breq.count = 0;
478   breq.memory = memory;
479
480   if (v4l2_ioctl (allocator->video_fd, VIDIOC_REQBUFS, &breq) == 0) {
481     struct v4l2_create_buffers bcreate = { 0 };
482
483     flags |= breq_flag;
484
485     bcreate.memory = V4L2_MEMORY_MMAP;
486     bcreate.format = allocator->format;
487
488     if ((v4l2_ioctl (allocator->video_fd, VIDIOC_CREATE_BUFS, &bcreate) == 0))
489       flags |= bcreate_flag;
490   }
491
492   return flags;
493 }
494
495 static GstV4l2MemoryGroup *
496 gst_v4l2_allocator_create_buf (GstV4l2Allocator * allocator)
497 {
498   struct v4l2_create_buffers bcreate = { 0 };
499   GstV4l2MemoryGroup *group = NULL;
500
501   GST_OBJECT_LOCK (allocator);
502
503   if (!allocator->active)
504     goto done;
505
506   bcreate.memory = allocator->memory;
507   bcreate.format = allocator->format;
508   bcreate.count = 1;
509
510   if (!allocator->can_allocate)
511     goto done;
512
513   if (v4l2_ioctl (allocator->video_fd, VIDIOC_CREATE_BUFS, &bcreate) < 0)
514     goto create_bufs_failed;
515
516   group = gst_v4l2_memory_group_new (allocator, bcreate.index);
517
518   if (group) {
519     allocator->groups[bcreate.index] = group;
520     allocator->count++;
521   }
522
523 done:
524   GST_OBJECT_UNLOCK (allocator);
525   return group;
526
527 create_bufs_failed:
528   {
529     GST_WARNING_OBJECT (allocator, "error creating a new buffer: %s",
530         g_strerror (errno));
531     goto done;
532   }
533 }
534
535 static GstV4l2MemoryGroup *
536 gst_v4l2_allocator_alloc (GstV4l2Allocator * allocator)
537 {
538   GstV4l2MemoryGroup *group;
539
540   if (!g_atomic_int_get (&allocator->active))
541     return NULL;
542
543   group = gst_atomic_queue_pop (allocator->free_queue);
544
545   if (group == NULL) {
546     if (allocator->can_allocate) {
547       group = gst_v4l2_allocator_create_buf (allocator);
548
549       /* Don't hammer on CREATE_BUFS */
550       if (group == NULL)
551         allocator->can_allocate = FALSE;
552     }
553   }
554
555   return group;
556 }
557
558 static void
559 gst_v4l2_allocator_reset_size (GstV4l2Allocator * allocator,
560     GstV4l2MemoryGroup * group)
561 {
562   gsize size;
563
564   if (V4L2_TYPE_IS_MULTIPLANAR (allocator->type)) {
565     gint i;
566
567     for (i = 0; i < group->n_mem; i++) {
568       size = allocator->format.fmt.pix_mp.plane_fmt[i].sizeimage;
569       gst_memory_resize (group->mem[i], 0, size);
570     }
571
572   } else {
573     size = allocator->format.fmt.pix.sizeimage;
574     gst_memory_resize (group->mem[0], 0, size);
575   }
576 }
577
578 static void
579 _cleanup_failed_alloc (GstV4l2Allocator * allocator, GstV4l2MemoryGroup * group)
580 {
581   if (group->mems_allocated > 0) {
582     gint i;
583     /* If one or more mmap worked, we need to unref the memory, otherwise
584      * they will keep a ref on the allocator and leak it. This will put back
585      * the group into the free_queue */
586     for (i = 0; i < group->n_mem; i++)
587       gst_memory_unref (group->mem[i]);
588   } else {
589     /* Otherwise, group has to be on free queue for _stop() to work */
590     gst_atomic_queue_push (allocator->free_queue, group);
591   }
592 }
593
594
595
596 GstV4l2Allocator *
597 gst_v4l2_allocator_new (GstObject * parent, gint video_fd,
598     struct v4l2_format *format)
599 {
600   GstV4l2Allocator *allocator;
601   guint32 flags = 0;
602   gchar *name, *parent_name;
603
604   parent_name = gst_object_get_name (parent);
605   name = g_strconcat (parent_name, ":allocator", NULL);
606   g_free (parent_name);
607
608   allocator = g_object_new (GST_TYPE_V4L2_ALLOCATOR, "name", name, NULL);
609   g_free (name);
610
611   /* Save everything */
612   allocator->video_fd = v4l2_dup (video_fd);
613   allocator->type = format->type;
614   allocator->format = *format;
615
616   flags |= GST_V4L2_ALLOCATOR_PROBE (allocator, MMAP);
617   flags |= GST_V4L2_ALLOCATOR_PROBE (allocator, USERPTR);
618   flags |= GST_V4L2_ALLOCATOR_PROBE (allocator, DMABUF);
619
620   GST_OBJECT_FLAG_SET (allocator, flags);
621
622   if (flags == 0)
623     goto not_supported;
624
625   return allocator;
626
627 not_supported:
628   {
629     GST_ERROR_OBJECT (allocator,
630         "No memory model supported by GStreamer for this device");
631     g_object_unref (allocator);
632     return NULL;
633   }
634 }
635
636 guint
637 gst_v4l2_allocator_start (GstV4l2Allocator * allocator, guint32 count,
638     guint32 memory)
639 {
640   struct v4l2_requestbuffers breq = { count, allocator->type, memory };
641   gboolean can_allocate;
642   gint i;
643
644   g_return_val_if_fail (count != 0, 0);
645
646   GST_OBJECT_LOCK (allocator);
647
648   if (allocator->active)
649     goto already_active;
650
651   if (v4l2_ioctl (allocator->video_fd, VIDIOC_REQBUFS, &breq) < 0)
652     goto reqbufs_failed;
653
654   if (breq.count < 1)
655     goto out_of_memory;
656
657   switch (memory) {
658     case V4L2_MEMORY_MMAP:
659       can_allocate = GST_V4L2_ALLOCATOR_CAN_ALLOCATE (allocator, MMAP);
660       break;
661     case V4L2_MEMORY_USERPTR:
662       can_allocate = GST_V4L2_ALLOCATOR_CAN_ALLOCATE (allocator, USERPTR);
663       break;
664     case V4L2_MEMORY_DMABUF:
665       can_allocate = GST_V4L2_ALLOCATOR_CAN_ALLOCATE (allocator, DMABUF);
666       break;
667     default:
668       can_allocate = FALSE;
669       break;
670   }
671
672   GST_DEBUG_OBJECT (allocator, "allocated %u %s buffers out of %u requested",
673       breq.count, memory_type_to_str (memory), count);
674
675   allocator->can_allocate = can_allocate;
676   allocator->count = breq.count;
677   allocator->memory = memory;
678
679   /* Create memory groups */
680   for (i = 0; i < allocator->count; i++) {
681     allocator->groups[i] = gst_v4l2_memory_group_new (allocator, i);
682     if (allocator->groups[i] == NULL)
683       goto error;
684
685     gst_atomic_queue_push (allocator->free_queue, allocator->groups[i]);
686   }
687
688   g_atomic_int_set (&allocator->active, TRUE);
689
690 done:
691   GST_OBJECT_UNLOCK (allocator);
692   return breq.count;
693
694 already_active:
695   {
696     GST_ERROR_OBJECT (allocator,
697         "error requesting %d buffers: %s", count, g_strerror (errno));
698     goto error;
699   }
700 reqbufs_failed:
701   {
702     GST_ERROR_OBJECT (allocator,
703         "error requesting %d buffers: %s", count, g_strerror (errno));
704     goto error;
705   }
706 out_of_memory:
707   {
708     GST_ERROR_OBJECT (allocator, "Not enough memory to allocate buffers");
709     goto error;
710   }
711 error:
712   {
713     breq.count = 0;
714     goto done;
715   }
716 }
717
718 GstV4l2Return
719 gst_v4l2_allocator_stop (GstV4l2Allocator * allocator)
720 {
721   struct v4l2_requestbuffers breq = { 0, allocator->type, allocator->memory };
722   gint i = 0;
723   GstV4l2Return ret = GST_V4L2_OK;
724
725   GST_DEBUG_OBJECT (allocator, "stop allocator");
726
727   GST_OBJECT_LOCK (allocator);
728
729   if (!allocator->active)
730     goto done;
731
732   if (gst_atomic_queue_length (allocator->free_queue) != allocator->count) {
733     GST_DEBUG_OBJECT (allocator, "allocator is still in use");
734     ret = GST_V4L2_BUSY;
735     goto done;
736   }
737
738   while (gst_atomic_queue_pop (allocator->free_queue)) {
739     /* nothing */
740   };
741
742   for (i = 0; i < allocator->count; i++) {
743     GstV4l2MemoryGroup *group = allocator->groups[i];
744     allocator->groups[i] = NULL;
745     if (group)
746       gst_v4l2_memory_group_free (group);
747   }
748
749   if (v4l2_ioctl (allocator->video_fd, VIDIOC_REQBUFS, &breq) < 0)
750     goto reqbufs_failed;
751
752   g_atomic_int_set (&allocator->active, FALSE);
753
754 done:
755   GST_OBJECT_UNLOCK (allocator);
756   return ret;
757
758 reqbufs_failed:
759   {
760     GST_ERROR_OBJECT (allocator,
761         "error releasing buffers buffers: %s", g_strerror (errno));
762     ret = GST_V4L2_ERROR;
763     goto done;
764   }
765 }
766
767 GstV4l2MemoryGroup *
768 gst_v4l2_allocator_alloc_mmap (GstV4l2Allocator * allocator)
769 {
770   GstV4l2MemoryGroup *group;
771   gint i;
772
773   g_return_val_if_fail (allocator->memory == V4L2_MEMORY_MMAP, NULL);
774
775   group = gst_v4l2_allocator_alloc (allocator);
776
777   if (group == NULL)
778     return NULL;
779
780   for (i = 0; i < group->n_mem; i++) {
781     if (group->mem[i] == NULL) {
782       gpointer data;
783       data = v4l2_mmap (NULL, group->planes[i].length, PROT_READ | PROT_WRITE,
784           MAP_SHARED, allocator->video_fd, group->planes[i].m.mem_offset);
785
786       if (data == MAP_FAILED)
787         goto mmap_failed;
788
789       GST_LOG_OBJECT (allocator,
790           "mmap buffer length %d, data offset %d, plane %d",
791           group->planes[i].length, group->planes[i].data_offset, i);
792
793       group->mem[i] = (GstMemory *) _v4l2mem_new (0, GST_ALLOCATOR (allocator),
794           NULL, group->planes[i].length, 0, 0, group->planes[i].length, i,
795           data, -1, group);
796     } else {
797       /* Take back the allocator reference */
798       gst_object_ref (allocator);
799     }
800
801     group->mems_allocated++;
802   }
803
804   /* Ensure group size. Unlike GST, v4l2 have size (bytesused) initially set
805    * to 0. As length might be bigger then the expected size exposed in the
806    * format, we simply set bytesused initially and reset it here for
807    * simplicity */
808   gst_v4l2_allocator_reset_size (allocator, group);
809
810   return group;
811
812 mmap_failed:
813   {
814     GST_ERROR_OBJECT (allocator, "Failed to mmap buffer: %s",
815         g_strerror (errno));
816     _cleanup_failed_alloc (allocator, group);
817     return NULL;
818   }
819 }
820
821 GstV4l2MemoryGroup *
822 gst_v4l2_allocator_alloc_dmabuf (GstV4l2Allocator * allocator,
823     GstAllocator * dmabuf_allocator)
824 {
825   GstV4l2MemoryGroup *group;
826   gint i;
827
828   g_return_val_if_fail (allocator->memory == V4L2_MEMORY_MMAP, NULL);
829
830   group = gst_v4l2_allocator_alloc (allocator);
831
832   if (group == NULL)
833     return NULL;
834
835   for (i = 0; i < group->n_mem; i++) {
836     GstV4l2Memory *mem;
837     GstMemory *dma_mem;
838     gint dmafd;
839
840     if (group->mem[i] == NULL) {
841       struct v4l2_exportbuffer expbuf = { 0 };
842
843       expbuf.type = allocator->type;
844       expbuf.index = group->buffer.index;
845       expbuf.plane = i;
846       expbuf.flags = O_CLOEXEC | O_RDWR;
847
848       if (v4l2_ioctl (allocator->video_fd, VIDIOC_EXPBUF, &expbuf) < 0)
849         goto expbuf_failed;
850
851       GST_LOG_OBJECT (allocator, "exported DMABUF as fd %i plane %d",
852           expbuf.fd, i);
853
854       group->mem[i] = (GstMemory *) _v4l2mem_new (0, GST_ALLOCATOR (allocator),
855           NULL, group->planes[i].length, 0, 0, group->planes[i].length, i,
856           NULL, expbuf.fd, group);
857     } else {
858       /* Take back the allocator reference */
859       gst_object_ref (allocator);
860     }
861
862     g_assert (gst_is_v4l2_memory (group->mem[i]));
863     mem = (GstV4l2Memory *) group->mem[i];
864
865     if ((dmafd = dup (mem->dmafd)) < 0)
866       goto dup_failed;
867
868     dma_mem = gst_dmabuf_allocator_alloc (dmabuf_allocator, dmafd,
869         mem->mem.maxsize);
870     _v4l2mem_parent_to_dmabuf (mem, dma_mem);
871
872     group->mem[i] = dma_mem;
873     group->mems_allocated++;
874   }
875
876   gst_v4l2_allocator_reset_size (allocator, group);
877
878   return group;
879
880 expbuf_failed:
881   {
882     GST_ERROR_OBJECT (allocator, "Failed to export DMABUF: %s",
883         g_strerror (errno));
884     goto cleanup;
885   }
886 dup_failed:
887   {
888     GST_ERROR_OBJECT (allocator, "Failed to dup DMABUF descriptor: %s",
889         g_strerror (errno));
890     goto cleanup;
891   }
892 cleanup:
893   {
894     _cleanup_failed_alloc (allocator, group);
895     return NULL;
896   }
897 }
898
899 static void
900 gst_v4l2_allocator_clear_dmabufin (GstV4l2Allocator * allocator,
901     GstV4l2MemoryGroup * group)
902 {
903   GstV4l2Memory *mem;
904   gint i;
905
906   g_return_if_fail (allocator->memory == V4L2_MEMORY_DMABUF);
907
908   for (i = 0; i < group->n_mem; i++) {
909
910     mem = (GstV4l2Memory *) group->mem[i];
911
912     GST_LOG_OBJECT (allocator, "clearing DMABUF import, fd %i plane %d",
913         mem->dmafd, i);
914
915     if (mem->dmafd >= 0)
916       close (mem->dmafd);
917
918     /* Update memory */
919     mem->mem.maxsize = 0;
920     mem->mem.offset = 0;
921     mem->mem.size = 0;
922     mem->dmafd = -1;
923
924     /* Update v4l2 structure */
925     group->planes[i].length = 0;
926     group->planes[i].bytesused = 0;
927     group->planes[i].m.fd = -1;
928     group->planes[i].data_offset = 0;
929   }
930
931   if (!V4L2_TYPE_IS_MULTIPLANAR (allocator->type)) {
932     group->buffer.bytesused = 0;
933     group->buffer.length = 0;
934     group->buffer.m.fd = -1;
935   }
936 }
937
938 GstV4l2MemoryGroup *
939 gst_v4l2_allocator_alloc_dmabufin (GstV4l2Allocator * allocator)
940 {
941   GstV4l2MemoryGroup *group;
942   gint i;
943
944   g_return_val_if_fail (allocator->memory == V4L2_MEMORY_DMABUF, NULL);
945
946   group = gst_v4l2_allocator_alloc (allocator);
947
948   if (group == NULL)
949     return NULL;
950
951   for (i = 0; i < group->n_mem; i++) {
952     GST_LOG_OBJECT (allocator, "allocation empty DMABUF import group");
953
954     if (group->mem[i] == NULL) {
955       group->mem[i] = (GstMemory *) _v4l2mem_new (0, GST_ALLOCATOR (allocator),
956           NULL, 0, 0, 0, 0, i, NULL, -1, group);
957     } else {
958       /* Take back the allocator reference */
959       gst_object_ref (allocator);
960     }
961
962     group->mems_allocated++;
963   }
964
965   gst_v4l2_allocator_clear_dmabufin (allocator, group);
966
967   return group;
968 }
969
970 static void
971 gst_v4l2_allocator_clear_userptr (GstV4l2Allocator * allocator,
972     GstV4l2MemoryGroup * group)
973 {
974   GstV4l2Memory *mem;
975   gint i;
976
977   g_return_if_fail (allocator->memory == V4L2_MEMORY_USERPTR);
978
979   for (i = 0; i < group->n_mem; i++) {
980     mem = (GstV4l2Memory *) group->mem[i];
981
982     GST_LOG_OBJECT (allocator, "clearing USERPTR %p plane %d size %"
983         G_GSIZE_FORMAT, mem->data, i, mem->mem.size);
984
985     mem->mem.maxsize = 0;
986     mem->mem.size = 0;
987     mem->data = NULL;
988
989     group->planes[i].length = 0;
990     group->planes[i].bytesused = 0;
991     group->planes[i].m.userptr = 0;
992   }
993
994   if (!V4L2_TYPE_IS_MULTIPLANAR (allocator->type)) {
995     group->buffer.bytesused = 0;
996     group->buffer.length = 0;
997     group->buffer.m.userptr = 0;
998   }
999 }
1000
1001 GstV4l2MemoryGroup *
1002 gst_v4l2_allocator_alloc_userptr (GstV4l2Allocator * allocator)
1003 {
1004   GstV4l2MemoryGroup *group;
1005   gint i;
1006
1007   g_return_val_if_fail (allocator->memory == V4L2_MEMORY_USERPTR, NULL);
1008
1009   group = gst_v4l2_allocator_alloc (allocator);
1010
1011   if (group == NULL)
1012     return NULL;
1013
1014   for (i = 0; i < group->n_mem; i++) {
1015
1016     GST_LOG_OBJECT (allocator, "allocating empty USERPTR group");
1017
1018     if (group->mem[i] == NULL) {
1019       group->mem[i] = (GstMemory *) _v4l2mem_new (0, GST_ALLOCATOR (allocator),
1020           NULL, 0, 0, 0, 0, i, NULL, -1, group);
1021     } else {
1022       /* Take back the allocator reference */
1023       gst_object_ref (allocator);
1024     }
1025
1026     group->mems_allocated++;
1027   }
1028
1029   gst_v4l2_allocator_clear_userptr (allocator, group);
1030
1031   return group;
1032 }
1033
1034 gboolean
1035 gst_v4l2_allocator_import_dmabuf (GstV4l2Allocator * allocator,
1036     GstV4l2MemoryGroup * group, gint n_mem, GstMemory ** dma_mem)
1037 {
1038   GstV4l2Memory *mem;
1039   gint i;
1040
1041   g_return_val_if_fail (allocator->memory == V4L2_MEMORY_DMABUF, FALSE);
1042
1043   if (group->n_mem != n_mem)
1044     goto n_mem_missmatch;
1045
1046   for (i = 0; i < group->n_mem; i++) {
1047     gint dmafd;
1048     gsize size, offset, maxsize;
1049
1050     if (!gst_is_dmabuf_memory (dma_mem[i]))
1051       goto not_dmabuf;
1052
1053     size = gst_memory_get_sizes (dma_mem[i], &offset, &maxsize);
1054
1055     if ((dmafd = dup (gst_dmabuf_memory_get_fd (dma_mem[i]))) < 0)
1056       goto dup_failed;
1057
1058     GST_LOG_OBJECT (allocator, "imported DMABUF as fd %i plane %d", dmafd, i);
1059
1060     mem = (GstV4l2Memory *) group->mem[i];
1061
1062     /* Update memory */
1063     mem->mem.maxsize = maxsize;
1064     mem->mem.offset = offset;
1065     mem->mem.size = size;
1066     mem->dmafd = dmafd;
1067
1068     /* Update v4l2 structure */
1069     group->planes[i].length = maxsize;
1070     group->planes[i].bytesused = size;
1071     group->planes[i].m.fd = dmafd;
1072     group->planes[i].data_offset = offset;
1073   }
1074
1075   /* Copy into buffer structure if not using planes */
1076   if (!V4L2_TYPE_IS_MULTIPLANAR (allocator->type)) {
1077     group->buffer.bytesused = group->planes[0].bytesused;
1078     group->buffer.length = group->planes[0].length;
1079     group->buffer.m.fd = group->planes[0].m.userptr;
1080   } else {
1081     group->buffer.length = group->n_mem;
1082   }
1083
1084   return TRUE;
1085
1086 n_mem_missmatch:
1087   {
1088     GST_ERROR_OBJECT (allocator, "Got %i dmabuf but needed %i", n_mem,
1089         group->n_mem);
1090     return FALSE;
1091   }
1092 not_dmabuf:
1093   {
1094     GST_ERROR_OBJECT (allocator, "Memory %i is not of DMABUF", i);
1095     return FALSE;
1096   }
1097 dup_failed:
1098   {
1099     GST_ERROR_OBJECT (allocator, "Failed to dup DMABUF descriptor: %s",
1100         g_strerror (errno));
1101     return FALSE;
1102   }
1103 }
1104
1105 gboolean
1106 gst_v4l2_allocator_import_userptr (GstV4l2Allocator * allocator,
1107     GstV4l2MemoryGroup * group, gsize img_size, int n_planes,
1108     gpointer * data, gsize * offset)
1109 {
1110   GstV4l2Memory *mem;
1111   gint i;
1112
1113   g_return_val_if_fail (allocator->memory == V4L2_MEMORY_USERPTR, FALSE);
1114
1115   /* TODO Support passing N plane from 1 memory to MPLANE v4l2 format */
1116   if (n_planes != group->n_mem)
1117     goto n_mem_missmatch;
1118
1119   for (i = 0; i < group->n_mem; i++) {
1120     gsize size, maxsize;
1121
1122     if (V4L2_TYPE_IS_MULTIPLANAR (allocator->type)) {
1123       struct v4l2_pix_format_mplane *pix = &allocator->format.fmt.pix_mp;
1124       maxsize = pix->plane_fmt[i].sizeimage;
1125     } else {
1126       maxsize = allocator->format.fmt.pix.sizeimage;
1127     }
1128
1129     if ((i + 1) == n_planes) {
1130       size = img_size - offset[i];
1131     } else {
1132       size = offset[i + 1] - offset[i];
1133     }
1134
1135     g_assert (size <= img_size);
1136
1137     GST_LOG_OBJECT (allocator, "imported USERPTR %p plane %d size %"
1138         G_GSIZE_FORMAT, data[i], i, size);
1139
1140     mem = (GstV4l2Memory *) group->mem[i];
1141
1142     mem->mem.maxsize = maxsize;
1143     mem->mem.size = size;
1144     mem->data = data[i];
1145
1146     group->planes[i].length = maxsize;
1147     group->planes[i].bytesused = size;
1148     group->planes[i].m.userptr = (unsigned long) data[i];
1149     group->planes[i].data_offset = 0;
1150   }
1151
1152   /* Copy into buffer structure if not using planes */
1153   if (!V4L2_TYPE_IS_MULTIPLANAR (allocator->type)) {
1154     group->buffer.bytesused = group->planes[0].bytesused;
1155     group->buffer.length = group->planes[0].length;
1156     group->buffer.m.userptr = group->planes[0].m.userptr;
1157   } else {
1158     group->buffer.length = group->n_mem;
1159   }
1160
1161   return TRUE;
1162
1163 n_mem_missmatch:
1164   {
1165     GST_ERROR_OBJECT (allocator, "Got %i userptr plane while driver need %i",
1166         n_planes, group->n_mem);
1167     return FALSE;
1168   }
1169 }
1170
1171 void
1172 gst_v4l2_allocator_flush (GstV4l2Allocator * allocator)
1173 {
1174   gint i;
1175
1176   GST_OBJECT_LOCK (allocator);
1177
1178   if (!allocator->active)
1179     goto done;
1180
1181   for (i = 0; i < allocator->count; i++) {
1182     GstV4l2MemoryGroup *group = allocator->groups[i];
1183     gint n;
1184
1185     if (IS_QUEUED (group->buffer)) {
1186       UNSET_QUEUED (group->buffer);
1187
1188       for (n = 0; n < group->n_mem; n++)
1189         gst_memory_unref (group->mem[n]);
1190     }
1191   }
1192
1193 done:
1194   GST_OBJECT_UNLOCK (allocator);
1195 }
1196
1197 gboolean
1198 gst_v4l2_allocator_qbuf (GstV4l2Allocator * allocator,
1199     GstV4l2MemoryGroup * group)
1200 {
1201   gboolean ret = TRUE;
1202   gint i;
1203
1204   /* update sizes */
1205   if (V4L2_TYPE_IS_MULTIPLANAR (allocator->type)) {
1206     for (i = 0; i < group->n_mem; i++)
1207       group->planes[i].bytesused =
1208           gst_memory_get_sizes (group->mem[i], NULL, NULL);
1209   } else {
1210     group->buffer.bytesused = gst_memory_get_sizes (group->mem[0], NULL, NULL);
1211   }
1212
1213   if (v4l2_ioctl (allocator->video_fd, VIDIOC_QBUF, &group->buffer) < 0) {
1214     GST_ERROR_OBJECT (allocator, "failed queing buffer %i: %s",
1215         group->buffer.index, g_strerror (errno));
1216     ret = FALSE;
1217     if (IS_QUEUED (group->buffer)) {
1218       GST_DEBUG_OBJECT (allocator,
1219           "driver pretends buffer is queued even if queue failed");
1220       UNSET_QUEUED (group->buffer);
1221     }
1222     goto done;
1223   }
1224
1225   GST_LOG_OBJECT (allocator, "queued buffer %i (flags 0x%X)",
1226       group->buffer.index, group->buffer.flags);
1227
1228   if (!IS_QUEUED (group->buffer)) {
1229     GST_DEBUG_OBJECT (allocator,
1230         "driver pretends buffer is not queued even if queue succeeded");
1231     SET_QUEUED (group->buffer);
1232   }
1233
1234   /* Ensure the memory will stay around and is RO */
1235   for (i = 0; i < group->n_mem; i++)
1236     gst_memory_ref (group->mem[i]);
1237
1238 done:
1239   return ret;
1240 }
1241
1242 GstV4l2MemoryGroup *
1243 gst_v4l2_allocator_dqbuf (GstV4l2Allocator * allocator)
1244 {
1245   struct v4l2_buffer buffer = { 0 };
1246   struct v4l2_plane planes[VIDEO_MAX_PLANES] = { {0} };
1247   gint i;
1248
1249   GstV4l2MemoryGroup *group = NULL;
1250
1251   buffer.type = allocator->type;
1252   buffer.memory = allocator->memory;
1253
1254   if (V4L2_TYPE_IS_MULTIPLANAR (allocator->type)) {
1255     buffer.length = allocator->format.fmt.pix_mp.num_planes;
1256     buffer.m.planes = planes;
1257   }
1258
1259   if (v4l2_ioctl (allocator->video_fd, VIDIOC_DQBUF, &buffer) < 0)
1260     goto error;
1261
1262   group = allocator->groups[buffer.index];
1263   group->buffer = buffer;
1264
1265   GST_LOG_OBJECT (allocator, "dequeued buffer %i (flags 0x%X)", buffer.index,
1266       buffer.flags);
1267
1268   if (IS_QUEUED (group->buffer)) {
1269     GST_DEBUG_OBJECT (allocator,
1270         "driver pretends buffer is queued even if dequeue succeeded");
1271     UNSET_QUEUED (group->buffer);
1272   }
1273
1274   if (V4L2_TYPE_IS_MULTIPLANAR (allocator->type)) {
1275     group->buffer.m.planes = group->planes;
1276     memcpy (group->planes, buffer.m.planes, sizeof (planes));
1277   } else {
1278     group->planes[0].bytesused = group->buffer.bytesused;
1279     group->planes[0].length = group->buffer.length;
1280     g_assert (sizeof (group->planes[0].m) == sizeof (group->buffer.m));
1281     memcpy (&group->planes[0].m, &group->buffer.m, sizeof (group->buffer.m));
1282   }
1283
1284   /* And update memory size */
1285   if (V4L2_TYPE_IS_OUTPUT (allocator->type)) {
1286     gst_v4l2_allocator_reset_size (allocator, group);
1287   } else {
1288     /* for capture, simply read the size */
1289     for (i = 0; i < group->n_mem; i++) {
1290       gst_memory_resize (group->mem[i], 0, group->planes[i].bytesused);
1291     }
1292   }
1293
1294   /* Release the memory, possibly making it RW again */
1295   for (i = 0; i < group->n_mem; i++)
1296     gst_memory_unref (group->mem[i]);
1297
1298   return group;
1299
1300 error:
1301   GST_ERROR_OBJECT (allocator, "failed dequeuing a %s buffer: %s",
1302       memory_type_to_str (allocator->memory), g_strerror (errno));
1303
1304   switch (errno) {
1305     case EAGAIN:
1306       GST_WARNING_OBJECT (allocator,
1307           "Non-blocking I/O has been selected using O_NONBLOCK and"
1308           " no buffer was in the outgoing queue.");
1309       break;
1310     case EINVAL:
1311       GST_ERROR_OBJECT (allocator,
1312           "The buffer type is not supported, or the index is out of bounds, "
1313           "or no buffers have been allocated yet, or the userptr "
1314           "or length are invalid.");
1315       break;
1316     case ENOMEM:
1317       GST_ERROR_OBJECT (allocator,
1318           "insufficient memory to enqueue a user pointer buffer");
1319       break;
1320     case EIO:
1321       GST_INFO_OBJECT (allocator,
1322           "VIDIOC_DQBUF failed due to an internal error."
1323           " Can also indicate temporary problems like signal loss."
1324           " Note the driver might dequeue an (empty) buffer despite"
1325           " returning an error, or even stop capturing.");
1326       /* have we de-queued a buffer ? */
1327       if (!IS_QUEUED (buffer)) {
1328         GST_DEBUG_OBJECT (allocator, "reenqueing buffer");
1329         /* FIXME ... should we do something here? */
1330       }
1331       break;
1332     case EINTR:
1333       GST_WARNING_OBJECT (allocator, "could not sync on a buffer on device");
1334       break;
1335     default:
1336       GST_WARNING_OBJECT (allocator,
1337           "Grabbing frame got interrupted unexpectedly. %d: %s.", errno,
1338           g_strerror (errno));
1339       break;
1340   }
1341
1342   return NULL;
1343 }
1344
1345 void
1346 gst_v4l2_allocator_reset_group (GstV4l2Allocator * allocator,
1347     GstV4l2MemoryGroup * group)
1348 {
1349   switch (allocator->memory) {
1350     case V4L2_MEMORY_USERPTR:
1351       gst_v4l2_allocator_clear_userptr (allocator, group);
1352       break;
1353     case V4L2_MEMORY_DMABUF:
1354       gst_v4l2_allocator_clear_dmabufin (allocator, group);
1355       break;
1356     case V4L2_MEMORY_MMAP:
1357       gst_v4l2_allocator_reset_size (allocator, group);
1358       break;
1359     default:
1360       g_assert_not_reached ();
1361       break;
1362   }
1363 }