Merge branch 'master' into 0.11
[platform/upstream/gst-plugins-good.git] / sys / ximage / gstximagesrc.c
1 /* GStreamer
2  *
3  * Copyright (C) 2006 Zaheer Merali <zaheerabbas at merali dot org>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  * Boston, MA 02111-1307, USA.
19  */
20
21 /**
22  * SECTION:element-ximagesrc
23  *
24  * This element captures your X Display and creates raw RGB video.  It uses
25  * the XDamage extension if available to only capture areas of the screen that
26  * have changed since the last frame.  It uses the XFixes extension if
27  * available to also capture your mouse pointer.  By default it will fixate to
28  * 25 frames per second.
29  *
30  * <refsect2>
31  * <title>Example pipelines</title>
32  * |[
33  * gst-launch ximagesrc ! video/x-raw-rgb,framerate=5/1 ! ffmpegcolorspace ! theoraenc ! oggmux ! filesink location=desktop.ogg
34  * ]| Encodes your X display to an Ogg theora video at 5 frames per second.
35  * </refsect2>
36  */
37
38 #ifdef HAVE_CONFIG_H
39 #include "config.h"
40 #endif
41 #include "gstximagesrc.h"
42
43 #include <string.h>
44 #include <stdlib.h>
45
46 #include <X11/Xlib.h>
47 #include <X11/Xutil.h>
48
49 #include <gst/gst.h>
50 #include <gst/gst-i18n-plugin.h>
51
52 GST_DEBUG_CATEGORY_STATIC (gst_debug_ximage_src);
53 #define GST_CAT_DEFAULT gst_debug_ximage_src
54
55 static GstStaticPadTemplate t =
56 GST_STATIC_PAD_TEMPLATE ("src", GST_PAD_SRC, GST_PAD_ALWAYS,
57     GST_STATIC_CAPS ("video/x-raw-rgb, "
58         "framerate = (fraction) [ 0, MAX ], "
59         "width = (int) [ 1, MAX ], " "height = (int) [ 1, MAX ], "
60         "pixel-aspect-ratio = (fraction) [ 0, MAX ]"));
61
62 enum
63 {
64   PROP_0,
65   PROP_DISPLAY_NAME,
66   PROP_SCREEN_NUM,
67   PROP_SHOW_POINTER,
68   PROP_USE_DAMAGE,
69   PROP_STARTX,
70   PROP_STARTY,
71   PROP_ENDX,
72   PROP_ENDY,
73   PROP_REMOTE,
74 };
75
76 GST_BOILERPLATE (GstXImageSrc, gst_ximage_src, GstPushSrc, GST_TYPE_PUSH_SRC);
77
78 static void gst_ximage_src_fixate (GstPad * pad, GstCaps * caps);
79 static void gst_ximage_src_clear_bufpool (GstXImageSrc * ximagesrc);
80
81 /* Called when a buffer is returned from the pipeline */
82 static void
83 gst_ximage_src_return_buf (GstXImageSrc * ximagesrc, GstBuffer * ximage)
84 {
85   GstMetaXImage *meta = GST_META_XIMAGE_GET (ximage);
86
87   /* If our geometry changed we can't reuse that image. */
88   if ((meta->width != ximagesrc->width) || (meta->height != ximagesrc->height)) {
89     GST_DEBUG_OBJECT (ximagesrc,
90         "destroy image %p as its size changed %dx%d vs current %dx%d",
91         ximage, meta->width, meta->height, ximagesrc->width, ximagesrc->height);
92     g_mutex_lock (ximagesrc->x_lock);
93     gst_ximageutil_ximage_destroy (ximagesrc->xcontext, ximage);
94     g_mutex_unlock (ximagesrc->x_lock);
95   } else {
96     /* In that case we can reuse the image and add it to our image pool. */
97     GST_LOG_OBJECT (ximagesrc, "recycling image %p in pool", ximage);
98     /* need to increment the refcount again to recycle */
99     gst_buffer_ref (ximage);
100     g_mutex_lock (ximagesrc->pool_lock);
101     ximagesrc->buffer_pool = g_slist_prepend (ximagesrc->buffer_pool, ximage);
102     g_mutex_unlock (ximagesrc->pool_lock);
103   }
104 }
105
106 static gboolean
107 gst_ximage_src_open_display (GstXImageSrc * s, const gchar * name)
108 {
109   g_return_val_if_fail (GST_IS_XIMAGE_SRC (s), FALSE);
110
111   if (s->xcontext != NULL)
112     return TRUE;
113
114   g_mutex_lock (s->x_lock);
115   s->xcontext = ximageutil_xcontext_get (GST_ELEMENT (s), name);
116   if (s->xcontext == NULL) {
117     g_mutex_unlock (s->x_lock);
118     GST_ELEMENT_ERROR (s, RESOURCE, OPEN_READ,
119         ("Could not open X display for reading"),
120         ("NULL returned from getting xcontext"));
121     return FALSE;
122   }
123   s->width = s->xcontext->width;
124   s->height = s->xcontext->height;
125
126   /* Always capture root window, for now */
127   s->xwindow = s->xcontext->root;
128
129 #ifdef HAVE_XFIXES
130   /* check if xfixes supported */
131   {
132     int error_base;
133
134     if (XFixesQueryExtension (s->xcontext->disp, &s->fixes_event_base,
135             &error_base)) {
136       s->have_xfixes = TRUE;
137       GST_DEBUG_OBJECT (s, "X Server supports XFixes");
138     } else {
139
140       GST_DEBUG_OBJECT (s, "X Server does not support XFixes");
141     }
142   }
143
144 #ifdef HAVE_XDAMAGE
145   /* check if xdamage is supported */
146   {
147     int error_base;
148     long evmask = NoEventMask;
149
150     s->have_xdamage = FALSE;
151     s->damage = None;
152     s->damage_copy_gc = None;
153     s->damage_region = None;
154
155     if (XDamageQueryExtension (s->xcontext->disp, &s->damage_event_base,
156             &error_base)) {
157       s->damage =
158           XDamageCreate (s->xcontext->disp, s->xwindow, XDamageReportNonEmpty);
159       if (s->damage != None) {
160         s->damage_region = XFixesCreateRegion (s->xcontext->disp, NULL, 0);
161         if (s->damage_region != None) {
162           XGCValues values;
163
164           GST_DEBUG_OBJECT (s, "Using XDamage extension");
165           values.subwindow_mode = IncludeInferiors;
166           s->damage_copy_gc = XCreateGC (s->xcontext->disp,
167               s->xwindow, GCSubwindowMode, &values);
168           XSelectInput (s->xcontext->disp, s->xwindow, evmask);
169
170           s->have_xdamage = TRUE;
171         } else {
172           XDamageDestroy (s->xcontext->disp, s->damage);
173           s->damage = None;
174         }
175       } else
176         GST_DEBUG_OBJECT (s, "Could not attach to XDamage");
177     } else {
178       GST_DEBUG_OBJECT (s, "X Server does not have XDamage extension");
179     }
180   }
181 #endif
182 #endif
183
184   g_mutex_unlock (s->x_lock);
185
186   if (s->xcontext == NULL)
187     return FALSE;
188
189   return TRUE;
190 }
191
192 static gboolean
193 gst_ximage_src_start (GstBaseSrc * basesrc)
194 {
195   GstXImageSrc *s = GST_XIMAGE_SRC (basesrc);
196
197   s->last_frame_no = -1;
198 #ifdef HAVE_XDAMAGE
199   if (s->last_ximage)
200     gst_buffer_unref (GST_BUFFER_CAST (s->last_ximage));
201   s->last_ximage = NULL;
202 #endif
203   return gst_ximage_src_open_display (s, s->display_name);
204 }
205
206 static gboolean
207 gst_ximage_src_stop (GstBaseSrc * basesrc)
208 {
209   GstXImageSrc *src = GST_XIMAGE_SRC (basesrc);
210
211 #ifdef HAVE_XDAMAGE
212   if (src->last_ximage)
213     gst_buffer_unref (GST_BUFFER_CAST (src->last_ximage));
214   src->last_ximage = NULL;
215 #endif
216
217   gst_ximage_src_clear_bufpool (src);
218
219 #ifdef HAVE_XFIXES
220   if (src->cursor_image)
221     XFree (src->cursor_image);
222   src->cursor_image = NULL;
223 #endif
224
225   if (src->xcontext) {
226     g_mutex_lock (src->x_lock);
227
228 #ifdef HAVE_XDAMAGE
229     if (src->damage_copy_gc != None) {
230       XFreeGC (src->xcontext->disp, src->damage_copy_gc);
231       src->damage_copy_gc = None;
232     }
233     if (src->damage_region != None) {
234       XFixesDestroyRegion (src->xcontext->disp, src->damage_region);
235       src->damage_region = None;
236     }
237     if (src->damage != None) {
238       XDamageDestroy (src->xcontext->disp, src->damage);
239       src->damage = None;
240     }
241 #endif
242
243     ximageutil_xcontext_clear (src->xcontext);
244     src->xcontext = NULL;
245     g_mutex_unlock (src->x_lock);
246   }
247
248   return TRUE;
249 }
250
251 static gboolean
252 gst_ximage_src_unlock (GstBaseSrc * basesrc)
253 {
254   GstXImageSrc *src = GST_XIMAGE_SRC (basesrc);
255
256   /* Awaken the create() func if it's waiting on the clock */
257   GST_OBJECT_LOCK (src);
258   if (src->clock_id) {
259     GST_DEBUG_OBJECT (src, "Waking up waiting clock");
260     gst_clock_id_unschedule (src->clock_id);
261   }
262   GST_OBJECT_UNLOCK (src);
263
264   return TRUE;
265 }
266
267 static gboolean
268 gst_ximage_src_recalc (GstXImageSrc * src)
269 {
270   if (!src->xcontext)
271     return FALSE;
272
273   /* Maybe later we can check the display hasn't changed size */
274   /* We could use XQueryPointer to get only the current window. */
275   return TRUE;
276 }
277
278 #ifdef HAVE_XFIXES
279 static void
280 composite_pixel (GstXContext * xcontext, guchar * dest, guchar * src)
281 {
282   guint8 r = src[2];
283   guint8 g = src[1];
284   guint8 b = src[0];
285   guint8 a = src[3];
286   guint8 dr, dg, db;
287   guint32 color;
288   gint r_shift, r_max, r_shift_out;
289   gint g_shift, g_max, g_shift_out;
290   gint b_shift, b_max, b_shift_out;
291
292   switch (xcontext->bpp) {
293     case 8:
294       color = *dest;
295       break;
296     case 16:
297       color = GUINT16_FROM_LE (*(guint16 *) (dest));
298       break;
299     case 32:
300       color = GUINT32_FROM_LE (*(guint32 *) (dest));
301       break;
302     default:
303       /* Should not reach here */
304       g_return_if_reached ();
305   }
306
307   /* possible optimisation:
308    * move the code that finds shift and max in the _link function */
309   for (r_shift = 0; !(xcontext->visual->red_mask & (1 << r_shift)); r_shift++);
310   for (g_shift = 0; !(xcontext->visual->green_mask & (1 << g_shift));
311       g_shift++);
312   for (b_shift = 0; !(xcontext->visual->blue_mask & (1 << b_shift)); b_shift++);
313
314   for (r_shift_out = 0; !(xcontext->visual->red_mask & (1 << r_shift_out));
315       r_shift_out++);
316   for (g_shift_out = 0; !(xcontext->visual->green_mask & (1 << g_shift_out));
317       g_shift_out++);
318   for (b_shift_out = 0; !(xcontext->visual->blue_mask & (1 << b_shift_out));
319       b_shift_out++);
320
321
322   r_max = (xcontext->visual->red_mask >> r_shift);
323   b_max = (xcontext->visual->blue_mask >> b_shift);
324   g_max = (xcontext->visual->green_mask >> g_shift);
325
326 #define RGBXXX_R(x)  (((x)>>r_shift) & (r_max))
327 #define RGBXXX_G(x)  (((x)>>g_shift) & (g_max))
328 #define RGBXXX_B(x)  (((x)>>b_shift) & (b_max))
329
330   dr = (RGBXXX_R (color) * 255) / r_max;
331   dg = (RGBXXX_G (color) * 255) / g_max;
332   db = (RGBXXX_B (color) * 255) / b_max;
333
334   dr = (r * a + (0xff - a) * dr) / 0xff;
335   dg = (g * a + (0xff - a) * dg) / 0xff;
336   db = (b * a + (0xff - a) * db) / 0xff;
337
338   color = (((dr * r_max) / 255) << r_shift_out) +
339       (((dg * g_max) / 255) << g_shift_out) +
340       (((db * b_max) / 255) << b_shift_out);
341
342   switch (xcontext->bpp) {
343     case 8:
344       *dest = color;
345       break;
346     case 16:
347       *(guint16 *) (dest) = color;
348       break;
349     case 32:
350       *(guint32 *) (dest) = color;
351       break;
352     default:
353       g_warning ("bpp %d not supported\n", xcontext->bpp);
354   }
355 }
356 #endif
357
358 /* Retrieve an XImageSrcBuffer, preferably from our
359  * pool of existing images and populate it from the window */
360 static GstBuffer *
361 gst_ximage_src_ximage_get (GstXImageSrc * ximagesrc)
362 {
363   GstBuffer *ximage = NULL;
364   GstMetaXImage *meta;
365
366   g_mutex_lock (ximagesrc->pool_lock);
367   while (ximagesrc->buffer_pool != NULL) {
368     ximage = ximagesrc->buffer_pool->data;
369
370     meta = GST_META_XIMAGE_GET (ximage);
371
372     if ((meta->width != ximagesrc->width) ||
373         (meta->height != ximagesrc->height)) {
374       gst_ximage_buffer_free (ximage);
375     }
376
377     ximagesrc->buffer_pool = g_slist_delete_link (ximagesrc->buffer_pool,
378         ximagesrc->buffer_pool);
379   }
380   g_mutex_unlock (ximagesrc->pool_lock);
381
382   if (ximage == NULL) {
383     GstXContext *xcontext;
384     GstCaps *caps = NULL;
385
386     GST_DEBUG_OBJECT (ximagesrc, "creating image (%dx%d)",
387         ximagesrc->width, ximagesrc->height);
388
389     g_mutex_lock (ximagesrc->x_lock);
390     ximage = gst_ximageutil_ximage_new (ximagesrc->xcontext,
391         GST_ELEMENT (ximagesrc), ximagesrc->width, ximagesrc->height,
392         (BufferReturnFunc) (gst_ximage_src_return_buf));
393     if (ximage == NULL) {
394       GST_ELEMENT_ERROR (ximagesrc, RESOURCE, WRITE, (NULL),
395           ("could not create a %dx%d ximage", ximagesrc->width,
396               ximagesrc->height));
397       g_mutex_unlock (ximagesrc->x_lock);
398       return NULL;
399     }
400
401     xcontext = ximagesrc->xcontext;
402
403
404     caps = gst_caps_new_simple ("video/x-raw-rgb",
405         "bpp", G_TYPE_INT, xcontext->bpp,
406         "depth", G_TYPE_INT, xcontext->depth,
407         "endianness", G_TYPE_INT, xcontext->endianness,
408         "red_mask", G_TYPE_INT, xcontext->r_mask_output,
409         "green_mask", G_TYPE_INT, xcontext->g_mask_output,
410         "blue_mask", G_TYPE_INT, xcontext->b_mask_output,
411         "width", G_TYPE_INT, ximagesrc->width,
412         "height", G_TYPE_INT, ximagesrc->height,
413         "framerate", GST_TYPE_FRACTION, ximagesrc->fps_n, ximagesrc->fps_d,
414         "pixel-aspect-ratio", GST_TYPE_FRACTION,
415         gst_value_get_fraction_numerator (xcontext->par),
416         gst_value_get_fraction_denominator (xcontext->par), NULL);
417
418     gst_buffer_set_caps (ximage, caps);
419     g_mutex_unlock (ximagesrc->x_lock);
420
421     gst_caps_unref (caps);
422   }
423
424   g_return_val_if_fail (GST_IS_XIMAGE_SRC (ximagesrc), NULL);
425
426   meta = GST_META_XIMAGE_GET (ximage);
427
428 #ifdef HAVE_XDAMAGE
429   if (ximagesrc->have_xdamage && ximagesrc->use_damage &&
430       ximagesrc->last_ximage != NULL) {
431     XEvent ev;
432
433     /* have_frame is TRUE when either the entire screen has been
434      * grabbed or when the last image has been copied */
435     gboolean have_frame = FALSE;
436
437     GST_DEBUG_OBJECT (ximagesrc, "Retrieving screen using XDamage");
438
439     do {
440       XNextEvent (ximagesrc->xcontext->disp, &ev);
441
442       if (ev.type == ximagesrc->damage_event_base + XDamageNotify) {
443         XserverRegion parts;
444         XRectangle *rects;
445         int nrects;
446
447         parts = XFixesCreateRegion (ximagesrc->xcontext->disp, 0, 0);
448         XDamageSubtract (ximagesrc->xcontext->disp, ximagesrc->damage, None,
449             parts);
450         /* Now copy out all of the damaged rectangles. */
451         rects = XFixesFetchRegion (ximagesrc->xcontext->disp, parts, &nrects);
452         if (rects != NULL) {
453           int i;
454
455           if (!have_frame) {
456             GST_LOG_OBJECT (ximagesrc,
457                 "Copying from last frame ximage->size: %d",
458                 GST_BUFFER_SIZE (GST_BUFFER (ximage)));
459             memcpy (GST_BUFFER_DATA (GST_BUFFER (ximage)),
460                 GST_BUFFER_DATA (GST_BUFFER (ximagesrc->last_ximage)),
461                 GST_BUFFER_SIZE (GST_BUFFER (ximage)));
462             have_frame = TRUE;
463           }
464           for (i = 0; i < nrects; i++) {
465             GST_LOG_OBJECT (ximagesrc,
466                 "Damaged sub-region @ %d,%d size %dx%d reported",
467                 rects[i].x, rects[i].y, rects[i].width, rects[i].height);
468
469             /* if we only want a small area, clip this damage region to
470              * area we want */
471             if (ximagesrc->endx > ximagesrc->startx &&
472                 ximagesrc->endy > ximagesrc->starty) {
473               /* see if damage area intersects */
474               if (rects[i].x + rects[i].width - 1 < ximagesrc->startx ||
475                   rects[i].x > ximagesrc->endx) {
476                 /* trivial reject */
477               } else if (rects[i].y + rects[i].height - 1 < ximagesrc->starty ||
478                   rects[i].y > ximagesrc->endy) {
479                 /* trivial reject */
480               } else {
481                 /* find intersect region */
482                 int startx, starty, width, height;
483
484                 startx = (rects[i].x < ximagesrc->startx) ? ximagesrc->startx :
485                     rects[i].x;
486                 starty = (rects[i].y < ximagesrc->starty) ? ximagesrc->starty :
487                     rects[i].y;
488                 width = (rects[i].x + rects[i].width - 1 < ximagesrc->endx) ?
489                     rects[i].x + rects[i].width - startx :
490                     ximagesrc->endx - startx + 1;
491                 height = (rects[i].y + rects[i].height - 1 < ximagesrc->endy) ?
492                     rects[i].y + rects[i].height - starty : ximagesrc->endy -
493                     starty + 1;
494
495                 GST_LOG_OBJECT (ximagesrc,
496                     "Retrieving damaged sub-region @ %d,%d size %dx%d as intersect region",
497                     startx, starty, width, height);
498                 XGetSubImage (ximagesrc->xcontext->disp, ximagesrc->xwindow,
499                     startx, starty, width, height, AllPlanes, ZPixmap,
500                     meta->ximage, startx - ximagesrc->startx,
501                     starty - ximagesrc->starty);
502               }
503             } else {
504
505               GST_LOG_OBJECT (ximagesrc,
506                   "Retrieving damaged sub-region @ %d,%d size %dx%d",
507                   rects[i].x, rects[i].y, rects[i].width, rects[i].height);
508
509               XGetSubImage (ximagesrc->xcontext->disp, ximagesrc->xwindow,
510                   rects[i].x, rects[i].y,
511                   rects[i].width, rects[i].height,
512                   AllPlanes, ZPixmap, meta->ximage, rects[i].x, rects[i].y);
513             }
514           }
515           free (rects);
516         }
517       }
518     } while (XPending (ximagesrc->xcontext->disp));
519     if (!have_frame) {
520       GST_LOG_OBJECT (ximagesrc,
521           "Copying from last frame ximage->size: %d",
522           GST_BUFFER_SIZE (GST_BUFFER (ximage)));
523       memcpy (GST_BUFFER_DATA (GST_BUFFER (ximage)),
524           GST_BUFFER_DATA (GST_BUFFER (ximagesrc->last_ximage)),
525           GST_BUFFER_SIZE (GST_BUFFER (ximage)));
526     }
527 #ifdef HAVE_XFIXES
528     /* re-get area where last mouse pointer was  but only if in our clipping
529      * bounds */
530     if (ximagesrc->cursor_image) {
531       gint x, y, width, height;
532
533       x = ximagesrc->cursor_image->x - ximagesrc->cursor_image->xhot;
534       y = ximagesrc->cursor_image->y - ximagesrc->cursor_image->yhot;
535       width = ximagesrc->cursor_image->width;
536       height = ximagesrc->cursor_image->height;
537
538       /* bounds checking */
539       if (x < 0)
540         x = 0;
541       if (y < 0)
542         y = 0;
543       if (x + width > ximagesrc->xcontext->width)
544         width = ximagesrc->xcontext->width - x;
545       if (y + height > ximagesrc->xcontext->height)
546         height = ximagesrc->xcontext->height - y;
547       g_assert (x >= 0);
548       g_assert (y >= 0);
549       GST_DEBUG_OBJECT (ximagesrc,
550           "Cursor was at (%d,%d) width: %d, height: %d and our range is: (%d,%d) - (%d,%d)",
551           x, y, width, height, ximagesrc->startx, ximagesrc->starty,
552           ximagesrc->endx, ximagesrc->endy);
553       /* only get where cursor last was, if it is in our range */
554       if (ximagesrc->endx > ximagesrc->startx &&
555           ximagesrc->endy > ximagesrc->starty) {
556         /* check bounds */
557         if (x + width < ximagesrc->startx || x > ximagesrc->endx) {
558           /* trivial reject */
559         } else if (y + height < ximagesrc->starty || y > ximagesrc->endy) {
560           /* trivial reject */
561         } else {
562           /* find intersect region */
563           int startx, starty, iwidth, iheight;
564
565           startx = (x < ximagesrc->startx) ? ximagesrc->startx : x;
566           starty = (y < ximagesrc->starty) ? ximagesrc->starty : y;
567           iwidth = (x + width < ximagesrc->endx) ?
568               x + width - startx : ximagesrc->endx - startx;
569           iheight = (y + height < ximagesrc->endy) ?
570               y + height - starty : ximagesrc->endy - starty;
571           GST_DEBUG_OBJECT (ximagesrc, "Removing cursor from %d,%d", x, y);
572           XGetSubImage (ximagesrc->xcontext->disp, ximagesrc->xwindow,
573               startx, starty, iwidth, iheight, AllPlanes, ZPixmap,
574               meta->ximage, startx - ximagesrc->startx,
575               starty - ximagesrc->starty);
576         }
577       } else {
578
579         GST_DEBUG_OBJECT (ximagesrc, "Removing cursor from %d,%d", x, y);
580         XGetSubImage (ximagesrc->xcontext->disp, ximagesrc->xwindow,
581             x, y, width, height, AllPlanes, ZPixmap, meta->ximage, x, y);
582       }
583     }
584 #endif
585
586
587   } else {
588 #endif
589
590 #ifdef HAVE_XSHM
591     if (ximagesrc->xcontext->use_xshm) {
592       GST_DEBUG_OBJECT (ximagesrc, "Retrieving screen using XShm");
593       XShmGetImage (ximagesrc->xcontext->disp, ximagesrc->xwindow,
594           meta->ximage, ximagesrc->startx, ximagesrc->starty, AllPlanes);
595
596     } else
597 #endif /* HAVE_XSHM */
598     {
599       GST_DEBUG_OBJECT (ximagesrc, "Retrieving screen using XGetImage");
600       if (ximagesrc->remote) {
601         XGetSubImage (ximagesrc->xcontext->disp, ximagesrc->xwindow,
602             ximagesrc->startx, ximagesrc->starty, ximagesrc->width,
603             ximagesrc->height, AllPlanes, ZPixmap, meta->ximage, 0, 0);
604       } else {
605         meta->ximage =
606             XGetImage (ximagesrc->xcontext->disp, ximagesrc->xwindow,
607             ximagesrc->startx, ximagesrc->starty, ximagesrc->width,
608             ximagesrc->height, AllPlanes, ZPixmap);
609       }
610     }
611 #ifdef HAVE_XDAMAGE
612   }
613 #endif
614
615 #ifdef HAVE_XFIXES
616   if (ximagesrc->show_pointer && ximagesrc->have_xfixes) {
617
618     GST_DEBUG_OBJECT (ximagesrc, "Using XFixes to draw cursor");
619     /* get cursor */
620     if (ximagesrc->cursor_image)
621       XFree (ximagesrc->cursor_image);
622     ximagesrc->cursor_image = XFixesGetCursorImage (ximagesrc->xcontext->disp);
623     if (ximagesrc->cursor_image != NULL) {
624       int cx, cy, i, j, count;
625       int startx, starty, iwidth, iheight;
626       gboolean cursor_in_image = TRUE;
627
628       cx = ximagesrc->cursor_image->x - ximagesrc->cursor_image->xhot;
629       if (cx < 0)
630         cx = 0;
631       cy = ximagesrc->cursor_image->y - ximagesrc->cursor_image->yhot;
632       if (cy < 0)
633         cy = 0;
634       count = ximagesrc->cursor_image->width * ximagesrc->cursor_image->height;
635
636       /* only get where cursor last was, if it is in our range */
637       if (ximagesrc->endx > ximagesrc->startx &&
638           ximagesrc->endy > ximagesrc->starty) {
639         /* check bounds */
640         if (cx + ximagesrc->cursor_image->width < ximagesrc->startx ||
641             cx > ximagesrc->endx) {
642           /* trivial reject */
643           cursor_in_image = FALSE;
644         } else if (cy + ximagesrc->cursor_image->height < ximagesrc->starty ||
645             cy > ximagesrc->endy) {
646           /* trivial reject */
647           cursor_in_image = FALSE;
648         } else {
649           /* find intersect region */
650
651           startx = (cx < ximagesrc->startx) ? ximagesrc->startx : cx;
652           starty = (cy < ximagesrc->starty) ? ximagesrc->starty : cy;
653           iwidth = (cx + ximagesrc->cursor_image->width < ximagesrc->endx) ?
654               cx + ximagesrc->cursor_image->width - startx :
655               ximagesrc->endx - startx;
656           iheight = (cy + ximagesrc->cursor_image->height < ximagesrc->endy) ?
657               cy + ximagesrc->cursor_image->height - starty :
658               ximagesrc->endy - starty;
659         }
660       } else {
661         startx = cx;
662         starty = cy;
663         iwidth = ximagesrc->cursor_image->width;
664         iheight = ximagesrc->cursor_image->height;
665       }
666
667       if (cursor_in_image) {
668         GST_DEBUG_OBJECT (ximagesrc, "Cursor is in image so trying to draw it");
669         for (i = 0; i < count; i++)
670           ximagesrc->cursor_image->pixels[i] =
671               GUINT_TO_LE (ximagesrc->cursor_image->pixels[i]);
672         /* copy those pixels across */
673         for (j = starty;
674             j < starty + iheight && j < ximagesrc->starty + ximagesrc->height;
675             j++) {
676           for (i = startx;
677               i < startx + iwidth && i < ximagesrc->startx + ximagesrc->width;
678               i++) {
679             guint8 *src, *dest;
680
681             src =
682                 (guint8 *) & (ximagesrc->cursor_image->pixels[((j -
683                             cy) * ximagesrc->cursor_image->width + (i - cx))]);
684             dest =
685                 (guint8 *) & (meta->ximage->data[((j -
686                             ximagesrc->starty) * ximagesrc->width + (i -
687                             ximagesrc->startx)) * (ximagesrc->xcontext->bpp /
688                         8)]);
689
690             composite_pixel (ximagesrc->xcontext, (guint8 *) dest,
691                 (guint8 *) src);
692           }
693         }
694       }
695     }
696   }
697 #endif
698 #ifdef HAVE_XDAMAGE
699   if (ximagesrc->have_xdamage && ximagesrc->use_damage) {
700     /* need to ref ximage to put in last_ximage */
701     gst_buffer_ref (GST_BUFFER (ximage));
702     if (ximagesrc->last_ximage) {
703       gst_buffer_unref (GST_BUFFER (ximagesrc->last_ximage));
704     }
705     ximagesrc->last_ximage = ximage;
706     GST_LOG_OBJECT (ximagesrc, "reffing current buffer for last_ximage");
707   }
708 #endif
709   return ximage;
710 }
711
712 static GstFlowReturn
713 gst_ximage_src_create (GstPushSrc * bs, GstBuffer ** buf)
714 {
715   GstXImageSrc *s = GST_XIMAGE_SRC (bs);
716   GstBuffer *image;
717   GstClockTime base_time;
718   GstClockTime next_capture_ts;
719   GstClockTime dur;
720   gint64 next_frame_no;
721
722   if (!gst_ximage_src_recalc (s)) {
723     GST_ELEMENT_ERROR (s, RESOURCE, FAILED,
724         (_("Changing resolution at runtime is not yet supported.")), (NULL));
725     return GST_FLOW_ERROR;
726   }
727
728   if (s->fps_n <= 0 || s->fps_d <= 0)
729     return GST_FLOW_NOT_NEGOTIATED;     /* FPS must be > 0 */
730
731   /* Now, we might need to wait for the next multiple of the fps
732    * before capturing */
733
734   GST_OBJECT_LOCK (s);
735   if (GST_ELEMENT_CLOCK (s) == NULL) {
736     GST_OBJECT_UNLOCK (s);
737     GST_ELEMENT_ERROR (s, RESOURCE, FAILED,
738         (_("Cannot operate without a clock")), (NULL));
739     return GST_FLOW_ERROR;
740   }
741
742   base_time = GST_ELEMENT_CAST (s)->base_time;
743   next_capture_ts = gst_clock_get_time (GST_ELEMENT_CLOCK (s));
744   next_capture_ts -= base_time;
745
746   /* Figure out which 'frame number' position we're at, based on the cur time
747    * and frame rate */
748   next_frame_no = gst_util_uint64_scale (next_capture_ts,
749       s->fps_n, GST_SECOND * s->fps_d);
750   if (next_frame_no == s->last_frame_no) {
751     GstClockID id;
752     GstClockReturn ret;
753
754     /* Need to wait for the next frame */
755     next_frame_no += 1;
756
757     /* Figure out what the next frame time is */
758     next_capture_ts = gst_util_uint64_scale (next_frame_no,
759         s->fps_d * GST_SECOND, s->fps_n);
760
761     id = gst_clock_new_single_shot_id (GST_ELEMENT_CLOCK (s),
762         next_capture_ts + base_time);
763     s->clock_id = id;
764
765     /* release the object lock while waiting */
766     GST_OBJECT_UNLOCK (s);
767
768     GST_DEBUG_OBJECT (s, "Waiting for next frame time %" G_GUINT64_FORMAT,
769         next_capture_ts);
770     ret = gst_clock_id_wait (id, NULL);
771     GST_OBJECT_LOCK (s);
772
773     gst_clock_id_unref (id);
774     s->clock_id = NULL;
775     if (ret == GST_CLOCK_UNSCHEDULED) {
776       /* Got woken up by the unlock function */
777       GST_OBJECT_UNLOCK (s);
778       return GST_FLOW_WRONG_STATE;
779     }
780     /* Duration is a complete 1/fps frame duration */
781     dur = gst_util_uint64_scale_int (GST_SECOND, s->fps_d, s->fps_n);
782   } else {
783     GstClockTime next_frame_ts;
784
785     GST_DEBUG_OBJECT (s, "No need to wait for next frame time %"
786         G_GUINT64_FORMAT " next frame = %" G_GINT64_FORMAT " prev = %"
787         G_GINT64_FORMAT, next_capture_ts, next_frame_no, s->last_frame_no);
788     next_frame_ts = gst_util_uint64_scale (next_frame_no + 1,
789         s->fps_d * GST_SECOND, s->fps_n);
790     /* Frame duration is from now until the next expected capture time */
791     dur = next_frame_ts - next_capture_ts;
792   }
793   s->last_frame_no = next_frame_no;
794   GST_OBJECT_UNLOCK (s);
795
796   image = gst_ximage_src_ximage_get (s);
797   if (!image)
798     return GST_FLOW_ERROR;
799
800   *buf = GST_BUFFER (image);
801   GST_BUFFER_TIMESTAMP (*buf) = next_capture_ts;
802   GST_BUFFER_DURATION (*buf) = dur;
803
804   return GST_FLOW_OK;
805 }
806
807 static void
808 gst_ximage_src_set_property (GObject * object, guint prop_id,
809     const GValue * value, GParamSpec * pspec)
810 {
811   GstXImageSrc *src = GST_XIMAGE_SRC (object);
812
813   switch (prop_id) {
814     case PROP_DISPLAY_NAME:
815
816       g_free (src->display_name);
817       src->display_name = g_strdup (g_value_get_string (value));
818       break;
819     case PROP_SCREEN_NUM:
820       src->screen_num = g_value_get_uint (value);
821       break;
822     case PROP_SHOW_POINTER:
823       src->show_pointer = g_value_get_boolean (value);
824       break;
825     case PROP_USE_DAMAGE:
826       src->use_damage = g_value_get_boolean (value);
827       break;
828     case PROP_STARTX:
829       src->startx = g_value_get_uint (value);
830       break;
831     case PROP_STARTY:
832       src->starty = g_value_get_uint (value);
833       break;
834     case PROP_ENDX:
835       src->endx = g_value_get_uint (value);
836       break;
837     case PROP_ENDY:
838       src->endy = g_value_get_uint (value);
839       break;
840     case PROP_REMOTE:
841       src->remote = g_value_get_boolean (value);
842       break;
843     default:
844       break;
845   }
846 }
847
848 static void
849 gst_ximage_src_get_property (GObject * object, guint prop_id, GValue * value,
850     GParamSpec * pspec)
851 {
852   GstXImageSrc *src = GST_XIMAGE_SRC (object);
853
854   switch (prop_id) {
855     case PROP_DISPLAY_NAME:
856       if (src->xcontext)
857         g_value_set_string (value, DisplayString (src->xcontext->disp));
858       else
859         g_value_set_string (value, src->display_name);
860
861       break;
862     case PROP_SCREEN_NUM:
863       g_value_set_uint (value, src->screen_num);
864       break;
865     case PROP_SHOW_POINTER:
866       g_value_set_boolean (value, src->show_pointer);
867       break;
868     case PROP_USE_DAMAGE:
869       g_value_set_boolean (value, src->use_damage);
870       break;
871     case PROP_STARTX:
872       g_value_set_uint (value, src->startx);
873       break;
874     case PROP_STARTY:
875       g_value_set_uint (value, src->starty);
876       break;
877     case PROP_ENDX:
878       g_value_set_uint (value, src->endx);
879       break;
880     case PROP_ENDY:
881       g_value_set_uint (value, src->endy);
882       break;
883     case PROP_REMOTE:
884       g_value_set_boolean (value, src->remote);
885       break;
886     default:
887       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
888       break;
889   }
890 }
891
892 static void
893 gst_ximage_src_clear_bufpool (GstXImageSrc * ximagesrc)
894 {
895   g_mutex_lock (ximagesrc->pool_lock);
896   while (ximagesrc->buffer_pool != NULL) {
897     GstBuffer *ximage = ximagesrc->buffer_pool->data;
898
899     gst_ximage_buffer_free (ximage);
900
901     ximagesrc->buffer_pool = g_slist_delete_link (ximagesrc->buffer_pool,
902         ximagesrc->buffer_pool);
903   }
904   g_mutex_unlock (ximagesrc->pool_lock);
905 }
906
907 static void
908 gst_ximage_src_base_init (gpointer g_class)
909 {
910   GstElementClass *ec = GST_ELEMENT_CLASS (g_class);
911
912   gst_element_class_set_details_simple (ec, "Ximage video source",
913       "Source/Video",
914       "Creates a screenshot video stream",
915       "Lutz Mueller <lutz@users.sourceforge.net>, "
916       "Jan Schmidt <thaytan@mad.scientist.com>, "
917       "Zaheer Merali <zaheerabbas at merali dot org>");
918   gst_element_class_add_pad_template (ec, gst_static_pad_template_get (&t));
919 }
920
921 static void
922 gst_ximage_src_dispose (GObject * object)
923 {
924   /* Drop references in the buffer_pool */
925   gst_ximage_src_clear_bufpool (GST_XIMAGE_SRC (object));
926
927   G_OBJECT_CLASS (parent_class)->dispose (object);
928 }
929
930 static void
931 gst_ximage_src_finalize (GObject * object)
932 {
933   GstXImageSrc *src = GST_XIMAGE_SRC (object);
934
935   if (src->xcontext)
936     ximageutil_xcontext_clear (src->xcontext);
937
938   g_mutex_free (src->pool_lock);
939   g_mutex_free (src->x_lock);
940
941   G_OBJECT_CLASS (parent_class)->finalize (object);
942 }
943
944 static GstCaps *
945 gst_ximage_src_get_caps (GstBaseSrc * bs)
946 {
947   GstXImageSrc *s = GST_XIMAGE_SRC (bs);
948   GstXContext *xcontext;
949   gint width, height;
950
951   if ((!s->xcontext) && (!gst_ximage_src_open_display (s, s->display_name)))
952     return
953         gst_caps_copy (gst_pad_get_pad_template_caps (GST_BASE_SRC
954             (s)->srcpad));
955
956   if (!gst_ximage_src_recalc (s))
957     return
958         gst_caps_copy (gst_pad_get_pad_template_caps (GST_BASE_SRC
959             (s)->srcpad));
960
961   xcontext = s->xcontext;
962
963   width = xcontext->width;
964   height = xcontext->height;
965
966   /* property comments say 0 means right/bottom, means we can't capture
967      the top left pixel alone */
968   if (s->endx == 0)
969     s->endx = width - 1;
970   if (s->endy == 0)
971     s->endy = height - 1;
972
973   if (s->endx >= s->startx && s->endy >= s->starty) {
974     /* this means user has put in values */
975     if (s->startx < xcontext->width && s->endx < xcontext->width &&
976         s->starty < xcontext->height && s->endy < xcontext->height &&
977         s->startx >= 0 && s->starty >= 0) {
978       /* values are fine */
979       s->width = width = s->endx - s->startx + 1;
980       s->height = height = s->endy - s->starty + 1;
981     } else {
982       GST_WARNING
983           ("User put in co-ordinates overshooting the X resolution, setting to full screen");
984       s->startx = 0;
985       s->starty = 0;
986       s->endx = width - 1;
987       s->endy = height - 1;
988     }
989   } else {
990     GST_WARNING ("User put in bogus co-ordinates, setting to full screen");
991     s->startx = 0;
992     s->starty = 0;
993     s->endx = width - 1;
994     s->endy = height - 1;
995   }
996   GST_DEBUG ("width = %d, height=%d", width, height);
997   return gst_caps_new_simple ("video/x-raw-rgb",
998       "bpp", G_TYPE_INT, xcontext->bpp,
999       "depth", G_TYPE_INT, xcontext->depth,
1000       "endianness", G_TYPE_INT, xcontext->endianness,
1001       "red_mask", G_TYPE_INT, xcontext->r_mask_output,
1002       "green_mask", G_TYPE_INT, xcontext->g_mask_output,
1003       "blue_mask", G_TYPE_INT, xcontext->b_mask_output,
1004       "width", G_TYPE_INT, width,
1005       "height", G_TYPE_INT, height,
1006       "framerate", GST_TYPE_FRACTION_RANGE, 1, G_MAXINT, G_MAXINT, 1,
1007       "pixel-aspect-ratio", GST_TYPE_FRACTION_RANGE, 1, G_MAXINT, G_MAXINT, 1,
1008       NULL);
1009 }
1010
1011 static gboolean
1012 gst_ximage_src_set_caps (GstBaseSrc * bs, GstCaps * caps)
1013 {
1014   GstXImageSrc *s = GST_XIMAGE_SRC (bs);
1015   GstStructure *structure;
1016   const GValue *new_fps;
1017
1018   /* If not yet opened, disallow setcaps until later */
1019   if (!s->xcontext)
1020     return FALSE;
1021
1022   /* The only thing that can change is the framerate downstream wants */
1023   structure = gst_caps_get_structure (caps, 0);
1024   new_fps = gst_structure_get_value (structure, "framerate");
1025   if (!new_fps)
1026     return FALSE;
1027
1028   /* Store this FPS for use when generating buffers */
1029   s->fps_n = gst_value_get_fraction_numerator (new_fps);
1030   s->fps_d = gst_value_get_fraction_denominator (new_fps);
1031
1032   GST_DEBUG_OBJECT (s, "peer wants %d/%d fps", s->fps_n, s->fps_d);
1033
1034   return TRUE;
1035 }
1036
1037 static void
1038 gst_ximage_src_fixate (GstPad * pad, GstCaps * caps)
1039 {
1040   gint i;
1041   GstStructure *structure;
1042
1043   for (i = 0; i < gst_caps_get_size (caps); ++i) {
1044     structure = gst_caps_get_structure (caps, i);
1045
1046     gst_structure_fixate_field_nearest_fraction (structure, "framerate", 25, 1);
1047   }
1048 }
1049
1050 static void
1051 gst_ximage_src_class_init (GstXImageSrcClass * klass)
1052 {
1053   GObjectClass *gc = G_OBJECT_CLASS (klass);
1054   GstBaseSrcClass *bc = GST_BASE_SRC_CLASS (klass);
1055   GstPushSrcClass *push_class = GST_PUSH_SRC_CLASS (klass);
1056
1057   gc->set_property = gst_ximage_src_set_property;
1058   gc->get_property = gst_ximage_src_get_property;
1059   gc->dispose = gst_ximage_src_dispose;
1060   gc->finalize = gst_ximage_src_finalize;
1061
1062   g_object_class_install_property (gc, PROP_DISPLAY_NAME,
1063       g_param_spec_string ("display-name", "Display", "X Display Name", NULL,
1064           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1065   g_object_class_install_property (gc, PROP_SCREEN_NUM,
1066       g_param_spec_uint ("screen-num", "Screen number", "X Screen Number",
1067           0, G_MAXINT, 0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1068   g_object_class_install_property (gc, PROP_SHOW_POINTER,
1069       g_param_spec_boolean ("show-pointer", "Show Mouse Pointer",
1070           "Show mouse pointer (if XFixes extension enabled)", TRUE,
1071           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1072   /**
1073    * GstXImageSrc:use-damage
1074    *
1075    * Use XDamage (if the XDamage extension is enabled)
1076    *
1077    * Since: 0.10.4
1078    **/
1079   g_object_class_install_property (gc, PROP_USE_DAMAGE,
1080       g_param_spec_boolean ("use-damage", "Use XDamage",
1081           "Use XDamage (if XDamage extension enabled)", TRUE,
1082           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1083   /**
1084    * GstXImageSrc:startx
1085    *
1086    * X coordinate of top left corner of area to be recorded
1087    * (0 for top left of screen)
1088    *
1089    * Since: 0.10.4
1090    **/
1091   g_object_class_install_property (gc, PROP_STARTX,
1092       g_param_spec_uint ("startx", "Start X co-ordinate",
1093           "X coordinate of top left corner of area to be recorded (0 for top left of screen)",
1094           0, G_MAXINT, 0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1095   /**
1096    * GstXImageSrc:starty
1097    *
1098    * Y coordinate of top left corner of area to be recorded
1099    * (0 for top left of screen)
1100    *
1101    * Since: 0.10.4
1102    **/
1103   g_object_class_install_property (gc, PROP_STARTY,
1104       g_param_spec_uint ("starty", "Start Y co-ordinate",
1105           "Y coordinate of top left corner of area to be recorded (0 for top left of screen)",
1106           0, G_MAXINT, 0, G_PARAM_READWRITE));
1107   /**
1108    * GstXImageSrc:endx
1109    *
1110    * X coordinate of bottom right corner of area to be recorded
1111    * (0 for bottom right of screen)
1112    *
1113    * Since: 0.10.4
1114    **/
1115   g_object_class_install_property (gc, PROP_ENDX,
1116       g_param_spec_uint ("endx", "End X",
1117           "X coordinate of bottom right corner of area to be recorded (0 for bottom right of screen)",
1118           0, G_MAXINT, 0, G_PARAM_READWRITE));
1119   /**
1120    * GstXImageSrc:endy
1121    *
1122    * Y coordinate of bottom right corner of area to be recorded
1123    * (0 for bottom right of screen)
1124    *
1125    * Since: 0.10.4
1126    **/
1127   g_object_class_install_property (gc, PROP_ENDY,
1128       g_param_spec_uint ("endy", "End Y",
1129           "Y coordinate of bottom right corner of area to be recorded (0 for bottom right of screen)",
1130           0, G_MAXINT, 0, G_PARAM_READWRITE));
1131
1132   /**
1133    * GstXImageSrc:remote
1134    *
1135    * Whether the X display is remote. The element will try to use alternate calls
1136    * known to work better with remote displays.
1137    *
1138    * Since: 0.10.26
1139    **/
1140   g_object_class_install_property (gc, PROP_REMOTE,
1141       g_param_spec_boolean ("remote", "Remote dispay",
1142           "Whether the display is remote", FALSE,
1143           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1144
1145   parent_class = g_type_class_peek_parent (klass);
1146
1147   push_class->create = gst_ximage_src_create;
1148   bc->get_caps = gst_ximage_src_get_caps;
1149   bc->set_caps = gst_ximage_src_set_caps;
1150   bc->start = gst_ximage_src_start;
1151   bc->stop = gst_ximage_src_stop;
1152   bc->unlock = gst_ximage_src_unlock;
1153 }
1154
1155 static void
1156 gst_ximage_src_init (GstXImageSrc * ximagesrc, GstXImageSrcClass * klass)
1157 {
1158   gst_base_src_set_format (GST_BASE_SRC (ximagesrc), GST_FORMAT_TIME);
1159   gst_base_src_set_live (GST_BASE_SRC (ximagesrc), TRUE);
1160   gst_pad_set_fixatecaps_function (GST_BASE_SRC_PAD (ximagesrc),
1161       gst_ximage_src_fixate);
1162
1163   ximagesrc->pool_lock = g_mutex_new ();
1164   ximagesrc->x_lock = g_mutex_new ();
1165   ximagesrc->show_pointer = TRUE;
1166   ximagesrc->use_damage = TRUE;
1167   ximagesrc->startx = 0;
1168   ximagesrc->starty = 0;
1169   ximagesrc->endx = 0;
1170   ximagesrc->endy = 0;
1171   ximagesrc->remote = FALSE;
1172 }
1173
1174 static gboolean
1175 plugin_init (GstPlugin * plugin)
1176 {
1177   gboolean ret;
1178
1179   GST_DEBUG_CATEGORY_INIT (gst_debug_ximage_src, "ximagesrc", 0,
1180       "ximagesrc element debug");
1181
1182   ret = gst_element_register (plugin, "ximagesrc", GST_RANK_NONE,
1183       GST_TYPE_XIMAGE_SRC);
1184
1185   return ret;
1186 }
1187
1188 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
1189     GST_VERSION_MINOR,
1190     "ximagesrc",
1191     "X11 video input plugin using standard Xlib calls",
1192     plugin_init, VERSION, GST_LICENSE, GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN);