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