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