msdk: change the wait time for encoder and vpp
[platform/upstream/gstreamer.git] / sys / msdk / gstmsdkvpp.c
1 /* GStreamer Intel MSDK plugin
2  * Copyright (c) 2018, Intel Corporation
3  * All rights reserved.
4  *
5  * Author: Sreerenj Balachaandran <sreerenj.balachandran@intel.com>
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright notice,
11  *    this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright notice,
14  *    this list of conditions and the following disclaimer in the documentation
15  *    and/or other materials provided with the distribution.
16  *
17  * 3. Neither the name of the copyright holder nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
22  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
23  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
25  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
26  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
27  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
28  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
29  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
30  * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
31  * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33
34 #ifdef HAVE_CONFIG_H
35 #  include <config.h>
36 #endif
37
38 #include <stdlib.h>
39
40 #include "gstmsdkvpp.h"
41 #include "gstmsdkbufferpool.h"
42 #include "gstmsdkvideomemory.h"
43 #include "gstmsdksystemmemory.h"
44 #include "gstmsdkcontextutil.h"
45 #include "gstmsdkvpputil.h"
46
47 #ifndef _WIN32
48 #include "gstmsdkallocator_libva.h"
49 #endif
50
51 GST_DEBUG_CATEGORY_EXTERN (gst_msdkvpp_debug);
52 #define GST_CAT_DEFAULT gst_msdkvpp_debug
53
54 static GstStaticPadTemplate gst_msdkvpp_sink_factory =
55     GST_STATIC_PAD_TEMPLATE ("sink",
56     GST_PAD_SINK,
57     GST_PAD_ALWAYS,
58     GST_STATIC_CAPS (GST_VIDEO_CAPS_MAKE
59         ("{ NV12, YV12, I420, YUY2, UYVY, BGRA, BGRx }")
60         ", " "interlace-mode = (string){ progressive, interleaved, mixed }" ";"
61         GST_VIDEO_CAPS_MAKE_WITH_FEATURES (GST_CAPS_FEATURE_MEMORY_DMABUF,
62             "{ NV12, BGRA, YUY2}")));
63
64 static GstStaticPadTemplate gst_msdkvpp_src_factory =
65     GST_STATIC_PAD_TEMPLATE ("src",
66     GST_PAD_SRC,
67     GST_PAD_ALWAYS,
68     GST_STATIC_CAPS (GST_VIDEO_CAPS_MAKE_WITH_FEATURES
69         (GST_CAPS_FEATURE_MEMORY_DMABUF,
70             "{ BGRA, YUY2, NV12}") ";"
71         GST_VIDEO_CAPS_MAKE ("{ NV12, YUY2, BGRA, BGRx }") ", "
72         "interlace-mode = (string){ progressive, interleaved, mixed }" ";"));
73
74 enum
75 {
76   PROP_0,
77   PROP_HARDWARE,
78   PROP_ASYNC_DEPTH,
79   PROP_DENOISE,
80   PROP_ROTATION,
81   PROP_DEINTERLACE_MODE,
82   PROP_DEINTERLACE_METHOD,
83   PROP_HUE,
84   PROP_SATURATION,
85   PROP_BRIGHTNESS,
86   PROP_CONTRAST,
87   PROP_DETAIL,
88   PROP_MIRRORING,
89   PROP_SCALING_MODE,
90   PROP_FORCE_ASPECT_RATIO,
91   PROP_FRC_ALGORITHM,
92   PROP_N,
93 };
94
95 #define PROP_HARDWARE_DEFAULT            TRUE
96 #define PROP_ASYNC_DEPTH_DEFAULT         1
97 #define PROP_DENOISE_DEFAULT             0
98 #define PROP_ROTATION_DEFAULT            MFX_ANGLE_0
99 #define PROP_DEINTERLACE_MODE_DEFAULT    GST_MSDKVPP_DEINTERLACE_MODE_AUTO
100 #define PROP_DEINTERLACE_METHOD_DEFAULT  MFX_DEINTERLACING_BOB
101 #define PROP_HUE_DEFAULT                 0
102 #define PROP_SATURATION_DEFAULT          1
103 #define PROP_BRIGHTNESS_DEFAULT          0
104 #define PROP_CONTRAST_DEFAULT            1
105 #define PROP_DETAIL_DEFAULT              0
106 #define PROP_MIRRORING_DEFAULT           MFX_MIRRORING_DISABLED
107 #define PROP_SCALING_MODE_DEFAULT        MFX_SCALING_MODE_DEFAULT
108 #define PROP_FORCE_ASPECT_RATIO_DEFAULT  TRUE
109 #define PROP_FRC_ALGORITHM_DEFAULT       _MFX_FRC_ALGORITHM_NONE
110
111 #define gst_msdkvpp_parent_class parent_class
112 G_DEFINE_TYPE (GstMsdkVPP, gst_msdkvpp, GST_TYPE_BASE_TRANSFORM);
113
114 typedef struct
115 {
116   mfxFrameSurface1 *surface;
117   GstBuffer *buf;
118 } MsdkSurface;
119
120 static void
121 free_msdk_surface (MsdkSurface * surface)
122 {
123   if (surface->buf)
124     gst_buffer_unref (surface->buf);
125   g_slice_free (MsdkSurface, surface);
126 }
127
128 static void
129 gst_msdkvpp_add_extra_param (GstMsdkVPP * thiz, mfxExtBuffer * param)
130 {
131   if (thiz->num_extra_params < MAX_EXTRA_PARAMS) {
132     thiz->extra_params[thiz->num_extra_params] = param;
133     thiz->num_extra_params++;
134   }
135 }
136
137 static gboolean
138 ensure_context (GstBaseTransform * trans)
139 {
140   GstMsdkVPP *thiz = GST_MSDKVPP (trans);
141
142   if (gst_msdk_context_prepare (GST_ELEMENT_CAST (thiz), &thiz->context)) {
143     GST_INFO_OBJECT (thiz, "Found context from neighbour %" GST_PTR_FORMAT,
144         thiz->context);
145
146     if (gst_msdk_context_get_job_type (thiz->context) & GST_MSDK_JOB_VPP) {
147       GstMsdkContext *parent_context, *msdk_context;
148
149       parent_context = thiz->context;
150       msdk_context = gst_msdk_context_new_with_parent (parent_context);
151
152       if (!msdk_context) {
153         GST_ERROR_OBJECT (thiz, "Context creation failed");
154         return FALSE;
155       }
156
157       thiz->context = msdk_context;
158       gst_object_unref (parent_context);
159
160       GST_INFO_OBJECT (thiz,
161           "Creating new context %" GST_PTR_FORMAT " with joined session",
162           thiz->context);
163     } else {
164       gst_msdk_context_add_job_type (thiz->context, GST_MSDK_JOB_VPP);
165     }
166   } else {
167     if (!gst_msdk_context_ensure_context (GST_ELEMENT_CAST (thiz),
168             thiz->hardware, GST_MSDK_JOB_VPP))
169       return FALSE;
170     GST_INFO_OBJECT (thiz, "Creating new context %" GST_PTR_FORMAT,
171         thiz->context);
172   }
173
174   gst_msdk_context_add_shared_async_depth (thiz->context, thiz->async_depth);
175
176   return TRUE;
177 }
178
179 static GstBuffer *
180 create_output_buffer (GstMsdkVPP * thiz)
181 {
182   GstBuffer *outbuf;
183   GstFlowReturn ret;
184   GstBufferPool *pool = thiz->srcpad_buffer_pool;
185
186   g_return_val_if_fail (pool != NULL, NULL);
187
188   if (!gst_buffer_pool_is_active (pool) &&
189       !gst_buffer_pool_set_active (pool, TRUE))
190     goto error_activate_pool;
191
192   outbuf = NULL;
193   ret = gst_buffer_pool_acquire_buffer (pool, &outbuf, NULL);
194   if (ret != GST_FLOW_OK || !outbuf)
195     goto error_create_buffer;
196
197   return outbuf;
198
199   /* ERRORS */
200 error_activate_pool:
201   {
202     GST_ERROR_OBJECT (thiz, "failed to activate output video buffer pool");
203     return NULL;
204   }
205 error_create_buffer:
206   {
207     GST_ERROR_OBJECT (thiz, "failed to create output video buffer");
208     return NULL;
209   }
210 }
211
212 static GstFlowReturn
213 gst_msdkvpp_prepare_output_buffer (GstBaseTransform * trans,
214     GstBuffer * inbuf, GstBuffer ** outbuf_ptr)
215 {
216   GstMsdkVPP *thiz = GST_MSDKVPP (trans);
217
218   if (gst_base_transform_is_passthrough (trans)) {
219     *outbuf_ptr = inbuf;
220     return GST_FLOW_OK;
221   }
222
223   *outbuf_ptr = create_output_buffer (thiz);
224   return *outbuf_ptr ? GST_FLOW_OK : GST_FLOW_ERROR;
225 }
226
227 static GstBufferPool *
228 gst_msdkvpp_create_buffer_pool (GstMsdkVPP * thiz, GstPadDirection direction,
229     GstCaps * caps, guint min_num_buffers)
230 {
231   GstBufferPool *pool = NULL;
232   GstStructure *config;
233   GstAllocator *allocator = NULL;
234   GstVideoInfo info;
235   GstVideoInfo *pool_info = NULL;
236   GstVideoAlignment align;
237   GstAllocationParams params = { 0, 31, 0, 0, };
238   mfxFrameAllocResponse *alloc_resp = NULL;
239   gboolean use_dmabuf = FALSE;
240
241   if (direction == GST_PAD_SINK) {
242     alloc_resp = &thiz->in_alloc_resp;
243     pool_info = &thiz->sinkpad_buffer_pool_info;
244     use_dmabuf = thiz->use_sinkpad_dmabuf;
245   } else if (direction == GST_PAD_SRC) {
246     alloc_resp = &thiz->out_alloc_resp;
247     pool_info = &thiz->srcpad_buffer_pool_info;
248     use_dmabuf = thiz->use_srcpad_dmabuf;
249   }
250
251   pool = gst_msdk_buffer_pool_new (thiz->context, alloc_resp);
252   if (!pool)
253     goto error_no_pool;
254
255   if (!gst_video_info_from_caps (&info, caps))
256     goto error_no_video_info;
257
258   gst_msdk_set_video_alignment (&info, &align);
259   gst_video_info_align (&info, &align);
260
261   if (use_dmabuf)
262     allocator =
263         gst_msdk_dmabuf_allocator_new (thiz->context, &info, alloc_resp);
264   else if (thiz->use_video_memory)
265     allocator = gst_msdk_video_allocator_new (thiz->context, &info, alloc_resp);
266   else
267     allocator = gst_msdk_system_allocator_new (&info);
268
269   if (!allocator)
270     goto error_no_allocator;
271
272   config = gst_buffer_pool_get_config (GST_BUFFER_POOL_CAST (pool));
273   gst_buffer_pool_config_set_params (config, caps, info.size, min_num_buffers,
274       0);
275
276   gst_buffer_pool_config_add_option (config, GST_BUFFER_POOL_OPTION_VIDEO_META);
277   gst_buffer_pool_config_add_option (config,
278       GST_BUFFER_POOL_OPTION_VIDEO_ALIGNMENT);
279   if (thiz->use_video_memory) {
280     gst_buffer_pool_config_add_option (config,
281         GST_BUFFER_POOL_OPTION_MSDK_USE_VIDEO_MEMORY);
282     if (use_dmabuf)
283       gst_buffer_pool_config_add_option (config,
284           GST_BUFFER_POOL_OPTION_MSDK_USE_DMABUF);
285   }
286
287   gst_buffer_pool_config_set_video_alignment (config, &align);
288   gst_buffer_pool_config_set_allocator (config, allocator, &params);
289   gst_object_unref (allocator);
290
291   if (!gst_buffer_pool_set_config (pool, config))
292     goto error_pool_config;
293
294   /* Updating pool_info with algined info of allocator */
295   *pool_info = info;
296
297   return pool;
298
299 error_no_pool:
300   {
301     GST_INFO_OBJECT (thiz, "Failed to create bufferpool");
302     return NULL;
303   }
304 error_no_video_info:
305   {
306     GST_INFO_OBJECT (thiz, "Failed to get Video info from caps");
307     return NULL;
308   }
309 error_no_allocator:
310   {
311     GST_INFO_OBJECT (thiz, "Failed to create allocator");
312     if (pool)
313       gst_object_unref (pool);
314     return NULL;
315   }
316 error_pool_config:
317   {
318     GST_INFO_OBJECT (thiz, "Failed to set config");
319     if (pool)
320       gst_object_unref (pool);
321     if (allocator)
322       gst_object_unref (allocator);
323     return NULL;
324   }
325 }
326
327 static gboolean
328 _gst_caps_has_feature (const GstCaps * caps, const gchar * feature)
329 {
330   guint i;
331
332   for (i = 0; i < gst_caps_get_size (caps); i++) {
333     GstCapsFeatures *const features = gst_caps_get_features (caps, i);
334     /* Skip ANY features, we need an exact match for correct evaluation */
335     if (gst_caps_features_is_any (features))
336       continue;
337     if (gst_caps_features_contains (features, feature))
338       return TRUE;
339   }
340   return FALSE;
341 }
342
343 static gboolean
344 gst_msdkvpp_decide_allocation (GstBaseTransform * trans, GstQuery * query)
345 {
346   GstMsdkVPP *thiz = GST_MSDKVPP (trans);
347   GstVideoInfo info;
348   GstBufferPool *pool = NULL;
349   GstStructure *config = NULL;
350   GstCaps *caps;
351   guint size = 0, min_buffers = 0, max_buffers = 0;
352   GstAllocator *allocator = NULL;
353   GstAllocationParams params;
354   gboolean update_pool = FALSE;
355
356   gst_query_parse_allocation (query, &caps, NULL);
357   if (!caps) {
358     GST_ERROR_OBJECT (thiz, "Failed to parse the decide_allocation caps");
359     return FALSE;
360   }
361   if (!gst_video_info_from_caps (&info, caps)) {
362     GST_ERROR_OBJECT (thiz, "Failed to get video info");
363     return FALSE;
364   }
365   /* if downstream allocation query supports dmabuf-capsfeatures,
366    * we do allocate dmabuf backed memory */
367   if (_gst_caps_has_feature (caps, GST_CAPS_FEATURE_MEMORY_DMABUF)) {
368     GST_INFO_OBJECT (thiz, "MSDK VPP srcpad uses DMABuf memory");
369     thiz->use_srcpad_dmabuf = TRUE;
370   }
371
372   if (gst_query_find_allocation_meta (query, GST_VIDEO_META_API_TYPE, NULL))
373     thiz->add_video_meta = TRUE;
374   else
375     thiz->add_video_meta = FALSE;
376
377   /* Check whether the query has pool */
378   if (gst_query_get_n_allocation_pools (query) > 0)
379     update_pool = TRUE;
380
381   /* increase the min_buffers with number of concurrent vpp operations */
382   min_buffers += thiz->async_depth;
383
384   /* invalidate the cached pool if there is an allocation_query */
385   if (thiz->srcpad_buffer_pool)
386     gst_object_unref (thiz->srcpad_buffer_pool);
387
388   /* Always create a pool for vpp out buffers. Each of the msdk element
389    * has to create it's own mfxsurfacepool which is an msdk contraint.
390    * For eg: Each Msdk component (vpp, dec and enc) will invoke the external
391    * Frame allocator for video-memory usage.So sharing the pool between
392    * gst-msdk elements might not be a good idea, rather each element
393    * can check the buffer type (whether it is from msdk-buffer pool)
394    * to make sure there is no copy. Since we share the context between
395    * msdk elements, using buffers from one sdk's framealloator in another
396    * sdk-components is perfectly fine */
397   pool = gst_msdkvpp_create_buffer_pool (thiz, GST_PAD_SRC, caps, min_buffers);
398   thiz->srcpad_buffer_pool = pool;
399
400   /* get the configured pool properties inorder to set in query */
401   config = gst_buffer_pool_get_config (pool);
402   gst_buffer_pool_config_get_params (config, &caps, &size, &min_buffers,
403       &max_buffers);
404   if (gst_buffer_pool_config_get_allocator (config, &allocator, &params))
405     gst_query_add_allocation_param (query, allocator, &params);
406   gst_structure_free (config);
407
408   if (update_pool)
409     gst_query_set_nth_allocation_pool (query, 0, pool, size, min_buffers,
410         max_buffers);
411   else
412     gst_query_add_allocation_pool (query, pool, size, min_buffers, max_buffers);
413
414   gst_query_add_allocation_meta (query, GST_VIDEO_META_API_TYPE, NULL);
415
416   /* Fixme if downstream doesn't have videometa support, msdkvpp should
417    * copy the output buffers */
418
419   return TRUE;
420 }
421
422 static gboolean
423 gst_msdkvpp_propose_allocation (GstBaseTransform * trans,
424     GstQuery * decide_query, GstQuery * query)
425 {
426   GstMsdkVPP *thiz = GST_MSDKVPP (trans);
427   GstVideoInfo info;
428   GstBufferPool *pool = NULL;
429   GstAllocator *allocator = NULL;
430   GstCaps *caps;
431   GstStructure *config;
432   gboolean need_pool;
433   GstAllocationParams params;
434   guint size;
435   guint min_buffers = thiz->async_depth + 1;
436
437   gst_query_parse_allocation (query, &caps, &need_pool);
438   if (!caps) {
439     GST_ERROR_OBJECT (thiz, "Failed to parse the allocation caps");
440     return FALSE;
441   }
442
443   if (!gst_video_info_from_caps (&info, caps)) {
444     GST_ERROR_OBJECT (thiz, "Failed to get video info");
445     return FALSE;
446   }
447
448   /* if upstream allocation query supports dmabuf-capsfeatures,
449    * we do allocate dmabuf backed memory */
450   if (_gst_caps_has_feature (caps, GST_CAPS_FEATURE_MEMORY_DMABUF)) {
451     GST_INFO_OBJECT (thiz, "MSDK VPP srcpad uses DMABuf memory");
452     thiz->use_sinkpad_dmabuf = TRUE;
453   }
454
455   if (need_pool) {
456     /* alwys provide a new pool for upstream to help re-negotiation
457      * more info here: https://bugzilla.gnome.org/show_bug.cgi?id=748344 */
458     pool = gst_msdkvpp_create_buffer_pool (thiz, GST_PAD_SINK, caps,
459         min_buffers);
460   }
461
462   /* Update the internal pool if any allocation attribute changed */
463   if (!gst_video_info_is_equal (&thiz->sinkpad_buffer_pool_info, &info)) {
464     gst_object_unref (thiz->sinkpad_buffer_pool);
465     thiz->sinkpad_buffer_pool = gst_msdkvpp_create_buffer_pool (thiz,
466         GST_PAD_SINK, caps, min_buffers);
467   }
468
469   /* get the size and allocator params from configured pool and set it in query */
470   if (!need_pool)
471     pool = gst_object_ref (thiz->sinkpad_buffer_pool);
472   config = gst_buffer_pool_get_config (GST_BUFFER_POOL_CAST (pool));
473   gst_buffer_pool_config_get_params (config, NULL, &size, NULL, NULL);
474   if (gst_buffer_pool_config_get_allocator (config, &allocator, &params))
475     gst_query_add_allocation_param (query, allocator, &params);
476   gst_structure_free (config);
477
478   /* if upstream does't have a pool requirement, set only
479    *  size, min_buffers and max_buffers in query */
480   gst_query_add_allocation_pool (query, need_pool ? pool : NULL, size,
481       min_buffers, 0);
482   gst_query_add_allocation_meta (query, GST_VIDEO_META_API_TYPE, NULL);
483
484   gst_object_unref (pool);
485
486   return GST_BASE_TRANSFORM_CLASS (parent_class)->propose_allocation (trans,
487       decide_query, query);
488 }
489
490 static MsdkSurface *
491 get_surface_from_pool (GstMsdkVPP * thiz, GstBufferPool * pool,
492     GstBufferPoolAcquireParams * params)
493 {
494   GstBuffer *new_buffer;
495   mfxFrameSurface1 *new_surface;
496   MsdkSurface *msdk_surface;
497
498   if (!gst_buffer_pool_is_active (pool) &&
499       !gst_buffer_pool_set_active (pool, TRUE)) {
500     GST_ERROR_OBJECT (pool, "failed to activate buffer pool");
501     return NULL;
502   }
503
504   if (gst_buffer_pool_acquire_buffer (pool, &new_buffer, params) != GST_FLOW_OK) {
505     GST_ERROR_OBJECT (pool, "failed to acquire a buffer from pool");
506     return NULL;
507   }
508
509   if (gst_msdk_is_msdk_buffer (new_buffer))
510     new_surface = gst_msdk_get_surface_from_buffer (new_buffer);
511   else {
512     GST_ERROR_OBJECT (pool, "the acquired memory is not MSDK memory");
513     return NULL;
514   }
515
516   msdk_surface = g_slice_new0 (MsdkSurface);
517   msdk_surface->surface = new_surface;
518   msdk_surface->buf = new_buffer;
519
520   return msdk_surface;
521 }
522
523 #ifndef _WIN32
524 static gboolean
525 import_dmabuf_to_msdk_surface (GstMsdkVPP * thiz, GstBuffer * buf,
526     MsdkSurface * msdk_surface)
527 {
528   GstMemory *mem = NULL;
529   GstVideoInfo vinfo;
530   GstVideoMeta *vmeta;
531   GstMsdkMemoryID *msdk_mid = NULL;
532   mfxFrameSurface1 *mfx_surface = NULL;
533   gint fd, i;
534
535   mem = gst_buffer_peek_memory (buf, 0);
536   fd = gst_dmabuf_memory_get_fd (mem);
537   if (fd < 0)
538     return FALSE;
539
540   vinfo = thiz->sinkpad_info;
541
542   /* Update offset/stride/size if there is VideoMeta attached to
543    * the buffer */
544   vmeta = gst_buffer_get_video_meta (buf);
545   if (vmeta) {
546     if (GST_VIDEO_INFO_FORMAT (&vinfo) != vmeta->format ||
547         GST_VIDEO_INFO_WIDTH (&vinfo) != vmeta->width ||
548         GST_VIDEO_INFO_HEIGHT (&vinfo) != vmeta->height ||
549         GST_VIDEO_INFO_N_PLANES (&vinfo) != vmeta->n_planes) {
550       GST_ERROR_OBJECT (thiz, "VideoMeta attached to buffer is not matching"
551           "the negotiated width/height/format");
552       return FALSE;
553     }
554     for (i = 0; i < GST_VIDEO_INFO_N_PLANES (&vinfo); ++i) {
555       GST_VIDEO_INFO_PLANE_OFFSET (&vinfo, i) = vmeta->offset[i];
556       GST_VIDEO_INFO_PLANE_STRIDE (&vinfo, i) = vmeta->stride[i];
557     }
558     GST_VIDEO_INFO_SIZE (&vinfo) = gst_buffer_get_size (buf);
559   }
560
561   /* Upstream neither accepted the msdk pool nor the msdk buffer size restrictions.
562    * Current media-driver and GMMLib will fail due to strict memory size restrictions.
563    * Ideally, media-driver should accept what ever memory coming from other drivers
564    * in case of dmabuf-import and this is how the intel-vaapi-driver works.
565    * For now, in order to avoid any crash we check the buffer size and fallback
566    * to copy frame method.
567    *
568    * See this: https://github.com/intel/media-driver/issues/169
569    * */
570   if (GST_VIDEO_INFO_SIZE (&vinfo) <
571       GST_VIDEO_INFO_SIZE (&thiz->sinkpad_buffer_pool_info))
572     return FALSE;
573
574   mfx_surface = msdk_surface->surface;
575   msdk_mid = (GstMsdkMemoryID *) mfx_surface->Data.MemId;
576
577   /* release the internal memory storage of associated mfxSurface */
578   gst_msdk_replace_mfx_memid (thiz->context, mfx_surface, VA_INVALID_ID);
579
580   /* export dmabuf to vasurface */
581   if (!gst_msdk_export_dmabuf_to_vasurface (thiz->context, &vinfo, fd,
582           msdk_mid->surface))
583     return FALSE;
584
585   return TRUE;
586 }
587 #endif
588
589 static MsdkSurface *
590 get_msdk_surface_from_input_buffer (GstMsdkVPP * thiz, GstBuffer * inbuf)
591 {
592   GstVideoFrame src_frame, out_frame;
593   MsdkSurface *msdk_surface;
594   GstMemory *mem = NULL;
595
596   if (gst_msdk_is_msdk_buffer (inbuf)) {
597     msdk_surface = g_slice_new0 (MsdkSurface);
598     msdk_surface->surface = gst_msdk_get_surface_from_buffer (inbuf);
599     msdk_surface->buf = gst_buffer_ref (inbuf);
600     return msdk_surface;
601   }
602
603   /* If upstream hasn't accpeted the proposed msdk bufferpool,
604    * just copy frame (if not dmabuf backed) to msdk buffer and
605    * take a surface from it.   */
606   if (!(msdk_surface =
607           get_surface_from_pool (thiz, thiz->sinkpad_buffer_pool, NULL)))
608     goto error;
609
610 #ifndef _WIN32
611   /************ dmabuf-import ************* */
612   /* if upstream provided a dmabuf backed memory, but not an msdk
613    * buffer, we could export the dmabuf to underlined vasurface */
614   mem = gst_buffer_peek_memory (inbuf, 0);
615   if (gst_is_dmabuf_memory (mem)) {
616     if (import_dmabuf_to_msdk_surface (thiz, inbuf, msdk_surface))
617       return msdk_surface;
618     else
619       GST_INFO_OBJECT (thiz, "Upstream dmabuf-backed memory is not imported"
620           "to the msdk surface, fall back to the copy input frame method");
621   }
622 #endif
623
624   if (!gst_video_frame_map (&src_frame, &thiz->sinkpad_info, inbuf,
625           GST_MAP_READ)) {
626     GST_ERROR_OBJECT (thiz, "failed to map the frame for source");
627     goto error;
628   }
629
630   if (!gst_video_frame_map (&out_frame, &thiz->sinkpad_buffer_pool_info,
631           msdk_surface->buf, GST_MAP_WRITE)) {
632     GST_ERROR_OBJECT (thiz, "failed to map the frame for destination");
633     gst_video_frame_unmap (&src_frame);
634     goto error;
635   }
636
637   if (!gst_video_frame_copy (&out_frame, &src_frame)) {
638     GST_ERROR_OBJECT (thiz, "failed to copy frame");
639     gst_video_frame_unmap (&out_frame);
640     gst_video_frame_unmap (&src_frame);
641     goto error;
642   }
643
644   gst_video_frame_unmap (&out_frame);
645   gst_video_frame_unmap (&src_frame);
646
647   return msdk_surface;
648
649 error:
650   return NULL;
651 }
652
653 static GstFlowReturn
654 gst_msdkvpp_transform (GstBaseTransform * trans, GstBuffer * inbuf,
655     GstBuffer * outbuf)
656 {
657   GstMsdkVPP *thiz = GST_MSDKVPP (trans);
658   GstClockTime timestamp;
659   GstFlowReturn ret = GST_FLOW_OK;
660   mfxSession session;
661   mfxSyncPoint sync_point = NULL;
662   mfxStatus status;
663   MsdkSurface *in_surface = NULL;
664   MsdkSurface *out_surface = NULL;
665
666   timestamp = GST_BUFFER_TIMESTAMP (inbuf);
667
668   in_surface = get_msdk_surface_from_input_buffer (thiz, inbuf);
669   if (!in_surface)
670     return GST_FLOW_ERROR;
671
672   if (gst_msdk_is_msdk_buffer (outbuf)) {
673     out_surface = g_slice_new0 (MsdkSurface);
674     out_surface->surface = gst_msdk_get_surface_from_buffer (outbuf);
675   } else {
676     GST_ERROR ("Failed to get msdk outsurface!");
677     return GST_FLOW_ERROR;
678   }
679
680   session = gst_msdk_context_get_session (thiz->context);
681
682   /* outer loop is for handling FrameRate Control and deinterlace use cases */
683   do {
684     for (;;) {
685       status =
686           MFXVideoVPP_RunFrameVPPAsync (session, in_surface->surface,
687           out_surface->surface, NULL, &sync_point);
688       if (status != MFX_WRN_DEVICE_BUSY)
689         break;
690       /* If device is busy, wait 1ms and retry, as per MSDK's recommendation */
691       g_usleep (1000);
692     };
693
694     if (status != MFX_ERR_NONE && status != MFX_ERR_MORE_DATA
695         && status != MFX_ERR_MORE_SURFACE)
696       goto vpp_error;
697
698     /* No output generated */
699     if (status == MFX_ERR_MORE_DATA)
700       goto error_more_data;
701
702     /* Wait for vpp operation to complete, the magic number 300000 below
703      * is used in MSDK samples
704      * #define MSDK_VPP_WAIT_INTERVAL 300000
705      */
706     if (sync_point)
707       MFXVideoCORE_SyncOperation (session, sync_point, 300000);
708
709     /* More than one output buffers are generated */
710     if (status == MFX_ERR_MORE_SURFACE) {
711       GST_BUFFER_TIMESTAMP (outbuf) = timestamp;
712       GST_BUFFER_DURATION (outbuf) = thiz->buffer_duration;
713       timestamp += thiz->buffer_duration;
714       ret = gst_pad_push (GST_BASE_TRANSFORM_SRC_PAD (trans), outbuf);
715       if (ret != GST_FLOW_OK)
716         goto error_push_buffer;
717       outbuf = create_output_buffer (thiz);
718     } else {
719       GST_BUFFER_TIMESTAMP (outbuf) = timestamp;
720       GST_BUFFER_DURATION (outbuf) = thiz->buffer_duration;
721     }
722   } while (status == MFX_ERR_MORE_SURFACE);
723
724   free_msdk_surface (in_surface);
725   return ret;
726
727 vpp_error:
728   GST_ERROR_OBJECT (thiz, "MSDK Failed to do VPP");
729   free_msdk_surface (in_surface);
730   free_msdk_surface (out_surface);
731   return GST_FLOW_ERROR;
732
733 error_more_data:
734   GST_WARNING_OBJECT (thiz,
735       "MSDK Requries additional input for processing, "
736       "Retruning FLOW_DROPPED since no output buffer was generated");
737   free_msdk_surface (in_surface);
738   return GST_BASE_TRANSFORM_FLOW_DROPPED;
739
740 error_push_buffer:
741   {
742     free_msdk_surface (in_surface);
743     free_msdk_surface (out_surface);
744     GST_DEBUG_OBJECT (thiz, "failed to push output buffer: %s",
745         gst_flow_get_name (ret));
746     return ret;
747   }
748 }
749
750 static void
751 gst_msdkvpp_close (GstMsdkVPP * thiz)
752 {
753   mfxStatus status;
754
755   if (!thiz->context)
756     return;
757
758   GST_DEBUG_OBJECT (thiz, "Closing VPP 0x%p", thiz->context);
759   status = MFXVideoVPP_Close (gst_msdk_context_get_session (thiz->context));
760   if (status != MFX_ERR_NONE && status != MFX_ERR_NOT_INITIALIZED) {
761     GST_WARNING_OBJECT (thiz, "VPP close failed (%s)",
762         msdk_status_to_string (status));
763   }
764
765   if (thiz->context)
766     gst_object_replace ((GstObject **) & thiz->context, NULL);
767
768   memset (&thiz->param, 0, sizeof (thiz->param));
769
770   if (thiz->sinkpad_buffer_pool)
771     gst_object_unref (thiz->sinkpad_buffer_pool);
772   thiz->sinkpad_buffer_pool = NULL;
773   if (thiz->srcpad_buffer_pool)
774     gst_object_unref (thiz->srcpad_buffer_pool);
775   thiz->srcpad_buffer_pool = NULL;
776
777   thiz->buffer_duration = GST_CLOCK_TIME_NONE;
778   gst_video_info_init (&thiz->sinkpad_info);
779   gst_video_info_init (&thiz->srcpad_info);
780 }
781
782 static void
783 ensure_filters (GstMsdkVPP * thiz)
784 {
785
786   /* Denoise */
787   if (thiz->flags & GST_MSDK_FLAG_DENOISE) {
788     mfxExtVPPDenoise *mfx_denoise = &thiz->mfx_denoise;
789     mfx_denoise->Header.BufferId = MFX_EXTBUFF_VPP_DENOISE;
790     mfx_denoise->Header.BufferSz = sizeof (mfxExtVPPDenoise);
791     mfx_denoise->DenoiseFactor = thiz->denoise_factor;
792     gst_msdkvpp_add_extra_param (thiz, (mfxExtBuffer *) mfx_denoise);
793   }
794
795   /* Rotation */
796   if (thiz->flags & GST_MSDK_FLAG_ROTATION) {
797     mfxExtVPPRotation *mfx_rotation = &thiz->mfx_rotation;
798     mfx_rotation->Header.BufferId = MFX_EXTBUFF_VPP_ROTATION;
799     mfx_rotation->Header.BufferSz = sizeof (mfxExtVPPRotation);
800     mfx_rotation->Angle = thiz->rotation;
801     gst_msdkvpp_add_extra_param (thiz, (mfxExtBuffer *) mfx_rotation);
802   }
803
804   /* Deinterlace */
805   if (thiz->flags & GST_MSDK_FLAG_DEINTERLACE) {
806     mfxExtVPPDeinterlacing *mfx_deinterlace = &thiz->mfx_deinterlace;
807     mfx_deinterlace->Header.BufferId = MFX_EXTBUFF_VPP_DEINTERLACING;
808     mfx_deinterlace->Header.BufferSz = sizeof (mfxExtVPPDeinterlacing);
809     mfx_deinterlace->Mode = thiz->deinterlace_method;
810     gst_msdkvpp_add_extra_param (thiz, (mfxExtBuffer *) mfx_deinterlace);
811   }
812
813   /* Colorbalance(ProcAmp) */
814   if (thiz->flags & (GST_MSDK_FLAG_HUE | GST_MSDK_FLAG_SATURATION |
815           GST_MSDK_FLAG_BRIGHTNESS | GST_MSDK_FLAG_CONTRAST)) {
816     mfxExtVPPProcAmp *mfx_procamp = &thiz->mfx_procamp;
817     mfx_procamp->Header.BufferId = MFX_EXTBUFF_VPP_PROCAMP;
818     mfx_procamp->Header.BufferSz = sizeof (mfxExtVPPProcAmp);
819     mfx_procamp->Hue = thiz->hue;
820     mfx_procamp->Saturation = thiz->saturation;
821     mfx_procamp->Brightness = thiz->brightness;
822     mfx_procamp->Contrast = thiz->contrast;
823     gst_msdkvpp_add_extra_param (thiz, (mfxExtBuffer *) mfx_procamp);
824   }
825
826   /* Detail/Edge enhancement */
827   if (thiz->flags & GST_MSDK_FLAG_DETAIL) {
828     mfxExtVPPDetail *mfx_detail = &thiz->mfx_detail;
829     mfx_detail->Header.BufferId = MFX_EXTBUFF_VPP_DETAIL;
830     mfx_detail->Header.BufferSz = sizeof (mfxExtVPPDetail);
831     mfx_detail->DetailFactor = thiz->detail;
832     gst_msdkvpp_add_extra_param (thiz, (mfxExtBuffer *) mfx_detail);
833   }
834
835   /* Mirroring */
836   if (thiz->flags & GST_MSDK_FLAG_MIRRORING) {
837     mfxExtVPPMirroring *mfx_mirroring = &thiz->mfx_mirroring;
838     mfx_mirroring->Header.BufferId = MFX_EXTBUFF_VPP_MIRRORING;
839     mfx_mirroring->Header.BufferSz = sizeof (mfxExtVPPMirroring);
840     mfx_mirroring->Type = thiz->mirroring;
841     gst_msdkvpp_add_extra_param (thiz, (mfxExtBuffer *) mfx_mirroring);
842   }
843
844   /* Scaling Mode */
845   if (thiz->flags & GST_MSDK_FLAG_SCALING_MODE) {
846     mfxExtVPPScaling *mfx_scaling = &thiz->mfx_scaling;
847     mfx_scaling->Header.BufferId = MFX_EXTBUFF_VPP_SCALING;
848     mfx_scaling->Header.BufferSz = sizeof (mfxExtVPPScaling);
849     mfx_scaling->ScalingMode = thiz->scaling_mode;
850     gst_msdkvpp_add_extra_param (thiz, (mfxExtBuffer *) mfx_scaling);
851   }
852
853   /* FRC */
854   if (thiz->flags & GST_MSDK_FLAG_FRC) {
855     mfxExtVPPFrameRateConversion *mfx_frc = &thiz->mfx_frc;
856     mfx_frc->Header.BufferId = MFX_EXTBUFF_VPP_FRAME_RATE_CONVERSION;
857     mfx_frc->Header.BufferSz = sizeof (mfxExtVPPFrameRateConversion);
858     mfx_frc->Algorithm = thiz->frc_algm;
859     gst_msdkvpp_add_extra_param (thiz, (mfxExtBuffer *) mfx_frc);
860   }
861 }
862
863 static void
864 gst_msdkvpp_set_passthrough (GstMsdkVPP * thiz)
865 {
866   gboolean passthrough = TRUE;
867
868   /* no passthrough if any of the filter algorithm is enabled */
869   if (thiz->flags)
870     passthrough = FALSE;
871
872   /* vpp could be needed in some specific circumstances, for eg:
873    * input surface is dmabuf and output must be videomemory. So far
874    * the underline iHD driver doesn't seems to support dmabuf mapping,
875    * so we could explicitly ask msdkvpp to provide non-dambuf videomemory
876    * surfaces as output thourgh capsfileters */
877   if (thiz->need_vpp)
878     passthrough = FALSE;
879
880   /* no passthrough if there is change in out width,height or format */
881   if (GST_VIDEO_INFO_WIDTH (&thiz->sinkpad_info) !=
882       GST_VIDEO_INFO_WIDTH (&thiz->srcpad_info)
883       || GST_VIDEO_INFO_HEIGHT (&thiz->sinkpad_info) !=
884       GST_VIDEO_INFO_HEIGHT (&thiz->srcpad_info)
885       || GST_VIDEO_INFO_FORMAT (&thiz->sinkpad_info) !=
886       GST_VIDEO_INFO_FORMAT (&thiz->srcpad_info))
887     passthrough = FALSE;
888
889   gst_base_transform_set_passthrough (GST_BASE_TRANSFORM (thiz), passthrough);
890 }
891
892 static gboolean
893 gst_msdkvpp_initialize (GstMsdkVPP * thiz)
894 {
895   mfxSession session;
896   mfxStatus status;
897   mfxFrameAllocRequest request[2];
898
899   if (!thiz->context) {
900     GST_WARNING_OBJECT (thiz, "No MSDK Context");
901     return FALSE;
902   }
903
904   GST_OBJECT_LOCK (thiz);
905   session = gst_msdk_context_get_session (thiz->context);
906
907   if (thiz->use_video_memory) {
908     gst_msdk_set_frame_allocator (thiz->context);
909     thiz->param.IOPattern =
910         MFX_IOPATTERN_IN_VIDEO_MEMORY | MFX_IOPATTERN_OUT_VIDEO_MEMORY;
911   } else {
912     thiz->param.IOPattern =
913         MFX_IOPATTERN_IN_SYSTEM_MEMORY | MFX_IOPATTERN_OUT_SYSTEM_MEMORY;
914   }
915
916   /* update input video attributes */
917   gst_msdk_set_mfx_frame_info_from_video_info (&thiz->param.vpp.In,
918       &thiz->sinkpad_info);
919
920   /* update output video attributes, only CSC and Scaling are supported for now */
921   gst_msdk_set_mfx_frame_info_from_video_info (&thiz->param.vpp.Out,
922       &thiz->srcpad_info);
923
924   /* use msdk frame rarte control if there is a mismatch in In & OUt fps  */
925   if (GST_VIDEO_INFO_FPS_N (&thiz->srcpad_info) &&
926       (GST_VIDEO_INFO_FPS_N (&thiz->sinkpad_info) !=
927           GST_VIDEO_INFO_FPS_N (&thiz->srcpad_info)
928           || GST_VIDEO_INFO_FPS_D (&thiz->sinkpad_info) !=
929           GST_VIDEO_INFO_FPS_D (&thiz->srcpad_info))) {
930     thiz->flags |= GST_MSDK_FLAG_FRC;
931     /* So far this is the only algorithm which is working somewhat good */
932     thiz->frc_algm = MFX_FRCALGM_PRESERVE_TIMESTAMP;
933   }
934
935   /* work-around to avoid zero fps in msdk structure */
936   if (!thiz->param.vpp.In.FrameRateExtN)
937     thiz->param.vpp.In.FrameRateExtN = 30;
938   if (!thiz->param.vpp.Out.FrameRateExtN)
939     thiz->param.vpp.Out.FrameRateExtN = thiz->param.vpp.In.FrameRateExtN;
940
941   /* set vpp out picstruct as progressive if deinterlacing enabled */
942   if (thiz->flags & GST_MSDK_FLAG_DEINTERLACE)
943     thiz->param.vpp.Out.PicStruct = MFX_PICSTRUCT_PROGRESSIVE;
944
945   /* Enable the required filters */
946   ensure_filters (thiz);
947
948   /* Add exteneded buffers */
949   if (thiz->num_extra_params) {
950     thiz->param.NumExtParam = thiz->num_extra_params;
951     thiz->param.ExtParam = thiz->extra_params;
952   }
953
954   /* validate parameters and allow the Media SDK to make adjustments */
955   status = MFXVideoVPP_Query (session, &thiz->param, &thiz->param);
956   if (status < MFX_ERR_NONE) {
957     GST_ERROR_OBJECT (thiz, "Video VPP Query failed (%s)",
958         msdk_status_to_string (status));
959     goto no_vpp;
960   } else if (status > MFX_ERR_NONE) {
961     GST_WARNING_OBJECT (thiz, "Video VPP Query returned: %s",
962         msdk_status_to_string (status));
963   }
964
965   status = MFXVideoVPP_QueryIOSurf (session, &thiz->param, request);
966   if (status < MFX_ERR_NONE) {
967     GST_ERROR_OBJECT (thiz, "VPP Query IO surfaces failed (%s)",
968         msdk_status_to_string (status));
969     goto no_vpp;
970   } else if (status > MFX_ERR_NONE) {
971     GST_WARNING_OBJECT (thiz, "VPP Query IO surfaces returned: %s",
972         msdk_status_to_string (status));
973   }
974
975   if (thiz->use_video_memory) {
976     /* Input surface pool pre-allocation */
977     request[0].Type |= MFX_MEMTYPE_VIDEO_MEMORY_PROCESSOR_TARGET;
978     if (thiz->use_sinkpad_dmabuf)
979       request[0].Type |= MFX_MEMTYPE_EXPORT_FRAME;
980     gst_msdk_frame_alloc (thiz->context, &(request[0]), &thiz->in_alloc_resp);
981
982     /* Output surface pool pre-allocation */
983     request[1].Type |= MFX_MEMTYPE_VIDEO_MEMORY_PROCESSOR_TARGET;
984     if (thiz->use_srcpad_dmabuf)
985       request[1].Type |= MFX_MEMTYPE_EXPORT_FRAME;
986     gst_msdk_frame_alloc (thiz->context, &(request[1]), &thiz->out_alloc_resp);
987   }
988
989   thiz->in_num_surfaces = request[0].NumFrameSuggested;
990   thiz->out_num_surfaces = request[1].NumFrameSuggested;
991
992
993   status = MFXVideoVPP_Init (session, &thiz->param);
994   if (status < MFX_ERR_NONE) {
995     GST_ERROR_OBJECT (thiz, "Init failed (%s)", msdk_status_to_string (status));
996     goto no_vpp;
997   } else if (status > MFX_ERR_NONE) {
998     GST_WARNING_OBJECT (thiz, "Init returned: %s",
999         msdk_status_to_string (status));
1000   }
1001
1002   thiz->initialized = TRUE;
1003   GST_OBJECT_UNLOCK (thiz);
1004   return TRUE;
1005
1006 no_vpp:
1007   GST_OBJECT_UNLOCK (thiz);
1008   if (thiz->context)
1009     gst_object_replace ((GstObject **) & thiz->context, NULL);
1010   return FALSE;
1011 }
1012
1013 static gboolean
1014 gst_msdkvpp_set_caps (GstBaseTransform * trans, GstCaps * caps,
1015     GstCaps * out_caps)
1016 {
1017   GstMsdkVPP *thiz = GST_MSDKVPP (trans);
1018   GstVideoInfo in_info, out_info;
1019   gboolean sinkpad_info_changed = FALSE;
1020   gboolean srcpad_info_changed = FALSE;
1021   gboolean deinterlace;
1022
1023   if (gst_caps_get_features (caps, 0) != gst_caps_get_features (out_caps, 0))
1024     thiz->need_vpp = 1;
1025
1026   gst_video_info_from_caps (&in_info, caps);
1027   gst_video_info_from_caps (&out_info, out_caps);
1028
1029   if (!gst_video_info_is_equal (&in_info, &thiz->sinkpad_info))
1030     sinkpad_info_changed = TRUE;
1031   if (!gst_video_info_is_equal (&out_info, &thiz->srcpad_info))
1032     srcpad_info_changed = TRUE;
1033
1034   thiz->sinkpad_info = in_info;
1035   thiz->srcpad_info = out_info;
1036 #ifndef _WIN32
1037   thiz->use_video_memory = TRUE;
1038 #else
1039   thiz->use_video_memory = FALSE;
1040 #endif
1041
1042   if (!sinkpad_info_changed && !srcpad_info_changed && thiz->initialized)
1043     return TRUE;
1044
1045   /* check for deinterlace requirement */
1046   deinterlace = gst_msdkvpp_is_deinterlace_enabled (thiz, &in_info);
1047   if (deinterlace)
1048     thiz->flags |= GST_MSDK_FLAG_DEINTERLACE;
1049
1050   thiz->buffer_duration = GST_VIDEO_INFO_FPS_N (&out_info) > 0 ?
1051       gst_util_uint64_scale (GST_SECOND, GST_VIDEO_INFO_FPS_D (&out_info),
1052       GST_VIDEO_INFO_FPS_N (&out_info)) : 0;
1053
1054   if (!gst_msdkvpp_initialize (thiz))
1055     return FALSE;
1056
1057   /* set passthrough according to filter operation change */
1058   gst_msdkvpp_set_passthrough (thiz);
1059
1060   /* Ensure sinkpad buffer pool */
1061   thiz->sinkpad_buffer_pool =
1062       gst_msdkvpp_create_buffer_pool (thiz, GST_PAD_SINK, caps,
1063       thiz->in_num_surfaces);
1064   if (!thiz->sinkpad_buffer_pool) {
1065     GST_ERROR_OBJECT (thiz, "Failed to ensure the sinkpad buffer pool");
1066     return FALSE;
1067   }
1068   /* Ensure a srcpad buffer pool */
1069   thiz->srcpad_buffer_pool =
1070       gst_msdkvpp_create_buffer_pool (thiz, GST_PAD_SRC, out_caps,
1071       thiz->out_num_surfaces);
1072   if (!thiz->srcpad_buffer_pool) {
1073     GST_ERROR_OBJECT (thiz, "Failed to ensure the srcpad buffer pool");
1074     return FALSE;
1075   }
1076
1077   return TRUE;
1078 }
1079
1080 static gboolean
1081 pad_can_dmabuf (GstMsdkVPP * thiz, GstPadDirection direction, GstCaps * filter)
1082 {
1083   gboolean ret = FALSE;
1084   GstCaps *caps, *out_caps;
1085   GstPad *pad;
1086   GstBaseTransform *trans = GST_BASE_TRANSFORM (thiz);
1087
1088   if (direction == GST_PAD_SRC)
1089     pad = GST_BASE_TRANSFORM_SRC_PAD (trans);
1090   else
1091     pad = GST_BASE_TRANSFORM_SINK_PAD (trans);
1092
1093   /* make a copy of filter caps since we need to alter the structure
1094    * by adding dmabuf-capsfeatures */
1095   caps = gst_caps_copy (filter);
1096   gst_caps_set_features (caps, 0,
1097       gst_caps_features_from_string (GST_CAPS_FEATURE_MEMORY_DMABUF));
1098
1099   out_caps = gst_pad_peer_query_caps (pad, caps);
1100   if (!out_caps)
1101     goto done;
1102
1103   if (gst_caps_is_any (out_caps) || gst_caps_is_empty (out_caps)
1104       || out_caps == caps)
1105     goto done;
1106
1107   if (_gst_caps_has_feature (out_caps, GST_CAPS_FEATURE_MEMORY_DMABUF))
1108     ret = TRUE;
1109 done:
1110   if (caps)
1111     gst_caps_unref (caps);
1112   if (out_caps)
1113     gst_caps_unref (out_caps);
1114   return ret;
1115 }
1116
1117 static GstCaps *
1118 gst_msdkvpp_fixate_caps (GstBaseTransform * trans,
1119     GstPadDirection direction, GstCaps * caps, GstCaps * othercaps)
1120 {
1121   GstMsdkVPP *thiz = GST_MSDKVPP (trans);
1122   GstCaps *result = NULL;
1123   gboolean *use_dmabuf;
1124
1125   if (direction == GST_PAD_SRC) {
1126     result = gst_caps_fixate (result);
1127     use_dmabuf = &thiz->use_sinkpad_dmabuf;
1128   } else {
1129     result = gst_msdkvpp_fixate_srccaps (thiz, caps, othercaps);
1130     use_dmabuf = &thiz->use_srcpad_dmabuf;
1131   }
1132
1133   GST_DEBUG_OBJECT (trans, "fixated to %" GST_PTR_FORMAT, result);
1134   gst_caps_unref (othercaps);
1135
1136   if (pad_can_dmabuf (thiz,
1137           direction == GST_PAD_SRC ? GST_PAD_SINK : GST_PAD_SRC, result)) {
1138     gst_caps_set_features (result, 0,
1139         gst_caps_features_new (GST_CAPS_FEATURE_MEMORY_DMABUF, NULL));
1140     *use_dmabuf = TRUE;
1141   }
1142
1143   return result;
1144 }
1145
1146 /* Generic code for now, requires changes in future when we
1147  * add hardware query for supported formats, Framerate control etc */
1148 static GstCaps *
1149 gst_msdkvpp_transform_caps (GstBaseTransform * trans,
1150     GstPadDirection direction, GstCaps * caps, GstCaps * filter)
1151 {
1152   GstCaps *out_caps;
1153
1154   GST_DEBUG_OBJECT (trans,
1155       "Transforming caps %" GST_PTR_FORMAT " in direction %s", caps,
1156       (direction == GST_PAD_SINK) ? "sink" : "src");
1157
1158   if (direction == GST_PAD_SRC)
1159     out_caps = gst_static_pad_template_get_caps (&gst_msdkvpp_sink_factory);
1160   else
1161     out_caps = gst_static_pad_template_get_caps (&gst_msdkvpp_src_factory);
1162
1163   if (out_caps && filter) {
1164     GstCaps *intersection;
1165
1166     intersection = gst_caps_intersect_full (out_caps, filter,
1167         GST_CAPS_INTERSECT_FIRST);
1168     gst_caps_unref (out_caps);
1169     out_caps = intersection;
1170   }
1171
1172   GST_DEBUG_OBJECT (trans, "returning caps: %" GST_PTR_FORMAT, out_caps);
1173   return out_caps;
1174 }
1175
1176 static gboolean
1177 gst_msdkvpp_start (GstBaseTransform * trans)
1178 {
1179   if (!ensure_context (trans))
1180     return FALSE;
1181   return TRUE;
1182 }
1183
1184 static gboolean
1185 gst_msdkvpp_stop (GstBaseTransform * trans)
1186 {
1187   gst_msdkvpp_close (GST_MSDKVPP (trans));
1188   return TRUE;
1189 }
1190
1191 static void
1192 gst_msdkvpp_set_property (GObject * object, guint prop_id,
1193     const GValue * value, GParamSpec * pspec)
1194 {
1195   GstMsdkVPP *thiz = GST_MSDKVPP (object);
1196
1197   switch (prop_id) {
1198     case PROP_HARDWARE:
1199       thiz->hardware = g_value_get_boolean (value);
1200       break;
1201     case PROP_ASYNC_DEPTH:
1202       thiz->async_depth = g_value_get_uint (value);
1203       break;
1204     case PROP_DENOISE:
1205       thiz->denoise_factor = g_value_get_uint (value);
1206       thiz->flags |= GST_MSDK_FLAG_DENOISE;
1207       break;
1208     case PROP_ROTATION:
1209       thiz->rotation = g_value_get_enum (value);
1210       thiz->flags |= GST_MSDK_FLAG_ROTATION;
1211       break;
1212     case PROP_DEINTERLACE_MODE:
1213       thiz->deinterlace_mode = g_value_get_enum (value);
1214       break;
1215     case PROP_DEINTERLACE_METHOD:
1216       thiz->deinterlace_method = g_value_get_enum (value);
1217       break;
1218     case PROP_HUE:
1219       thiz->hue = g_value_get_float (value);
1220       thiz->flags |= GST_MSDK_FLAG_HUE;
1221       break;
1222     case PROP_SATURATION:
1223       thiz->saturation = g_value_get_float (value);
1224       thiz->flags |= GST_MSDK_FLAG_SATURATION;
1225       break;
1226     case PROP_BRIGHTNESS:
1227       thiz->brightness = g_value_get_float (value);
1228       thiz->flags |= GST_MSDK_FLAG_BRIGHTNESS;
1229       break;
1230     case PROP_CONTRAST:
1231       thiz->contrast = g_value_get_float (value);
1232       thiz->flags |= GST_MSDK_FLAG_CONTRAST;
1233       break;
1234     case PROP_DETAIL:
1235       thiz->detail = g_value_get_uint (value);
1236       thiz->flags |= GST_MSDK_FLAG_DETAIL;
1237       break;
1238     case PROP_MIRRORING:
1239       thiz->mirroring = g_value_get_enum (value);
1240       thiz->flags |= GST_MSDK_FLAG_MIRRORING;
1241       break;
1242     case PROP_SCALING_MODE:
1243       thiz->scaling_mode = g_value_get_enum (value);
1244       thiz->flags |= GST_MSDK_FLAG_SCALING_MODE;
1245       break;
1246     case PROP_FORCE_ASPECT_RATIO:
1247       thiz->keep_aspect = g_value_get_boolean (value);
1248       break;
1249     case PROP_FRC_ALGORITHM:
1250       thiz->frc_algm = g_value_get_enum (value);
1251       break;
1252     default:
1253       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1254       break;
1255   }
1256 }
1257
1258 static void
1259 gst_msdkvpp_get_property (GObject * object, guint prop_id,
1260     GValue * value, GParamSpec * pspec)
1261 {
1262   GstMsdkVPP *thiz = GST_MSDKVPP (object);
1263
1264   switch (prop_id) {
1265     case PROP_HARDWARE:
1266       g_value_set_boolean (value, thiz->hardware);
1267       break;
1268     case PROP_ASYNC_DEPTH:
1269       g_value_set_uint (value, thiz->async_depth);
1270       break;
1271     case PROP_DENOISE:
1272       g_value_set_uint (value, thiz->denoise_factor);
1273       break;
1274     case PROP_ROTATION:
1275       g_value_set_enum (value, thiz->rotation);
1276       break;
1277     case PROP_DEINTERLACE_MODE:
1278       g_value_set_enum (value, thiz->deinterlace_mode);
1279       break;
1280     case PROP_DEINTERLACE_METHOD:
1281       g_value_set_enum (value, thiz->deinterlace_method);
1282       break;
1283     case PROP_HUE:
1284       g_value_set_float (value, thiz->hue);
1285       break;
1286     case PROP_SATURATION:
1287       g_value_set_float (value, thiz->saturation);
1288       break;
1289     case PROP_BRIGHTNESS:
1290       g_value_set_float (value, thiz->brightness);
1291       break;
1292     case PROP_CONTRAST:
1293       g_value_set_float (value, thiz->contrast);
1294       break;
1295     case PROP_DETAIL:
1296       g_value_set_uint (value, thiz->detail);
1297       break;
1298     case PROP_MIRRORING:
1299       g_value_set_enum (value, thiz->mirroring);
1300       break;
1301     case PROP_SCALING_MODE:
1302       g_value_set_enum (value, thiz->scaling_mode);
1303       break;
1304     case PROP_FORCE_ASPECT_RATIO:
1305       g_value_set_boolean (value, thiz->keep_aspect);
1306       break;
1307     case PROP_FRC_ALGORITHM:
1308       g_value_set_enum (value, thiz->frc_algm);
1309       break;
1310     default:
1311       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1312       break;
1313   }
1314 }
1315
1316 static void
1317 gst_msdkvpp_finalize (GObject * object)
1318 {
1319   G_OBJECT_CLASS (parent_class)->finalize (object);
1320 }
1321
1322 static void
1323 gst_msdkvpp_set_context (GstElement * element, GstContext * context)
1324 {
1325   GstMsdkContext *msdk_context = NULL;
1326   GstMsdkVPP *thiz = GST_MSDKVPP (element);
1327
1328   if (gst_msdk_context_get_context (context, &msdk_context)) {
1329     gst_object_replace ((GstObject **) & thiz->context,
1330         (GstObject *) msdk_context);
1331     gst_object_unref (msdk_context);
1332   }
1333
1334   GST_ELEMENT_CLASS (parent_class)->set_context (element, context);
1335 }
1336
1337 static void
1338 gst_msdkvpp_class_init (GstMsdkVPPClass * klass)
1339 {
1340   GObjectClass *gobject_class;
1341   GstElementClass *element_class;
1342   GstBaseTransformClass *trans_class;
1343   GParamSpec *obj_properties[PROP_N] = { NULL, };
1344
1345   gobject_class = G_OBJECT_CLASS (klass);
1346   element_class = GST_ELEMENT_CLASS (klass);
1347   trans_class = GST_BASE_TRANSFORM_CLASS (klass);
1348
1349   gobject_class->set_property = gst_msdkvpp_set_property;
1350   gobject_class->get_property = gst_msdkvpp_get_property;
1351   gobject_class->finalize = gst_msdkvpp_finalize;
1352
1353   element_class->set_context = gst_msdkvpp_set_context;
1354
1355   gst_element_class_add_static_pad_template (element_class,
1356       &gst_msdkvpp_src_factory);
1357   gst_element_class_add_static_pad_template (element_class,
1358       &gst_msdkvpp_sink_factory);
1359
1360   gst_element_class_set_static_metadata (element_class,
1361       "MSDK Video Postprocessor",
1362       "Filter/Converter/Video;Filter/Converter/Video/Scaler;"
1363       "Filter/Effect/Video;Filter/Effect/Video/Deinterlace",
1364       "A MediaSDK Video Postprocessing Filter",
1365       "Sreerenj Balachandrn <sreerenj.balachandran@intel.com>");
1366
1367   trans_class->start = GST_DEBUG_FUNCPTR (gst_msdkvpp_start);
1368   trans_class->stop = GST_DEBUG_FUNCPTR (gst_msdkvpp_stop);
1369   trans_class->transform_caps = GST_DEBUG_FUNCPTR (gst_msdkvpp_transform_caps);
1370   trans_class->fixate_caps = GST_DEBUG_FUNCPTR (gst_msdkvpp_fixate_caps);
1371   trans_class->set_caps = GST_DEBUG_FUNCPTR (gst_msdkvpp_set_caps);
1372   trans_class->transform = GST_DEBUG_FUNCPTR (gst_msdkvpp_transform);
1373   trans_class->propose_allocation =
1374       GST_DEBUG_FUNCPTR (gst_msdkvpp_propose_allocation);
1375   trans_class->decide_allocation =
1376       GST_DEBUG_FUNCPTR (gst_msdkvpp_decide_allocation);
1377   trans_class->prepare_output_buffer =
1378       GST_DEBUG_FUNCPTR (gst_msdkvpp_prepare_output_buffer);
1379
1380   obj_properties[PROP_HARDWARE] =
1381       g_param_spec_boolean ("hardware", "Hardware", "Enable hardware VPP",
1382       PROP_HARDWARE_DEFAULT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
1383
1384   obj_properties[PROP_ASYNC_DEPTH] =
1385       g_param_spec_uint ("async-depth", "Async Depth",
1386       "Depth of asynchronous pipeline",
1387       1, 1, PROP_ASYNC_DEPTH_DEFAULT,
1388       G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
1389
1390   obj_properties[PROP_DENOISE] =
1391       g_param_spec_uint ("denoise", "Denoising factor",
1392       "Denoising Factor",
1393       0, 100, PROP_DENOISE_DEFAULT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
1394
1395   obj_properties[PROP_ROTATION] =
1396       g_param_spec_enum ("rotation", "Rotation",
1397       "Rotation Angle", gst_msdkvpp_rotation_get_type (),
1398       PROP_ROTATION_DEFAULT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
1399
1400   obj_properties[PROP_DEINTERLACE_MODE] =
1401       g_param_spec_enum ("deinterlace-mode", "Deinterlace Mode",
1402       "Deinterlace mode to use", gst_msdkvpp_deinterlace_mode_get_type (),
1403       PROP_DEINTERLACE_MODE_DEFAULT,
1404       G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
1405
1406   obj_properties[PROP_DEINTERLACE_METHOD] =
1407       g_param_spec_enum ("deinterlace-method", "Deinterlace Method",
1408       "Deinterlace method to use", gst_msdkvpp_deinterlace_method_get_type (),
1409       PROP_DEINTERLACE_METHOD_DEFAULT,
1410       G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
1411
1412   obj_properties[PROP_HUE] =
1413       g_param_spec_float ("hue", "Hue",
1414       "The hue of the video",
1415       -180, 180, PROP_HUE_DEFAULT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
1416
1417   obj_properties[PROP_SATURATION] =
1418       g_param_spec_float ("saturation", "Saturation",
1419       "The Saturation of the video",
1420       0, 10, PROP_SATURATION_DEFAULT,
1421       G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
1422
1423   obj_properties[PROP_BRIGHTNESS] =
1424       g_param_spec_float ("brightness", "Brightness",
1425       "The Brightness of the video",
1426       -100, 100, PROP_BRIGHTNESS_DEFAULT,
1427       G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
1428
1429   obj_properties[PROP_CONTRAST] =
1430       g_param_spec_float ("contrast", "Contrast",
1431       "The Contrast of the video",
1432       0, 10, PROP_CONTRAST_DEFAULT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
1433
1434   obj_properties[PROP_DETAIL] =
1435       g_param_spec_uint ("detail", "Detail",
1436       "The factor of detail/edge enhancement filter algorithm",
1437       0, 100, PROP_DETAIL_DEFAULT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
1438
1439   obj_properties[PROP_MIRRORING] =
1440       g_param_spec_enum ("mirroring", "Mirroring",
1441       "The Mirroring type", gst_msdkvpp_mirroring_get_type (),
1442       PROP_MIRRORING_DEFAULT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
1443
1444   obj_properties[PROP_SCALING_MODE] =
1445       g_param_spec_enum ("scaling-mode", "Scaling Mode",
1446       "The Scaling mode to use", gst_msdkvpp_scaling_mode_get_type (),
1447       PROP_SCALING_MODE_DEFAULT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
1448
1449   obj_properties[PROP_FORCE_ASPECT_RATIO] =
1450       g_param_spec_boolean ("force-aspect-ratio", "Force Aspect Ratio",
1451       "When enabled, scaling will respect original aspect ratio",
1452       PROP_FORCE_ASPECT_RATIO_DEFAULT,
1453       G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
1454
1455   obj_properties[PROP_FRC_ALGORITHM] =
1456       g_param_spec_enum ("frc-algorithm", "FrameRateControl Algorithm",
1457       "The Framerate Control Alogorithm to use",
1458       gst_msdkvpp_frc_algorithm_get_type (), PROP_FRC_ALGORITHM_DEFAULT,
1459       G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
1460
1461   g_object_class_install_properties (gobject_class, PROP_N, obj_properties);
1462 }
1463
1464 static void
1465 gst_msdkvpp_init (GstMsdkVPP * thiz)
1466 {
1467   thiz->initialized = FALSE;
1468   thiz->hardware = PROP_HARDWARE_DEFAULT;
1469   thiz->async_depth = PROP_ASYNC_DEPTH_DEFAULT;
1470   thiz->denoise_factor = PROP_DENOISE_DEFAULT;
1471   thiz->rotation = PROP_ROTATION_DEFAULT;
1472   thiz->deinterlace_mode = PROP_DEINTERLACE_MODE_DEFAULT;
1473   thiz->deinterlace_method = PROP_DEINTERLACE_METHOD_DEFAULT;
1474   thiz->buffer_duration = GST_CLOCK_TIME_NONE;
1475   thiz->hue = PROP_HUE_DEFAULT;
1476   thiz->saturation = PROP_SATURATION_DEFAULT;
1477   thiz->brightness = PROP_BRIGHTNESS_DEFAULT;
1478   thiz->contrast = PROP_CONTRAST_DEFAULT;
1479   thiz->detail = PROP_DETAIL_DEFAULT;
1480   thiz->mirroring = PROP_MIRRORING_DEFAULT;
1481   thiz->scaling_mode = PROP_SCALING_MODE_DEFAULT;
1482   thiz->keep_aspect = PROP_FORCE_ASPECT_RATIO_DEFAULT;
1483   thiz->frc_algm = PROP_FRC_ALGORITHM_DEFAULT;
1484   gst_video_info_init (&thiz->sinkpad_info);
1485   gst_video_info_init (&thiz->srcpad_info);
1486 }