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