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