upload tizen1.0 source
[framework/multimedia/gst-plugins-good0.10.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,
84     GstXImageSrcBuffer * ximage)
85 {
86   /* If our geometry changed we can't reuse that image. */
87   if ((ximage->width != ximagesrc->width) ||
88       (ximage->height != ximagesrc->height)) {
89     GST_DEBUG_OBJECT (ximagesrc,
90         "destroy image %p as its size changed %dx%d vs current %dx%d",
91         ximage, ximage->width, ximage->height,
92         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 (GST_BUFFER (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 /* Retrieve an XImageSrcBuffer, preferably from our
360  * pool of existing images and populate it from the window */
361 static GstXImageSrcBuffer *
362 gst_ximage_src_ximage_get (GstXImageSrc * ximagesrc)
363 {
364   GstXImageSrcBuffer *ximage = NULL;
365
366   g_mutex_lock (ximagesrc->pool_lock);
367   while (ximagesrc->buffer_pool != NULL) {
368     ximage = ximagesrc->buffer_pool->data;
369
370     if ((ximage->width != ximagesrc->width) ||
371         (ximage->height != ximagesrc->height)) {
372       gst_ximage_buffer_free (ximage);
373     }
374
375     ximagesrc->buffer_pool = g_slist_delete_link (ximagesrc->buffer_pool,
376         ximagesrc->buffer_pool);
377   }
378   g_mutex_unlock (ximagesrc->pool_lock);
379
380   if (ximage == NULL) {
381     GstXContext *xcontext;
382     GstCaps *caps = NULL;
383
384     GST_DEBUG_OBJECT (ximagesrc, "creating image (%dx%d)",
385         ximagesrc->width, ximagesrc->height);
386
387     g_mutex_lock (ximagesrc->x_lock);
388     ximage = gst_ximageutil_ximage_new (ximagesrc->xcontext,
389         GST_ELEMENT (ximagesrc), ximagesrc->width, ximagesrc->height,
390         (BufferReturnFunc) (gst_ximage_src_return_buf));
391     if (ximage == NULL) {
392       GST_ELEMENT_ERROR (ximagesrc, RESOURCE, WRITE, (NULL),
393           ("could not create a %dx%d ximage", ximagesrc->width,
394               ximagesrc->height));
395       g_mutex_unlock (ximagesrc->x_lock);
396       return NULL;
397     }
398
399     xcontext = ximagesrc->xcontext;
400
401
402     caps = gst_caps_new_simple ("video/x-raw-rgb",
403         "bpp", G_TYPE_INT, xcontext->bpp,
404         "depth", G_TYPE_INT, xcontext->depth,
405         "endianness", G_TYPE_INT, xcontext->endianness,
406         "red_mask", G_TYPE_INT, xcontext->r_mask_output,
407         "green_mask", G_TYPE_INT, xcontext->g_mask_output,
408         "blue_mask", G_TYPE_INT, xcontext->b_mask_output,
409         "width", G_TYPE_INT, ximagesrc->width,
410         "height", G_TYPE_INT, ximagesrc->height,
411         "framerate", GST_TYPE_FRACTION, ximagesrc->fps_n, ximagesrc->fps_d,
412         "pixel-aspect-ratio", GST_TYPE_FRACTION,
413         gst_value_get_fraction_numerator (xcontext->par),
414         gst_value_get_fraction_denominator (xcontext->par), NULL);
415
416     gst_buffer_set_caps (GST_BUFFER (ximage), caps);
417     g_mutex_unlock (ximagesrc->x_lock);
418
419     gst_caps_unref (caps);
420   }
421
422   g_return_val_if_fail (GST_IS_XIMAGE_SRC (ximagesrc), NULL);
423 #ifdef HAVE_XDAMAGE
424   if (ximagesrc->have_xdamage && ximagesrc->use_damage &&
425       ximagesrc->last_ximage != NULL) {
426     XEvent ev;
427
428     /* have_frame is TRUE when either the entire screen has been
429      * grabbed or when the last image has been copied */
430     gboolean have_frame = FALSE;
431
432     GST_DEBUG_OBJECT (ximagesrc, "Retrieving screen using XDamage");
433
434     do {
435       XNextEvent (ximagesrc->xcontext->disp, &ev);
436
437       if (ev.type == ximagesrc->damage_event_base + XDamageNotify) {
438         XserverRegion parts;
439         XRectangle *rects;
440         int nrects;
441
442         parts = XFixesCreateRegion (ximagesrc->xcontext->disp, 0, 0);
443         XDamageSubtract (ximagesrc->xcontext->disp, ximagesrc->damage, None,
444             parts);
445         /* Now copy out all of the damaged rectangles. */
446         rects = XFixesFetchRegion (ximagesrc->xcontext->disp, parts, &nrects);
447         if (rects != NULL) {
448           int i;
449
450           if (!have_frame) {
451             GST_LOG_OBJECT (ximagesrc,
452                 "Copying from last frame ximage->size: %d",
453                 GST_BUFFER_SIZE (GST_BUFFER (ximage)));
454             memcpy (GST_BUFFER_DATA (GST_BUFFER (ximage)),
455                 GST_BUFFER_DATA (GST_BUFFER (ximagesrc->last_ximage)),
456                 GST_BUFFER_SIZE (GST_BUFFER (ximage)));
457             have_frame = TRUE;
458           }
459           for (i = 0; i < nrects; i++) {
460             GST_LOG_OBJECT (ximagesrc,
461                 "Damaged sub-region @ %d,%d size %dx%d reported",
462                 rects[i].x, rects[i].y, rects[i].width, rects[i].height);
463
464             /* if we only want a small area, clip this damage region to
465              * area we want */
466             if (ximagesrc->endx > ximagesrc->startx &&
467                 ximagesrc->endy > ximagesrc->starty) {
468               /* see if damage area intersects */
469               if (rects[i].x + rects[i].width - 1 < ximagesrc->startx ||
470                   rects[i].x > ximagesrc->endx) {
471                 /* trivial reject */
472               } else if (rects[i].y + rects[i].height - 1 < ximagesrc->starty ||
473                   rects[i].y > ximagesrc->endy) {
474                 /* trivial reject */
475               } else {
476                 /* find intersect region */
477                 int startx, starty, width, height;
478
479                 startx = (rects[i].x < ximagesrc->startx) ? ximagesrc->startx :
480                     rects[i].x;
481                 starty = (rects[i].y < ximagesrc->starty) ? ximagesrc->starty :
482                     rects[i].y;
483                 width = (rects[i].x + rects[i].width - 1 < ximagesrc->endx) ?
484                     rects[i].x + rects[i].width - startx :
485                     ximagesrc->endx - startx + 1;
486                 height = (rects[i].y + rects[i].height - 1 < ximagesrc->endy) ?
487                     rects[i].y + rects[i].height - starty : ximagesrc->endy -
488                     starty + 1;
489
490                 GST_LOG_OBJECT (ximagesrc,
491                     "Retrieving damaged sub-region @ %d,%d size %dx%d as intersect region",
492                     startx, starty, width, height);
493                 XGetSubImage (ximagesrc->xcontext->disp, ximagesrc->xwindow,
494                     startx, starty, width, height, AllPlanes, ZPixmap,
495                     ximage->ximage, startx - ximagesrc->startx,
496                     starty - ximagesrc->starty);
497               }
498             } else {
499
500               GST_LOG_OBJECT (ximagesrc,
501                   "Retrieving damaged sub-region @ %d,%d size %dx%d",
502                   rects[i].x, rects[i].y, rects[i].width, rects[i].height);
503
504               XGetSubImage (ximagesrc->xcontext->disp, ximagesrc->xwindow,
505                   rects[i].x, rects[i].y,
506                   rects[i].width, rects[i].height,
507                   AllPlanes, ZPixmap, ximage->ximage, rects[i].x, rects[i].y);
508             }
509           }
510           free (rects);
511         }
512       }
513     } while (XPending (ximagesrc->xcontext->disp));
514     if (!have_frame) {
515       GST_LOG_OBJECT (ximagesrc,
516           "Copying from last frame ximage->size: %d",
517           GST_BUFFER_SIZE (GST_BUFFER (ximage)));
518       memcpy (GST_BUFFER_DATA (GST_BUFFER (ximage)),
519           GST_BUFFER_DATA (GST_BUFFER (ximagesrc->last_ximage)),
520           GST_BUFFER_SIZE (GST_BUFFER (ximage)));
521     }
522 #ifdef HAVE_XFIXES
523     /* re-get area where last mouse pointer was  but only if in our clipping
524      * bounds */
525     if (ximagesrc->cursor_image) {
526       gint x, y, width, height;
527
528       x = ximagesrc->cursor_image->x - ximagesrc->cursor_image->xhot;
529       y = ximagesrc->cursor_image->y - ximagesrc->cursor_image->yhot;
530       width = ximagesrc->cursor_image->width;
531       height = ximagesrc->cursor_image->height;
532
533       /* bounds checking */
534       if (x < 0)
535         x = 0;
536       if (y < 0)
537         y = 0;
538       if (x + width > ximagesrc->xcontext->width)
539         width = ximagesrc->xcontext->width - x;
540       if (y + height > ximagesrc->xcontext->height)
541         height = ximagesrc->xcontext->height - y;
542       g_assert (x >= 0);
543       g_assert (y >= 0);
544       GST_DEBUG_OBJECT (ximagesrc,
545           "Cursor was at (%d,%d) width: %d, height: %d and our range is: (%d,%d) - (%d,%d)",
546           x, y, width, height, ximagesrc->startx, ximagesrc->starty,
547           ximagesrc->endx, ximagesrc->endy);
548       /* only get where cursor last was, if it is in our range */
549       if (ximagesrc->endx > ximagesrc->startx &&
550           ximagesrc->endy > ximagesrc->starty) {
551         /* check bounds */
552         if (x + width < ximagesrc->startx || x > ximagesrc->endx) {
553           /* trivial reject */
554         } else if (y + height < ximagesrc->starty || y > ximagesrc->endy) {
555           /* trivial reject */
556         } else {
557           /* find intersect region */
558           int startx, starty, iwidth, iheight;
559
560           startx = (x < ximagesrc->startx) ? ximagesrc->startx : x;
561           starty = (y < ximagesrc->starty) ? ximagesrc->starty : y;
562           iwidth = (x + width < ximagesrc->endx) ?
563               x + width - startx : ximagesrc->endx - startx;
564           iheight = (y + height < ximagesrc->endy) ?
565               y + height - starty : ximagesrc->endy - starty;
566           GST_DEBUG_OBJECT (ximagesrc, "Removing cursor from %d,%d", x, y);
567           XGetSubImage (ximagesrc->xcontext->disp, ximagesrc->xwindow,
568               startx, starty, iwidth, iheight, AllPlanes, ZPixmap,
569               ximage->ximage, startx - ximagesrc->startx,
570               starty - ximagesrc->starty);
571         }
572       } else {
573
574         GST_DEBUG_OBJECT (ximagesrc, "Removing cursor from %d,%d", x, y);
575         XGetSubImage (ximagesrc->xcontext->disp, ximagesrc->xwindow,
576             x, y, width, height, AllPlanes, ZPixmap, ximage->ximage, x, y);
577       }
578     }
579 #endif
580
581
582   } else {
583 #endif
584
585 #ifdef HAVE_XSHM
586     if (ximagesrc->xcontext->use_xshm) {
587       GST_DEBUG_OBJECT (ximagesrc, "Retrieving screen using XShm");
588       XShmGetImage (ximagesrc->xcontext->disp, ximagesrc->xwindow,
589           ximage->ximage, ximagesrc->startx, ximagesrc->starty, AllPlanes);
590
591     } else
592 #endif /* HAVE_XSHM */
593     {
594       GST_DEBUG_OBJECT (ximagesrc, "Retrieving screen using XGetImage");
595       if (ximagesrc->remote) {
596         XGetSubImage (ximagesrc->xcontext->disp, ximagesrc->xwindow,
597             ximagesrc->startx, ximagesrc->starty, ximagesrc->width,
598             ximagesrc->height, AllPlanes, ZPixmap, ximage->ximage, 0, 0);
599       } else {
600         ximage->ximage =
601             XGetImage (ximagesrc->xcontext->disp, ximagesrc->xwindow,
602             ximagesrc->startx, ximagesrc->starty, ximagesrc->width,
603             ximagesrc->height, AllPlanes, ZPixmap);
604       }
605     }
606 #ifdef HAVE_XDAMAGE
607   }
608 #endif
609
610 #ifdef HAVE_XFIXES
611   if (ximagesrc->show_pointer && ximagesrc->have_xfixes) {
612
613     GST_DEBUG_OBJECT (ximagesrc, "Using XFixes to draw cursor");
614     /* get cursor */
615     if (ximagesrc->cursor_image)
616       XFree (ximagesrc->cursor_image);
617     ximagesrc->cursor_image = XFixesGetCursorImage (ximagesrc->xcontext->disp);
618     if (ximagesrc->cursor_image != NULL) {
619       int cx, cy, i, j, count;
620       int startx, starty, iwidth, iheight;
621       gboolean cursor_in_image = TRUE;
622
623       cx = ximagesrc->cursor_image->x - ximagesrc->cursor_image->xhot;
624       if (cx < 0)
625         cx = 0;
626       cy = ximagesrc->cursor_image->y - ximagesrc->cursor_image->yhot;
627       if (cy < 0)
628         cy = 0;
629       count = ximagesrc->cursor_image->width * ximagesrc->cursor_image->height;
630
631       /* only get where cursor last was, if it is in our range */
632       if (ximagesrc->endx > ximagesrc->startx &&
633           ximagesrc->endy > ximagesrc->starty) {
634         /* check bounds */
635         if (cx + ximagesrc->cursor_image->width < ximagesrc->startx ||
636             cx > ximagesrc->endx) {
637           /* trivial reject */
638           cursor_in_image = FALSE;
639         } else if (cy + ximagesrc->cursor_image->height < ximagesrc->starty ||
640             cy > ximagesrc->endy) {
641           /* trivial reject */
642           cursor_in_image = FALSE;
643         } else {
644           /* find intersect region */
645
646           startx = (cx < ximagesrc->startx) ? ximagesrc->startx : cx;
647           starty = (cy < ximagesrc->starty) ? ximagesrc->starty : cy;
648           iwidth = (cx + ximagesrc->cursor_image->width < ximagesrc->endx) ?
649               cx + ximagesrc->cursor_image->width - startx :
650               ximagesrc->endx - startx;
651           iheight = (cy + ximagesrc->cursor_image->height < ximagesrc->endy) ?
652               cy + ximagesrc->cursor_image->height - starty :
653               ximagesrc->endy - starty;
654         }
655       } else {
656         startx = cx;
657         starty = cy;
658         iwidth = ximagesrc->cursor_image->width;
659         iheight = ximagesrc->cursor_image->height;
660       }
661
662       if (cursor_in_image) {
663         GST_DEBUG_OBJECT (ximagesrc, "Cursor is in image so trying to draw it");
664         for (i = 0; i < count; i++)
665           ximagesrc->cursor_image->pixels[i] =
666               GUINT_TO_LE (ximagesrc->cursor_image->pixels[i]);
667         /* copy those pixels across */
668         for (j = starty;
669             j < starty + iheight && j < ximagesrc->starty + ximagesrc->height;
670             j++) {
671           for (i = startx;
672               i < startx + iwidth && i < ximagesrc->startx + ximagesrc->width;
673               i++) {
674             guint8 *src, *dest;
675
676             src =
677                 (guint8 *) & (ximagesrc->cursor_image->pixels[((j -
678                             cy) * ximagesrc->cursor_image->width + (i - cx))]);
679             dest =
680                 (guint8 *) & (ximage->ximage->data[((j -
681                             ximagesrc->starty) * ximagesrc->width + (i -
682                             ximagesrc->startx)) * (ximagesrc->xcontext->bpp /
683                         8)]);
684
685             composite_pixel (ximagesrc->xcontext, (guint8 *) dest,
686                 (guint8 *) src);
687           }
688         }
689       }
690     }
691   }
692 #endif
693 #ifdef HAVE_XDAMAGE
694   if (ximagesrc->have_xdamage && ximagesrc->use_damage) {
695     /* need to ref ximage to put in last_ximage */
696     gst_buffer_ref (GST_BUFFER (ximage));
697     if (ximagesrc->last_ximage) {
698       gst_buffer_unref (GST_BUFFER (ximagesrc->last_ximage));
699     }
700     ximagesrc->last_ximage = ximage;
701     GST_LOG_OBJECT (ximagesrc, "reffing current buffer for last_ximage");
702   }
703 #endif
704   return ximage;
705 }
706
707 static GstFlowReturn
708 gst_ximage_src_create (GstPushSrc * bs, GstBuffer ** buf)
709 {
710   GstXImageSrc *s = GST_XIMAGE_SRC (bs);
711   GstXImageSrcBuffer *image;
712   GstClockTime base_time;
713   GstClockTime next_capture_ts;
714   GstClockTime dur;
715   gint64 next_frame_no;
716
717   if (!gst_ximage_src_recalc (s)) {
718     GST_ELEMENT_ERROR (s, RESOURCE, FAILED,
719         (_("Changing resolution at runtime is not yet supported.")), (NULL));
720     return GST_FLOW_ERROR;
721   }
722
723   if (s->fps_n <= 0 || s->fps_d <= 0)
724     return GST_FLOW_NOT_NEGOTIATED;     /* FPS must be > 0 */
725
726   /* Now, we might need to wait for the next multiple of the fps
727    * before capturing */
728
729   GST_OBJECT_LOCK (s);
730   if (GST_ELEMENT_CLOCK (s) == NULL) {
731     GST_OBJECT_UNLOCK (s);
732     GST_ELEMENT_ERROR (s, RESOURCE, FAILED,
733         (_("Cannot operate without a clock")), (NULL));
734     return GST_FLOW_ERROR;
735   }
736
737   base_time = GST_ELEMENT_CAST (s)->base_time;
738   next_capture_ts = gst_clock_get_time (GST_ELEMENT_CLOCK (s));
739   next_capture_ts -= base_time;
740
741   /* Figure out which 'frame number' position we're at, based on the cur time
742    * and frame rate */
743   next_frame_no = gst_util_uint64_scale (next_capture_ts,
744       s->fps_n, GST_SECOND * s->fps_d);
745   if (next_frame_no == s->last_frame_no) {
746     GstClockID id;
747     GstClockReturn ret;
748
749     /* Need to wait for the next frame */
750     next_frame_no += 1;
751
752     /* Figure out what the next frame time is */
753     next_capture_ts = gst_util_uint64_scale (next_frame_no,
754         s->fps_d * GST_SECOND, s->fps_n);
755
756     id = gst_clock_new_single_shot_id (GST_ELEMENT_CLOCK (s),
757         next_capture_ts + base_time);
758     s->clock_id = id;
759
760     /* release the object lock while waiting */
761     GST_OBJECT_UNLOCK (s);
762
763     GST_DEBUG_OBJECT (s, "Waiting for next frame time %" G_GUINT64_FORMAT,
764         next_capture_ts);
765     ret = gst_clock_id_wait (id, NULL);
766     GST_OBJECT_LOCK (s);
767
768     gst_clock_id_unref (id);
769     s->clock_id = NULL;
770     if (ret == GST_CLOCK_UNSCHEDULED) {
771       /* Got woken up by the unlock function */
772       GST_OBJECT_UNLOCK (s);
773       return GST_FLOW_WRONG_STATE;
774     }
775     /* Duration is a complete 1/fps frame duration */
776     dur = gst_util_uint64_scale_int (GST_SECOND, s->fps_d, s->fps_n);
777   } else {
778     GstClockTime next_frame_ts;
779
780     GST_DEBUG_OBJECT (s, "No need to wait for next frame time %"
781         G_GUINT64_FORMAT " next frame = %" G_GINT64_FORMAT " prev = %"
782         G_GINT64_FORMAT, next_capture_ts, next_frame_no, s->last_frame_no);
783     next_frame_ts = gst_util_uint64_scale (next_frame_no + 1,
784         s->fps_d * GST_SECOND, s->fps_n);
785     /* Frame duration is from now until the next expected capture time */
786     dur = next_frame_ts - next_capture_ts;
787   }
788   s->last_frame_no = next_frame_no;
789   GST_OBJECT_UNLOCK (s);
790
791   image = gst_ximage_src_ximage_get (s);
792   if (!image)
793     return GST_FLOW_ERROR;
794
795   *buf = GST_BUFFER (image);
796   GST_BUFFER_TIMESTAMP (*buf) = next_capture_ts;
797   GST_BUFFER_DURATION (*buf) = dur;
798
799   return GST_FLOW_OK;
800 }
801
802 static void
803 gst_ximage_src_set_property (GObject * object, guint prop_id,
804     const GValue * value, GParamSpec * pspec)
805 {
806   GstXImageSrc *src = GST_XIMAGE_SRC (object);
807
808   switch (prop_id) {
809     case PROP_DISPLAY_NAME:
810
811       g_free (src->display_name);
812       src->display_name = g_strdup (g_value_get_string (value));
813       break;
814     case PROP_SCREEN_NUM:
815       src->screen_num = g_value_get_uint (value);
816       break;
817     case PROP_SHOW_POINTER:
818       src->show_pointer = g_value_get_boolean (value);
819       break;
820     case PROP_USE_DAMAGE:
821       src->use_damage = g_value_get_boolean (value);
822       break;
823     case PROP_STARTX:
824       src->startx = g_value_get_uint (value);
825       break;
826     case PROP_STARTY:
827       src->starty = g_value_get_uint (value);
828       break;
829     case PROP_ENDX:
830       src->endx = g_value_get_uint (value);
831       break;
832     case PROP_ENDY:
833       src->endy = g_value_get_uint (value);
834       break;
835     case PROP_REMOTE:
836       src->remote = g_value_get_boolean (value);
837       break;
838     default:
839       break;
840   }
841 }
842
843 static void
844 gst_ximage_src_get_property (GObject * object, guint prop_id, GValue * value,
845     GParamSpec * pspec)
846 {
847   GstXImageSrc *src = GST_XIMAGE_SRC (object);
848
849   switch (prop_id) {
850     case PROP_DISPLAY_NAME:
851       if (src->xcontext)
852         g_value_set_string (value, DisplayString (src->xcontext->disp));
853       else
854         g_value_set_string (value, src->display_name);
855
856       break;
857     case PROP_SCREEN_NUM:
858       g_value_set_uint (value, src->screen_num);
859       break;
860     case PROP_SHOW_POINTER:
861       g_value_set_boolean (value, src->show_pointer);
862       break;
863     case PROP_USE_DAMAGE:
864       g_value_set_boolean (value, src->use_damage);
865       break;
866     case PROP_STARTX:
867       g_value_set_uint (value, src->startx);
868       break;
869     case PROP_STARTY:
870       g_value_set_uint (value, src->starty);
871       break;
872     case PROP_ENDX:
873       g_value_set_uint (value, src->endx);
874       break;
875     case PROP_ENDY:
876       g_value_set_uint (value, src->endy);
877       break;
878     case PROP_REMOTE:
879       g_value_set_boolean (value, src->remote);
880       break;
881     default:
882       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
883       break;
884   }
885 }
886
887 static void
888 gst_ximage_src_clear_bufpool (GstXImageSrc * ximagesrc)
889 {
890   g_mutex_lock (ximagesrc->pool_lock);
891   while (ximagesrc->buffer_pool != NULL) {
892     GstXImageSrcBuffer *ximage = ximagesrc->buffer_pool->data;
893
894     gst_ximage_buffer_free (ximage);
895
896     ximagesrc->buffer_pool = g_slist_delete_link (ximagesrc->buffer_pool,
897         ximagesrc->buffer_pool);
898   }
899   g_mutex_unlock (ximagesrc->pool_lock);
900 }
901
902 static void
903 gst_ximage_src_base_init (gpointer g_class)
904 {
905   GstElementClass *ec = GST_ELEMENT_CLASS (g_class);
906
907   gst_element_class_set_details_simple (ec, "Ximage video source",
908       "Source/Video",
909       "Creates a screenshot video stream",
910       "Lutz Mueller <lutz@users.sourceforge.net>, "
911       "Jan Schmidt <thaytan@mad.scientist.com>, "
912       "Zaheer Merali <zaheerabbas at merali dot org>");
913   gst_element_class_add_pad_template (ec, gst_static_pad_template_get (&t));
914 }
915
916 static void
917 gst_ximage_src_dispose (GObject * object)
918 {
919   /* Drop references in the buffer_pool */
920   gst_ximage_src_clear_bufpool (GST_XIMAGE_SRC (object));
921
922   G_OBJECT_CLASS (parent_class)->dispose (object);
923 }
924
925 static void
926 gst_ximage_src_finalize (GObject * object)
927 {
928   GstXImageSrc *src = GST_XIMAGE_SRC (object);
929
930   if (src->xcontext)
931     ximageutil_xcontext_clear (src->xcontext);
932
933   g_mutex_free (src->pool_lock);
934   g_mutex_free (src->x_lock);
935
936   G_OBJECT_CLASS (parent_class)->finalize (object);
937 }
938
939 static GstCaps *
940 gst_ximage_src_get_caps (GstBaseSrc * bs)
941 {
942   GstXImageSrc *s = GST_XIMAGE_SRC (bs);
943   GstXContext *xcontext;
944   gint width, height;
945
946   if ((!s->xcontext) && (!gst_ximage_src_open_display (s, s->display_name)))
947     return
948         gst_caps_copy (gst_pad_get_pad_template_caps (GST_BASE_SRC
949             (s)->srcpad));
950
951   if (!gst_ximage_src_recalc (s))
952     return
953         gst_caps_copy (gst_pad_get_pad_template_caps (GST_BASE_SRC
954             (s)->srcpad));
955
956   xcontext = s->xcontext;
957
958   width = xcontext->width;
959   height = xcontext->height;
960
961   /* property comments say 0 means right/bottom, means we can't capture
962      the top left pixel alone */
963   if (s->endx == 0)
964     s->endx = width - 1;
965   if (s->endy == 0)
966     s->endy = height - 1;
967
968   if (s->endx >= s->startx && s->endy >= s->starty) {
969     /* this means user has put in values */
970     if (s->startx < xcontext->width && s->endx < xcontext->width &&
971         s->starty < xcontext->height && s->endy < xcontext->height &&
972         s->startx >= 0 && s->starty >= 0) {
973       /* values are fine */
974       s->width = width = s->endx - s->startx + 1;
975       s->height = height = s->endy - s->starty + 1;
976     } else {
977       GST_WARNING
978           ("User put in co-ordinates overshooting the X resolution, setting to full screen");
979       s->startx = 0;
980       s->starty = 0;
981       s->endx = width - 1;
982       s->endy = height - 1;
983     }
984   } else {
985     GST_WARNING ("User put in bogus co-ordinates, setting to full screen");
986     s->startx = 0;
987     s->starty = 0;
988     s->endx = width - 1;
989     s->endy = height - 1;
990   }
991   GST_DEBUG ("width = %d, height=%d", width, height);
992   return gst_caps_new_simple ("video/x-raw-rgb",
993       "bpp", G_TYPE_INT, xcontext->bpp,
994       "depth", G_TYPE_INT, xcontext->depth,
995       "endianness", G_TYPE_INT, xcontext->endianness,
996       "red_mask", G_TYPE_INT, xcontext->r_mask_output,
997       "green_mask", G_TYPE_INT, xcontext->g_mask_output,
998       "blue_mask", G_TYPE_INT, xcontext->b_mask_output,
999       "width", G_TYPE_INT, width,
1000       "height", G_TYPE_INT, height,
1001       "framerate", GST_TYPE_FRACTION_RANGE, 1, G_MAXINT, G_MAXINT, 1,
1002       "pixel-aspect-ratio", GST_TYPE_FRACTION_RANGE, 1, G_MAXINT, G_MAXINT, 1,
1003       NULL);
1004 }
1005
1006 static gboolean
1007 gst_ximage_src_set_caps (GstBaseSrc * bs, GstCaps * caps)
1008 {
1009   GstXImageSrc *s = GST_XIMAGE_SRC (bs);
1010   GstStructure *structure;
1011   const GValue *new_fps;
1012
1013   /* If not yet opened, disallow setcaps until later */
1014   if (!s->xcontext)
1015     return FALSE;
1016
1017   /* The only thing that can change is the framerate downstream wants */
1018   structure = gst_caps_get_structure (caps, 0);
1019   new_fps = gst_structure_get_value (structure, "framerate");
1020   if (!new_fps)
1021     return FALSE;
1022
1023   /* Store this FPS for use when generating buffers */
1024   s->fps_n = gst_value_get_fraction_numerator (new_fps);
1025   s->fps_d = gst_value_get_fraction_denominator (new_fps);
1026
1027   GST_DEBUG_OBJECT (s, "peer wants %d/%d fps", s->fps_n, s->fps_d);
1028
1029   return TRUE;
1030 }
1031
1032 static void
1033 gst_ximage_src_fixate (GstPad * pad, GstCaps * caps)
1034 {
1035   gint i;
1036   GstStructure *structure;
1037
1038   for (i = 0; i < gst_caps_get_size (caps); ++i) {
1039     structure = gst_caps_get_structure (caps, i);
1040
1041     gst_structure_fixate_field_nearest_fraction (structure, "framerate", 25, 1);
1042   }
1043 }
1044
1045 static void
1046 gst_ximage_src_class_init (GstXImageSrcClass * klass)
1047 {
1048   GObjectClass *gc = G_OBJECT_CLASS (klass);
1049   GstBaseSrcClass *bc = GST_BASE_SRC_CLASS (klass);
1050   GstPushSrcClass *push_class = GST_PUSH_SRC_CLASS (klass);
1051
1052   gc->set_property = gst_ximage_src_set_property;
1053   gc->get_property = gst_ximage_src_get_property;
1054   gc->dispose = gst_ximage_src_dispose;
1055   gc->finalize = gst_ximage_src_finalize;
1056
1057   g_object_class_install_property (gc, PROP_DISPLAY_NAME,
1058       g_param_spec_string ("display-name", "Display", "X Display Name", NULL,
1059           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1060   g_object_class_install_property (gc, PROP_SCREEN_NUM,
1061       g_param_spec_uint ("screen-num", "Screen number", "X Screen Number",
1062           0, G_MAXINT, 0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1063   g_object_class_install_property (gc, PROP_SHOW_POINTER,
1064       g_param_spec_boolean ("show-pointer", "Show Mouse Pointer",
1065           "Show mouse pointer (if XFixes extension enabled)", TRUE,
1066           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1067   /**
1068    * GstXImageSrc:use-damage
1069    *
1070    * Use XDamage (if the XDamage extension is enabled)
1071    *
1072    * Since: 0.10.4
1073    **/
1074   g_object_class_install_property (gc, PROP_USE_DAMAGE,
1075       g_param_spec_boolean ("use-damage", "Use XDamage",
1076           "Use XDamage (if XDamage extension enabled)", TRUE,
1077           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1078   /**
1079    * GstXImageSrc:startx
1080    *
1081    * X coordinate of top left corner of area to be recorded
1082    * (0 for top left of screen)
1083    *
1084    * Since: 0.10.4
1085    **/
1086   g_object_class_install_property (gc, PROP_STARTX,
1087       g_param_spec_uint ("startx", "Start X co-ordinate",
1088           "X coordinate of top left corner of area to be recorded (0 for top left of screen)",
1089           0, G_MAXINT, 0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1090   /**
1091    * GstXImageSrc:starty
1092    *
1093    * Y coordinate of top left corner of area to be recorded
1094    * (0 for top left of screen)
1095    *
1096    * Since: 0.10.4
1097    **/
1098   g_object_class_install_property (gc, PROP_STARTY,
1099       g_param_spec_uint ("starty", "Start Y co-ordinate",
1100           "Y coordinate of top left corner of area to be recorded (0 for top left of screen)",
1101           0, G_MAXINT, 0, G_PARAM_READWRITE));
1102   /**
1103    * GstXImageSrc:endx
1104    *
1105    * X coordinate of bottom right corner of area to be recorded
1106    * (0 for bottom right of screen)
1107    *
1108    * Since: 0.10.4
1109    **/
1110   g_object_class_install_property (gc, PROP_ENDX,
1111       g_param_spec_uint ("endx", "End X",
1112           "X coordinate of bottom right corner of area to be recorded (0 for bottom right of screen)",
1113           0, G_MAXINT, 0, G_PARAM_READWRITE));
1114   /**
1115    * GstXImageSrc:endy
1116    *
1117    * Y coordinate of bottom right corner of area to be recorded
1118    * (0 for bottom right of screen)
1119    *
1120    * Since: 0.10.4
1121    **/
1122   g_object_class_install_property (gc, PROP_ENDY,
1123       g_param_spec_uint ("endy", "End Y",
1124           "Y coordinate of bottom right corner of area to be recorded (0 for bottom right of screen)",
1125           0, G_MAXINT, 0, G_PARAM_READWRITE));
1126
1127   /**
1128    * GstXImageSrc:remote
1129    *
1130    * Whether the X display is remote. The element will try to use alternate calls
1131    * known to work better with remote displays.
1132    *
1133    * Since: 0.10.26
1134    **/
1135   g_object_class_install_property (gc, PROP_REMOTE,
1136       g_param_spec_boolean ("remote", "Remote dispay",
1137           "Whether the display is remote", FALSE,
1138           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1139
1140   parent_class = g_type_class_peek_parent (klass);
1141
1142   push_class->create = gst_ximage_src_create;
1143   bc->get_caps = gst_ximage_src_get_caps;
1144   bc->set_caps = gst_ximage_src_set_caps;
1145   bc->start = gst_ximage_src_start;
1146   bc->stop = gst_ximage_src_stop;
1147   bc->unlock = gst_ximage_src_unlock;
1148 }
1149
1150 static void
1151 gst_ximage_src_init (GstXImageSrc * ximagesrc, GstXImageSrcClass * klass)
1152 {
1153   gst_base_src_set_format (GST_BASE_SRC (ximagesrc), GST_FORMAT_TIME);
1154   gst_base_src_set_live (GST_BASE_SRC (ximagesrc), TRUE);
1155   gst_pad_set_fixatecaps_function (GST_BASE_SRC_PAD (ximagesrc),
1156       gst_ximage_src_fixate);
1157
1158   ximagesrc->pool_lock = g_mutex_new ();
1159   ximagesrc->x_lock = g_mutex_new ();
1160   ximagesrc->show_pointer = TRUE;
1161   ximagesrc->use_damage = TRUE;
1162   ximagesrc->startx = 0;
1163   ximagesrc->starty = 0;
1164   ximagesrc->endx = 0;
1165   ximagesrc->endy = 0;
1166   ximagesrc->remote = FALSE;
1167 }
1168
1169 static gboolean
1170 plugin_init (GstPlugin * plugin)
1171 {
1172   gboolean ret;
1173
1174   GST_DEBUG_CATEGORY_INIT (gst_debug_ximage_src, "ximagesrc", 0,
1175       "ximagesrc element debug");
1176
1177   ret = gst_element_register (plugin, "ximagesrc", GST_RANK_NONE,
1178       GST_TYPE_XIMAGE_SRC);
1179
1180   return ret;
1181 }
1182
1183 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
1184     GST_VERSION_MINOR,
1185     "ximagesrc",
1186     "X11 video input plugin using standard Xlib calls",
1187     plugin_init, VERSION, GST_LICENSE, GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN);