494b5b8d755090a68929ad6447d3ca558b19fc42
[platform/upstream/gst-plugins-good.git] / sys / v4l2 / gstv4l2bufferpool.c
1 /* GStreamer
2  *
3  * Copyright (C) 2001-2002 Ronald Bultje <rbultje@ronald.bitfreak.net>
4  *               2006 Edgard Lima <edgard.lima@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) {
627     updated = TRUE;
628     min_buffers = GST_V4L2_MIN_BUFFERS;
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 recommand 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 immediatly. 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->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) {
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) everytime 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
934       /* There is no rational to not get what we asked */
935       if (count < min_buffers) {
936         min_buffers = count;
937         goto no_buffers;
938       }
939
940       min_buffers = count;
941       break;
942     }
943     case GST_V4L2_IO_DMABUF_IMPORT:
944     {
945       guint count;
946
947       can_allocate = GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, DMABUF);
948
949       GST_DEBUG_OBJECT (pool, "requesting %d DMABUF buffers", min_buffers);
950
951       count = gst_v4l2_allocator_start (pool->vallocator, min_buffers,
952           V4L2_MEMORY_DMABUF);
953
954       /* There is no rational to not get what we asked */
955       if (count < min_buffers) {
956         min_buffers = count;
957         goto no_buffers;
958       }
959
960       min_buffers = count;
961       break;
962     }
963     default:
964       min_buffers = 0;
965       copy_threshold = 0;
966       g_assert_not_reached ();
967       break;
968   }
969
970   if (can_allocate)
971     max_latency = max_buffers;
972   else
973     max_latency = min_buffers;
974
975   pool->size = size;
976   pool->copy_threshold = copy_threshold;
977   pool->max_latency = max_latency;
978   pool->min_latency = min_latency;
979   pool->num_queued = 0;
980
981   if (max_buffers != 0 && max_buffers < min_buffers)
982     max_buffers = min_buffers;
983
984   gst_buffer_pool_config_set_params (config, caps, size, min_buffers,
985       max_buffers);
986   pclass->set_config (bpool, config);
987   gst_structure_free (config);
988
989   /* now, allocate the buffers: */
990   if (!pclass->start (bpool))
991     goto start_failed;
992
993   if (!V4L2_TYPE_IS_OUTPUT (obj->type)) {
994     if (g_atomic_int_get (&pool->num_queued) < min_buffers)
995       goto queue_failed;
996
997     pool->group_released_handler =
998         g_signal_connect_swapped (pool->vallocator, "group-released",
999         G_CALLBACK (gst_v4l2_buffer_pool_resurrect_buffer), pool);
1000     ret = gst_v4l2_buffer_pool_streamon (pool);
1001   }
1002
1003   return ret;
1004
1005   /* ERRORS */
1006 wrong_config:
1007   {
1008     GST_ERROR_OBJECT (pool, "invalid config %" GST_PTR_FORMAT, config);
1009     gst_structure_free (config);
1010     return FALSE;
1011   }
1012 no_buffers:
1013   {
1014     GST_ERROR_OBJECT (pool,
1015         "we received %d buffer from device '%s', we want at least %d",
1016         min_buffers, obj->videodev, GST_V4L2_MIN_BUFFERS);
1017     gst_structure_free (config);
1018     return FALSE;
1019   }
1020 start_failed:
1021   {
1022     GST_ERROR_OBJECT (pool, "allocate failed");
1023     return FALSE;
1024   }
1025 other_pool_failed:
1026   {
1027     GST_ERROR_OBJECT (pool, "failed to activate the other pool %"
1028         GST_PTR_FORMAT, pool->other_pool);
1029     return FALSE;
1030   }
1031 queue_failed:
1032   {
1033     GST_ERROR_OBJECT (pool, "failed to queue buffers into the capture queue");
1034     return FALSE;
1035   }
1036 cannot_import:
1037   {
1038     GST_ERROR_OBJECT (pool, "cannot import buffers from downstream pool");
1039     return FALSE;
1040   }
1041 }
1042
1043 static gboolean
1044 gst_v4l2_buffer_pool_vallocator_stop (GstV4l2BufferPool * pool)
1045 {
1046   GstV4l2Return vret;
1047
1048   if (!pool->vallocator)
1049     return TRUE;
1050
1051   vret = gst_v4l2_allocator_stop (pool->vallocator);
1052
1053   if (vret == GST_V4L2_BUSY)
1054     GST_WARNING_OBJECT (pool, "some buffers are still outstanding");
1055
1056   return (vret == GST_V4L2_OK);
1057 }
1058
1059 static gboolean
1060 gst_v4l2_buffer_pool_stop (GstBufferPool * bpool)
1061 {
1062   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
1063   gboolean ret;
1064
1065   if (pool->orphaned)
1066     return gst_v4l2_buffer_pool_vallocator_stop (pool);
1067
1068   GST_DEBUG_OBJECT (pool, "stopping pool");
1069
1070   if (pool->group_released_handler > 0) {
1071     g_signal_handler_disconnect (pool->vallocator,
1072         pool->group_released_handler);
1073     pool->group_released_handler = 0;
1074   }
1075
1076   if (pool->other_pool) {
1077     gst_buffer_pool_set_active (pool->other_pool, FALSE);
1078     gst_object_unref (pool->other_pool);
1079     pool->other_pool = NULL;
1080   }
1081
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   if (!GST_V4L2_ALLOCATOR_CAN_ORPHAN_BUFS (pool->vallocator))
1099     return FALSE;
1100
1101   if (g_getenv ("GST_V4L2_FORCE_DRAIN"))
1102     return FALSE;
1103
1104   GST_DEBUG_OBJECT (pool, "orphaning pool");
1105
1106   gst_buffer_pool_set_active (*bpool, FALSE);
1107   /*
1108    * If the buffer pool has outstanding buffers, it will not be stopped
1109    * by the base class when set inactive. Stop it manually and mark it
1110    * as orphaned
1111    */
1112   ret = gst_v4l2_buffer_pool_stop (*bpool);
1113   if (!ret)
1114     ret = gst_v4l2_allocator_orphan (pool->vallocator);
1115
1116   if (!ret)
1117     goto orphan_failed;
1118
1119   pool->orphaned = TRUE;
1120   gst_object_unref (*bpool);
1121   *bpool = NULL;
1122
1123 orphan_failed:
1124   return ret;
1125 }
1126
1127 static void
1128 gst_v4l2_buffer_pool_flush_start (GstBufferPool * bpool)
1129 {
1130   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
1131
1132   GST_DEBUG_OBJECT (pool, "start flushing");
1133
1134   gst_poll_set_flushing (pool->poll, TRUE);
1135
1136   GST_OBJECT_LOCK (pool);
1137   pool->empty = FALSE;
1138   g_cond_broadcast (&pool->empty_cond);
1139   GST_OBJECT_UNLOCK (pool);
1140
1141   if (pool->other_pool)
1142     gst_buffer_pool_set_flushing (pool->other_pool, TRUE);
1143 }
1144
1145 static void
1146 gst_v4l2_buffer_pool_flush_stop (GstBufferPool * bpool)
1147 {
1148   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
1149
1150   GST_DEBUG_OBJECT (pool, "stop flushing");
1151
1152   if (pool->other_pool)
1153     gst_buffer_pool_set_flushing (pool->other_pool, FALSE);
1154
1155   gst_poll_set_flushing (pool->poll, FALSE);
1156 }
1157
1158 static GstFlowReturn
1159 gst_v4l2_buffer_pool_poll (GstV4l2BufferPool * pool, gboolean wait)
1160 {
1161   gint ret;
1162   GstClockTime timeout;
1163
1164   if (wait)
1165     timeout = GST_CLOCK_TIME_NONE;
1166   else
1167     timeout = 0;
1168
1169   /* In RW mode there is no queue, hence no need to wait while the queue is
1170    * empty */
1171   if (pool->obj->mode != GST_V4L2_IO_RW) {
1172     GST_OBJECT_LOCK (pool);
1173
1174     if (!wait && pool->empty) {
1175       GST_OBJECT_UNLOCK (pool);
1176       goto no_buffers;
1177     }
1178
1179     while (pool->empty)
1180       g_cond_wait (&pool->empty_cond, GST_OBJECT_GET_LOCK (pool));
1181
1182     GST_OBJECT_UNLOCK (pool);
1183   }
1184
1185   if (!pool->can_poll_device) {
1186     if (wait)
1187       goto done;
1188     else
1189       goto no_buffers;
1190   }
1191
1192   GST_LOG_OBJECT (pool, "polling device");
1193
1194 again:
1195   ret = gst_poll_wait (pool->poll, timeout);
1196   if (G_UNLIKELY (ret < 0)) {
1197     switch (errno) {
1198       case EBUSY:
1199         goto stopped;
1200       case EAGAIN:
1201       case EINTR:
1202         goto again;
1203       case ENXIO:
1204         GST_WARNING_OBJECT (pool,
1205             "v4l2 device doesn't support polling. Disabling"
1206             " using libv4l2 in this case may cause deadlocks");
1207         pool->can_poll_device = FALSE;
1208         goto done;
1209       default:
1210         goto select_error;
1211     }
1212   }
1213
1214   if (gst_poll_fd_has_error (pool->poll, &pool->pollfd))
1215     goto select_error;
1216
1217   if (ret == 0)
1218     goto no_buffers;
1219
1220 done:
1221   return GST_FLOW_OK;
1222
1223   /* ERRORS */
1224 stopped:
1225   {
1226     GST_DEBUG_OBJECT (pool, "stop called");
1227     return GST_FLOW_FLUSHING;
1228   }
1229 select_error:
1230   {
1231     GST_ELEMENT_ERROR (pool->obj->element, RESOURCE, READ, (NULL),
1232         ("poll error %d: %s (%d)", ret, g_strerror (errno), errno));
1233     return GST_FLOW_ERROR;
1234   }
1235 no_buffers:
1236   return GST_FLOW_CUSTOM_SUCCESS;
1237 }
1238
1239 static GstFlowReturn
1240 gst_v4l2_buffer_pool_qbuf (GstV4l2BufferPool * pool, GstBuffer * buf,
1241     GstV4l2MemoryGroup * group)
1242 {
1243   const GstV4l2Object *obj = pool->obj;
1244   GstClockTime timestamp;
1245   gint index;
1246
1247   index = group->buffer.index;
1248
1249   if (pool->buffers[index] != NULL)
1250     goto already_queued;
1251
1252   GST_LOG_OBJECT (pool, "queuing buffer %i", index);
1253
1254   if (V4L2_TYPE_IS_OUTPUT (obj->type)) {
1255     enum v4l2_field field;
1256
1257     /* Except when field is set to alternate, buffer field is the same as
1258      * the one defined in format */
1259     if (V4L2_TYPE_IS_MULTIPLANAR (obj->type))
1260       field = obj->format.fmt.pix_mp.field;
1261     else
1262       field = obj->format.fmt.pix.field;
1263
1264     /* NB: At this moment, we can't have alternate mode because it not handled
1265      * yet */
1266     if (field == V4L2_FIELD_ALTERNATE) {
1267       if (GST_BUFFER_FLAG_IS_SET (buf, GST_VIDEO_FRAME_FLAG_TFF))
1268         field = V4L2_FIELD_TOP;
1269       else
1270         field = V4L2_FIELD_BOTTOM;
1271     }
1272
1273     group->buffer.field = field;
1274   }
1275
1276   if (GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
1277     timestamp = GST_BUFFER_TIMESTAMP (buf);
1278     GST_TIME_TO_TIMEVAL (timestamp, group->buffer.timestamp);
1279   }
1280
1281   GST_OBJECT_LOCK (pool);
1282   g_atomic_int_inc (&pool->num_queued);
1283   pool->buffers[index] = buf;
1284
1285   if (!gst_v4l2_allocator_qbuf (pool->vallocator, group))
1286     goto queue_failed;
1287
1288   pool->empty = FALSE;
1289   g_cond_signal (&pool->empty_cond);
1290   GST_OBJECT_UNLOCK (pool);
1291
1292   return GST_FLOW_OK;
1293
1294 already_queued:
1295   {
1296     GST_ERROR_OBJECT (pool, "the buffer %i was already queued", index);
1297     return GST_FLOW_ERROR;
1298   }
1299 queue_failed:
1300   {
1301     GST_ERROR_OBJECT (pool, "could not queue a buffer %i", index);
1302     /* Mark broken buffer to the allocator */
1303     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_TAG_MEMORY);
1304     g_atomic_int_add (&pool->num_queued, -1);
1305     pool->buffers[index] = NULL;
1306     GST_OBJECT_UNLOCK (pool);
1307     return GST_FLOW_ERROR;
1308   }
1309 }
1310
1311 static GstFlowReturn
1312 gst_v4l2_buffer_pool_dqbuf (GstV4l2BufferPool * pool, GstBuffer ** buffer,
1313     gboolean wait)
1314 {
1315   GstFlowReturn res;
1316   GstBuffer *outbuf = NULL;
1317   GstV4l2Object *obj = pool->obj;
1318   GstClockTime timestamp;
1319   GstV4l2MemoryGroup *group;
1320   GstVideoMeta *vmeta;
1321   gsize size;
1322   gint i;
1323 #ifdef TIZEN_FEATURE_V4L2_TBM_SUPPORT
1324   GstV4l2TizenBuffer *tizen_buffer = NULL;
1325 #endif /* TIZEN_FEATURE_V4L2_TBM_SUPPORT */
1326
1327   if ((res = gst_v4l2_buffer_pool_poll (pool, wait)) < GST_FLOW_OK)
1328     goto poll_failed;
1329
1330   if (res == GST_FLOW_CUSTOM_SUCCESS) {
1331     GST_LOG_OBJECT (pool, "nothing to dequeue");
1332     goto done;
1333   }
1334
1335   GST_LOG_OBJECT (pool, "dequeueing a buffer");
1336
1337   res = gst_v4l2_allocator_dqbuf (pool->vallocator, &group);
1338   if (res == GST_FLOW_EOS)
1339     goto eos;
1340   if (res != GST_FLOW_OK)
1341     goto dqbuf_failed;
1342
1343   /* get our GstBuffer with that index from the pool, if the buffer was
1344    * outstanding we have a serious problem.
1345    */
1346   outbuf = pool->buffers[group->buffer.index];
1347   if (outbuf == NULL)
1348     goto no_buffer;
1349
1350   /* mark the buffer outstanding */
1351   pool->buffers[group->buffer.index] = NULL;
1352   if (g_atomic_int_dec_and_test (&pool->num_queued)) {
1353     GST_OBJECT_LOCK (pool);
1354     pool->empty = TRUE;
1355     GST_OBJECT_UNLOCK (pool);
1356   }
1357
1358   timestamp = GST_TIMEVAL_TO_TIME (group->buffer.timestamp);
1359
1360   size = 0;
1361   vmeta = gst_buffer_get_video_meta (outbuf);
1362   for (i = 0; i < group->n_mem; i++) {
1363     GST_LOG_OBJECT (pool,
1364         "dequeued buffer %p seq:%d (ix=%d), mem %p used %d, plane=%d, flags %08x, ts %"
1365         GST_TIME_FORMAT ", pool-queued=%d, buffer=%p", outbuf,
1366         group->buffer.sequence, group->buffer.index, group->mem[i],
1367         group->planes[i].bytesused, i, group->buffer.flags,
1368         GST_TIME_ARGS (timestamp), pool->num_queued, outbuf);
1369
1370     if (vmeta) {
1371       vmeta->offset[i] = size;
1372       size += gst_memory_get_sizes (group->mem[i], NULL, NULL);
1373     }
1374   }
1375
1376   /* Ignore timestamp and field for OUTPUT device */
1377   if (V4L2_TYPE_IS_OUTPUT (obj->type))
1378     goto done;
1379
1380   /* Check for driver bug in reporting feild */
1381   if (group->buffer.field == V4L2_FIELD_ANY) {
1382     /* Only warn once to avoid the spamming */
1383 #ifndef GST_DISABLE_GST_DEBUG
1384     if (!pool->has_warned_on_buggy_field) {
1385       pool->has_warned_on_buggy_field = TRUE;
1386       GST_WARNING_OBJECT (pool,
1387           "Driver should never set v4l2_buffer.field to ANY");
1388     }
1389 #endif
1390
1391     /* Use the value from the format (works for UVC bug) */
1392     group->buffer.field = obj->format.fmt.pix.field;
1393
1394     /* If driver also has buggy S_FMT, assume progressive */
1395     if (group->buffer.field == V4L2_FIELD_ANY) {
1396 #ifndef GST_DISABLE_GST_DEBUG
1397       if (!pool->has_warned_on_buggy_field) {
1398         pool->has_warned_on_buggy_field = TRUE;
1399         GST_WARNING_OBJECT (pool,
1400             "Driver should never set v4l2_format.pix.field to ANY");
1401       }
1402 #endif
1403
1404       group->buffer.field = V4L2_FIELD_NONE;
1405     }
1406   }
1407
1408   /* set top/bottom field first if v4l2_buffer has the information */
1409   switch (group->buffer.field) {
1410     case V4L2_FIELD_NONE:
1411       GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_FLAG_INTERLACED);
1412       GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
1413       break;
1414     case V4L2_FIELD_INTERLACED_TB:
1415       GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_INTERLACED);
1416       GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
1417       break;
1418     case V4L2_FIELD_INTERLACED_BT:
1419       GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_INTERLACED);
1420       GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
1421       break;
1422     case V4L2_FIELD_INTERLACED:
1423       GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_INTERLACED);
1424       if (obj->tv_norm == V4L2_STD_NTSC_M ||
1425           obj->tv_norm == V4L2_STD_NTSC_M_JP ||
1426           obj->tv_norm == V4L2_STD_NTSC_M_KR) {
1427         GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
1428       } else {
1429         GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
1430       }
1431       break;
1432     default:
1433       GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_FLAG_INTERLACED);
1434       GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
1435       GST_FIXME_OBJECT (pool,
1436           "Unhandled enum v4l2_field %d - treating as progressive",
1437           group->buffer.field);
1438       break;
1439   }
1440
1441   if (GST_VIDEO_INFO_FORMAT (&obj->info) == GST_VIDEO_FORMAT_ENCODED) {
1442     if ((group->buffer.flags & V4L2_BUF_FLAG_KEYFRAME) ||
1443         GST_V4L2_PIXELFORMAT (obj) == V4L2_PIX_FMT_MJPEG ||
1444         GST_V4L2_PIXELFORMAT (obj) == V4L2_PIX_FMT_JPEG ||
1445         GST_V4L2_PIXELFORMAT (obj) == V4L2_PIX_FMT_PJPG)
1446       GST_BUFFER_FLAG_UNSET (outbuf, GST_BUFFER_FLAG_DELTA_UNIT);
1447     else
1448       GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DELTA_UNIT);
1449   }
1450
1451   if (group->buffer.flags & V4L2_BUF_FLAG_ERROR)
1452     GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_CORRUPTED);
1453
1454   GST_BUFFER_TIMESTAMP (outbuf) = timestamp;
1455   GST_BUFFER_OFFSET (outbuf) = group->buffer.sequence;
1456   GST_BUFFER_OFFSET_END (outbuf) = group->buffer.sequence + 1;
1457
1458 #ifdef TIZEN_FEATURE_V4L2_TBM_SUPPORT
1459   if (group->surface) {
1460     tizen_buffer = gst_v4l2_tizen_buffer_new (outbuf, group->buffer.index, pool);
1461     if (!tizen_buffer) {
1462       GST_ERROR_OBJECT (pool, "tizen buffer failed for index[%d]", group->buffer.index);
1463       goto no_buffer;
1464     }
1465     outbuf = tizen_buffer->gst_buffer;
1466   }
1467 #endif /* TIZEN_FEATURE_V4L2_TBM_SUPPORT */
1468 done:
1469   *buffer = outbuf;
1470
1471   return res;
1472
1473   /* ERRORS */
1474 poll_failed:
1475   {
1476     GST_DEBUG_OBJECT (pool, "poll error %s", gst_flow_get_name (res));
1477     return res;
1478   }
1479 eos:
1480   {
1481     return GST_FLOW_EOS;
1482   }
1483 dqbuf_failed:
1484   {
1485     return GST_FLOW_ERROR;
1486   }
1487 no_buffer:
1488   {
1489     GST_ERROR_OBJECT (pool, "No free buffer found in the pool at index %d.",
1490         group->buffer.index);
1491     return GST_FLOW_ERROR;
1492   }
1493 }
1494
1495 static GstFlowReturn
1496 gst_v4l2_buffer_pool_acquire_buffer (GstBufferPool * bpool, GstBuffer ** buffer,
1497     GstBufferPoolAcquireParams * params)
1498 {
1499   GstFlowReturn ret;
1500   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
1501   GstBufferPoolClass *pclass = GST_BUFFER_POOL_CLASS (parent_class);
1502   GstV4l2Object *obj = pool->obj;
1503
1504   GST_DEBUG_OBJECT (pool, "acquire");
1505
1506   /* If this is being called to resurrect a lost buffer */
1507   if (params && params->flags & GST_V4L2_BUFFER_POOL_ACQUIRE_FLAG_RESURRECT) {
1508     ret = pclass->acquire_buffer (bpool, buffer, params);
1509     goto done;
1510   }
1511
1512   switch (obj->type) {
1513     case V4L2_BUF_TYPE_VIDEO_CAPTURE:
1514     case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE:
1515       /* capture, This function should return a buffer with new captured data */
1516       switch (obj->mode) {
1517         case GST_V4L2_IO_RW:
1518         {
1519           /* take empty buffer from the pool */
1520           ret = pclass->acquire_buffer (bpool, buffer, params);
1521           break;
1522         }
1523         case GST_V4L2_IO_DMABUF:
1524         case GST_V4L2_IO_MMAP:
1525         case GST_V4L2_IO_USERPTR:
1526         case GST_V4L2_IO_DMABUF_IMPORT:
1527         {
1528           /* just dequeue a buffer, we basically use the queue of v4l2 as the
1529            * storage for our buffers. This function does poll first so we can
1530            * interrupt it fine. */
1531           ret = gst_v4l2_buffer_pool_dqbuf (pool, buffer, TRUE);
1532           break;
1533         }
1534         default:
1535           ret = GST_FLOW_ERROR;
1536           g_assert_not_reached ();
1537           break;
1538       }
1539       break;
1540
1541
1542     case V4L2_BUF_TYPE_VIDEO_OUTPUT:
1543     case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE:
1544       /* playback, This function should return an empty buffer */
1545       switch (obj->mode) {
1546         case GST_V4L2_IO_RW:
1547           /* get an empty buffer */
1548           ret = pclass->acquire_buffer (bpool, buffer, params);
1549           break;
1550
1551         case GST_V4L2_IO_MMAP:
1552         case GST_V4L2_IO_DMABUF:
1553         case GST_V4L2_IO_USERPTR:
1554         case GST_V4L2_IO_DMABUF_IMPORT:
1555           /* get a free unqueued buffer */
1556           ret = pclass->acquire_buffer (bpool, buffer, params);
1557           break;
1558
1559         default:
1560           ret = GST_FLOW_ERROR;
1561           g_assert_not_reached ();
1562           break;
1563       }
1564       break;
1565
1566     default:
1567       ret = GST_FLOW_ERROR;
1568       g_assert_not_reached ();
1569       break;
1570   }
1571 done:
1572   return ret;
1573 }
1574
1575 static void
1576 gst_v4l2_buffer_pool_release_buffer (GstBufferPool * bpool, GstBuffer * buffer)
1577 {
1578   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
1579   GstBufferPoolClass *pclass = GST_BUFFER_POOL_CLASS (parent_class);
1580   GstV4l2Object *obj = pool->obj;
1581
1582   GST_DEBUG_OBJECT (pool, "release buffer %p", buffer);
1583
1584   /* If the buffer's pool has been orphaned, dispose of it so that
1585    * the pool resources can be freed */
1586   if (pool->orphaned) {
1587     GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_TAG_MEMORY);
1588     pclass->release_buffer (bpool, buffer);
1589     return;
1590   }
1591
1592   switch (obj->type) {
1593     case V4L2_BUF_TYPE_VIDEO_CAPTURE:
1594     case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE:
1595       /* capture, put the buffer back in the queue so that we can refill it
1596        * later. */
1597       switch (obj->mode) {
1598         case GST_V4L2_IO_RW:
1599           /* release back in the pool */
1600           pclass->release_buffer (bpool, buffer);
1601           break;
1602
1603         case GST_V4L2_IO_DMABUF:
1604         case GST_V4L2_IO_MMAP:
1605         case GST_V4L2_IO_USERPTR:
1606         case GST_V4L2_IO_DMABUF_IMPORT:
1607         {
1608           GstV4l2MemoryGroup *group;
1609           if (gst_v4l2_is_buffer_valid (buffer, &group)) {
1610             GstFlowReturn ret = GST_FLOW_OK;
1611
1612             gst_v4l2_allocator_reset_group (pool->vallocator, group);
1613             /* queue back in the device */
1614             if (pool->other_pool)
1615               ret = gst_v4l2_buffer_pool_prepare_buffer (pool, buffer, NULL);
1616             if (ret != GST_FLOW_OK ||
1617                 gst_v4l2_buffer_pool_qbuf (pool, buffer, group) != GST_FLOW_OK)
1618               pclass->release_buffer (bpool, buffer);
1619           } else {
1620             /* Simply release invalide/modified buffer, the allocator will
1621              * give it back later */
1622             GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_TAG_MEMORY);
1623             pclass->release_buffer (bpool, buffer);
1624           }
1625           break;
1626         }
1627         default:
1628           g_assert_not_reached ();
1629           break;
1630       }
1631       break;
1632
1633     case V4L2_BUF_TYPE_VIDEO_OUTPUT:
1634     case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE:
1635       switch (obj->mode) {
1636         case GST_V4L2_IO_RW:
1637           /* release back in the pool */
1638           pclass->release_buffer (bpool, buffer);
1639           break;
1640
1641         case GST_V4L2_IO_MMAP:
1642         case GST_V4L2_IO_DMABUF:
1643         case GST_V4L2_IO_USERPTR:
1644         case GST_V4L2_IO_DMABUF_IMPORT:
1645         {
1646           GstV4l2MemoryGroup *group;
1647           guint index;
1648
1649           if (!gst_v4l2_is_buffer_valid (buffer, &group)) {
1650             /* Simply release invalide/modified buffer, the allocator will
1651              * give it back later */
1652             GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_TAG_MEMORY);
1653             pclass->release_buffer (bpool, buffer);
1654             break;
1655           }
1656
1657           index = group->buffer.index;
1658
1659           if (pool->buffers[index] == NULL) {
1660             GST_LOG_OBJECT (pool, "buffer %u not queued, putting on free list",
1661                 index);
1662
1663             /* Remove qdata, this will unmap any map data in userptr */
1664             gst_mini_object_set_qdata (GST_MINI_OBJECT (buffer),
1665                 GST_V4L2_IMPORT_QUARK, NULL, NULL);
1666
1667             /* reset to default size */
1668             gst_v4l2_allocator_reset_group (pool->vallocator, group);
1669
1670             /* playback, put the buffer back in the queue to refill later. */
1671             pclass->release_buffer (bpool, buffer);
1672           } else {
1673             /* the buffer is queued in the device but maybe not played yet. We just
1674              * leave it there and not make it available for future calls to acquire
1675              * for now. The buffer will be dequeued and reused later. */
1676             GST_LOG_OBJECT (pool, "buffer %u is queued", index);
1677           }
1678           break;
1679         }
1680
1681         default:
1682           g_assert_not_reached ();
1683           break;
1684       }
1685       break;
1686
1687     default:
1688       g_assert_not_reached ();
1689       break;
1690   }
1691 }
1692
1693 static void
1694 gst_v4l2_buffer_pool_dispose (GObject * object)
1695 {
1696   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (object);
1697
1698   if (pool->vallocator)
1699     gst_object_unref (pool->vallocator);
1700   pool->vallocator = NULL;
1701
1702   if (pool->allocator)
1703     gst_object_unref (pool->allocator);
1704   pool->allocator = NULL;
1705
1706 #ifdef TIZEN_FEATURE_V4L2_TBM_SUPPORT
1707   g_cond_clear (&pool->buffer_cond);
1708   g_mutex_clear (&pool->buffer_lock);
1709
1710   if (pool->tallocator)
1711     gst_object_unref (pool->tallocator);
1712   pool->tallocator = NULL;
1713 #endif /* TIZEN_FEATURE_V4L2_TBM_SUPPORT */
1714   if (pool->other_pool)
1715     gst_object_unref (pool->other_pool);
1716   pool->other_pool = NULL;
1717
1718   G_OBJECT_CLASS (parent_class)->dispose (object);
1719 }
1720
1721 static void
1722 gst_v4l2_buffer_pool_finalize (GObject * object)
1723 {
1724   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (object);
1725
1726   if (pool->video_fd >= 0)
1727     pool->obj->close (pool->video_fd);
1728
1729   gst_poll_free (pool->poll);
1730
1731   /* This can't be done in dispose method because we must not set pointer
1732    * to NULL as it is part of the v4l2object and dispose could be called
1733    * multiple times */
1734   gst_object_unref (pool->obj->element);
1735
1736   g_cond_clear (&pool->empty_cond);
1737
1738   /* FIXME have we done enough here ? */
1739
1740   G_OBJECT_CLASS (parent_class)->finalize (object);
1741 }
1742
1743 static void
1744 gst_v4l2_buffer_pool_init (GstV4l2BufferPool * pool)
1745 {
1746   pool->poll = gst_poll_new (TRUE);
1747   pool->can_poll_device = TRUE;
1748   g_cond_init (&pool->empty_cond);
1749   pool->empty = TRUE;
1750   pool->orphaned = FALSE;
1751 }
1752
1753 static void
1754 gst_v4l2_buffer_pool_class_init (GstV4l2BufferPoolClass * klass)
1755 {
1756   GObjectClass *object_class = G_OBJECT_CLASS (klass);
1757   GstBufferPoolClass *bufferpool_class = GST_BUFFER_POOL_CLASS (klass);
1758
1759   object_class->dispose = gst_v4l2_buffer_pool_dispose;
1760   object_class->finalize = gst_v4l2_buffer_pool_finalize;
1761
1762   bufferpool_class->start = gst_v4l2_buffer_pool_start;
1763   bufferpool_class->stop = gst_v4l2_buffer_pool_stop;
1764   bufferpool_class->set_config = gst_v4l2_buffer_pool_set_config;
1765   bufferpool_class->alloc_buffer = gst_v4l2_buffer_pool_alloc_buffer;
1766   bufferpool_class->acquire_buffer = gst_v4l2_buffer_pool_acquire_buffer;
1767   bufferpool_class->release_buffer = gst_v4l2_buffer_pool_release_buffer;
1768   bufferpool_class->flush_start = gst_v4l2_buffer_pool_flush_start;
1769   bufferpool_class->flush_stop = gst_v4l2_buffer_pool_flush_stop;
1770
1771   GST_DEBUG_CATEGORY_INIT (v4l2bufferpool_debug, "v4l2bufferpool", 0,
1772       "V4L2 Buffer Pool");
1773   GST_DEBUG_CATEGORY_GET (CAT_PERFORMANCE, "GST_PERFORMANCE");
1774 }
1775
1776 /**
1777  * gst_v4l2_buffer_pool_new:
1778  * @obj:  the v4l2 object owning the pool
1779  *
1780  * Construct a new buffer pool.
1781  *
1782  * Returns: the new pool, use gst_object_unref() to free resources
1783  */
1784 GstBufferPool *
1785 gst_v4l2_buffer_pool_new (GstV4l2Object * obj, GstCaps * caps)
1786 {
1787   GstV4l2BufferPool *pool;
1788   GstStructure *config;
1789   gchar *name, *parent_name;
1790   gint fd;
1791
1792   fd = obj->dup (obj->video_fd);
1793   if (fd < 0)
1794     goto dup_failed;
1795
1796   /* setting a significant unique name */
1797   parent_name = gst_object_get_name (GST_OBJECT (obj->element));
1798   name = g_strconcat (parent_name, ":", "pool:",
1799       V4L2_TYPE_IS_OUTPUT (obj->type) ? "sink" : "src", NULL);
1800   g_free (parent_name);
1801
1802   pool = (GstV4l2BufferPool *) g_object_new (GST_TYPE_V4L2_BUFFER_POOL,
1803       "name", name, NULL);
1804   g_object_ref_sink (pool);
1805   g_free (name);
1806
1807   gst_poll_fd_init (&pool->pollfd);
1808   pool->pollfd.fd = fd;
1809   gst_poll_add_fd (pool->poll, &pool->pollfd);
1810   if (V4L2_TYPE_IS_OUTPUT (obj->type))
1811     gst_poll_fd_ctl_write (pool->poll, &pool->pollfd, TRUE);
1812   else
1813     gst_poll_fd_ctl_read (pool->poll, &pool->pollfd, TRUE);
1814
1815   pool->video_fd = fd;
1816   pool->obj = obj;
1817   pool->can_poll_device = TRUE;
1818
1819 #ifdef TIZEN_FEATURE_V4L2_TBM_SUPPORT
1820   pool->tallocator = gst_tizen_allocator_new ();
1821   if (pool->tallocator == NULL)
1822     goto allocator_failed;
1823
1824   g_mutex_init (&pool->buffer_lock);
1825   g_cond_init (&pool->buffer_cond);
1826 #endif /* TIZEN_FEATURE_V4L2_TBM_SUPPORT */
1827   pool->vallocator = gst_v4l2_allocator_new (GST_OBJECT (pool), obj);
1828   if (pool->vallocator == NULL)
1829     goto allocator_failed;
1830
1831   gst_object_ref (obj->element);
1832
1833   config = gst_buffer_pool_get_config (GST_BUFFER_POOL_CAST (pool));
1834   gst_buffer_pool_config_set_params (config, caps, obj->info.size, 0, 0);
1835   /* This will simply set a default config, but will not configure the pool
1836    * because min and max are not valid */
1837   gst_buffer_pool_set_config (GST_BUFFER_POOL_CAST (pool), config);
1838
1839   return GST_BUFFER_POOL (pool);
1840
1841   /* ERRORS */
1842 dup_failed:
1843   {
1844     GST_ERROR ("failed to dup fd %d (%s)", errno, g_strerror (errno));
1845     return NULL;
1846   }
1847 allocator_failed:
1848   {
1849 #ifdef TIZEN_FEATURE_V4L2_TBM_SUPPORT
1850     if (pool->tallocator) {
1851       gst_object_unref (pool->tallocator);
1852       pool->tallocator = NULL;
1853     }
1854 #endif /* TIZEN_FEATURE_V4L2_TBM_SUPPORT */
1855     GST_ERROR_OBJECT (pool, "Failed to create V4L2 allocator");
1856     gst_object_unref (pool);
1857     return NULL;
1858   }
1859 }
1860
1861 static GstFlowReturn
1862 gst_v4l2_do_read (GstV4l2BufferPool * pool, GstBuffer * buf)
1863 {
1864   GstFlowReturn res;
1865   GstV4l2Object *obj = pool->obj;
1866   gint amount;
1867   GstMapInfo map;
1868   gint toread;
1869
1870   toread = obj->info.size;
1871
1872   GST_LOG_OBJECT (pool, "reading %d bytes into buffer %p", toread, buf);
1873
1874   gst_buffer_map (buf, &map, GST_MAP_WRITE);
1875
1876   do {
1877     if ((res = gst_v4l2_buffer_pool_poll (pool, TRUE)) != GST_FLOW_OK)
1878       goto poll_error;
1879
1880     amount = obj->read (obj->video_fd, map.data, toread);
1881
1882     if (amount == toread) {
1883       break;
1884     } else if (amount == -1) {
1885       if (errno == EAGAIN || errno == EINTR) {
1886         continue;
1887       } else
1888         goto read_error;
1889     } else {
1890       /* short reads can happen if a signal interrupts the read */
1891       continue;
1892     }
1893   } while (TRUE);
1894
1895   GST_LOG_OBJECT (pool, "read %d bytes", amount);
1896   gst_buffer_unmap (buf, &map);
1897   gst_buffer_resize (buf, 0, amount);
1898
1899   return GST_FLOW_OK;
1900
1901   /* ERRORS */
1902 poll_error:
1903   {
1904     GST_DEBUG ("poll error %s", gst_flow_get_name (res));
1905     goto cleanup;
1906   }
1907 read_error:
1908   {
1909     GST_ELEMENT_ERROR (obj->element, RESOURCE, READ,
1910         (_("Error reading %d bytes from device '%s'."),
1911             toread, obj->videodev), GST_ERROR_SYSTEM);
1912     res = GST_FLOW_ERROR;
1913     goto cleanup;
1914   }
1915 cleanup:
1916   {
1917     gst_buffer_unmap (buf, &map);
1918     gst_buffer_resize (buf, 0, 0);
1919     return res;
1920   }
1921 }
1922
1923 /**
1924  * gst_v4l2_buffer_pool_process:
1925  * @bpool: a #GstBufferPool
1926  * @buf: a #GstBuffer, maybe be replaced
1927  *
1928  * Process @buf in @bpool. For capture devices, this functions fills @buf with
1929  * data from the device. For output devices, this functions send the contents of
1930  * @buf to the device for playback.
1931  *
1932  * Returns: %GST_FLOW_OK on success.
1933  */
1934 GstFlowReturn
1935 gst_v4l2_buffer_pool_process (GstV4l2BufferPool * pool, GstBuffer ** buf)
1936 {
1937   GstFlowReturn ret = GST_FLOW_OK;
1938   GstBufferPool *bpool = GST_BUFFER_POOL_CAST (pool);
1939   GstV4l2Object *obj = pool->obj;
1940
1941   GST_DEBUG_OBJECT (pool, "process buffer %p", buf);
1942
1943   if (GST_BUFFER_POOL_IS_FLUSHING (pool))
1944     return GST_FLOW_FLUSHING;
1945
1946   switch (obj->type) {
1947     case V4L2_BUF_TYPE_VIDEO_CAPTURE:
1948     case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE:
1949       /* capture */
1950       switch (obj->mode) {
1951         case GST_V4L2_IO_RW:
1952           /* capture into the buffer */
1953           ret = gst_v4l2_do_read (pool, *buf);
1954           break;
1955
1956         case GST_V4L2_IO_MMAP:
1957         case GST_V4L2_IO_DMABUF:
1958         {
1959           GstBuffer *tmp;
1960
1961           if ((*buf)->pool == bpool) {
1962             guint num_queued;
1963             gsize size = gst_buffer_get_size (*buf);
1964
1965             /* Legacy M2M devices return empty buffer when drained */
1966             if (size == 0 && GST_V4L2_IS_M2M (obj->device_caps))
1967               goto eos;
1968
1969             if (GST_VIDEO_INFO_FORMAT (&pool->caps_info) !=
1970                 GST_VIDEO_FORMAT_ENCODED && size < pool->size)
1971               goto buffer_truncated;
1972
1973             num_queued = g_atomic_int_get (&pool->num_queued);
1974             GST_TRACE_OBJECT (pool, "Only %i buffer left in the capture queue.",
1975                 num_queued);
1976
1977             /* If we have no more buffer, and can allocate it time to do so */
1978             if (num_queued == 0) {
1979               if (GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, MMAP)) {
1980                 ret = gst_v4l2_buffer_pool_resurrect_buffer (pool);
1981                 if (ret == GST_FLOW_OK)
1982                   goto done;
1983               }
1984             }
1985
1986             /* start copying buffers when we are running low on buffers */
1987             if (num_queued < pool->copy_threshold) {
1988               GstBuffer *copy;
1989
1990               if (GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, MMAP)) {
1991                 ret = gst_v4l2_buffer_pool_resurrect_buffer (pool);
1992                 if (ret == GST_FLOW_OK)
1993                   goto done;
1994               }
1995
1996               /* copy the buffer */
1997               copy = gst_buffer_copy_region (*buf,
1998                   GST_BUFFER_COPY_ALL | GST_BUFFER_COPY_DEEP, 0, -1);
1999               GST_LOG_OBJECT (pool, "copy buffer %p->%p", *buf, copy);
2000
2001               /* and requeue so that we can continue capturing */
2002               gst_buffer_unref (*buf);
2003               *buf = copy;
2004             }
2005
2006             ret = GST_FLOW_OK;
2007             /* nothing, data was inside the buffer when we did _acquire() */
2008             goto done;
2009           }
2010
2011           /* buffer not from our pool, grab a frame and copy it into the target */
2012           if ((ret = gst_v4l2_buffer_pool_dqbuf (pool, &tmp, TRUE))
2013               != GST_FLOW_OK)
2014             goto done;
2015
2016           /* An empty buffer on capture indicates the end of stream */
2017           if (gst_buffer_get_size (tmp) == 0) {
2018             gst_v4l2_buffer_pool_release_buffer (bpool, tmp);
2019
2020             /* Legacy M2M devices return empty buffer when drained */
2021             if (GST_V4L2_IS_M2M (obj->device_caps))
2022               goto eos;
2023           }
2024 #ifdef TIZEN_FEATURE_V4L2_TBM_SUPPORT
2025           if (pool->obj->tbm_output && pool->obj->mode == GST_V4L2_IO_DMABUF) {
2026             gst_buffer_unref (*buf);
2027             *buf = tmp;
2028           } else {
2029 #endif /* TIZEN_FEATURE_V4L2_TBM_SUPPORT */
2030           ret = gst_v4l2_buffer_pool_copy_buffer (pool, *buf, tmp);
2031
2032           /* an queue the buffer again after the copy */
2033           gst_v4l2_buffer_pool_release_buffer (bpool, tmp);
2034 #ifdef TIZEN_FEATURE_V4L2_TBM_SUPPORT
2035           }
2036 #endif /* TIZEN_FEATURE_V4L2_TBM_SUPPORT */
2037
2038           if (ret != GST_FLOW_OK)
2039             goto copy_failed;
2040           break;
2041         }
2042
2043         case GST_V4L2_IO_USERPTR:
2044         {
2045           struct UserPtrData *data;
2046           GstBuffer *tmp;
2047
2048           /* Replace our buffer with downstream allocated buffer */
2049           data = gst_mini_object_steal_qdata (GST_MINI_OBJECT (*buf),
2050               GST_V4L2_IMPORT_QUARK);
2051           tmp = gst_buffer_ref (data->buffer);
2052           _unmap_userptr_frame (data);
2053
2054           /* Now tmp is writable, copy the flags and timestamp */
2055           gst_buffer_copy_into (tmp, *buf,
2056               GST_BUFFER_COPY_FLAGS | GST_BUFFER_COPY_TIMESTAMPS, 0, -1);
2057
2058           gst_buffer_replace (buf, tmp);
2059           gst_buffer_unref (tmp);
2060           break;
2061         }
2062
2063         case GST_V4L2_IO_DMABUF_IMPORT:
2064         {
2065           GstBuffer *tmp;
2066
2067           /* Replace our buffer with downstream allocated buffer */
2068           tmp = gst_mini_object_steal_qdata (GST_MINI_OBJECT (*buf),
2069               GST_V4L2_IMPORT_QUARK);
2070
2071           gst_buffer_copy_into (tmp, *buf,
2072               GST_BUFFER_COPY_FLAGS | GST_BUFFER_COPY_TIMESTAMPS, 0, -1);
2073
2074           gst_buffer_replace (buf, tmp);
2075           gst_buffer_unref (tmp);
2076           break;
2077         }
2078
2079         default:
2080           g_assert_not_reached ();
2081           break;
2082       }
2083       break;
2084
2085     case V4L2_BUF_TYPE_VIDEO_OUTPUT:
2086     case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE:
2087       /* playback */
2088       switch (obj->mode) {
2089         case GST_V4L2_IO_RW:
2090           /* FIXME, do write() */
2091           GST_WARNING_OBJECT (pool, "implement write()");
2092           break;
2093
2094         case GST_V4L2_IO_USERPTR:
2095         case GST_V4L2_IO_DMABUF_IMPORT:
2096         case GST_V4L2_IO_DMABUF:
2097         case GST_V4L2_IO_MMAP:
2098         {
2099           GstBuffer *to_queue = NULL;
2100           GstBuffer *buffer;
2101           GstV4l2MemoryGroup *group;
2102           gint index;
2103
2104           if ((*buf)->pool != bpool)
2105             goto copying;
2106
2107           if (!gst_v4l2_is_buffer_valid (*buf, &group))
2108             goto copying;
2109
2110           index = group->buffer.index;
2111
2112           GST_LOG_OBJECT (pool, "processing buffer %i from our pool", index);
2113
2114           if (pool->buffers[index] != NULL) {
2115             GST_LOG_OBJECT (pool, "buffer %i already queued, copying", index);
2116             goto copying;
2117           }
2118
2119           /* we can queue directly */
2120           to_queue = gst_buffer_ref (*buf);
2121
2122         copying:
2123           if (to_queue == NULL) {
2124             GstBufferPoolAcquireParams params = { 0 };
2125
2126             GST_LOG_OBJECT (pool, "alloc buffer from our pool");
2127
2128             /* this can return EOS if all buffers are outstanding which would
2129              * be strange because we would expect the upstream element to have
2130              * allocated them and returned to us.. */
2131             params.flags = GST_BUFFER_POOL_ACQUIRE_FLAG_DONTWAIT;
2132             ret = gst_buffer_pool_acquire_buffer (bpool, &to_queue, &params);
2133             if (ret != GST_FLOW_OK)
2134               goto acquire_failed;
2135
2136             ret = gst_v4l2_buffer_pool_prepare_buffer (pool, to_queue, *buf);
2137             if (ret != GST_FLOW_OK) {
2138               gst_buffer_unref (to_queue);
2139               goto prepare_failed;
2140             }
2141
2142             /* retreive the group */
2143             gst_v4l2_is_buffer_valid (to_queue, &group);
2144           }
2145
2146           if ((ret = gst_v4l2_buffer_pool_qbuf (pool, to_queue, group))
2147               != GST_FLOW_OK)
2148             goto queue_failed;
2149
2150           /* if we are not streaming yet (this is the first buffer, start
2151            * streaming now */
2152           if (!gst_v4l2_buffer_pool_streamon (pool)) {
2153             /* don't check return value because qbuf would have failed */
2154             gst_v4l2_is_buffer_valid (to_queue, &group);
2155
2156             /* qbuf has stored to_queue buffer but we are not in
2157              * streaming state, so the flush logic won't be performed.
2158              * To avoid leaks, flush the allocator and restore the queued
2159              * buffer as non-queued */
2160             gst_v4l2_allocator_flush (pool->vallocator);
2161
2162             pool->buffers[group->buffer.index] = NULL;
2163
2164             gst_mini_object_set_qdata (GST_MINI_OBJECT (to_queue),
2165                 GST_V4L2_IMPORT_QUARK, NULL, NULL);
2166             gst_buffer_unref (to_queue);
2167             g_atomic_int_add (&pool->num_queued, -1);
2168             goto start_failed;
2169           }
2170
2171           /* Remove our ref, we will still hold this buffer in acquire as needed,
2172            * otherwise the pool will think it is outstanding and will refuse to stop. */
2173           gst_buffer_unref (to_queue);
2174
2175           /* release as many buffer as possible */
2176           while (gst_v4l2_buffer_pool_dqbuf (pool, &buffer, FALSE) ==
2177               GST_FLOW_OK) {
2178             if (buffer->pool == NULL)
2179               gst_v4l2_buffer_pool_release_buffer (bpool, buffer);
2180           }
2181
2182           if (g_atomic_int_get (&pool->num_queued) >= pool->min_latency) {
2183             /* all buffers are queued, try to dequeue one and release it back
2184              * into the pool so that _acquire can get to it again. */
2185             ret = gst_v4l2_buffer_pool_dqbuf (pool, &buffer, TRUE);
2186             if (ret == GST_FLOW_OK && buffer->pool == NULL)
2187               /* release the rendered buffer back into the pool. This wakes up any
2188                * thread waiting for a buffer in _acquire(). */
2189               gst_v4l2_buffer_pool_release_buffer (bpool, buffer);
2190           }
2191           break;
2192         }
2193         default:
2194           g_assert_not_reached ();
2195           break;
2196       }
2197       break;
2198     default:
2199       g_assert_not_reached ();
2200       break;
2201   }
2202 done:
2203   return ret;
2204
2205   /* ERRORS */
2206 copy_failed:
2207   {
2208     GST_ERROR_OBJECT (pool, "failed to copy buffer");
2209     return ret;
2210   }
2211 buffer_truncated:
2212   {
2213     GST_WARNING_OBJECT (pool,
2214         "Dropping truncated buffer, this is likely a driver bug.");
2215     gst_buffer_unref (*buf);
2216     *buf = NULL;
2217     return GST_V4L2_FLOW_CORRUPTED_BUFFER;
2218   }
2219 eos:
2220   {
2221     GST_DEBUG_OBJECT (pool, "end of stream reached");
2222     gst_buffer_unref (*buf);
2223     *buf = NULL;
2224     return GST_V4L2_FLOW_LAST_BUFFER;
2225   }
2226 acquire_failed:
2227   {
2228     if (ret == GST_FLOW_FLUSHING)
2229       GST_DEBUG_OBJECT (pool, "flushing");
2230     else
2231       GST_WARNING_OBJECT (pool, "failed to acquire a buffer: %s",
2232           gst_flow_get_name (ret));
2233     return ret;
2234   }
2235 prepare_failed:
2236   {
2237     GST_ERROR_OBJECT (pool, "failed to prepare data");
2238     return ret;
2239   }
2240 queue_failed:
2241   {
2242     GST_ERROR_OBJECT (pool, "failed to queue buffer");
2243     return ret;
2244   }
2245 start_failed:
2246   {
2247     GST_ERROR_OBJECT (pool, "failed to start streaming");
2248     return GST_FLOW_ERROR;
2249   }
2250 }
2251
2252 void
2253 gst_v4l2_buffer_pool_set_other_pool (GstV4l2BufferPool * pool,
2254     GstBufferPool * other_pool)
2255 {
2256   g_return_if_fail (!gst_buffer_pool_is_active (GST_BUFFER_POOL (pool)));
2257
2258   if (pool->other_pool)
2259     gst_object_unref (pool->other_pool);
2260   pool->other_pool = gst_object_ref (other_pool);
2261 }
2262
2263 void
2264 gst_v4l2_buffer_pool_copy_at_threshold (GstV4l2BufferPool * pool, gboolean copy)
2265 {
2266   GST_OBJECT_LOCK (pool);
2267   pool->enable_copy_threshold = copy;
2268   GST_OBJECT_UNLOCK (pool);
2269 }
2270
2271 gboolean
2272 gst_v4l2_buffer_pool_flush (GstBufferPool * bpool)
2273 {
2274   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
2275   gboolean ret = TRUE;
2276
2277   gst_v4l2_buffer_pool_streamoff (pool);
2278
2279   if (!V4L2_TYPE_IS_OUTPUT (pool->obj->type))
2280     ret = gst_v4l2_buffer_pool_streamon (pool);
2281
2282   return ret;
2283 }