Waylandsink : initialize display, window, pool and display_name to NULL in waylandsin...
[platform/upstream/gstreamer.git] / ext / wayland / gstwaylandsink.c
1 /* GStreamer Wayland video sink
2  *
3  * Copyright (C) 2011 Intel Corporation
4  * Copyright (C) 2011 Sreerenj Balachandran <sreerenj.balachandran@intel.com>
5  * Copyright (C) 2012 Wim Taymans <wim.taymans@gmail.com>
6  * Copyright (C) 2014 Collabora Ltd.
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the Free
20  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21  * Boston, MA 02110-1301 USA.
22  */
23
24 /**
25  * SECTION:element-waylandsink
26  *
27  *  The waylandsink is creating its own window and render the decoded video frames to that.
28  *  Setup the Wayland environment as described in
29  *  <ulink url="http://wayland.freedesktop.org/building.html">Wayland</ulink> home page.
30  *  The current implementaion is based on weston compositor.
31  *
32  * <refsect2>
33  * <title>Example pipelines</title>
34  * |[
35  * gst-launch -v videotestsrc ! waylandsink
36  * ]| test the video rendering in wayland
37  * </refsect2>
38  */
39
40 #ifdef HAVE_CONFIG_H
41 #include <config.h>
42 #endif
43
44 #include "gstwaylandsink.h"
45 #ifdef GST_WLSINK_ENHANCEMENT
46 #include <mm_types.h>
47 #include "tizen-wlvideoformat.h"
48 #else
49 #include "wlvideoformat.h"
50 #endif
51 #include "waylandpool.h"
52
53 #include <gst/wayland/wayland.h>
54 #include <gst/video/videooverlay.h>
55
56 /* signals */
57 enum
58 {
59   SIGNAL_0,
60   LAST_SIGNAL
61 };
62
63 /* Properties */
64 enum
65 {
66   PROP_0,
67   PROP_DISPLAY
68 };
69
70 GST_DEBUG_CATEGORY (gstwayland_debug);
71 #define GST_CAT_DEFAULT gstwayland_debug
72
73 static GstStaticPadTemplate sink_template = GST_STATIC_PAD_TEMPLATE ("sink",
74     GST_PAD_SINK,
75     GST_PAD_ALWAYS,
76     GST_STATIC_CAPS (GST_VIDEO_CAPS_MAKE
77         ("{ BGRx, BGRA, RGBx, xBGR, xRGB, RGBA, ABGR, ARGB, RGB, BGR, "
78             "RGB16, BGR16, YUY2, YVYU, UYVY, AYUV, NV12, NV21, NV16, "
79 #ifdef GST_WLSINK_ENHANCEMENT
80             "SN12, ST12, "
81 #endif
82             "YUV9, YVU9, Y41B, I420, YV12, Y42B, v308 }"))
83     );
84
85 static void gst_wayland_sink_get_property (GObject * object,
86     guint prop_id, GValue * value, GParamSpec * pspec);
87 static void gst_wayland_sink_set_property (GObject * object,
88     guint prop_id, const GValue * value, GParamSpec * pspec);
89 static void gst_wayland_sink_finalize (GObject * object);
90
91 static GstStateChangeReturn gst_wayland_sink_change_state (GstElement * element,
92     GstStateChange transition);
93 static void gst_wayland_sink_set_context (GstElement * element,
94     GstContext * context);
95
96 static GstCaps *gst_wayland_sink_get_caps (GstBaseSink * bsink,
97     GstCaps * filter);
98 static gboolean gst_wayland_sink_set_caps (GstBaseSink * bsink, GstCaps * caps);
99 static gboolean gst_wayland_sink_preroll (GstBaseSink * bsink,
100     GstBuffer * buffer);
101 static gboolean
102 gst_wayland_sink_propose_allocation (GstBaseSink * bsink, GstQuery * query);
103 static gboolean gst_wayland_sink_render (GstBaseSink * bsink,
104     GstBuffer * buffer);
105
106 /* VideoOverlay interface */
107 static void gst_wayland_sink_videooverlay_init (GstVideoOverlayInterface *
108     iface);
109 static void gst_wayland_sink_set_window_handle (GstVideoOverlay * overlay,
110     guintptr handle);
111 static void gst_wayland_sink_set_render_rectangle (GstVideoOverlay * overlay,
112     gint x, gint y, gint w, gint h);
113 static void gst_wayland_sink_expose (GstVideoOverlay * overlay);
114
115 /* WaylandVideo interface */
116 static void gst_wayland_sink_waylandvideo_init (GstWaylandVideoInterface *
117     iface);
118 static void gst_wayland_sink_begin_geometry_change (GstWaylandVideo * video);
119 static void gst_wayland_sink_end_geometry_change (GstWaylandVideo * video);
120
121 #define gst_wayland_sink_parent_class parent_class
122 G_DEFINE_TYPE_WITH_CODE (GstWaylandSink, gst_wayland_sink, GST_TYPE_VIDEO_SINK,
123     G_IMPLEMENT_INTERFACE (GST_TYPE_VIDEO_OVERLAY,
124         gst_wayland_sink_videooverlay_init)
125     G_IMPLEMENT_INTERFACE (GST_TYPE_WAYLAND_VIDEO,
126         gst_wayland_sink_waylandvideo_init));
127
128 static void
129 gst_wayland_sink_class_init (GstWaylandSinkClass * klass)
130 {
131   FUNCTION_ENTER ();
132   GObjectClass *gobject_class;
133   GstElementClass *gstelement_class;
134   GstBaseSinkClass *gstbasesink_class;
135
136   gobject_class = (GObjectClass *) klass;
137   gstelement_class = (GstElementClass *) klass;
138   gstbasesink_class = (GstBaseSinkClass *) klass;
139
140   gobject_class->set_property = gst_wayland_sink_set_property;
141   gobject_class->get_property = gst_wayland_sink_get_property;
142   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_wayland_sink_finalize);
143
144   gst_element_class_add_pad_template (gstelement_class,
145       gst_static_pad_template_get (&sink_template));
146
147   gst_element_class_set_static_metadata (gstelement_class,
148       "wayland video sink", "Sink/Video",
149       "Output to wayland surface",
150       "Sreerenj Balachandran <sreerenj.balachandran@intel.com>, "
151       "George Kiagiadakis <george.kiagiadakis@collabora.com>");
152
153   gstelement_class->change_state =
154       GST_DEBUG_FUNCPTR (gst_wayland_sink_change_state);
155   gstelement_class->set_context =
156       GST_DEBUG_FUNCPTR (gst_wayland_sink_set_context);
157
158   gstbasesink_class->get_caps = GST_DEBUG_FUNCPTR (gst_wayland_sink_get_caps);
159   gstbasesink_class->set_caps = GST_DEBUG_FUNCPTR (gst_wayland_sink_set_caps);
160   gstbasesink_class->preroll = GST_DEBUG_FUNCPTR (gst_wayland_sink_preroll);
161   gstbasesink_class->propose_allocation =
162       GST_DEBUG_FUNCPTR (gst_wayland_sink_propose_allocation);
163   gstbasesink_class->render = GST_DEBUG_FUNCPTR (gst_wayland_sink_render);
164
165   g_object_class_install_property (gobject_class, PROP_DISPLAY,
166       g_param_spec_string ("display", "Wayland Display name", "Wayland "
167           "display name to connect to, if not supplied via the GstContext",
168           NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
169 }
170
171 static void
172 gst_wayland_sink_init (GstWaylandSink * sink)
173 {
174   FUNCTION_ENTER ();
175   g_mutex_init (&sink->display_lock);
176   g_mutex_init (&sink->render_lock);
177 }
178
179 static void
180 gst_wayland_sink_get_property (GObject * object,
181     guint prop_id, GValue * value, GParamSpec * pspec)
182 {
183   FUNCTION_ENTER ();
184
185   GstWaylandSink *sink = GST_WAYLAND_SINK (object);
186   switch (prop_id) {
187     case PROP_DISPLAY:
188       GST_OBJECT_LOCK (sink);
189       g_value_set_string (value, sink->display_name);
190       GST_OBJECT_UNLOCK (sink);
191       break;
192     default:
193       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
194       break;
195   }
196 }
197
198 static void
199 gst_wayland_sink_set_property (GObject * object,
200     guint prop_id, const GValue * value, GParamSpec * pspec)
201 {
202   FUNCTION_ENTER ();
203
204   GstWaylandSink *sink = GST_WAYLAND_SINK (object);
205   switch (prop_id) {
206     case PROP_DISPLAY:
207       GST_OBJECT_LOCK (sink);
208       sink->display_name = g_value_dup_string (value);
209       GST_OBJECT_UNLOCK (sink);
210       break;
211     default:
212       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
213       break;
214   }
215 }
216
217 static void
218 gst_wayland_sink_finalize (GObject * object)
219 {
220   FUNCTION_ENTER ();
221
222   GstWaylandSink *sink = GST_WAYLAND_SINK (object);
223   GST_DEBUG_OBJECT (sink, "Finalizing the sink..");
224
225   if (sink->last_buffer)
226     gst_buffer_unref (sink->last_buffer);
227   if (sink->display) {
228     /* see comment about this call in gst_wayland_sink_change_state() */
229 #ifdef GST_WLSINK_ENHANCEMENT
230     if (sink->pool && !sink->display->is_native_format)
231 #else
232     if (sink->pool)
233 #endif
234       gst_wayland_compositor_release_all_buffers (GST_WAYLAND_BUFFER_POOL
235           (sink->pool));
236
237     g_object_unref (sink->display);
238     sink->display = NULL;
239   }
240   if (sink->window) {
241     g_object_unref (sink->window);
242     sink->window = NULL;
243   }
244   if (sink->pool) {
245     gst_object_unref (sink->pool);
246     sink->pool = NULL;
247   }
248
249   if (sink->display_name) {
250     g_free (sink->display_name);
251     sink->display_name = NULL;
252   }
253
254   g_mutex_clear (&sink->display_lock);
255   g_mutex_clear (&sink->render_lock);
256
257   G_OBJECT_CLASS (parent_class)->finalize (object);
258 }
259
260 /* must be called with the display_lock */
261 static void
262 gst_wayland_sink_set_display_from_context (GstWaylandSink * sink,
263     GstContext * context)
264 {
265   FUNCTION_ENTER ();
266
267   struct wl_display *display;
268   GError *error = NULL;
269
270   display = gst_wayland_display_handle_context_get_handle (context);
271   sink->display = gst_wl_display_new_existing (display, FALSE, &error);
272
273   if (error) {
274     GST_ELEMENT_WARNING (sink, RESOURCE, OPEN_READ_WRITE,
275         ("Could not set display handle"),
276         ("Failed to use the external wayland display: '%s'", error->message));
277     g_error_free (error);
278   }
279 }
280
281 static gboolean
282 gst_wayland_sink_find_display (GstWaylandSink * sink)
283 {
284   FUNCTION_ENTER ();
285
286   GstQuery *query;
287   GstMessage *msg;
288   GstContext *context = NULL;
289   GError *error = NULL;
290   gboolean ret = TRUE;
291
292   g_mutex_lock (&sink->display_lock);
293
294   if (!sink->display) {
295     /* first query upstream for the needed display handle */
296     query = gst_query_new_context (GST_WAYLAND_DISPLAY_HANDLE_CONTEXT_TYPE);
297     if (gst_pad_peer_query (GST_VIDEO_SINK_PAD (sink), query)) {
298       gst_query_parse_context (query, &context);
299       gst_wayland_sink_set_display_from_context (sink, context);
300     }
301     gst_query_unref (query);
302
303     if (G_LIKELY (!sink->display)) {
304       /* now ask the application to set the display handle */
305       msg = gst_message_new_need_context (GST_OBJECT_CAST (sink),
306           GST_WAYLAND_DISPLAY_HANDLE_CONTEXT_TYPE);
307
308       g_mutex_unlock (&sink->display_lock);
309       gst_element_post_message (GST_ELEMENT_CAST (sink), msg);
310       /* at this point we expect gst_wayland_sink_set_context
311        * to get called and fill sink->display */
312       g_mutex_lock (&sink->display_lock);
313
314       if (!sink->display) {
315         /* if the application didn't set a display, let's create it ourselves */
316         GST_OBJECT_LOCK (sink);
317         sink->display = gst_wl_display_new (sink->display_name, &error);
318         GST_OBJECT_UNLOCK (sink);
319
320         if (error) {
321           GST_ELEMENT_WARNING (sink, RESOURCE, OPEN_READ_WRITE,
322               ("Could not initialise Wayland output"),
323               ("Failed to create GstWlDisplay: '%s'", error->message));
324           g_error_free (error);
325           ret = FALSE;
326         } else {
327           /* inform the world about the new display */
328           context =
329               gst_wayland_display_handle_context_new (sink->display->display);
330           msg = gst_message_new_have_context (GST_OBJECT_CAST (sink), context);
331           gst_element_post_message (GST_ELEMENT_CAST (sink), msg);
332         }
333       }
334     }
335   }
336
337   g_mutex_unlock (&sink->display_lock);
338
339   return ret;
340 }
341
342 static GstStateChangeReturn
343 gst_wayland_sink_change_state (GstElement * element, GstStateChange transition)
344 {
345   FUNCTION_ENTER ();
346
347   GstWaylandSink *sink = GST_WAYLAND_SINK (element);
348   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
349
350   switch (transition) {
351     case GST_STATE_CHANGE_NULL_TO_READY:
352       if (!gst_wayland_sink_find_display (sink))
353         return GST_STATE_CHANGE_FAILURE;
354       break;
355     default:
356       break;
357   }
358
359   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
360   if (ret == GST_STATE_CHANGE_FAILURE)
361     return ret;
362
363   switch (transition) {
364     case GST_STATE_CHANGE_PAUSED_TO_READY:
365       gst_buffer_replace (&sink->last_buffer, NULL);
366       if (sink->window) {
367         if (gst_wl_window_is_toplevel (sink->window)) {
368           g_clear_object (&sink->window);
369         } else {
370           /* remove buffer from surface, show nothing */
371           wl_surface_attach (sink->window->surface, NULL, 0, 0);
372           wl_surface_damage (sink->window->surface, 0, 0,
373               sink->window->surface_width, sink->window->surface_height);
374           wl_surface_commit (sink->window->surface);
375           wl_display_flush (sink->display->display);
376         }
377       }
378       break;
379     case GST_STATE_CHANGE_READY_TO_NULL:
380       g_mutex_lock (&sink->display_lock);
381       /* If we had a toplevel window, we most likely have our own connection
382        * to the display too, and it is a good idea to disconnect and allow
383        * potentially the application to embed us with GstVideoOverlay
384        * (which requires to re-use the same display connection as the parent
385        * surface). If we didn't have a toplevel window, then the display
386        * connection that we have is definitely shared with the application
387        * and it's better to keep it around (together with the window handle)
388        * to avoid requesting them again from the application if/when we are
389        * restarted (GstVideoOverlay behaves like that in other sinks)
390        */
391       if (sink->display && !sink->window) {     /* -> the window was toplevel */
392         /* Force all buffers to return to the pool, regardless of
393          * whether the compositor has released them or not. We are
394          * going to kill the display, so we need to return all buffers
395          * to be destroyed before this happens.
396          * Note that this is done here instead of the pool destructor
397          * because the buffers hold a reference to the pool. Also,
398          * the buffers can only be unref'ed from the display's event loop
399          * and the pool holds a reference to the display. If we drop
400          * our references here, when the compositor releases the buffers,
401          * they will be unref'ed from the event loop thread, which will
402          * unref the pool and therefore the display, which will try to
403          * stop the thread from within itself and cause a deadlock.
404          */
405         if (sink->pool) {
406           gst_wayland_compositor_release_all_buffers (GST_WAYLAND_BUFFER_POOL
407               (sink->pool));
408         }
409         g_clear_object (&sink->display);
410         g_clear_object (&sink->pool);
411       }
412       g_mutex_unlock (&sink->display_lock);
413       break;
414     default:
415       break;
416   }
417
418   return ret;
419 }
420
421 static void
422 gst_wayland_sink_set_context (GstElement * element, GstContext * context)
423 {
424   FUNCTION_ENTER ();
425
426   GstWaylandSink *sink = GST_WAYLAND_SINK (element);
427   if (gst_context_has_context_type (context,
428           GST_WAYLAND_DISPLAY_HANDLE_CONTEXT_TYPE)) {
429     g_mutex_lock (&sink->display_lock);
430     if (G_LIKELY (!sink->display)) {
431       gst_wayland_sink_set_display_from_context (sink, context);
432     } else {
433       GST_WARNING_OBJECT (element, "changing display handle is not supported");
434       g_mutex_unlock (&sink->display_lock);
435       return;
436     }
437     g_mutex_unlock (&sink->display_lock);
438   }
439
440   GST_INFO ("element %p context %p", element, context);
441   if (GST_ELEMENT_CLASS (parent_class)->set_context)
442     GST_ELEMENT_CLASS (parent_class)->set_context (element, context);
443 }
444
445 static GstCaps *
446 gst_wayland_sink_get_caps (GstBaseSink * bsink, GstCaps * filter)
447 {
448   FUNCTION_ENTER ();
449
450   GstWaylandSink *sink;
451   GstCaps *caps;
452   sink = GST_WAYLAND_SINK (bsink);
453
454   caps = gst_pad_get_pad_template_caps (GST_VIDEO_SINK_PAD (sink));
455
456   g_mutex_lock (&sink->display_lock);
457
458   if (sink->display) {
459     GValue list = G_VALUE_INIT;
460     GValue value = G_VALUE_INIT;
461     GArray *formats;
462     gint i;
463 #ifdef GST_WLSINK_ENHANCEMENT
464     enum tizen_buffer_pool_format fmt;
465 #else
466     enum wl_shm_format fmt;
467 #endif
468
469     g_value_init (&list, GST_TYPE_LIST);
470     g_value_init (&value, G_TYPE_STRING);
471
472     formats = sink->display->formats;
473     for (i = 0; i < formats->len; i++) {
474       fmt = g_array_index (formats, uint32_t, i);
475       g_value_set_string (&value, gst_wayland_format_to_string (fmt));
476       gst_value_list_append_value (&list, &value);
477     }
478
479     caps = gst_caps_make_writable (caps);
480     gst_structure_set_value (gst_caps_get_structure (caps, 0), "format", &list);
481
482     GST_DEBUG_OBJECT (sink, "display caps: %" GST_PTR_FORMAT, caps);
483   }
484
485   g_mutex_unlock (&sink->display_lock);
486
487   if (filter) {
488     GstCaps *intersection;
489
490     intersection =
491         gst_caps_intersect_full (filter, caps, GST_CAPS_INTERSECT_FIRST);
492     gst_caps_unref (caps);
493     caps = intersection;
494   }
495
496   return caps;
497 }
498
499 static gboolean
500 gst_wayland_sink_set_caps (GstBaseSink * bsink, GstCaps * caps)
501 {
502   FUNCTION_ENTER ();
503
504   GstWaylandSink *sink;
505   GstBufferPool *newpool;
506   GstVideoInfo info;
507 #ifdef GST_WLSINK_ENHANCEMENT
508   enum tizen_buffer_pool_format format;
509 #else
510   enum wl_shm_format format;
511 #endif
512   GArray *formats;
513   gint i;
514   GstStructure *structure;
515   static GstAllocationParams params = { 0, 0, 0, 15, };
516   sink = GST_WAYLAND_SINK (bsink);
517
518   GST_DEBUG_OBJECT (sink, "set caps %" GST_PTR_FORMAT, caps);
519
520   /* extract info from caps */
521   if (!gst_video_info_from_caps (&info, caps))
522     goto invalid_format;
523 #ifdef GST_WLSINK_ENHANCEMENT
524   sink->caps = gst_caps_copy (caps);
525 #endif
526
527   format = gst_video_format_to_wayland_format (GST_VIDEO_INFO_FORMAT (&info));
528   if ((gint) format == -1)
529     goto invalid_format;
530
531   /* verify we support the requested format */
532   formats = sink->display->formats;
533   for (i = 0; i < formats->len; i++) {
534     if (g_array_index (formats, uint32_t, i) == format)
535       break;
536   }
537
538   if (i >= formats->len)
539     goto unsupported_format;
540
541 #ifdef GST_WLSINK_ENHANCEMENT
542   if (GST_VIDEO_INFO_FORMAT (&info) == GST_VIDEO_FORMAT_SN12 ||
543       GST_VIDEO_INFO_FORMAT (&info) == GST_VIDEO_FORMAT_ST12) {
544     sink->display->is_native_format = TRUE;
545   } else {
546     sink->display->is_native_format = FALSE;
547
548     /* create a new pool for the new configuration */
549     newpool = gst_wayland_buffer_pool_new (sink->display);
550     if (!newpool)
551       goto pool_failed;
552
553     structure = gst_buffer_pool_get_config (newpool);
554     gst_buffer_pool_config_set_params (structure, caps, info.size, 2, 0);
555     gst_buffer_pool_config_set_allocator (structure, NULL, &params);
556     if (!gst_buffer_pool_set_config (newpool, structure))
557       goto config_failed;
558
559     gst_object_replace ((GstObject **) & sink->pool, (GstObject *) newpool);
560     gst_object_unref (newpool);
561
562   }
563   /* store the video info */
564   sink->video_info = info;
565   sink->video_info_changed = TRUE;
566 #else
567   /* create a new pool for the new configuration */
568   newpool = gst_wayland_buffer_pool_new (sink->display);
569   if (!newpool)
570     goto pool_failed;
571
572   structure = gst_buffer_pool_get_config (newpool);
573   gst_buffer_pool_config_set_params (structure, caps, info.size, 2, 0);
574   gst_buffer_pool_config_set_allocator (structure, NULL, &params);
575   if (!gst_buffer_pool_set_config (newpool, structure))
576     goto config_failed;
577
578   /* store the video info */
579   sink->video_info = info;
580   sink->video_info_changed = TRUE;
581
582   gst_object_replace ((GstObject **) & sink->pool, (GstObject *) newpool);
583   gst_object_unref (newpool);
584 #endif
585   return TRUE;
586
587 invalid_format:
588   {
589     GST_DEBUG_OBJECT (sink,
590         "Could not locate image format from caps %" GST_PTR_FORMAT, caps);
591     return FALSE;
592   }
593 unsupported_format:
594   {
595     GST_DEBUG_OBJECT (sink, "Format %s is not available on the display",
596         gst_wayland_format_to_string (format));
597     return FALSE;
598   }
599 pool_failed:
600   {
601     GST_DEBUG_OBJECT (sink, "Failed to create new pool");
602     return FALSE;
603   }
604 config_failed:
605   {
606     GST_DEBUG_OBJECT (bsink, "failed setting config");
607     gst_object_unref (newpool);
608     return FALSE;
609   }
610 }
611
612 static gboolean
613 gst_wayland_sink_propose_allocation (GstBaseSink * bsink, GstQuery * query)
614 {
615   FUNCTION_ENTER ();
616
617   GstWaylandSink *sink = GST_WAYLAND_SINK (bsink);
618   GstBufferPool *pool = NULL;
619   GstStructure *config;
620   GstCaps *caps;
621   guint size;
622   gboolean need_pool;
623
624   if (sink->display->is_native_format == TRUE)
625     return TRUE;
626
627   gst_query_parse_allocation (query, &caps, &need_pool);
628
629   if (caps == NULL)
630     goto no_caps;
631
632   if (sink->pool)
633     pool = gst_object_ref (sink->pool);
634
635   if (pool != NULL) {
636     GstCaps *pcaps;
637
638     /* we had a pool, check caps */
639     config = gst_buffer_pool_get_config (pool);
640     gst_buffer_pool_config_get_params (config, &pcaps, &size, NULL, NULL);
641
642     if (!gst_caps_is_equal (caps, pcaps)) {
643       /* different caps, we can't use this pool */
644       gst_object_unref (pool);
645       pool = NULL;
646     }
647     gst_structure_free (config);
648   }
649
650   if (pool == NULL && need_pool) {
651     GstVideoInfo info;
652
653     if (!gst_video_info_from_caps (&info, caps))
654       goto invalid_caps;
655
656     GST_DEBUG_OBJECT (sink, "create new pool");
657     pool = gst_wayland_buffer_pool_new (sink->display);
658
659     /* the normal size of a frame */
660     size = info.size;
661
662     config = gst_buffer_pool_get_config (pool);
663     gst_buffer_pool_config_set_params (config, caps, size, 2, 0);
664     if (!gst_buffer_pool_set_config (pool, config))
665       goto config_failed;
666   }
667   if (pool) {
668     gst_query_add_allocation_pool (query, pool, size, 2, 0);
669     gst_object_unref (pool);
670   }
671
672   return TRUE;
673
674   /* ERRORS */
675 no_caps:
676   {
677     GST_DEBUG_OBJECT (bsink, "no caps specified");
678     return FALSE;
679   }
680 invalid_caps:
681   {
682     GST_DEBUG_OBJECT (bsink, "invalid caps specified");
683     return FALSE;
684   }
685 config_failed:
686   {
687     GST_DEBUG_OBJECT (bsink, "failed setting config");
688     gst_object_unref (pool);
689     return FALSE;
690   }
691 }
692
693 static GstFlowReturn
694 gst_wayland_sink_preroll (GstBaseSink * bsink, GstBuffer * buffer)
695 {
696   FUNCTION_ENTER ();
697
698   GST_DEBUG_OBJECT (bsink, "preroll buffer %p", buffer);
699   return gst_wayland_sink_render (bsink, buffer);
700 }
701
702 static void
703 frame_redraw_callback (void *data, struct wl_callback *callback, uint32_t time)
704 {
705   FUNCTION_ENTER ();
706
707   GstWaylandSink *sink = data;
708
709   GST_LOG ("frame_redraw_cb");
710
711   g_atomic_int_set (&sink->redraw_pending, FALSE);
712   wl_callback_destroy (callback);
713 }
714
715 static const struct wl_callback_listener frame_callback_listener = {
716   frame_redraw_callback
717 };
718
719 /* must be called with the render lock */
720 static void
721 render_last_buffer (GstWaylandSink * sink)
722 {
723   FUNCTION_ENTER ();
724
725   GstWlMeta *meta;
726   struct wl_surface *surface;
727   struct wl_callback *callback;
728
729   meta = gst_buffer_get_wl_meta (sink->last_buffer);
730   surface = gst_wl_window_get_wl_surface (sink->window);
731
732   g_atomic_int_set (&sink->redraw_pending, TRUE);
733   callback = wl_surface_frame (surface);
734   wl_callback_add_listener (callback, &frame_callback_listener, sink);
735
736   /* Here we essentially add a reference to the buffer. This represents
737    * the fact that the compositor is using the buffer and it should
738    * not return back to the pool and be reused until the compositor
739    * releases it. The release is handled internally in the pool */
740   gst_wayland_compositor_acquire_buffer (meta->pool, sink->last_buffer);
741
742   GST_DEBUG ("wl_surface_attach wl_buffer %p", meta->wbuffer);
743
744   wl_surface_attach (surface, meta->wbuffer, 0, 0);
745   wl_surface_damage (surface, 0, 0, sink->window->surface_width,
746       sink->window->surface_height);
747
748   wl_surface_commit (surface);
749   wl_display_flush (sink->display->display);
750 }
751
752 static GstFlowReturn
753 gst_wayland_sink_render (GstBaseSink * bsink, GstBuffer * buffer)
754 {
755   FUNCTION_ENTER ();
756
757   GstWaylandSink *sink = GST_WAYLAND_SINK (bsink);
758   GstBuffer *to_render;
759   GstWlMeta *meta;
760   GstFlowReturn ret = GST_FLOW_OK;
761
762 #ifdef GST_WLSINK_ENHANCEMENT
763   GstBufferPool *newpool;
764   GstStructure *structure;
765   static GstAllocationParams params = { 0, 0, 0, 15, };
766 #endif
767
768   g_mutex_lock (&sink->render_lock);
769
770   GST_LOG_OBJECT (sink, "render buffer %p", buffer);
771
772   if (G_UNLIKELY (!sink->window)) {
773     /* ask for window handle. Unlock render_lock while doing that because
774      * set_window_handle & friends will lock it in this context */
775     g_mutex_unlock (&sink->render_lock);
776     gst_video_overlay_prepare_window_handle (GST_VIDEO_OVERLAY (sink));
777     g_mutex_lock (&sink->render_lock);
778
779     if (sink->window) {
780       /* inform the window about our caps */
781       gst_wl_window_set_video_info (sink->window, &sink->video_info);
782     } else {
783       /* if we were not provided a window, create one ourselves */
784       sink->window =
785           gst_wl_window_new_toplevel (sink->display, &sink->video_info);
786     }
787     sink->video_info_changed = FALSE;
788   }
789
790   /* drop buffers until we get a frame callback */
791   if (g_atomic_int_get (&sink->redraw_pending) == TRUE)
792     goto done;
793
794   if (G_UNLIKELY (sink->video_info_changed)) {
795     gst_wl_window_set_video_info (sink->window, &sink->video_info);
796     sink->video_info_changed = FALSE;
797
798   }
799   GST_INFO ("window->render_rectangle(%d,%d %d x %d)",
800       sink->window->render_rectangle.x,
801       sink->window->render_rectangle.y,
802       sink->window->render_rectangle.w, sink->window->render_rectangle.h);
803   GST_INFO ("window->surface_width(%d),window->surface_height(%d)",
804       sink->window->surface_width, sink->window->surface_height);
805
806   /* now that we have for sure set the video info on the window, it must have
807    * a valid size, otherwise this means that the application has called
808    * set_window_handle() without calling set_render_rectangle(), which is
809    * absolutely necessary for us.
810    */
811   if (G_UNLIKELY (sink->window->surface_width == 0 ||
812           sink->window->surface_height == 0))
813     goto no_window_size;
814
815   meta = gst_buffer_get_wl_meta (buffer);
816
817   if (meta && meta->pool->display == sink->display) {
818     GST_LOG_OBJECT (sink, "buffer %p from our pool, writing directly", buffer);
819     to_render = buffer;
820   } else {
821     GstMapInfo src;
822     GST_LOG_OBJECT (sink, "buffer %p not from our pool, copying", buffer);
823
824 #ifdef GST_WLSINK_ENHANCEMENT
825     if (sink->display->is_native_format == TRUE) {
826       /*in case of SN12 or ST12 video  format */
827       GstMemory *mem;
828       GstMapInfo mem_info = GST_MAP_INFO_INIT;
829       MMVideoBuffer *mm_video_buf = NULL;
830
831       mem = gst_buffer_peek_memory (buffer, 1);
832       gst_memory_map (mem, &mem_info, GST_MAP_READ);
833       mm_video_buf = (MMVideoBuffer *) mem_info.data;
834       gst_memory_unmap (mem, &mem_info);
835
836       if (mm_video_buf == NULL) {
837         GST_WARNING_OBJECT (sink, "mm_video_buf is NULL. Skip rendering");
838         return ret;
839       }
840       /* assign mm_video_buf info */
841       if (mm_video_buf->type == MM_VIDEO_BUFFER_TYPE_TBM_BO) {
842         GST_DEBUG_OBJECT (sink, "TBM bo %p %p %p", mm_video_buf->handle.bo[0],
843             mm_video_buf->handle.bo[1], mm_video_buf->handle.bo[2]);
844
845         sink->display->native_video_size = 0;
846
847         for (int i = 0; i < NV_BUF_PLANE_NUM; i++) {
848           if (mm_video_buf->handle.bo[i] != NULL) {
849             sink->display->bo[i] = mm_video_buf->handle.bo[i];
850           } else {
851             sink->display->bo[i] = 0;
852           }
853           sink->display->plane_size[i] = mm_video_buf->size[i];
854           sink->display->stride_width[i] = mm_video_buf->stride_width[i];
855           sink->display->stride_height[i] = mm_video_buf->stride_height[i];
856           sink->display->native_video_size += sink->display->plane_size[i];
857         }
858       } else {
859         GST_ERROR_OBJECT (sink, "Buffer type is not TBM");
860         return ret;
861       }
862
863       if (!sink->pool) {
864
865         /* create a new pool for the new configuration */
866         newpool = gst_wayland_buffer_pool_new (sink->display);
867         if (!newpool) {
868           GST_DEBUG_OBJECT (sink, "Failed to create new pool");
869           return FALSE;
870         }
871         structure = gst_buffer_pool_get_config (newpool);
872         gst_buffer_pool_config_set_params (structure, sink->caps,
873             sink->video_info.size, 2, 0);
874         gst_buffer_pool_config_set_allocator (structure, NULL, &params);
875         if (!gst_buffer_pool_set_config (newpool, structure)) {
876           GST_DEBUG_OBJECT (bsink, "failed setting config");
877           gst_object_unref (newpool);
878           return FALSE;
879         }
880
881         gst_object_replace ((GstObject **) & sink->pool, (GstObject *) newpool);
882         gst_object_unref (newpool);
883
884       }
885
886       if (!gst_buffer_pool_set_active (sink->pool, TRUE))
887         goto activate_failed;
888
889       ret = gst_buffer_pool_acquire_buffer (sink->pool, &to_render, NULL);
890       if (ret != GST_FLOW_OK)
891         goto no_buffer;
892
893     } else {
894       /*in case of normal video format and pool is not our pool */
895
896       if (!sink->pool)
897         goto no_pool;
898
899       if (!gst_buffer_pool_set_active (sink->pool, TRUE))
900         goto activate_failed;
901
902       ret = gst_buffer_pool_acquire_buffer (sink->pool, &to_render, NULL);
903       if (ret != GST_FLOW_OK)
904         goto no_buffer;
905
906       gst_buffer_map (buffer, &src, GST_MAP_READ);
907       gst_buffer_fill (to_render, 0, src.data, src.size);
908       gst_buffer_unmap (buffer, &src);
909     }
910
911 #else
912     if (!sink->pool)
913       goto no_pool;
914
915     if (!gst_buffer_pool_set_active (sink->pool, TRUE))
916       goto activate_failed;
917
918     ret = gst_buffer_pool_acquire_buffer (sink->pool, &to_render, NULL);
919     if (ret != GST_FLOW_OK)
920       goto no_buffer;
921
922     gst_buffer_map (buffer, &src, GST_MAP_READ);
923     gst_buffer_fill (to_render, 0, src.data, src.size);
924     gst_buffer_unmap (buffer, &src);
925 #endif
926   }
927
928   gst_buffer_replace (&sink->last_buffer, to_render);
929   render_last_buffer (sink);
930
931   if (buffer != to_render) {
932     GST_LOG_OBJECT (sink, "Decrease ref count of buffer");
933     gst_buffer_unref (to_render);
934  }
935   goto done;
936
937 no_window_size:
938   {
939     GST_ELEMENT_ERROR (sink, RESOURCE, WRITE,
940         ("Window has no size set"),
941         ("Make sure you set the size after calling set_window_handle"));
942     ret = GST_FLOW_ERROR;
943     goto done;
944   }
945 no_buffer:
946   {
947     GST_WARNING_OBJECT (sink, "could not create image");
948     goto done;
949   }
950 no_pool:
951   {
952     GST_ELEMENT_ERROR (sink, RESOURCE, WRITE,
953         ("Internal error: can't allocate images"),
954         ("We don't have a bufferpool negotiated"));
955     ret = GST_FLOW_ERROR;
956     goto done;
957   }
958 activate_failed:
959   {
960     GST_ERROR_OBJECT (sink, "failed to activate bufferpool.");
961     ret = GST_FLOW_ERROR;
962     goto done;
963   }
964 done:
965   {
966     g_mutex_unlock (&sink->render_lock);
967     return ret;
968   }
969 }
970
971 static void
972 gst_wayland_sink_videooverlay_init (GstVideoOverlayInterface * iface)
973 {
974   FUNCTION_ENTER ();
975
976   iface->set_window_handle = gst_wayland_sink_set_window_handle;
977   iface->set_render_rectangle = gst_wayland_sink_set_render_rectangle;
978   iface->expose = gst_wayland_sink_expose;
979 }
980
981 static void
982 gst_wayland_sink_set_window_handle (GstVideoOverlay * overlay, guintptr handle)
983 {
984   FUNCTION_ENTER ();
985
986   GstWaylandSink *sink = GST_WAYLAND_SINK (overlay);
987   struct wl_surface *surface = (struct wl_surface *) handle;
988
989   g_return_if_fail (sink != NULL);
990
991   if (sink->window != NULL) {
992     GST_WARNING_OBJECT (sink, "changing window handle is not supported");
993     return;
994   }
995
996   g_mutex_lock (&sink->render_lock);
997
998   GST_DEBUG_OBJECT (sink, "Setting window handle %" GST_PTR_FORMAT,
999       (void *) handle);
1000
1001   g_clear_object (&sink->window);
1002
1003   if (handle) {
1004     if (G_LIKELY (gst_wayland_sink_find_display (sink))) {
1005       /* we cannot use our own display with an external window handle */
1006       if (G_UNLIKELY (sink->display->own_display)) {
1007         GST_ELEMENT_ERROR (sink, RESOURCE, OPEN_READ_WRITE,
1008             ("Application did not provide a wayland display handle"),
1009             ("waylandsink cannot use an externally-supplied surface without "
1010                 "an externally-supplied display handle. Consider providing a "
1011                 "display handle from your application with GstContext"));
1012       } else {
1013         sink->window = gst_wl_window_new_in_surface (sink->display, surface);
1014         GST_DEBUG ("sink->window %p", sink->window);
1015       }
1016     } else {
1017       GST_ERROR_OBJECT (sink, "Failed to find display handle, "
1018           "ignoring window handle");
1019     }
1020   }
1021
1022   g_mutex_unlock (&sink->render_lock);
1023 }
1024
1025 static void
1026 gst_wayland_sink_set_render_rectangle (GstVideoOverlay * overlay,
1027     gint x, gint y, gint w, gint h)
1028 {
1029   FUNCTION_ENTER ();
1030
1031   GstWaylandSink *sink = GST_WAYLAND_SINK (overlay);
1032
1033   g_return_if_fail (sink != NULL);
1034
1035   g_mutex_lock (&sink->render_lock);
1036   if (!sink->window) {
1037     g_mutex_unlock (&sink->render_lock);
1038     GST_WARNING_OBJECT (sink,
1039         "set_render_rectangle called without window, ignoring");
1040     return;
1041   }
1042
1043   GST_DEBUG_OBJECT (sink, "window geometry changed to (%d, %d) %d x %d",
1044       x, y, w, h);
1045   gst_wl_window_set_render_rectangle (sink->window, x, y, w, h);
1046
1047   g_mutex_unlock (&sink->render_lock);
1048 }
1049
1050 static void
1051 gst_wayland_sink_expose (GstVideoOverlay * overlay)
1052 {
1053   FUNCTION_ENTER ();
1054
1055   GstWaylandSink *sink = GST_WAYLAND_SINK (overlay);
1056
1057   g_return_if_fail (sink != NULL);
1058
1059   GST_DEBUG_OBJECT (sink, "expose");
1060
1061   g_mutex_lock (&sink->render_lock);
1062   if (sink->last_buffer && g_atomic_int_get (&sink->redraw_pending) == FALSE) {
1063     GST_DEBUG_OBJECT (sink, "redrawing last buffer");
1064     render_last_buffer (sink);
1065   }
1066   g_mutex_unlock (&sink->render_lock);
1067 }
1068
1069 static void
1070 gst_wayland_sink_waylandvideo_init (GstWaylandVideoInterface * iface)
1071 {
1072   FUNCTION_ENTER ();
1073
1074   iface->begin_geometry_change = gst_wayland_sink_begin_geometry_change;
1075   iface->end_geometry_change = gst_wayland_sink_end_geometry_change;
1076 }
1077
1078 static void
1079 gst_wayland_sink_begin_geometry_change (GstWaylandVideo * video)
1080 {
1081   FUNCTION_ENTER ();
1082
1083   GstWaylandSink *sink = GST_WAYLAND_SINK (video);
1084   g_return_if_fail (sink != NULL);
1085
1086   g_mutex_lock (&sink->render_lock);
1087   if (!sink->window || !sink->window->subsurface) {
1088     g_mutex_unlock (&sink->render_lock);
1089     GST_INFO_OBJECT (sink,
1090         "begin_geometry_change called without window, ignoring");
1091     return;
1092   }
1093
1094   wl_subsurface_set_sync (sink->window->subsurface);
1095   g_mutex_unlock (&sink->render_lock);
1096 }
1097
1098 static void
1099 gst_wayland_sink_end_geometry_change (GstWaylandVideo * video)
1100 {
1101   FUNCTION_ENTER ();
1102
1103   GstWaylandSink *sink = GST_WAYLAND_SINK (video);
1104   g_return_if_fail (sink != NULL);
1105
1106   g_mutex_lock (&sink->render_lock);
1107   if (!sink->window || !sink->window->subsurface) {
1108     g_mutex_unlock (&sink->render_lock);
1109     GST_INFO_OBJECT (sink,
1110         "end_geometry_change called without window, ignoring");
1111     return;
1112   }
1113
1114   wl_subsurface_set_desync (sink->window->subsurface);
1115   g_mutex_unlock (&sink->render_lock);
1116 }
1117
1118 static gboolean
1119 plugin_init (GstPlugin * plugin)
1120 {
1121   FUNCTION_ENTER ();
1122
1123   GST_DEBUG_CATEGORY_INIT (gstwayland_debug, "waylandsink", 0,
1124       " wayland video sink");
1125
1126   return gst_element_register (plugin, "waylandsink", GST_RANK_MARGINAL,
1127       GST_TYPE_WAYLAND_SINK);
1128 }
1129
1130 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
1131     GST_VERSION_MINOR,
1132     waylandsink,
1133     "Wayland Video Sink", plugin_init, VERSION, "LGPL", GST_PACKAGE_NAME,
1134     GST_PACKAGE_ORIGIN)