Merge branch 'move_subdir_good' into tizen_gst_1.19.2_mono
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-good / sys / v4l2 / gstv4l2bufferpool.c
1 /* GStreamer
2  *
3  * Copyright (C) 2001-2002 Ronald Bultje <rbultje@ronald.bitfreak.net>
4  *               2006 Edgard Lima <edgard.lima@gmail.com>
5  *               2009 Texas Instruments, Inc - http://www.ti.com/
6  *
7  * gstv4l2bufferpool.c V4L2 buffer pool class
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public
20  * License along with this library; if not, write to the
21  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
22  * Boston, MA 02110-1301, USA.
23  */
24
25 #ifdef HAVE_CONFIG_H
26 #  include <config.h>
27 #endif
28
29 #ifndef _GNU_SOURCE
30 # define _GNU_SOURCE            /* O_CLOEXEC */
31 #endif
32 #include <fcntl.h>
33
34 #include <sys/mman.h>
35 #include <string.h>
36 #include <unistd.h>
37
38 #include "gst/video/video.h"
39 #include "gst/video/gstvideometa.h"
40 #include "gst/video/gstvideopool.h"
41 #include "gst/allocators/gstdmabuf.h"
42
43 #include <gstv4l2bufferpool.h>
44
45 #include "gstv4l2object.h"
46 #include "gst/gst-i18n-plugin.h"
47 #include <gst/glib-compat-private.h>
48 #ifdef TIZEN_FEATURE_V4L2_TBM_SUPPORT
49 #include <gst/allocators/gsttizenmemory.h>
50 #endif /* TIZEN_FEATURE_V4L2_TBM_SUPPORT */
51
52 GST_DEBUG_CATEGORY_STATIC (v4l2bufferpool_debug);
53 GST_DEBUG_CATEGORY_STATIC (CAT_PERFORMANCE);
54 #define GST_CAT_DEFAULT v4l2bufferpool_debug
55
56 #define GST_V4L2_IMPORT_QUARK gst_v4l2_buffer_pool_import_quark ()
57
58 /*
59  * GstV4l2BufferPool:
60  */
61 #define gst_v4l2_buffer_pool_parent_class parent_class
62 G_DEFINE_TYPE (GstV4l2BufferPool, gst_v4l2_buffer_pool, GST_TYPE_BUFFER_POOL);
63
64 enum _GstV4l2BufferPoolAcquireFlags
65 {
66   GST_V4L2_BUFFER_POOL_ACQUIRE_FLAG_RESURRECT =
67       GST_BUFFER_POOL_ACQUIRE_FLAG_LAST,
68   GST_V4L2_BUFFER_POOL_ACQUIRE_FLAG_LAST
69 };
70
71 static void gst_v4l2_buffer_pool_release_buffer (GstBufferPool * bpool,
72     GstBuffer * buffer);
73 #ifdef TIZEN_FEATURE_V4L2_TBM_SUPPORT
74 typedef struct _GstV4l2TizenBuffer GstV4l2TizenBuffer;
75 struct _GstV4l2TizenBuffer {
76   int index;
77   GstBuffer *gst_buffer;
78   GstBuffer *v4l2_buffer;
79   GstV4l2BufferPool *v4l2_pool;
80 };
81
82 static void gst_v4l2_tizen_buffer_finalize (GstV4l2TizenBuffer *tizen_buffer)
83 {
84   GstV4l2BufferPool *pool = NULL;
85
86   if (!tizen_buffer) {
87     GST_ERROR ("NULL buffer");
88     return;
89   }
90
91   pool = tizen_buffer->v4l2_pool;
92
93   gst_v4l2_buffer_pool_release_buffer (GST_BUFFER_POOL_CAST (pool), tizen_buffer->v4l2_buffer);
94
95   g_mutex_lock (&pool->buffer_lock);
96
97   pool->live_buffer_count--;
98
99   GST_DEBUG_OBJECT (pool, "release buffer[%d][tizen:%p,v4l2:%p,gst:%p], live[%d]",
100       tizen_buffer->index, tizen_buffer, tizen_buffer->v4l2_buffer,
101       tizen_buffer->gst_buffer, pool->live_buffer_count);
102
103   g_cond_signal (&pool->buffer_cond);
104
105   g_mutex_unlock (&pool->buffer_lock);
106
107   gst_object_unref (pool);
108
109   g_free(tizen_buffer);
110 }
111
112 static GstV4l2TizenBuffer *gst_v4l2_tizen_buffer_new (GstBuffer *v4l2_buffer, int index, GstV4l2BufferPool *v4l2_pool)
113 {
114   GstV4l2TizenBuffer *tizen_buffer = NULL;
115   GstMemory *memory = NULL;
116
117   tizen_buffer = g_new0 (GstV4l2TizenBuffer, 1);
118   tizen_buffer->index = index;
119   tizen_buffer->v4l2_buffer = v4l2_buffer;
120   tizen_buffer->gst_buffer = gst_buffer_new ();
121   tizen_buffer->v4l2_pool = gst_object_ref (v4l2_pool);
122
123   memory = gst_tizen_allocator_alloc_surface (v4l2_pool->tallocator,
124       &v4l2_pool->obj->info, v4l2_pool->vallocator->groups[index]->surface, (gpointer)tizen_buffer,
125       (GDestroyNotify)gst_v4l2_tizen_buffer_finalize);
126
127   gst_buffer_append_memory (tizen_buffer->gst_buffer, memory);
128   gst_buffer_set_size (tizen_buffer->gst_buffer, v4l2_pool->vallocator->s_info.size);
129
130   g_mutex_lock (&v4l2_pool->buffer_lock);
131
132   v4l2_pool->live_buffer_count++;
133
134   GST_DEBUG_OBJECT (v4l2_pool, "new buffer[tizen:%p,v4l2:%p,gst:%p], size[%d], live[%d]",
135       tizen_buffer, v4l2_buffer, tizen_buffer->gst_buffer,
136       v4l2_pool->vallocator->s_info.size, v4l2_pool->live_buffer_count);
137
138   g_mutex_unlock (&v4l2_pool->buffer_lock);
139
140   return tizen_buffer;
141 }
142 #endif /* TIZEN_FEATURE_V4L2_TBM_SUPPORT */
143
144 static gboolean
145 gst_v4l2_is_buffer_valid (GstBuffer * buffer, GstV4l2MemoryGroup ** out_group)
146 {
147   GstMemory *mem = gst_buffer_peek_memory (buffer, 0);
148   gboolean valid = FALSE;
149
150   if (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_TAG_MEMORY))
151     goto done;
152
153   if (gst_is_dmabuf_memory (mem))
154     mem = gst_mini_object_get_qdata (GST_MINI_OBJECT (mem),
155         GST_V4L2_MEMORY_QUARK);
156
157   if (mem && gst_is_v4l2_memory (mem)) {
158     GstV4l2Memory *vmem = (GstV4l2Memory *) mem;
159     GstV4l2MemoryGroup *group = vmem->group;
160     gint i;
161
162     if (group->n_mem != gst_buffer_n_memory (buffer))
163       goto done;
164
165     for (i = 0; i < group->n_mem; i++) {
166       if (group->mem[i] != gst_buffer_peek_memory (buffer, i))
167         goto done;
168
169       if (!gst_memory_is_writable (group->mem[i]))
170         goto done;
171     }
172
173     valid = TRUE;
174     if (out_group)
175       *out_group = group;
176   }
177
178 done:
179   return valid;
180 }
181
182 static GstFlowReturn
183 gst_v4l2_buffer_pool_copy_buffer (GstV4l2BufferPool * pool, GstBuffer * dest,
184     GstBuffer * src)
185 {
186   const GstVideoFormatInfo *finfo = pool->caps_info.finfo;
187
188   GST_LOG_OBJECT (pool, "copying buffer");
189
190   if (finfo && (finfo->format != GST_VIDEO_FORMAT_UNKNOWN &&
191           finfo->format != GST_VIDEO_FORMAT_ENCODED)) {
192     GstVideoFrame src_frame, dest_frame;
193
194     GST_DEBUG_OBJECT (pool, "copy video frame");
195
196     /* we have raw video, use videoframe copy to get strides right */
197     if (!gst_video_frame_map (&src_frame, &pool->caps_info, src, GST_MAP_READ))
198       goto invalid_buffer;
199
200     if (!gst_video_frame_map (&dest_frame, &pool->caps_info, dest,
201             GST_MAP_WRITE)) {
202       gst_video_frame_unmap (&src_frame);
203       goto invalid_buffer;
204     }
205
206     gst_video_frame_copy (&dest_frame, &src_frame);
207
208     gst_video_frame_unmap (&src_frame);
209     gst_video_frame_unmap (&dest_frame);
210   } else {
211     GstMapInfo map;
212
213     GST_DEBUG_OBJECT (pool, "copy raw bytes");
214
215     if (!gst_buffer_map (src, &map, GST_MAP_READ))
216       goto invalid_buffer;
217
218     gst_buffer_fill (dest, 0, map.data, gst_buffer_get_size (src));
219
220     gst_buffer_unmap (src, &map);
221     gst_buffer_resize (dest, 0, gst_buffer_get_size (src));
222   }
223
224   gst_buffer_copy_into (dest, src,
225       GST_BUFFER_COPY_FLAGS | GST_BUFFER_COPY_TIMESTAMPS, 0, -1);
226
227   GST_CAT_LOG_OBJECT (CAT_PERFORMANCE, pool, "slow copy into buffer %p", dest);
228
229   return GST_FLOW_OK;
230
231 invalid_buffer:
232   {
233     GST_ERROR_OBJECT (pool, "could not map buffer");
234     return GST_FLOW_ERROR;
235   }
236 }
237
238 struct UserPtrData
239 {
240   GstBuffer *buffer;
241   gboolean is_frame;
242   GstVideoFrame frame;
243   GstMapInfo map;
244 };
245
246 static GQuark
247 gst_v4l2_buffer_pool_import_quark (void)
248 {
249   static GQuark quark = 0;
250
251   if (quark == 0)
252     quark = g_quark_from_string ("GstV4l2BufferPoolUsePtrData");
253
254   return quark;
255 }
256
257 static void
258 _unmap_userptr_frame (struct UserPtrData *data)
259 {
260   if (data->is_frame)
261     gst_video_frame_unmap (&data->frame);
262   else
263     gst_buffer_unmap (data->buffer, &data->map);
264
265   if (data->buffer)
266     gst_buffer_unref (data->buffer);
267
268   g_slice_free (struct UserPtrData, data);
269 }
270
271 static GstFlowReturn
272 gst_v4l2_buffer_pool_import_userptr (GstV4l2BufferPool * pool,
273     GstBuffer * dest, GstBuffer * src)
274 {
275   GstFlowReturn ret = GST_FLOW_OK;
276   GstV4l2MemoryGroup *group = NULL;
277   GstMapFlags flags;
278   const GstVideoFormatInfo *finfo = pool->caps_info.finfo;
279   struct UserPtrData *data = NULL;
280
281   GST_LOG_OBJECT (pool, "importing userptr");
282
283   /* get the group */
284   if (!gst_v4l2_is_buffer_valid (dest, &group))
285     goto not_our_buffer;
286
287   if (V4L2_TYPE_IS_OUTPUT (pool->obj->type))
288     flags = GST_MAP_READ;
289   else
290     flags = GST_MAP_WRITE;
291
292   data = g_slice_new0 (struct UserPtrData);
293
294   if (finfo && (finfo->format != GST_VIDEO_FORMAT_UNKNOWN &&
295           finfo->format != GST_VIDEO_FORMAT_ENCODED)) {
296     gsize size[GST_VIDEO_MAX_PLANES] = { 0, };
297     gint i;
298
299     data->is_frame = TRUE;
300
301     if (!gst_video_frame_map (&data->frame, &pool->caps_info, src, flags))
302       goto invalid_buffer;
303
304     for (i = 0; i < GST_VIDEO_FORMAT_INFO_N_PLANES (finfo); i++) {
305       if (GST_VIDEO_FORMAT_INFO_IS_TILED (finfo)) {
306         gint tinfo = GST_VIDEO_FRAME_PLANE_STRIDE (&data->frame, i);
307         gint pstride;
308         guint pheight;
309
310         pstride = GST_VIDEO_TILE_X_TILES (tinfo) <<
311             GST_VIDEO_FORMAT_INFO_TILE_WS (finfo);
312
313         pheight = GST_VIDEO_TILE_Y_TILES (tinfo) <<
314             GST_VIDEO_FORMAT_INFO_TILE_HS (finfo);
315
316         size[i] = pstride * pheight;
317       } else {
318         size[i] = GST_VIDEO_FRAME_PLANE_STRIDE (&data->frame, i) *
319             GST_VIDEO_FRAME_COMP_HEIGHT (&data->frame, i);
320       }
321     }
322
323     /* In the single planar API, planes must be contiguous in memory and
324      * therefore they must have expected size. ie: no padding.
325      * To check these conditions, we check that plane 'i' start address
326      * + plane 'i' size equals to plane 'i+1' start address */
327     if (!V4L2_TYPE_IS_MULTIPLANAR (pool->obj->type)) {
328       for (i = 0; i < (GST_VIDEO_FORMAT_INFO_N_PLANES (finfo) - 1); i++) {
329         const struct v4l2_pix_format *pix_fmt = &pool->obj->format.fmt.pix;
330         gpointer tmp;
331         gint estride = gst_v4l2_object_extrapolate_stride (finfo, i,
332             pix_fmt->bytesperline);
333         guint eheight = GST_VIDEO_FORMAT_INFO_SCALE_HEIGHT (finfo, i,
334             pix_fmt->height);
335
336         tmp = ((guint8 *) data->frame.data[i]) + estride * eheight;
337         if (tmp != data->frame.data[i + 1])
338           goto non_contiguous_mem;
339       }
340     }
341
342     if (!gst_v4l2_allocator_import_userptr (pool->vallocator, group,
343             data->frame.info.size, finfo->n_planes, data->frame.data, size))
344       goto import_failed;
345   } else {
346     gpointer ptr[1];
347     gsize size[1];
348
349     data->is_frame = FALSE;
350
351     if (!gst_buffer_map (src, &data->map, flags))
352       goto invalid_buffer;
353
354     ptr[0] = data->map.data;
355     size[0] = data->map.size;
356
357     if (!gst_v4l2_allocator_import_userptr (pool->vallocator, group,
358             data->map.size, 1, ptr, size))
359       goto import_failed;
360   }
361
362   data->buffer = gst_buffer_ref (src);
363
364   gst_mini_object_set_qdata (GST_MINI_OBJECT (dest), GST_V4L2_IMPORT_QUARK,
365       data, (GDestroyNotify) _unmap_userptr_frame);
366
367   gst_buffer_copy_into (dest, src,
368       GST_BUFFER_COPY_FLAGS | GST_BUFFER_COPY_TIMESTAMPS, 0, -1);
369
370   return ret;
371
372 not_our_buffer:
373   {
374     GST_ERROR_OBJECT (pool, "destination buffer invalid or not from our pool");
375     return GST_FLOW_ERROR;
376   }
377 invalid_buffer:
378   {
379     GST_ERROR_OBJECT (pool, "could not map buffer");
380     g_slice_free (struct UserPtrData, data);
381     return GST_FLOW_ERROR;
382   }
383 non_contiguous_mem:
384   {
385     GST_ERROR_OBJECT (pool, "memory is not contiguous or plane size mismatch");
386     _unmap_userptr_frame (data);
387     return GST_FLOW_ERROR;
388   }
389 import_failed:
390   {
391     GST_ERROR_OBJECT (pool, "failed to import data");
392     _unmap_userptr_frame (data);
393     return GST_FLOW_ERROR;
394   }
395 }
396
397 static GstFlowReturn
398 gst_v4l2_buffer_pool_import_dmabuf (GstV4l2BufferPool * pool,
399     GstBuffer * dest, GstBuffer * src)
400 {
401   GstV4l2MemoryGroup *group = NULL;
402   GstMemory *dma_mem[GST_VIDEO_MAX_PLANES] = { 0 };
403   guint n_mem = gst_buffer_n_memory (src);
404   gint i;
405
406   GST_LOG_OBJECT (pool, "importing dmabuf");
407
408   if (!gst_v4l2_is_buffer_valid (dest, &group))
409     goto not_our_buffer;
410
411   if (n_mem > GST_VIDEO_MAX_PLANES)
412     goto too_many_mems;
413
414   for (i = 0; i < n_mem; i++)
415     dma_mem[i] = gst_buffer_peek_memory (src, i);
416
417   if (!gst_v4l2_allocator_import_dmabuf (pool->vallocator, group, n_mem,
418           dma_mem))
419     goto import_failed;
420
421   gst_mini_object_set_qdata (GST_MINI_OBJECT (dest), GST_V4L2_IMPORT_QUARK,
422       gst_buffer_ref (src), (GDestroyNotify) gst_buffer_unref);
423
424   gst_buffer_copy_into (dest, src,
425       GST_BUFFER_COPY_FLAGS | GST_BUFFER_COPY_TIMESTAMPS, 0, -1);
426
427   return GST_FLOW_OK;
428
429 not_our_buffer:
430   {
431     GST_ERROR_OBJECT (pool, "destination buffer invalid or not from our pool");
432     return GST_FLOW_ERROR;
433   }
434 too_many_mems:
435   {
436     GST_ERROR_OBJECT (pool, "could not map buffer");
437     return GST_FLOW_ERROR;
438   }
439 import_failed:
440   {
441     GST_ERROR_OBJECT (pool, "failed to import dmabuf");
442     return GST_FLOW_ERROR;
443   }
444 }
445
446 static GstFlowReturn
447 gst_v4l2_buffer_pool_prepare_buffer (GstV4l2BufferPool * pool,
448     GstBuffer * dest, GstBuffer * src)
449 {
450   GstFlowReturn ret = GST_FLOW_OK;
451   gboolean own_src = FALSE;
452
453   if (src == NULL) {
454     if (pool->other_pool == NULL) {
455       GST_ERROR_OBJECT (pool, "can't prepare buffer, source buffer missing");
456       return GST_FLOW_ERROR;
457     }
458
459     ret = gst_buffer_pool_acquire_buffer (pool->other_pool, &src, NULL);
460     if (ret != GST_FLOW_OK) {
461       GST_ERROR_OBJECT (pool, "failed to acquire buffer from downstream pool");
462       goto done;
463     }
464
465     own_src = TRUE;
466   }
467
468   switch (pool->obj->mode) {
469     case GST_V4L2_IO_MMAP:
470     case GST_V4L2_IO_DMABUF:
471       ret = gst_v4l2_buffer_pool_copy_buffer (pool, dest, src);
472       break;
473     case GST_V4L2_IO_USERPTR:
474       ret = gst_v4l2_buffer_pool_import_userptr (pool, dest, src);
475       break;
476     case GST_V4L2_IO_DMABUF_IMPORT:
477       ret = gst_v4l2_buffer_pool_import_dmabuf (pool, dest, src);
478       break;
479     default:
480       break;
481   }
482
483   if (own_src)
484     gst_buffer_unref (src);
485
486 done:
487   return ret;
488 }
489
490 static GstFlowReturn
491 gst_v4l2_buffer_pool_alloc_buffer (GstBufferPool * bpool, GstBuffer ** buffer,
492     GstBufferPoolAcquireParams * params)
493 {
494   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
495   GstV4l2MemoryGroup *group = NULL;
496   GstBuffer *newbuf = NULL;
497   GstV4l2Object *obj;
498   GstVideoInfo *info;
499
500   obj = pool->obj;
501   info = &obj->info;
502
503   switch (obj->mode) {
504     case GST_V4L2_IO_RW:
505       newbuf =
506           gst_buffer_new_allocate (pool->allocator, pool->size, &pool->params);
507       break;
508     case GST_V4L2_IO_MMAP:
509       group = gst_v4l2_allocator_alloc_mmap (pool->vallocator);
510       break;
511     case GST_V4L2_IO_DMABUF:
512       group = gst_v4l2_allocator_alloc_dmabuf (pool->vallocator,
513           pool->allocator);
514       break;
515     case GST_V4L2_IO_USERPTR:
516       group = gst_v4l2_allocator_alloc_userptr (pool->vallocator);
517       break;
518     case GST_V4L2_IO_DMABUF_IMPORT:
519       group = gst_v4l2_allocator_alloc_dmabufin (pool->vallocator);
520       break;
521     default:
522       newbuf = NULL;
523       g_assert_not_reached ();
524       break;
525   }
526
527   if (group != NULL) {
528     gint i;
529     newbuf = gst_buffer_new ();
530
531     for (i = 0; i < group->n_mem; i++)
532       gst_buffer_append_memory (newbuf, group->mem[i]);
533   } else if (newbuf == NULL) {
534     goto allocation_failed;
535   }
536
537   /* add metadata to raw video buffers */
538   if (pool->add_videometa)
539     gst_buffer_add_video_meta_full (newbuf, GST_VIDEO_FRAME_FLAG_NONE,
540         GST_VIDEO_INFO_FORMAT (info), GST_VIDEO_INFO_WIDTH (info),
541         GST_VIDEO_INFO_HEIGHT (info), GST_VIDEO_INFO_N_PLANES (info),
542         info->offset, info->stride);
543
544   *buffer = newbuf;
545
546   return GST_FLOW_OK;
547
548   /* ERRORS */
549 allocation_failed:
550   {
551     GST_ERROR_OBJECT (pool, "failed to allocate buffer");
552     return GST_FLOW_ERROR;
553   }
554 }
555
556 static gboolean
557 gst_v4l2_buffer_pool_set_config (GstBufferPool * bpool, GstStructure * config)
558 {
559   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
560   GstV4l2Object *obj = pool->obj;
561   GstCaps *caps;
562   guint size, min_buffers, max_buffers;
563   GstAllocator *allocator;
564   GstAllocationParams params;
565   gboolean can_allocate = FALSE;
566   gboolean updated = FALSE;
567   gboolean ret;
568
569   pool->add_videometa =
570       gst_buffer_pool_config_has_option (config,
571       GST_BUFFER_POOL_OPTION_VIDEO_META);
572
573   /* parse the config and keep around */
574   if (!gst_buffer_pool_config_get_params (config, &caps, &size, &min_buffers,
575           &max_buffers))
576     goto wrong_config;
577
578   if (!gst_buffer_pool_config_get_allocator (config, &allocator, &params))
579     goto wrong_config;
580
581   GST_DEBUG_OBJECT (pool, "config %" GST_PTR_FORMAT, config);
582
583   if (pool->allocator)
584     gst_object_unref (pool->allocator);
585   pool->allocator = NULL;
586
587   switch (obj->mode) {
588     case GST_V4L2_IO_DMABUF:
589       pool->allocator = gst_dmabuf_allocator_new ();
590       can_allocate = GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, MMAP);
591       break;
592     case GST_V4L2_IO_MMAP:
593       can_allocate = GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, MMAP);
594       break;
595     case GST_V4L2_IO_USERPTR:
596       can_allocate =
597           GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, USERPTR);
598       break;
599     case GST_V4L2_IO_DMABUF_IMPORT:
600       can_allocate = GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, DMABUF);
601       break;
602     case GST_V4L2_IO_RW:
603       if (allocator)
604         pool->allocator = g_object_ref (allocator);
605       pool->params = params;
606       /* No need to change the configuration */
607       goto done;
608       break;
609     default:
610       g_assert_not_reached ();
611       break;
612   }
613
614   /* libv4l2 conversion code does not handle CREATE_BUFS, and may lead to
615    * instability and crash, disable it for now */
616   if (can_allocate && obj->fmtdesc->flags & V4L2_FMT_FLAG_EMULATED) {
617     GST_WARNING_OBJECT (pool,
618         "libv4l2 converter detected, disabling CREATE_BUFS");
619     can_allocate = FALSE;
620     GST_OBJECT_FLAG_UNSET (pool->vallocator,
621         GST_V4L2_ALLOCATOR_FLAG_MMAP_CREATE_BUFS
622         | GST_V4L2_ALLOCATOR_FLAG_USERPTR_CREATE_BUFS
623         | GST_V4L2_ALLOCATOR_FLAG_DMABUF_CREATE_BUFS);
624   }
625
626   if (min_buffers < GST_V4L2_MIN_BUFFERS (obj)) {
627     updated = TRUE;
628     min_buffers = GST_V4L2_MIN_BUFFERS (obj);
629     GST_INFO_OBJECT (pool, "increasing minimum buffers to %u", min_buffers);
630   }
631
632   /* respect driver requirements */
633   if (min_buffers < obj->min_buffers) {
634     updated = TRUE;
635     min_buffers = obj->min_buffers;
636     GST_INFO_OBJECT (pool, "increasing minimum buffers to %u", min_buffers);
637   }
638
639   if (max_buffers > VIDEO_MAX_FRAME || max_buffers == 0) {
640     updated = TRUE;
641     max_buffers = VIDEO_MAX_FRAME;
642     GST_INFO_OBJECT (pool, "reducing maximum buffers to %u", max_buffers);
643   }
644
645   if (min_buffers > max_buffers) {
646     updated = TRUE;
647     min_buffers = max_buffers;
648     GST_INFO_OBJECT (pool, "reducing minimum buffers to %u", min_buffers);
649   } else if (min_buffers != max_buffers) {
650     if (!can_allocate) {
651       updated = TRUE;
652       max_buffers = min_buffers;
653       GST_INFO_OBJECT (pool, "can't allocate, setting maximum to minimum");
654     }
655   }
656
657   if (!pool->add_videometa && obj->need_video_meta) {
658     GST_INFO_OBJECT (pool, "adding needed video meta");
659     updated = TRUE;
660     gst_buffer_pool_config_add_option (config,
661         GST_BUFFER_POOL_OPTION_VIDEO_META);
662   }
663
664   /* Always update the config to ensure the configured size matches */
665   gst_buffer_pool_config_set_params (config, caps, obj->info.size, min_buffers,
666       max_buffers);
667
668   /* keep a GstVideoInfo with defaults for the when we need to copy */
669   gst_video_info_from_caps (&pool->caps_info, caps);
670
671 done:
672   ret = GST_BUFFER_POOL_CLASS (parent_class)->set_config (bpool, config);
673
674   /* If anything was changed documentation recommend to return FALSE */
675   return !updated && ret;
676
677   /* ERRORS */
678 wrong_config:
679   {
680     GST_ERROR_OBJECT (pool, "invalid config %" GST_PTR_FORMAT, config);
681     return FALSE;
682   }
683 }
684
685 static GstFlowReturn
686 gst_v4l2_buffer_pool_resurrect_buffer (GstV4l2BufferPool * pool)
687 {
688   GstBufferPoolAcquireParams params = { 0 };
689   GstBuffer *buffer = NULL;
690   GstFlowReturn ret;
691
692   GST_DEBUG_OBJECT (pool, "A buffer was lost, reallocating it");
693
694   /* block recursive calls to this function */
695   g_signal_handler_block (pool->vallocator, pool->group_released_handler);
696
697   params.flags =
698       (GstBufferPoolAcquireFlags) GST_V4L2_BUFFER_POOL_ACQUIRE_FLAG_RESURRECT |
699       GST_BUFFER_POOL_ACQUIRE_FLAG_DONTWAIT;
700   ret =
701       gst_buffer_pool_acquire_buffer (GST_BUFFER_POOL (pool), &buffer, &params);
702
703   if (ret == GST_FLOW_OK)
704     gst_buffer_unref (buffer);
705
706   g_signal_handler_unblock (pool->vallocator, pool->group_released_handler);
707
708   return ret;
709 }
710
711 static gboolean
712 gst_v4l2_buffer_pool_streamon (GstV4l2BufferPool * pool)
713 {
714   GstV4l2Object *obj = pool->obj;
715
716   if (pool->streaming)
717     return TRUE;
718
719   switch (obj->mode) {
720     case GST_V4L2_IO_MMAP:
721     case GST_V4L2_IO_USERPTR:
722     case GST_V4L2_IO_DMABUF:
723     case GST_V4L2_IO_DMABUF_IMPORT:
724       if (!V4L2_TYPE_IS_OUTPUT (pool->obj->type)) {
725         guint num_queued;
726         guint i, n = 0;
727
728         num_queued = g_atomic_int_get (&pool->num_queued);
729         if (num_queued < pool->num_allocated)
730           n = pool->num_allocated - num_queued;
731
732         /* For captures, we need to enqueue buffers before we start streaming,
733          * so the driver don't underflow immediately. As we have put then back
734          * into the base class queue, resurrect them, then releasing will queue
735          * them back. */
736         for (i = 0; i < n; i++)
737           gst_v4l2_buffer_pool_resurrect_buffer (pool);
738       }
739
740       if (obj->ioctl (pool->video_fd, VIDIOC_STREAMON, &obj->type) < 0)
741         goto streamon_failed;
742
743       pool->streaming = TRUE;
744
745       GST_DEBUG_OBJECT (pool, "Started streaming");
746       break;
747     default:
748       break;
749   }
750
751   return TRUE;
752
753 streamon_failed:
754   {
755     GST_ERROR_OBJECT (pool, "error with STREAMON %d (%s)", errno,
756         g_strerror (errno));
757     return FALSE;
758   }
759 }
760
761 /* Call with streamlock held, or when streaming threads are down */
762 static void
763 gst_v4l2_buffer_pool_streamoff (GstV4l2BufferPool * pool)
764 {
765   GstBufferPoolClass *pclass = GST_BUFFER_POOL_CLASS (parent_class);
766   GstV4l2Object *obj = pool->obj;
767   gint i;
768 #ifdef TIZEN_FEATURE_V4L2_TBM_SUPPORT
769   gint64 end_time = 0;
770 #endif /* TIZEN_FEATURE_V4L2_TBM_SUPPORT */
771
772   if (!pool->streaming)
773     return;
774
775 #ifdef TIZEN_FEATURE_V4L2_TBM_SUPPORT
776   if (obj->tbm_output && !V4L2_TYPE_IS_OUTPUT(pool->obj->type)) {
777     g_mutex_lock (&pool->buffer_lock);
778
779     GST_INFO_OBJECT (pool, "live buffer[%d]", pool->live_buffer_count);
780
781     if (pool->live_buffer_count > 0) {
782       end_time = g_get_monotonic_time () + G_TIME_SPAN_SECOND;
783
784       do {
785         GST_WARNING_OBJECT (pool, "wait for live buffer[%d]", pool->live_buffer_count);
786
787         if (!g_cond_wait_until (&pool->buffer_cond, &pool->buffer_lock, end_time)) {
788           GST_ERROR_OBJECT (pool, "failed to wait live buffer[%d]", pool->live_buffer_count);
789           break;
790         }
791
792         GST_WARNING_OBJECT (pool, "signal received, check again : live count[%d]",
793             pool->live_buffer_count);
794       } while (pool->live_buffer_count > 0);
795     }
796
797     g_mutex_unlock (&pool->buffer_lock);
798   }
799 #endif /* TIZEN_FEATURE_V4L2_TBM_SUPPORT */
800   switch (obj->mode) {
801     case GST_V4L2_IO_MMAP:
802     case GST_V4L2_IO_USERPTR:
803     case GST_V4L2_IO_DMABUF:
804     case GST_V4L2_IO_DMABUF_IMPORT:
805
806       if (obj->ioctl (pool->video_fd, VIDIOC_STREAMOFF, &obj->type) < 0)
807         GST_WARNING_OBJECT (pool, "STREAMOFF failed with errno %d (%s)",
808             errno, g_strerror (errno));
809
810       pool->streaming = FALSE;
811
812       GST_DEBUG_OBJECT (pool, "Stopped streaming");
813
814       if (pool->vallocator)
815         gst_v4l2_allocator_flush (pool->vallocator);
816       break;
817     default:
818       break;
819   }
820
821   for (i = 0; i < VIDEO_MAX_FRAME; i++) {
822     if (pool->buffers[i]) {
823       GstBuffer *buffer = pool->buffers[i];
824       GstBufferPool *bpool = GST_BUFFER_POOL (pool);
825
826       pool->buffers[i] = NULL;
827
828       if (V4L2_TYPE_IS_OUTPUT (pool->obj->type))
829         gst_v4l2_buffer_pool_release_buffer (bpool, buffer);
830       else                      /* Don't re-enqueue capture buffer on stop */
831         pclass->release_buffer (bpool, buffer);
832
833       g_atomic_int_add (&pool->num_queued, -1);
834     }
835   }
836 }
837
838 static gboolean
839 gst_v4l2_buffer_pool_start (GstBufferPool * bpool)
840 {
841   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
842   GstBufferPoolClass *pclass = GST_BUFFER_POOL_CLASS (parent_class);
843   GstV4l2Object *obj = pool->obj;
844   GstStructure *config;
845   GstCaps *caps;
846   guint size, min_buffers, max_buffers;
847   guint max_latency, min_latency, copy_threshold = 0;
848   gboolean can_allocate = FALSE, ret = TRUE;
849
850   GST_DEBUG_OBJECT (pool, "activating pool");
851
852   if (pool->other_pool) {
853     GstBuffer *buffer;
854
855     if (!gst_buffer_pool_set_active (pool->other_pool, TRUE))
856       goto other_pool_failed;
857
858     if (gst_buffer_pool_acquire_buffer (pool->other_pool, &buffer, NULL) !=
859         GST_FLOW_OK)
860       goto other_pool_failed;
861
862     if (!gst_v4l2_object_try_import (obj, buffer)) {
863       gst_buffer_unref (buffer);
864       goto cannot_import;
865     }
866     gst_buffer_unref (buffer);
867   }
868
869   config = gst_buffer_pool_get_config (bpool);
870   if (!gst_buffer_pool_config_get_params (config, &caps, &size, &min_buffers,
871           &max_buffers))
872     goto wrong_config;
873
874   min_latency = MAX (GST_V4L2_MIN_BUFFERS (obj), obj->min_buffers);
875
876   switch (obj->mode) {
877     case GST_V4L2_IO_RW:
878       can_allocate = TRUE;
879 #ifdef HAVE_LIBV4L2
880       /* This workaround a unfixable bug in libv4l2 when RW is emulated on top
881        * of MMAP. In this case, the first read initialize the queues, but the
882        * poll before that will always fail. Doing an empty read, forces the
883        * queue to be initialized now. We only do this if we have a streaming
884        * driver. */
885       if (obj->device_caps & V4L2_CAP_STREAMING)
886         obj->read (obj->video_fd, NULL, 0);
887 #endif
888       break;
889     case GST_V4L2_IO_DMABUF:
890     case GST_V4L2_IO_MMAP:
891     {
892       guint count;
893
894       can_allocate = GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, MMAP);
895
896       /* first, lets request buffers, and see how many we can get: */
897       GST_DEBUG_OBJECT (pool, "requesting %d MMAP buffers", min_buffers);
898
899       count = gst_v4l2_allocator_start (pool->vallocator, min_buffers,
900           V4L2_MEMORY_MMAP);
901       pool->num_allocated = count;
902
903       if (count < GST_V4L2_MIN_BUFFERS (obj)) {
904         min_buffers = count;
905         goto no_buffers;
906       }
907
908       /* V4L2 buffer pool are often very limited in the amount of buffers it
909        * can offer. The copy_threshold will workaround this limitation by
910        * falling back to copy if the pipeline needed more buffers. This also
911        * prevent having to do REQBUFS(N)/REQBUFS(0) every time configure is
912        * called. */
913       if (count != min_buffers || pool->enable_copy_threshold) {
914         GST_WARNING_OBJECT (pool,
915             "Uncertain or not enough buffers, enabling copy threshold");
916         min_buffers = count;
917         copy_threshold = min_latency;
918       }
919
920       break;
921     }
922     case GST_V4L2_IO_USERPTR:
923     {
924       guint count;
925
926       can_allocate =
927           GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, USERPTR);
928
929       GST_DEBUG_OBJECT (pool, "requesting %d USERPTR buffers", min_buffers);
930
931       count = gst_v4l2_allocator_start (pool->vallocator, min_buffers,
932           V4L2_MEMORY_USERPTR);
933       pool->num_allocated = count;
934
935       /* There is no rational to not get what we asked */
936       if (count < min_buffers) {
937         min_buffers = count;
938         goto no_buffers;
939       }
940
941       min_buffers = count;
942       break;
943     }
944     case GST_V4L2_IO_DMABUF_IMPORT:
945     {
946       guint count;
947
948       can_allocate = GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, DMABUF);
949
950       GST_DEBUG_OBJECT (pool, "requesting %d DMABUF buffers", min_buffers);
951
952       count = gst_v4l2_allocator_start (pool->vallocator, min_buffers,
953           V4L2_MEMORY_DMABUF);
954       pool->num_allocated = count;
955
956       /* There is no rational to not get what we asked */
957       if (count < min_buffers) {
958         min_buffers = count;
959         goto no_buffers;
960       }
961
962       min_buffers = count;
963       break;
964     }
965     default:
966       min_buffers = 0;
967       copy_threshold = 0;
968       g_assert_not_reached ();
969       break;
970   }
971
972   if (can_allocate)
973     max_latency = max_buffers;
974   else
975     max_latency = min_buffers;
976
977   pool->size = size;
978   pool->copy_threshold = copy_threshold;
979   pool->max_latency = max_latency;
980   pool->min_latency = min_latency;
981   pool->num_queued = 0;
982
983   if (max_buffers != 0 && max_buffers < min_buffers)
984     max_buffers = min_buffers;
985
986   gst_buffer_pool_config_set_params (config, caps, size, min_buffers,
987       max_buffers);
988   pclass->set_config (bpool, config);
989   gst_structure_free (config);
990
991   /* now, allocate the buffers: */
992   if (!pclass->start (bpool))
993     goto start_failed;
994
995   if (!V4L2_TYPE_IS_OUTPUT (obj->type)) {
996     if (g_atomic_int_get (&pool->num_queued) < pool->num_allocated)
997       goto queue_failed;
998
999     pool->group_released_handler =
1000         g_signal_connect_swapped (pool->vallocator, "group-released",
1001         G_CALLBACK (gst_v4l2_buffer_pool_resurrect_buffer), pool);
1002     ret = gst_v4l2_buffer_pool_streamon (pool);
1003   }
1004
1005   return ret;
1006
1007   /* ERRORS */
1008 wrong_config:
1009   {
1010     GST_ERROR_OBJECT (pool, "invalid config %" GST_PTR_FORMAT, config);
1011     gst_structure_free (config);
1012     return FALSE;
1013   }
1014 no_buffers:
1015   {
1016     GST_ERROR_OBJECT (pool,
1017         "we received %d buffer from device '%s', we want at least %d",
1018         min_buffers, obj->videodev, GST_V4L2_MIN_BUFFERS (obj));
1019     gst_structure_free (config);
1020     return FALSE;
1021   }
1022 start_failed:
1023   {
1024     GST_ERROR_OBJECT (pool, "allocate failed");
1025     return FALSE;
1026   }
1027 other_pool_failed:
1028   {
1029     GST_ERROR_OBJECT (pool, "failed to activate the other pool %"
1030         GST_PTR_FORMAT, pool->other_pool);
1031     return FALSE;
1032   }
1033 queue_failed:
1034   {
1035     GST_ERROR_OBJECT (pool, "failed to queue buffers into the capture queue");
1036     return FALSE;
1037   }
1038 cannot_import:
1039   {
1040     GST_ERROR_OBJECT (pool, "cannot import buffers from downstream pool");
1041     return FALSE;
1042   }
1043 }
1044
1045 static gboolean
1046 gst_v4l2_buffer_pool_vallocator_stop (GstV4l2BufferPool * pool)
1047 {
1048   GstV4l2Return vret;
1049
1050   if (!pool->vallocator)
1051     return TRUE;
1052
1053   vret = gst_v4l2_allocator_stop (pool->vallocator);
1054
1055   if (vret == GST_V4L2_BUSY)
1056     GST_WARNING_OBJECT (pool, "some buffers are still outstanding");
1057
1058   return (vret == GST_V4L2_OK);
1059 }
1060
1061 static gboolean
1062 gst_v4l2_buffer_pool_stop (GstBufferPool * bpool)
1063 {
1064   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
1065   gboolean ret;
1066
1067   GST_DEBUG_OBJECT (pool, "stopping pool");
1068
1069   if (pool->group_released_handler > 0) {
1070     g_signal_handler_disconnect (pool->vallocator,
1071         pool->group_released_handler);
1072     pool->group_released_handler = 0;
1073   }
1074
1075   if (pool->other_pool) {
1076     gst_buffer_pool_set_active (pool->other_pool, FALSE);
1077     gst_object_unref (pool->other_pool);
1078     pool->other_pool = NULL;
1079   }
1080
1081   if (!pool->orphaned)
1082     gst_v4l2_buffer_pool_streamoff (pool);
1083
1084   ret = GST_BUFFER_POOL_CLASS (parent_class)->stop (bpool);
1085
1086   if (ret)
1087     ret = gst_v4l2_buffer_pool_vallocator_stop (pool);
1088
1089   return ret;
1090 }
1091
1092 gboolean
1093 gst_v4l2_buffer_pool_orphan (GstBufferPool ** bpool)
1094 {
1095   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (*bpool);
1096   gboolean ret;
1097
1098   g_return_val_if_fail (pool->orphaned == FALSE, FALSE);
1099
1100   if (!GST_V4L2_ALLOCATOR_CAN_ORPHAN_BUFS (pool->vallocator))
1101     return FALSE;
1102
1103   if (g_getenv ("GST_V4L2_FORCE_DRAIN"))
1104     return FALSE;
1105
1106   GST_DEBUG_OBJECT (pool, "orphaning pool");
1107   gst_buffer_pool_set_active (*bpool, FALSE);
1108
1109   /* We lock to prevent racing with a return buffer in QBuf, and has a
1110    * workaround of not being able to use the pool hidden activation lock. */
1111   GST_OBJECT_LOCK (pool);
1112
1113   gst_v4l2_buffer_pool_streamoff (pool);
1114   ret = gst_v4l2_allocator_orphan (pool->vallocator);
1115   if (ret)
1116     pool->orphaned = TRUE;
1117
1118   GST_OBJECT_UNLOCK (pool);
1119
1120   if (ret) {
1121     gst_object_unref (*bpool);
1122     *bpool = NULL;
1123   }
1124
1125   return ret;
1126 }
1127
1128 static void
1129 gst_v4l2_buffer_pool_flush_start (GstBufferPool * bpool)
1130 {
1131   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
1132
1133   GST_DEBUG_OBJECT (pool, "start flushing");
1134
1135   gst_poll_set_flushing (pool->poll, TRUE);
1136
1137   GST_OBJECT_LOCK (pool);
1138   pool->empty = FALSE;
1139   g_cond_broadcast (&pool->empty_cond);
1140   GST_OBJECT_UNLOCK (pool);
1141
1142   if (pool->other_pool && gst_buffer_pool_is_active (pool->other_pool))
1143     gst_buffer_pool_set_flushing (pool->other_pool, TRUE);
1144 }
1145
1146 static void
1147 gst_v4l2_buffer_pool_flush_stop (GstBufferPool * bpool)
1148 {
1149   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
1150
1151   GST_DEBUG_OBJECT (pool, "stop flushing");
1152
1153   if (pool->other_pool && gst_buffer_pool_is_active (pool->other_pool))
1154     gst_buffer_pool_set_flushing (pool->other_pool, FALSE);
1155
1156   gst_poll_set_flushing (pool->poll, FALSE);
1157 }
1158
1159 static GstFlowReturn
1160 gst_v4l2_buffer_pool_poll (GstV4l2BufferPool * pool, gboolean wait)
1161 {
1162   gint ret;
1163   GstClockTime timeout;
1164
1165   if (wait)
1166     timeout = GST_CLOCK_TIME_NONE;
1167   else
1168     timeout = 0;
1169
1170   /* In RW mode there is no queue, hence no need to wait while the queue is
1171    * empty */
1172   if (pool->obj->mode != GST_V4L2_IO_RW) {
1173     GST_OBJECT_LOCK (pool);
1174
1175     if (!wait && pool->empty) {
1176       GST_OBJECT_UNLOCK (pool);
1177       goto no_buffers;
1178     }
1179
1180     while (pool->empty)
1181       g_cond_wait (&pool->empty_cond, GST_OBJECT_GET_LOCK (pool));
1182
1183     GST_OBJECT_UNLOCK (pool);
1184   }
1185
1186   if (!pool->can_poll_device) {
1187     if (wait)
1188       goto done;
1189     else
1190       goto no_buffers;
1191   }
1192
1193   GST_LOG_OBJECT (pool, "polling device");
1194
1195 again:
1196   ret = gst_poll_wait (pool->poll, timeout);
1197   if (G_UNLIKELY (ret < 0)) {
1198     switch (errno) {
1199       case EBUSY:
1200         goto stopped;
1201       case EAGAIN:
1202       case EINTR:
1203         goto again;
1204       case ENXIO:
1205         GST_WARNING_OBJECT (pool,
1206             "v4l2 device doesn't support polling. Disabling"
1207             " using libv4l2 in this case may cause deadlocks");
1208         pool->can_poll_device = FALSE;
1209         goto done;
1210       default:
1211         goto select_error;
1212     }
1213   }
1214
1215   if (gst_poll_fd_has_error (pool->poll, &pool->pollfd))
1216     goto select_error;
1217
1218   /* PRI is used to signal that events are available */
1219   if (gst_poll_fd_has_pri (pool->poll, &pool->pollfd)) {
1220     struct v4l2_event event = { 0, };
1221
1222     if (!gst_v4l2_dequeue_event (pool->obj, &event))
1223       goto dqevent_failed;
1224
1225     if (event.type != V4L2_EVENT_SOURCE_CHANGE) {
1226       GST_INFO_OBJECT (pool, "Received unhandled event, ignoring.");
1227       goto again;
1228     }
1229
1230     if ((event.u.src_change.changes & V4L2_EVENT_SRC_CH_RESOLUTION) == 0) {
1231       GST_DEBUG_OBJECT (pool,
1232           "Received non-resolution source-change, ignoring.");
1233       goto again;
1234     }
1235
1236     return GST_V4L2_FLOW_RESOLUTION_CHANGE;
1237   }
1238
1239   if (ret == 0)
1240     goto no_buffers;
1241
1242 done:
1243   return GST_FLOW_OK;
1244
1245   /* ERRORS */
1246 stopped:
1247   {
1248     GST_DEBUG_OBJECT (pool, "stop called");
1249     return GST_FLOW_FLUSHING;
1250   }
1251 select_error:
1252   {
1253     GST_ELEMENT_ERROR (pool->obj->element, RESOURCE, READ, (NULL),
1254         ("poll error %d: %s (%d)", ret, g_strerror (errno), errno));
1255     return GST_FLOW_ERROR;
1256   }
1257 no_buffers:
1258   {
1259     return GST_V4L2_FLOW_LAST_BUFFER;
1260   }
1261 dqevent_failed:
1262   {
1263     GST_ELEMENT_ERROR (pool->obj->element, RESOURCE, READ, (NULL),
1264         ("dqevent error: %s (%d)", g_strerror (errno), errno));
1265     return GST_FLOW_ERROR;
1266   }
1267 }
1268
1269 static GstFlowReturn
1270 gst_v4l2_buffer_pool_qbuf (GstV4l2BufferPool * pool, GstBuffer * buf,
1271     GstV4l2MemoryGroup * group, guint32 * frame_number)
1272 {
1273   const GstV4l2Object *obj = pool->obj;
1274   gint index;
1275
1276   index = group->buffer.index;
1277
1278   if (pool->buffers[index] != NULL)
1279     goto already_queued;
1280
1281   GST_LOG_OBJECT (pool, "queuing buffer %i", index);
1282
1283   if (V4L2_TYPE_IS_OUTPUT (obj->type)) {
1284     enum v4l2_field field;
1285
1286     /* Buffer field is the same as the one defined in format */
1287     if (V4L2_TYPE_IS_MULTIPLANAR (obj->type))
1288       field = obj->format.fmt.pix_mp.field;
1289     else
1290       field = obj->format.fmt.pix.field;
1291
1292     group->buffer.field = field;
1293   }
1294
1295   if (frame_number) {
1296     group->buffer.timestamp.tv_sec = *frame_number;
1297     group->buffer.timestamp.tv_usec = 0;
1298   } else {
1299     if (GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
1300       GstClockTime timestamp = GST_BUFFER_TIMESTAMP (buf);
1301       GST_TIME_TO_TIMEVAL (timestamp, group->buffer.timestamp);
1302     } else {
1303       group->buffer.timestamp.tv_sec = -1;
1304       group->buffer.timestamp.tv_usec = -1;
1305     }
1306   }
1307
1308   GST_OBJECT_LOCK (pool);
1309
1310   /* If the pool was orphaned, don't try to queue any returned buffers.
1311    * This is done with the objet lock in order to synchronize with
1312    * orphaning. */
1313   if (pool->orphaned)
1314     goto was_orphaned;
1315
1316   g_atomic_int_inc (&pool->num_queued);
1317   pool->buffers[index] = buf;
1318
1319   if (!gst_v4l2_allocator_qbuf (pool->vallocator, group))
1320     goto queue_failed;
1321
1322   pool->empty = FALSE;
1323   g_cond_signal (&pool->empty_cond);
1324   GST_OBJECT_UNLOCK (pool);
1325
1326   return GST_FLOW_OK;
1327
1328 already_queued:
1329   {
1330     GST_ERROR_OBJECT (pool, "the buffer %i was already queued", index);
1331     return GST_FLOW_ERROR;
1332   }
1333 was_orphaned:
1334   {
1335     GST_DEBUG_OBJECT (pool, "pool was orphaned, not queuing back buffer.");
1336     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_TAG_MEMORY);
1337     GST_OBJECT_UNLOCK (pool);
1338     return GST_FLOW_FLUSHING;
1339   }
1340 queue_failed:
1341   {
1342     GST_ERROR_OBJECT (pool, "could not queue a buffer %i", index);
1343     /* Mark broken buffer to the allocator */
1344     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_TAG_MEMORY);
1345     g_atomic_int_add (&pool->num_queued, -1);
1346     pool->buffers[index] = NULL;
1347     GST_OBJECT_UNLOCK (pool);
1348     return GST_FLOW_ERROR;
1349   }
1350 }
1351
1352 static GstFlowReturn
1353 gst_v4l2_buffer_pool_dqbuf (GstV4l2BufferPool * pool, GstBuffer ** buffer,
1354     gboolean wait)
1355 {
1356   GstFlowReturn res;
1357   GstBuffer *outbuf = NULL;
1358   GstV4l2Object *obj = pool->obj;
1359   GstClockTime timestamp;
1360   GstV4l2MemoryGroup *group;
1361   GstVideoMeta *vmeta;
1362   gsize size;
1363   gint i;
1364 #ifdef TIZEN_FEATURE_V4L2_TBM_SUPPORT
1365   GstV4l2TizenBuffer *tizen_buffer = NULL;
1366 #endif /* TIZEN_FEATURE_V4L2_TBM_SUPPORT */
1367
1368   if ((res = gst_v4l2_buffer_pool_poll (pool, wait)) < GST_FLOW_OK)
1369     goto poll_failed;
1370
1371   if (res == GST_V4L2_FLOW_LAST_BUFFER) {
1372     GST_LOG_OBJECT (pool, "nothing to dequeue");
1373     goto done;
1374   }
1375
1376   if (res == GST_V4L2_FLOW_RESOLUTION_CHANGE) {
1377     GST_INFO_OBJECT (pool, "Resolution change detected.");
1378     goto done;
1379   }
1380
1381   GST_LOG_OBJECT (pool, "dequeueing a buffer");
1382
1383   res = gst_v4l2_allocator_dqbuf (pool->vallocator, &group);
1384   if (res == GST_FLOW_EOS)
1385     goto eos;
1386   if (res != GST_FLOW_OK)
1387     goto dqbuf_failed;
1388
1389   /* get our GstBuffer with that index from the pool, if the buffer was
1390    * outstanding we have a serious problem.
1391    */
1392   outbuf = pool->buffers[group->buffer.index];
1393   if (outbuf == NULL)
1394     goto no_buffer;
1395
1396   /* mark the buffer outstanding */
1397   pool->buffers[group->buffer.index] = NULL;
1398   if (g_atomic_int_dec_and_test (&pool->num_queued)) {
1399     GST_OBJECT_LOCK (pool);
1400     pool->empty = TRUE;
1401     GST_OBJECT_UNLOCK (pool);
1402   }
1403
1404   timestamp = GST_TIMEVAL_TO_TIME (group->buffer.timestamp);
1405
1406   size = 0;
1407   vmeta = gst_buffer_get_video_meta (outbuf);
1408   for (i = 0; i < group->n_mem; i++) {
1409     GST_LOG_OBJECT (pool,
1410         "dequeued buffer %p seq:%d (ix=%d), mem %p used %d, plane=%d, flags %08x, ts %"
1411         GST_TIME_FORMAT ", pool-queued=%d, buffer=%p", outbuf,
1412         group->buffer.sequence, group->buffer.index, group->mem[i],
1413         group->planes[i].bytesused, i, group->buffer.flags,
1414         GST_TIME_ARGS (timestamp), pool->num_queued, outbuf);
1415
1416     if (vmeta) {
1417       vmeta->offset[i] = size;
1418       size += gst_memory_get_sizes (group->mem[i], NULL, NULL);
1419     }
1420   }
1421
1422   /* Ignore timestamp and field for OUTPUT device */
1423   if (V4L2_TYPE_IS_OUTPUT (obj->type))
1424     goto done;
1425
1426   /* Check for driver bug in reporting feild */
1427   if (group->buffer.field == V4L2_FIELD_ANY) {
1428     /* Only warn once to avoid the spamming */
1429 #ifndef GST_DISABLE_GST_DEBUG
1430     if (!pool->has_warned_on_buggy_field) {
1431       pool->has_warned_on_buggy_field = TRUE;
1432       GST_WARNING_OBJECT (pool,
1433           "Driver should never set v4l2_buffer.field to ANY");
1434     }
1435 #endif
1436
1437     /* Use the value from the format (works for UVC bug) */
1438     group->buffer.field = obj->format.fmt.pix.field;
1439
1440     /* If driver also has buggy S_FMT, assume progressive */
1441     if (group->buffer.field == V4L2_FIELD_ANY) {
1442 #ifndef GST_DISABLE_GST_DEBUG
1443       if (!pool->has_warned_on_buggy_field) {
1444         pool->has_warned_on_buggy_field = TRUE;
1445         GST_WARNING_OBJECT (pool,
1446             "Driver should never set v4l2_format.pix.field to ANY");
1447       }
1448 #endif
1449
1450       group->buffer.field = V4L2_FIELD_NONE;
1451     }
1452   }
1453
1454   /* set top/bottom field first if v4l2_buffer has the information */
1455   switch (group->buffer.field) {
1456     case V4L2_FIELD_NONE:
1457       GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_FLAG_INTERLACED);
1458       GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
1459       break;
1460     case V4L2_FIELD_TOP:
1461       GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_INTERLACED);
1462       GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_TOP_FIELD);
1463       break;
1464     case V4L2_FIELD_BOTTOM:
1465       GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_INTERLACED);
1466       GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_BOTTOM_FIELD);
1467       break;
1468     case V4L2_FIELD_INTERLACED_TB:
1469       GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_INTERLACED);
1470       GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
1471       break;
1472     case V4L2_FIELD_INTERLACED_BT:
1473       GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_INTERLACED);
1474       GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
1475       break;
1476     case V4L2_FIELD_INTERLACED:
1477       GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_INTERLACED);
1478       if (obj->tv_norm == V4L2_STD_NTSC_M ||
1479           obj->tv_norm == V4L2_STD_NTSC_M_JP ||
1480           obj->tv_norm == V4L2_STD_NTSC_M_KR) {
1481         GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
1482       } else {
1483         GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
1484       }
1485       break;
1486     default:
1487       GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_FLAG_INTERLACED);
1488       GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
1489       GST_FIXME_OBJECT (pool,
1490           "Unhandled enum v4l2_field %d - treating as progressive",
1491           group->buffer.field);
1492       break;
1493   }
1494
1495   if (GST_VIDEO_INFO_FORMAT (&obj->info) == GST_VIDEO_FORMAT_ENCODED) {
1496     if ((group->buffer.flags & V4L2_BUF_FLAG_KEYFRAME) ||
1497         GST_V4L2_PIXELFORMAT (obj) == V4L2_PIX_FMT_MJPEG ||
1498         GST_V4L2_PIXELFORMAT (obj) == V4L2_PIX_FMT_JPEG ||
1499         GST_V4L2_PIXELFORMAT (obj) == V4L2_PIX_FMT_PJPG)
1500       GST_BUFFER_FLAG_UNSET (outbuf, GST_BUFFER_FLAG_DELTA_UNIT);
1501     else
1502       GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DELTA_UNIT);
1503   }
1504
1505   if (group->buffer.flags & V4L2_BUF_FLAG_ERROR)
1506     GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_CORRUPTED);
1507
1508   GST_BUFFER_TIMESTAMP (outbuf) = timestamp;
1509   GST_BUFFER_OFFSET (outbuf) = group->buffer.sequence;
1510   GST_BUFFER_OFFSET_END (outbuf) = group->buffer.sequence + 1;
1511
1512 #ifdef TIZEN_FEATURE_V4L2_TBM_SUPPORT
1513   if (group->surface) {
1514     tizen_buffer = gst_v4l2_tizen_buffer_new (outbuf, group->buffer.index, pool);
1515     if (!tizen_buffer) {
1516       GST_ERROR_OBJECT (pool, "tizen buffer failed for index[%d]", group->buffer.index);
1517       goto no_buffer;
1518     }
1519     outbuf = tizen_buffer->gst_buffer;
1520   }
1521 #endif /* TIZEN_FEATURE_V4L2_TBM_SUPPORT */
1522 done:
1523   *buffer = outbuf;
1524
1525   return res;
1526
1527   /* ERRORS */
1528 poll_failed:
1529   {
1530     GST_DEBUG_OBJECT (pool, "poll error %s", gst_flow_get_name (res));
1531     return res;
1532   }
1533 eos:
1534   {
1535     return GST_FLOW_EOS;
1536   }
1537 dqbuf_failed:
1538   {
1539     return GST_FLOW_ERROR;
1540   }
1541 no_buffer:
1542   {
1543     GST_ERROR_OBJECT (pool, "No free buffer found in the pool at index %d.",
1544         group->buffer.index);
1545     return GST_FLOW_ERROR;
1546   }
1547 }
1548
1549 static GstFlowReturn
1550 gst_v4l2_buffer_pool_acquire_buffer (GstBufferPool * bpool, GstBuffer ** buffer,
1551     GstBufferPoolAcquireParams * params)
1552 {
1553   GstFlowReturn ret;
1554   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
1555   GstBufferPoolClass *pclass = GST_BUFFER_POOL_CLASS (parent_class);
1556   GstV4l2Object *obj = pool->obj;
1557
1558   GST_DEBUG_OBJECT (pool, "acquire");
1559
1560   /* If this is being called to resurrect a lost buffer */
1561   if (params && params->flags & GST_V4L2_BUFFER_POOL_ACQUIRE_FLAG_RESURRECT) {
1562     ret = pclass->acquire_buffer (bpool, buffer, params);
1563     goto done;
1564   }
1565
1566   switch (obj->type) {
1567     case V4L2_BUF_TYPE_VIDEO_CAPTURE:
1568     case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE:
1569       /* capture, This function should return a buffer with new captured data */
1570       switch (obj->mode) {
1571         case GST_V4L2_IO_RW:
1572         {
1573           /* take empty buffer from the pool */
1574           ret = pclass->acquire_buffer (bpool, buffer, params);
1575           break;
1576         }
1577         case GST_V4L2_IO_DMABUF:
1578         case GST_V4L2_IO_MMAP:
1579         case GST_V4L2_IO_USERPTR:
1580         case GST_V4L2_IO_DMABUF_IMPORT:
1581         {
1582           /* just dequeue a buffer, we basically use the queue of v4l2 as the
1583            * storage for our buffers. This function does poll first so we can
1584            * interrupt it fine. */
1585           ret = gst_v4l2_buffer_pool_dqbuf (pool, buffer, TRUE);
1586           break;
1587         }
1588         default:
1589           ret = GST_FLOW_ERROR;
1590           g_assert_not_reached ();
1591           break;
1592       }
1593       break;
1594
1595
1596     case V4L2_BUF_TYPE_VIDEO_OUTPUT:
1597     case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE:
1598       /* playback, This function should return an empty buffer */
1599       switch (obj->mode) {
1600         case GST_V4L2_IO_RW:
1601           /* get an empty buffer */
1602           ret = pclass->acquire_buffer (bpool, buffer, params);
1603           break;
1604
1605         case GST_V4L2_IO_MMAP:
1606         case GST_V4L2_IO_DMABUF:
1607         case GST_V4L2_IO_USERPTR:
1608         case GST_V4L2_IO_DMABUF_IMPORT:
1609           /* get a free unqueued buffer */
1610           ret = pclass->acquire_buffer (bpool, buffer, params);
1611           break;
1612
1613         default:
1614           ret = GST_FLOW_ERROR;
1615           g_assert_not_reached ();
1616           break;
1617       }
1618       break;
1619
1620     default:
1621       ret = GST_FLOW_ERROR;
1622       g_assert_not_reached ();
1623       break;
1624   }
1625 done:
1626   return ret;
1627 }
1628
1629 static void
1630 gst_v4l2_buffer_pool_release_buffer (GstBufferPool * bpool, GstBuffer * buffer)
1631 {
1632   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
1633   GstBufferPoolClass *pclass = GST_BUFFER_POOL_CLASS (parent_class);
1634   GstV4l2Object *obj = pool->obj;
1635
1636   GST_DEBUG_OBJECT (pool, "release buffer %p", buffer);
1637
1638   /* If the buffer's pool has been orphaned, dispose of it so that
1639    * the pool resources can be freed */
1640   if (pool->orphaned) {
1641     GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_TAG_MEMORY);
1642     pclass->release_buffer (bpool, buffer);
1643     return;
1644   }
1645
1646   switch (obj->type) {
1647     case V4L2_BUF_TYPE_VIDEO_CAPTURE:
1648     case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE:
1649       /* capture, put the buffer back in the queue so that we can refill it
1650        * later. */
1651       switch (obj->mode) {
1652         case GST_V4L2_IO_RW:
1653           /* release back in the pool */
1654           pclass->release_buffer (bpool, buffer);
1655           break;
1656
1657         case GST_V4L2_IO_DMABUF:
1658         case GST_V4L2_IO_MMAP:
1659         case GST_V4L2_IO_USERPTR:
1660         case GST_V4L2_IO_DMABUF_IMPORT:
1661         {
1662           GstV4l2MemoryGroup *group;
1663           if (gst_v4l2_is_buffer_valid (buffer, &group)) {
1664             GstFlowReturn ret = GST_FLOW_OK;
1665
1666             gst_v4l2_allocator_reset_group (pool->vallocator, group);
1667             /* queue back in the device */
1668             if (pool->other_pool)
1669               ret = gst_v4l2_buffer_pool_prepare_buffer (pool, buffer, NULL);
1670             if (ret != GST_FLOW_OK ||
1671                 gst_v4l2_buffer_pool_qbuf (pool, buffer, group,
1672                     NULL) != GST_FLOW_OK)
1673               pclass->release_buffer (bpool, buffer);
1674           } else {
1675             /* Simply release invalid/modified buffer, the allocator will
1676              * give it back later */
1677             GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_TAG_MEMORY);
1678             pclass->release_buffer (bpool, buffer);
1679           }
1680           break;
1681         }
1682         default:
1683           g_assert_not_reached ();
1684           break;
1685       }
1686       break;
1687
1688     case V4L2_BUF_TYPE_VIDEO_OUTPUT:
1689     case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE:
1690       switch (obj->mode) {
1691         case GST_V4L2_IO_RW:
1692           /* release back in the pool */
1693           pclass->release_buffer (bpool, buffer);
1694           break;
1695
1696         case GST_V4L2_IO_MMAP:
1697         case GST_V4L2_IO_DMABUF:
1698         case GST_V4L2_IO_USERPTR:
1699         case GST_V4L2_IO_DMABUF_IMPORT:
1700         {
1701           GstV4l2MemoryGroup *group;
1702           guint index;
1703
1704           if (!gst_v4l2_is_buffer_valid (buffer, &group)) {
1705             /* Simply release invalid/modified buffer, the allocator will
1706              * give it back later */
1707             GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_TAG_MEMORY);
1708             pclass->release_buffer (bpool, buffer);
1709             break;
1710           }
1711
1712           index = group->buffer.index;
1713
1714           if (pool->buffers[index] == NULL) {
1715             GST_LOG_OBJECT (pool, "buffer %u not queued, putting on free list",
1716                 index);
1717
1718             /* Remove qdata, this will unmap any map data in userptr */
1719             gst_mini_object_set_qdata (GST_MINI_OBJECT (buffer),
1720                 GST_V4L2_IMPORT_QUARK, NULL, NULL);
1721
1722             /* reset to default size */
1723             gst_v4l2_allocator_reset_group (pool->vallocator, group);
1724
1725             /* playback, put the buffer back in the queue to refill later. */
1726             pclass->release_buffer (bpool, buffer);
1727           } else {
1728             /* the buffer is queued in the device but maybe not played yet. We just
1729              * leave it there and not make it available for future calls to acquire
1730              * for now. The buffer will be dequeued and reused later. */
1731             GST_LOG_OBJECT (pool, "buffer %u is queued", index);
1732           }
1733           break;
1734         }
1735
1736         default:
1737           g_assert_not_reached ();
1738           break;
1739       }
1740       break;
1741
1742     default:
1743       g_assert_not_reached ();
1744       break;
1745   }
1746 }
1747
1748 static void
1749 gst_v4l2_buffer_pool_dispose (GObject * object)
1750 {
1751   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (object);
1752
1753   if (pool->vallocator)
1754     gst_object_unref (pool->vallocator);
1755   pool->vallocator = NULL;
1756
1757   if (pool->allocator)
1758     gst_object_unref (pool->allocator);
1759   pool->allocator = NULL;
1760
1761 #ifdef TIZEN_FEATURE_V4L2_TBM_SUPPORT
1762   g_cond_clear (&pool->buffer_cond);
1763   g_mutex_clear (&pool->buffer_lock);
1764
1765   if (pool->tallocator)
1766     gst_object_unref (pool->tallocator);
1767   pool->tallocator = NULL;
1768 #endif /* TIZEN_FEATURE_V4L2_TBM_SUPPORT */
1769   if (pool->other_pool)
1770     gst_object_unref (pool->other_pool);
1771   pool->other_pool = NULL;
1772
1773   G_OBJECT_CLASS (parent_class)->dispose (object);
1774 }
1775
1776 static void
1777 gst_v4l2_buffer_pool_finalize (GObject * object)
1778 {
1779   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (object);
1780
1781   if (pool->video_fd >= 0)
1782     pool->obj->close (pool->video_fd);
1783
1784   gst_poll_free (pool->poll);
1785
1786   /* This can't be done in dispose method because we must not set pointer
1787    * to NULL as it is part of the v4l2object and dispose could be called
1788    * multiple times */
1789   gst_object_unref (pool->obj->element);
1790
1791   g_cond_clear (&pool->empty_cond);
1792
1793   /* FIXME have we done enough here ? */
1794
1795   G_OBJECT_CLASS (parent_class)->finalize (object);
1796 }
1797
1798 static void
1799 gst_v4l2_buffer_pool_init (GstV4l2BufferPool * pool)
1800 {
1801   pool->poll = gst_poll_new (TRUE);
1802   pool->can_poll_device = TRUE;
1803   g_cond_init (&pool->empty_cond);
1804   pool->empty = TRUE;
1805   pool->orphaned = FALSE;
1806 }
1807
1808 static void
1809 gst_v4l2_buffer_pool_class_init (GstV4l2BufferPoolClass * klass)
1810 {
1811   GObjectClass *object_class = G_OBJECT_CLASS (klass);
1812   GstBufferPoolClass *bufferpool_class = GST_BUFFER_POOL_CLASS (klass);
1813
1814   object_class->dispose = gst_v4l2_buffer_pool_dispose;
1815   object_class->finalize = gst_v4l2_buffer_pool_finalize;
1816
1817   bufferpool_class->start = gst_v4l2_buffer_pool_start;
1818   bufferpool_class->stop = gst_v4l2_buffer_pool_stop;
1819   bufferpool_class->set_config = gst_v4l2_buffer_pool_set_config;
1820   bufferpool_class->alloc_buffer = gst_v4l2_buffer_pool_alloc_buffer;
1821   bufferpool_class->acquire_buffer = gst_v4l2_buffer_pool_acquire_buffer;
1822   bufferpool_class->release_buffer = gst_v4l2_buffer_pool_release_buffer;
1823   bufferpool_class->flush_start = gst_v4l2_buffer_pool_flush_start;
1824   bufferpool_class->flush_stop = gst_v4l2_buffer_pool_flush_stop;
1825
1826   GST_DEBUG_CATEGORY_INIT (v4l2bufferpool_debug, "v4l2bufferpool", 0,
1827       "V4L2 Buffer Pool");
1828   GST_DEBUG_CATEGORY_GET (CAT_PERFORMANCE, "GST_PERFORMANCE");
1829 }
1830
1831 /**
1832  * gst_v4l2_buffer_pool_new:
1833  * @obj:  the v4l2 object owning the pool
1834  *
1835  * Construct a new buffer pool.
1836  *
1837  * Returns: the new pool, use gst_object_unref() to free resources
1838  */
1839 GstBufferPool *
1840 gst_v4l2_buffer_pool_new (GstV4l2Object * obj, GstCaps * caps)
1841 {
1842   GstV4l2BufferPool *pool;
1843   GstStructure *config;
1844   gchar *name, *parent_name;
1845   gint fd;
1846
1847   fd = obj->dup (obj->video_fd);
1848   if (fd < 0)
1849     goto dup_failed;
1850
1851   /* setting a significant unique name */
1852   parent_name = gst_object_get_name (GST_OBJECT (obj->element));
1853   name = g_strdup_printf ("%s:pool%u:%s",
1854       parent_name, obj->pool_seq++,
1855       V4L2_TYPE_IS_OUTPUT (obj->type) ? "sink" : "src");
1856   g_free (parent_name);
1857
1858   pool = (GstV4l2BufferPool *) g_object_new (GST_TYPE_V4L2_BUFFER_POOL,
1859       "name", name, NULL);
1860   g_object_ref_sink (pool);
1861   g_free (name);
1862
1863   gst_poll_fd_init (&pool->pollfd);
1864   pool->pollfd.fd = fd;
1865   gst_poll_add_fd (pool->poll, &pool->pollfd);
1866   if (V4L2_TYPE_IS_OUTPUT (obj->type))
1867     gst_poll_fd_ctl_write (pool->poll, &pool->pollfd, TRUE);
1868   else
1869     gst_poll_fd_ctl_read (pool->poll, &pool->pollfd, TRUE);
1870
1871   pool->video_fd = fd;
1872   pool->obj = obj;
1873   pool->can_poll_device = TRUE;
1874
1875 #ifdef TIZEN_FEATURE_V4L2_TBM_SUPPORT
1876   pool->tallocator = gst_tizen_allocator_new ();
1877   if (pool->tallocator == NULL)
1878     goto allocator_failed;
1879
1880   g_mutex_init (&pool->buffer_lock);
1881   g_cond_init (&pool->buffer_cond);
1882 #endif /* TIZEN_FEATURE_V4L2_TBM_SUPPORT */
1883   pool->vallocator = gst_v4l2_allocator_new (GST_OBJECT (pool), obj);
1884   if (pool->vallocator == NULL)
1885     goto allocator_failed;
1886
1887   gst_object_ref (obj->element);
1888
1889   config = gst_buffer_pool_get_config (GST_BUFFER_POOL_CAST (pool));
1890   gst_buffer_pool_config_set_params (config, caps, obj->info.size, 0, 0);
1891   /* This will simply set a default config, but will not configure the pool
1892    * because min and max are not valid */
1893   gst_buffer_pool_set_config (GST_BUFFER_POOL_CAST (pool), config);
1894
1895   return GST_BUFFER_POOL (pool);
1896
1897   /* ERRORS */
1898 dup_failed:
1899   {
1900     GST_ERROR ("failed to dup fd %d (%s)", errno, g_strerror (errno));
1901     return NULL;
1902   }
1903 allocator_failed:
1904   {
1905 #ifdef TIZEN_FEATURE_V4L2_TBM_SUPPORT
1906     if (pool->tallocator) {
1907       gst_object_unref (pool->tallocator);
1908       pool->tallocator = NULL;
1909     }
1910 #endif /* TIZEN_FEATURE_V4L2_TBM_SUPPORT */
1911     GST_ERROR_OBJECT (pool, "Failed to create V4L2 allocator");
1912     gst_object_unref (pool);
1913     return NULL;
1914   }
1915 }
1916
1917 static GstFlowReturn
1918 gst_v4l2_do_read (GstV4l2BufferPool * pool, GstBuffer * buf)
1919 {
1920   GstFlowReturn res;
1921   GstV4l2Object *obj = pool->obj;
1922   gint amount;
1923   GstMapInfo map;
1924   gint toread;
1925
1926   toread = obj->info.size;
1927
1928   GST_LOG_OBJECT (pool, "reading %d bytes into buffer %p", toread, buf);
1929
1930   gst_buffer_map (buf, &map, GST_MAP_WRITE);
1931
1932   do {
1933     if ((res = gst_v4l2_buffer_pool_poll (pool, TRUE)) != GST_FLOW_OK)
1934       goto poll_error;
1935
1936     amount = obj->read (obj->video_fd, map.data, toread);
1937
1938     if (amount == toread) {
1939       break;
1940     } else if (amount == -1) {
1941       if (errno == EAGAIN || errno == EINTR) {
1942         continue;
1943       } else
1944         goto read_error;
1945     } else {
1946       /* short reads can happen if a signal interrupts the read */
1947       continue;
1948     }
1949   } while (TRUE);
1950
1951   GST_LOG_OBJECT (pool, "read %d bytes", amount);
1952   gst_buffer_unmap (buf, &map);
1953   gst_buffer_resize (buf, 0, amount);
1954
1955   return GST_FLOW_OK;
1956
1957   /* ERRORS */
1958 poll_error:
1959   {
1960     GST_DEBUG ("poll error %s", gst_flow_get_name (res));
1961     goto cleanup;
1962   }
1963 read_error:
1964   {
1965     GST_ELEMENT_ERROR (obj->element, RESOURCE, READ,
1966         (_("Error reading %d bytes from device '%s'."),
1967             toread, obj->videodev), GST_ERROR_SYSTEM);
1968     res = GST_FLOW_ERROR;
1969     goto cleanup;
1970   }
1971 cleanup:
1972   {
1973     gst_buffer_unmap (buf, &map);
1974     gst_buffer_resize (buf, 0, 0);
1975     return res;
1976   }
1977 }
1978
1979 /**
1980  * gst_v4l2_buffer_pool_process:
1981  * @bpool: a #GstBufferPool
1982  * @buf: a #GstBuffer, maybe be replaced
1983  * @frame_number: 32 bit frame number or %NULL
1984  *
1985  * Process @buf in @bpool. For capture devices, this functions fills @buf with
1986  * data from the device. For output devices, this functions send the contents of
1987  * @buf to the device for playback.
1988  *
1989  * If non-%NULL and an output device, @frame_number is stored inside the timestamp for output devices and read
1990  * back from the timestamp for capture devices.
1991  *
1992  * Returns: %GST_FLOW_OK on success.
1993  */
1994 GstFlowReturn
1995 gst_v4l2_buffer_pool_process (GstV4l2BufferPool * pool, GstBuffer ** buf,
1996     guint32 * frame_number)
1997 {
1998   GstFlowReturn ret = GST_FLOW_OK;
1999   GstBufferPool *bpool = GST_BUFFER_POOL_CAST (pool);
2000   GstV4l2Object *obj = pool->obj;
2001
2002   GST_DEBUG_OBJECT (pool, "process buffer %p", buf);
2003
2004   if (GST_BUFFER_POOL_IS_FLUSHING (pool))
2005     return GST_FLOW_FLUSHING;
2006
2007   switch (obj->type) {
2008     case V4L2_BUF_TYPE_VIDEO_CAPTURE:
2009     case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE:
2010       /* capture */
2011       switch (obj->mode) {
2012         case GST_V4L2_IO_RW:
2013           /* capture into the buffer */
2014           ret = gst_v4l2_do_read (pool, *buf);
2015           break;
2016
2017         case GST_V4L2_IO_MMAP:
2018         case GST_V4L2_IO_DMABUF:
2019         {
2020           GstBuffer *tmp;
2021
2022           if ((*buf)->pool == bpool) {
2023             guint num_queued;
2024             gsize size = gst_buffer_get_size (*buf);
2025
2026             /* Legacy M2M devices return empty buffer when drained */
2027             if (size == 0 && GST_V4L2_IS_M2M (obj->device_caps))
2028               goto eos;
2029
2030             if (GST_VIDEO_INFO_FORMAT (&pool->caps_info) !=
2031                 GST_VIDEO_FORMAT_ENCODED && size < pool->size)
2032               goto buffer_truncated;
2033
2034             num_queued = g_atomic_int_get (&pool->num_queued);
2035             GST_TRACE_OBJECT (pool, "Only %i buffer left in the capture queue.",
2036                 num_queued);
2037
2038             /* If we have no more buffer, and can allocate it time to do so */
2039             if (num_queued == 0) {
2040               if (GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, MMAP)) {
2041                 ret = gst_v4l2_buffer_pool_resurrect_buffer (pool);
2042                 if (ret == GST_FLOW_OK)
2043                   goto done;
2044               }
2045             }
2046
2047             /* start copying buffers when we are running low on buffers */
2048             if (num_queued < pool->copy_threshold) {
2049               GstBuffer *copy;
2050
2051               if (GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, MMAP)) {
2052                 ret = gst_v4l2_buffer_pool_resurrect_buffer (pool);
2053                 if (ret == GST_FLOW_OK)
2054                   goto done;
2055               }
2056
2057               /* copy the buffer */
2058               copy = gst_buffer_copy_region (*buf,
2059                   GST_BUFFER_COPY_ALL | GST_BUFFER_COPY_DEEP, 0, -1);
2060               GST_LOG_OBJECT (pool, "copy buffer %p->%p", *buf, copy);
2061
2062               /* and requeue so that we can continue capturing */
2063               gst_buffer_unref (*buf);
2064               *buf = copy;
2065             }
2066
2067             ret = GST_FLOW_OK;
2068             /* nothing, data was inside the buffer when we did _acquire() */
2069             goto done;
2070           }
2071
2072           /* buffer not from our pool, grab a frame and copy it into the target */
2073           if ((ret = gst_v4l2_buffer_pool_dqbuf (pool, &tmp, TRUE))
2074               != GST_FLOW_OK)
2075             goto done;
2076
2077           /* An empty buffer on capture indicates the end of stream */
2078           if (gst_buffer_get_size (tmp) == 0) {
2079             gst_v4l2_buffer_pool_release_buffer (bpool, tmp);
2080
2081             /* Legacy M2M devices return empty buffer when drained */
2082             if (GST_V4L2_IS_M2M (obj->device_caps))
2083               goto eos;
2084           }
2085 #ifdef TIZEN_FEATURE_V4L2_TBM_SUPPORT
2086           if (pool->obj->tbm_output && pool->obj->mode == GST_V4L2_IO_DMABUF) {
2087             gst_buffer_unref (*buf);
2088             *buf = tmp;
2089           } else {
2090 #endif /* TIZEN_FEATURE_V4L2_TBM_SUPPORT */
2091           ret = gst_v4l2_buffer_pool_copy_buffer (pool, *buf, tmp);
2092
2093           /* an queue the buffer again after the copy */
2094           gst_v4l2_buffer_pool_release_buffer (bpool, tmp);
2095 #ifdef TIZEN_FEATURE_V4L2_TBM_SUPPORT
2096           }
2097 #endif /* TIZEN_FEATURE_V4L2_TBM_SUPPORT */
2098
2099           if (ret != GST_FLOW_OK)
2100             goto copy_failed;
2101           break;
2102         }
2103
2104         case GST_V4L2_IO_USERPTR:
2105         {
2106           struct UserPtrData *data;
2107           GstBuffer *tmp;
2108
2109           /* Replace our buffer with downstream allocated buffer */
2110           data = gst_mini_object_steal_qdata (GST_MINI_OBJECT (*buf),
2111               GST_V4L2_IMPORT_QUARK);
2112           tmp = gst_buffer_ref (data->buffer);
2113           _unmap_userptr_frame (data);
2114
2115           /* Now tmp is writable, copy the flags and timestamp */
2116           gst_buffer_copy_into (tmp, *buf,
2117               GST_BUFFER_COPY_FLAGS | GST_BUFFER_COPY_TIMESTAMPS, 0, -1);
2118
2119           gst_buffer_replace (buf, tmp);
2120           gst_buffer_unref (tmp);
2121           break;
2122         }
2123
2124         case GST_V4L2_IO_DMABUF_IMPORT:
2125         {
2126           GstBuffer *tmp;
2127
2128           /* Replace our buffer with downstream allocated buffer */
2129           tmp = gst_mini_object_steal_qdata (GST_MINI_OBJECT (*buf),
2130               GST_V4L2_IMPORT_QUARK);
2131
2132           gst_buffer_copy_into (tmp, *buf,
2133               GST_BUFFER_COPY_FLAGS | GST_BUFFER_COPY_TIMESTAMPS, 0, -1);
2134
2135           gst_buffer_replace (buf, tmp);
2136           gst_buffer_unref (tmp);
2137           break;
2138         }
2139
2140         default:
2141           g_assert_not_reached ();
2142           break;
2143       }
2144       break;
2145
2146     case V4L2_BUF_TYPE_VIDEO_OUTPUT:
2147     case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE:
2148       /* playback */
2149       switch (obj->mode) {
2150         case GST_V4L2_IO_RW:
2151           /* FIXME, do write() */
2152           GST_WARNING_OBJECT (pool, "implement write()");
2153           break;
2154
2155         case GST_V4L2_IO_USERPTR:
2156         case GST_V4L2_IO_DMABUF_IMPORT:
2157         case GST_V4L2_IO_DMABUF:
2158         case GST_V4L2_IO_MMAP:
2159         {
2160           GstBuffer *to_queue = NULL;
2161           GstBuffer *buffer;
2162           GstV4l2MemoryGroup *group;
2163           gint index;
2164
2165           if ((*buf)->pool != bpool)
2166             goto copying;
2167
2168           if (!gst_v4l2_is_buffer_valid (*buf, &group))
2169             goto copying;
2170
2171           index = group->buffer.index;
2172
2173           GST_LOG_OBJECT (pool, "processing buffer %i from our pool", index);
2174
2175           if (pool->buffers[index] != NULL) {
2176             GST_LOG_OBJECT (pool, "buffer %i already queued, copying", index);
2177             goto copying;
2178           }
2179
2180           /* we can queue directly */
2181           to_queue = gst_buffer_ref (*buf);
2182
2183         copying:
2184           if (to_queue == NULL) {
2185             GstBufferPoolAcquireParams params = { 0 };
2186
2187             GST_LOG_OBJECT (pool, "alloc buffer from our pool");
2188
2189             /* this can return EOS if all buffers are outstanding which would
2190              * be strange because we would expect the upstream element to have
2191              * allocated them and returned to us.. */
2192             params.flags = GST_BUFFER_POOL_ACQUIRE_FLAG_DONTWAIT;
2193             ret = gst_buffer_pool_acquire_buffer (bpool, &to_queue, &params);
2194             if (ret != GST_FLOW_OK)
2195               goto acquire_failed;
2196
2197             ret = gst_v4l2_buffer_pool_prepare_buffer (pool, to_queue, *buf);
2198             if (ret != GST_FLOW_OK) {
2199               gst_buffer_unref (to_queue);
2200               goto prepare_failed;
2201             }
2202
2203             /* retrieve the group */
2204             gst_v4l2_is_buffer_valid (to_queue, &group);
2205           }
2206
2207           if ((ret =
2208                   gst_v4l2_buffer_pool_qbuf (pool, to_queue, group,
2209                       frame_number))
2210               != GST_FLOW_OK)
2211             goto queue_failed;
2212
2213           /* if we are not streaming yet (this is the first buffer, start
2214            * streaming now */
2215           if (!gst_v4l2_buffer_pool_streamon (pool)) {
2216             /* don't check return value because qbuf would have failed */
2217             gst_v4l2_is_buffer_valid (to_queue, &group);
2218
2219             /* qbuf has stored to_queue buffer but we are not in
2220              * streaming state, so the flush logic won't be performed.
2221              * To avoid leaks, flush the allocator and restore the queued
2222              * buffer as non-queued */
2223             gst_v4l2_allocator_flush (pool->vallocator);
2224
2225             pool->buffers[group->buffer.index] = NULL;
2226
2227             gst_mini_object_set_qdata (GST_MINI_OBJECT (to_queue),
2228                 GST_V4L2_IMPORT_QUARK, NULL, NULL);
2229             gst_buffer_unref (to_queue);
2230             g_atomic_int_add (&pool->num_queued, -1);
2231             goto start_failed;
2232           }
2233
2234           /* Remove our ref, we will still hold this buffer in acquire as needed,
2235            * otherwise the pool will think it is outstanding and will refuse to stop. */
2236           gst_buffer_unref (to_queue);
2237
2238           /* release as many buffer as possible */
2239           while (gst_v4l2_buffer_pool_dqbuf (pool, &buffer, FALSE) ==
2240               GST_FLOW_OK) {
2241             if (buffer->pool == NULL)
2242               gst_v4l2_buffer_pool_release_buffer (bpool, buffer);
2243           }
2244
2245           if (g_atomic_int_get (&pool->num_queued) >= pool->min_latency) {
2246             /* all buffers are queued, try to dequeue one and release it back
2247              * into the pool so that _acquire can get to it again. */
2248             ret = gst_v4l2_buffer_pool_dqbuf (pool, &buffer, TRUE);
2249             if (ret == GST_FLOW_OK && buffer->pool == NULL)
2250               /* release the rendered buffer back into the pool. This wakes up any
2251                * thread waiting for a buffer in _acquire(). */
2252               gst_v4l2_buffer_pool_release_buffer (bpool, buffer);
2253           }
2254           break;
2255         }
2256         default:
2257           g_assert_not_reached ();
2258           break;
2259       }
2260       break;
2261     default:
2262       g_assert_not_reached ();
2263       break;
2264   }
2265 done:
2266   return ret;
2267
2268   /* ERRORS */
2269 copy_failed:
2270   {
2271     GST_ERROR_OBJECT (pool, "failed to copy buffer");
2272     return ret;
2273   }
2274 buffer_truncated:
2275   {
2276     GST_WARNING_OBJECT (pool,
2277         "Dropping truncated buffer, this is likely a driver bug.");
2278     gst_buffer_unref (*buf);
2279     *buf = NULL;
2280     return GST_V4L2_FLOW_CORRUPTED_BUFFER;
2281   }
2282 eos:
2283   {
2284     GST_DEBUG_OBJECT (pool, "end of stream reached");
2285     gst_buffer_unref (*buf);
2286     *buf = NULL;
2287     return GST_V4L2_FLOW_LAST_BUFFER;
2288   }
2289 acquire_failed:
2290   {
2291     if (ret == GST_FLOW_FLUSHING)
2292       GST_DEBUG_OBJECT (pool, "flushing");
2293     else
2294       GST_WARNING_OBJECT (pool, "failed to acquire a buffer: %s",
2295           gst_flow_get_name (ret));
2296     return ret;
2297   }
2298 prepare_failed:
2299   {
2300     GST_ERROR_OBJECT (pool, "failed to prepare data");
2301     return ret;
2302   }
2303 queue_failed:
2304   {
2305     GST_ERROR_OBJECT (pool, "failed to queue buffer");
2306     return ret;
2307   }
2308 start_failed:
2309   {
2310     GST_ERROR_OBJECT (pool, "failed to start streaming");
2311     return GST_FLOW_ERROR;
2312   }
2313 }
2314
2315 void
2316 gst_v4l2_buffer_pool_set_other_pool (GstV4l2BufferPool * pool,
2317     GstBufferPool * other_pool)
2318 {
2319   g_return_if_fail (!gst_buffer_pool_is_active (GST_BUFFER_POOL (pool)));
2320
2321   if (pool->other_pool)
2322     gst_object_unref (pool->other_pool);
2323   pool->other_pool = gst_object_ref (other_pool);
2324 }
2325
2326 void
2327 gst_v4l2_buffer_pool_copy_at_threshold (GstV4l2BufferPool * pool, gboolean copy)
2328 {
2329   GST_OBJECT_LOCK (pool);
2330   pool->enable_copy_threshold = copy;
2331   GST_OBJECT_UNLOCK (pool);
2332 }
2333
2334 gboolean
2335 gst_v4l2_buffer_pool_flush (GstBufferPool * bpool)
2336 {
2337   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
2338   gboolean ret = TRUE;
2339
2340   gst_v4l2_buffer_pool_streamoff (pool);
2341
2342   if (!V4L2_TYPE_IS_OUTPUT (pool->obj->type))
2343     ret = gst_v4l2_buffer_pool_streamon (pool);
2344
2345   return ret;
2346 }
2347
2348 /**
2349  * gst_v4l2_buffer_pool_enable_resolution_change:
2350  * @pool: a #GstBufferPool
2351  *
2352  * When this is called, the pool will subscribe to the
2353  * %V4L2_EVENT_SOURCE_CHANGE. Upon receiving this event, it will notify
2354  * the element acquiring buffer with the special flow return
2355  * %GST_V4L2_FLOW_RESOLUTION_CHANGE.
2356  */
2357 void
2358 gst_v4l2_buffer_pool_enable_resolution_change (GstV4l2BufferPool * pool)
2359 {
2360   guint32 input_id = 0;
2361
2362   g_return_if_fail (!gst_buffer_pool_is_active (GST_BUFFER_POOL (pool)));
2363
2364   /* Make sure we subscribe for the current input */
2365   gst_v4l2_get_input (pool->obj, &input_id);
2366
2367   if (gst_v4l2_subscribe_event (pool->obj, V4L2_EVENT_SOURCE_CHANGE, input_id))
2368     gst_poll_fd_ctl_pri (pool->poll, &pool->pollfd, TRUE);
2369 }