summaryrefslogtreecommitdiff
path: root/sys/vdpau/gstvdpsink.c
blob: 933990f8c4d81df80047d6e1e4af0efb1917180b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
/* GStreamer
 * Copyright (C) 2009 Carl-Anton Ingmarsson <ca.ingmarsson@gmail.com>
 * Copyright (C) 2005 Julien Moutte <julien@moutte.net>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

/* Our interfaces */
#include <gst/interfaces/navigation.h>
#include <gst/interfaces/xoverlay.h>

/* Debugging category */
#include <gst/gstinfo.h>

#include "gstvdp/gstvdpoutputbuffer.h"

/* Object header */
#include "gstvdpsink.h"

GST_DEBUG_CATEGORY_STATIC (gst_vdp_sink_debug);
#define GST_CAT_DEFAULT gst_vdp_sink_debug

typedef struct
{
  unsigned long flags;
  unsigned long functions;
  unsigned long decorations;
  long input_mode;
  unsigned long status;
}
MotifWmHints, MwmHints;

#define MWM_HINTS_DECORATIONS   (1L << 1)

static void gst_vdp_sink_expose (GstXOverlay * overlay);

enum
{
  PROP_0,
  PROP_DISPLAY,
  PROP_SYNCHRONOUS,
  PROP_PIXEL_ASPECT_RATIO,
  PROP_HANDLE_EVENTS,
  PROP_HANDLE_EXPOSE
};

static GstVideoSinkClass *parent_class = NULL;

/* the capabilities of the inputs and outputs.
 *
 * describe the real formats here.
 */
static GstStaticPadTemplate sink_template = GST_STATIC_PAD_TEMPLATE ("sink",
    GST_PAD_SINK,
    GST_PAD_ALWAYS,
    GST_STATIC_CAPS (GST_VDP_OUTPUT_CAPS));

#define DEBUG_INIT(bla) \
GST_DEBUG_CATEGORY_INIT (gst_vdp_sink_debug, "vdpausink", 0, "VDPAU video sink");

/* ============================================================= */
/*                                                               */
/*                       Private Methods                         */
/*                                                               */
/* ============================================================= */

/* X11 stuff */

static gboolean
gst_vdp_sink_window_decorate (VdpSink * vdp_sink, GstVdpWindow * window)
{
  Atom hints_atom = None;
  MotifWmHints *hints;

  g_return_val_if_fail (GST_IS_VDP_SINK (vdp_sink), FALSE);
  g_return_val_if_fail (window != NULL, FALSE);

  g_mutex_lock (vdp_sink->x_lock);

  hints_atom = XInternAtom (vdp_sink->device->display, "_MOTIF_WM_HINTS", 1);
  if (hints_atom == None) {
    g_mutex_unlock (vdp_sink->x_lock);
    return FALSE;
  }

  hints = g_malloc0 (sizeof (MotifWmHints));

  hints->flags |= MWM_HINTS_DECORATIONS;
  hints->decorations = 1 << 0;

  XChangeProperty (vdp_sink->device->display, window->win,
      hints_atom, hints_atom, 32, PropModeReplace,
      (guchar *) hints, sizeof (MotifWmHints) / sizeof (long));

  XSync (vdp_sink->device->display, FALSE);

  g_mutex_unlock (vdp_sink->x_lock);

  g_free (hints);

  return TRUE;
}

static void
gst_vdp_sink_window_set_title (VdpSink * vdp_sink,
    GstVdpWindow * window, const gchar * media_title)
{
  if (media_title) {
    g_free (vdp_sink->media_title);
    vdp_sink->media_title = g_strdup (media_title);
  }
  if (window) {
    /* we have a window */
    if (window->internal) {
      XTextProperty xproperty;
      const gchar *app_name;
      const gchar *title = NULL;
      gchar *title_mem = NULL;

      /* set application name as a title */
      app_name = g_get_application_name ();

      if (app_name && vdp_sink->media_title) {
        title = title_mem = g_strconcat (vdp_sink->media_title, " : ",
            app_name, NULL);
      } else if (app_name) {
        title = app_name;
      } else if (vdp_sink->media_title) {
        title = vdp_sink->media_title;
      }

      if (title) {
        if ((XStringListToTextProperty (((char **) &title), 1,
                    &xproperty)) != 0)
          XSetWMName (vdp_sink->device->display, window->win, &xproperty);

        g_free (title_mem);
      }
    }
  }
}

/* This function handles a GstVdpWindow creation */
static GstVdpWindow *
gst_vdp_sink_window_new (VdpSink * vdp_sink, gint width, gint height)
{
  GstVdpWindow *window = NULL;
  GstVdpDevice *device = vdp_sink->device;

  Window root;
  gint screen_num;
  gulong black;

  VdpStatus status;
  VdpColor color = { 0, };

  g_return_val_if_fail (GST_IS_VDP_SINK (vdp_sink), NULL);

  window = g_new0 (GstVdpWindow, 1);

  window->width = width;
  window->height = height;
  window->internal = TRUE;

  g_mutex_lock (vdp_sink->x_lock);

  screen_num = DefaultScreen (device->display);
  root = DefaultRootWindow (device->display);
  black = XBlackPixel (device->display, screen_num);

  window->win = XCreateSimpleWindow (vdp_sink->device->display,
      root, 0, 0, window->width, window->height, 0, 0, black);

  /* We have to do that to prevent X from redrawing the background on 
     ConfigureNotify. This takes away flickering of video when resizing. */
  XSetWindowBackgroundPixmap (vdp_sink->device->display, window->win, None);

  /* set application name as a title */
  gst_vdp_sink_window_set_title (vdp_sink, window, NULL);

  if (vdp_sink->handle_events) {
    Atom wm_delete;

    XSelectInput (vdp_sink->device->display, window->win, ExposureMask |
        StructureNotifyMask | PointerMotionMask | KeyPressMask |
        KeyReleaseMask | ButtonPressMask | ButtonReleaseMask);

    /* Tell the window manager we'd like delete client messages instead of
     * being killed */
    wm_delete =
        XInternAtom (vdp_sink->device->display, "WM_DELETE_WINDOW", False);
    (void) XSetWMProtocols (vdp_sink->device->display, window->win, &wm_delete,
        1);
  }

  XMapRaised (vdp_sink->device->display, window->win);

  XSync (vdp_sink->device->display, FALSE);

  g_mutex_unlock (vdp_sink->x_lock);

  gst_vdp_sink_window_decorate (vdp_sink, window);

  status = device->vdp_presentation_queue_target_create_x11 (device->device,
      window->win, &window->target);
  if (status != VDP_STATUS_OK) {
    GST_ELEMENT_ERROR (vdp_sink, RESOURCE, READ,
        ("Could not create presentation target"),
        ("Error returned from vdpau was: %s",
            device->vdp_get_error_string (status)));
  }

  status =
      device->vdp_presentation_queue_create (device->device, window->target,
      &window->queue);
  if (status != VDP_STATUS_OK) {
    GST_ELEMENT_ERROR (vdp_sink, RESOURCE, READ,
        ("Could not create presentation queue"),
        ("Error returned from vdpau was: %s",
            device->vdp_get_error_string (status)));
  }

  status =
      device->vdp_presentation_queue_set_background_color (window->queue,
      &color);
  if (status != VDP_STATUS_OK) {
    GST_ELEMENT_ERROR (vdp_sink, RESOURCE, READ,
        ("Could not set background color"),
        ("Error returned from vdpau was: %s",
            device->vdp_get_error_string (status)));
  }

  gst_x_overlay_got_xwindow_id (GST_X_OVERLAY (vdp_sink), window->win);

  return window;
}

/* This function destroys a GstVdpWindow */
static void
gst_vdp_sink_window_destroy (VdpSink * vdp_sink, GstVdpWindow * window)
{
  g_return_if_fail (window != NULL);
  g_return_if_fail (GST_IS_VDP_SINK (vdp_sink));

  g_mutex_lock (vdp_sink->x_lock);

  /* If we did not create that window we just free the GC and let it live */
  if (window->internal)
    XDestroyWindow (vdp_sink->device->display, window->win);
  else
    XSelectInput (vdp_sink->device->display, window->win, 0);

  XSync (vdp_sink->device->display, FALSE);

  g_mutex_unlock (vdp_sink->x_lock);

  g_free (window);
}

static void
gst_vdp_sink_window_update_geometry (VdpSink * vdp_sink, GstVdpWindow * window)
{
  XWindowAttributes attr;

  g_return_if_fail (window != NULL);
  g_return_if_fail (GST_IS_VDP_SINK (vdp_sink));

  /* Update the window geometry */
  g_mutex_lock (vdp_sink->x_lock);

  XGetWindowAttributes (vdp_sink->device->display, window->win, &attr);

  window->width = attr.width;
  window->height = attr.height;

  g_mutex_unlock (vdp_sink->x_lock);
}

/* This function handles XEvents that might be in the queue. It generates
   GstEvent that will be sent upstream in the pipeline to handle interactivity
   and navigation.*/
static void
gst_vdp_sink_handle_xevents (VdpSink * vdp_sink)
{
  XEvent e;
  guint pointer_x = 0, pointer_y = 0;
  gboolean pointer_moved = FALSE;
  gboolean exposed = FALSE, configured = FALSE;

  g_return_if_fail (GST_IS_VDP_SINK (vdp_sink));

  /* Then we get all pointer motion events, only the last position is
     interesting. */
  g_mutex_lock (vdp_sink->flow_lock);
  g_mutex_lock (vdp_sink->x_lock);
  while (XCheckWindowEvent (vdp_sink->device->display,
          vdp_sink->window->win, PointerMotionMask, &e)) {
    g_mutex_unlock (vdp_sink->x_lock);
    g_mutex_unlock (vdp_sink->flow_lock);

    switch (e.type) {
      case MotionNotify:
        pointer_x = e.xmotion.x;
        pointer_y = e.xmotion.y;
        pointer_moved = TRUE;
        break;
      default:
        break;
    }
    g_mutex_lock (vdp_sink->flow_lock);
    g_mutex_lock (vdp_sink->x_lock);
  }

  if (pointer_moved) {
    g_mutex_unlock (vdp_sink->x_lock);
    g_mutex_unlock (vdp_sink->flow_lock);

    GST_DEBUG ("vdp_sink pointer moved over window at %d,%d",
        pointer_x, pointer_y);
    gst_navigation_send_mouse_event (GST_NAVIGATION (vdp_sink),
        "mouse-move", 0, pointer_x, pointer_y);

    g_mutex_lock (vdp_sink->flow_lock);
    g_mutex_lock (vdp_sink->x_lock);
  }

  /* We get all remaining events on our window to throw them upstream */
  while (XCheckWindowEvent (vdp_sink->device->display,
          vdp_sink->window->win,
          KeyPressMask | KeyReleaseMask |
          ButtonPressMask | ButtonReleaseMask, &e)) {
    KeySym keysym;

    /* We lock only for the X function call */
    g_mutex_unlock (vdp_sink->x_lock);
    g_mutex_unlock (vdp_sink->flow_lock);

    switch (e.type) {
      case ButtonPress:
        /* Mouse button pressed/released over our window. We send upstream
           events for interactivity/navigation */
        GST_DEBUG ("vdp_sink button %d pressed over window at %d,%d",
            e.xbutton.button, e.xbutton.x, e.xbutton.x);
        gst_navigation_send_mouse_event (GST_NAVIGATION (vdp_sink),
            "mouse-button-press", e.xbutton.button, e.xbutton.x, e.xbutton.y);
        break;
      case ButtonRelease:
        GST_DEBUG ("vdp_sink button %d release over window at %d,%d",
            e.xbutton.button, e.xbutton.x, e.xbutton.x);
        gst_navigation_send_mouse_event (GST_NAVIGATION (vdp_sink),
            "mouse-button-release", e.xbutton.button, e.xbutton.x, e.xbutton.y);
        break;
      case KeyPress:
      case KeyRelease:
        /* Key pressed/released over our window. We send upstream
           events for interactivity/navigation */
        GST_DEBUG ("vdp_sink key %d pressed over window at %d,%d",
            e.xkey.keycode, e.xkey.x, e.xkey.x);
        g_mutex_lock (vdp_sink->x_lock);
        keysym =
            XKeycodeToKeysym (vdp_sink->device->display, e.xkey.keycode, 0);
        g_mutex_unlock (vdp_sink->x_lock);
        if (keysym != NoSymbol) {
          char *key_str = NULL;

          g_mutex_lock (vdp_sink->x_lock);
          key_str = XKeysymToString (keysym);
          g_mutex_unlock (vdp_sink->x_lock);
          gst_navigation_send_key_event (GST_NAVIGATION (vdp_sink),
              e.type == KeyPress ? "key-press" : "key-release", key_str);

        } else {
          gst_navigation_send_key_event (GST_NAVIGATION (vdp_sink),
              e.type == KeyPress ? "key-press" : "key-release", "unknown");
        }
        break;
      default:
        GST_DEBUG_OBJECT (vdp_sink, "vdp_sink unhandled X event (%d)", e.type);
    }
    g_mutex_lock (vdp_sink->flow_lock);
    g_mutex_lock (vdp_sink->x_lock);
  }

  while (XCheckWindowEvent (vdp_sink->device->display,
          vdp_sink->window->win, ExposureMask | StructureNotifyMask, &e)) {
    switch (e.type) {
      case Expose:
        exposed = TRUE;
        break;
      case ConfigureNotify:
        configured = TRUE;
        break;
      default:
        break;
    }
  }

  if (vdp_sink->handle_expose && (exposed || configured)) {
    g_mutex_unlock (vdp_sink->x_lock);
    g_mutex_unlock (vdp_sink->flow_lock);

    gst_vdp_sink_expose (GST_X_OVERLAY (vdp_sink));

    g_mutex_lock (vdp_sink->flow_lock);
    g_mutex_lock (vdp_sink->x_lock);
  }

  /* Handle Display events */
  while (XPending (vdp_sink->device->display)) {
    XNextEvent (vdp_sink->device->display, &e);

    switch (e.type) {
      case ClientMessage:{
        Atom wm_delete;

        wm_delete = XInternAtom (vdp_sink->device->display,
            "WM_DELETE_WINDOW", False);
        if (wm_delete == (Atom) e.xclient.data.l[0]) {
          /* Handle window deletion by posting an error on the bus */
          GST_ELEMENT_ERROR (vdp_sink, RESOURCE, NOT_FOUND,
              ("Output window was closed"), (NULL));

          g_mutex_unlock (vdp_sink->x_lock);
          gst_vdp_sink_window_destroy (vdp_sink, vdp_sink->window);
          vdp_sink->window = NULL;
          g_mutex_lock (vdp_sink->x_lock);
        }
        break;
      }
      default:
        break;
    }
  }

  g_mutex_unlock (vdp_sink->x_lock);
  g_mutex_unlock (vdp_sink->flow_lock);
}

static gpointer
gst_vdp_sink_event_thread (VdpSink * vdp_sink)
{
  g_return_val_if_fail (GST_IS_VDP_SINK (vdp_sink), NULL);

  GST_OBJECT_LOCK (vdp_sink);
  while (vdp_sink->running) {
    GST_OBJECT_UNLOCK (vdp_sink);

    if (vdp_sink->window) {
      gst_vdp_sink_handle_xevents (vdp_sink);
    }
    g_usleep (100000);

    GST_OBJECT_LOCK (vdp_sink);
  }
  GST_OBJECT_UNLOCK (vdp_sink);

  return NULL;
}

/* This function calculates the pixel aspect ratio */
static GValue *
gst_vdp_sink_calculate_par (Display * display)
{
  static const gint par[][2] = {
    {1, 1},                     /* regular screen */
    {16, 15},                   /* PAL TV */
    {11, 10},                   /* 525 line Rec.601 video */
    {54, 59},                   /* 625 line Rec.601 video */
    {64, 45},                   /* 1280x1024 on 16:9 display */
    {5, 3},                     /* 1280x1024 on 4:3 display */
    {4, 3}                      /*  800x600 on 16:9 display */
  };
  gint screen_num;
  gint width, height;
  gint widthmm, heightmm;
  gint i;
  gint index;
  gdouble ratio;
  gdouble delta;
  GValue *par_value;

#define DELTA(idx) (ABS (ratio - ((gdouble) par[idx][0] / par[idx][1])))

  screen_num = DefaultScreen (display);
  width = DisplayWidth (display, screen_num);
  height = DisplayHeight (display, screen_num);
  widthmm = DisplayWidthMM (display, screen_num);
  heightmm = DisplayHeightMM (display, screen_num);

  /* first calculate the "real" ratio based on the X values;
   * which is the "physical" w/h divided by the w/h in pixels of the display */
  ratio = (gdouble) (widthmm * height)
      / (heightmm * width);

  /* DirectFB's X in 720x576 reports the physical dimensions wrong, so
   * override here */
  if (width == 720 && height == 576) {
    ratio = 4.0 * 576 / (3.0 * 720);
  }
  GST_DEBUG ("calculated pixel aspect ratio: %f", ratio);

  /* now find the one from par[][2] with the lowest delta to the real one */
  delta = DELTA (0);
  index = 0;

  for (i = 1; i < sizeof (par) / (sizeof (gint) * 2); ++i) {
    gdouble this_delta = DELTA (i);

    if (this_delta < delta) {
      index = i;
      delta = this_delta;
    }
  }

  GST_DEBUG ("Decided on index %d (%d/%d)", index,
      par[index][0], par[index][1]);

  par_value = g_new0 (GValue, 1);
  g_value_init (par_value, GST_TYPE_FRACTION);
  gst_value_set_fraction (par_value, par[index][0], par[index][1]);
  GST_DEBUG ("set X11 PAR to %d/%d",
      gst_value_get_fraction_numerator (par_value),
      gst_value_get_fraction_denominator (par_value));

  return par_value;
}

static GstCaps *
gst_vdp_sink_get_allowed_caps (GstVdpDevice * device, GValue * par)
{
  GstCaps *templ_caps, *allowed_caps, *caps;
  gint i;

  allowed_caps = gst_vdp_output_buffer_get_allowed_caps (device);
  templ_caps = gst_static_pad_template_get_caps (&sink_template);
  caps = gst_caps_intersect (allowed_caps, templ_caps);

  gst_caps_unref (allowed_caps);
  gst_caps_unref (templ_caps);

  if (!par)
    par = gst_vdp_sink_calculate_par (device->display);

  for (i = 0; i < gst_caps_get_size (caps); i++) {
    GstStructure *structure;

    structure = gst_caps_get_structure (caps, i);
    gst_structure_set_value (structure, "pixel-aspect-ratio", par);
  }

  return caps;
}

static GstVdpDevice *
gst_vdp_sink_setup_device (VdpSink * vdp_sink)
{
  GstVdpDevice *device;

  device = gst_vdp_get_device (vdp_sink->display_name);
  if (!device)
    return NULL;

  vdp_sink->caps = gst_vdp_sink_get_allowed_caps (device, vdp_sink->par);
  GST_DEBUG ("runtime calculated caps: %" GST_PTR_FORMAT, vdp_sink->caps);

  /* call XSynchronize with the current value of synchronous */
  GST_DEBUG_OBJECT (vdp_sink, "XSynchronize called with %s",
      vdp_sink->synchronous ? "TRUE" : "FALSE");
  XSynchronize (device->display, vdp_sink->synchronous);

  /* Setup our event listening thread */
  vdp_sink->running = TRUE;
  vdp_sink->event_thread = g_thread_create (
      (GThreadFunc) gst_vdp_sink_event_thread, vdp_sink, TRUE, NULL);

  return device;
}

static gboolean
gst_vdp_sink_start (GstBaseSink * bsink)
{
  VdpSink *vdp_sink = GST_VDP_SINK (bsink);
  gboolean res = TRUE;

  vdp_sink->window = NULL;
  vdp_sink->cur_image = NULL;

  vdp_sink->event_thread = NULL;

  vdp_sink->fps_n = 0;
  vdp_sink->fps_d = 1;

  GST_OBJECT_LOCK (vdp_sink);
  if (!vdp_sink->device) {
    if (!(vdp_sink->device = gst_vdp_sink_setup_device (vdp_sink)))
      res = FALSE;
  }
  GST_OBJECT_UNLOCK (vdp_sink);

  return res;
}

static void
gst_vdp_device_clear (VdpSink * vdp_sink)
{
  g_return_if_fail (GST_IS_VDP_SINK (vdp_sink));

  GST_OBJECT_LOCK (vdp_sink);
  if (vdp_sink->device == NULL) {
    GST_OBJECT_UNLOCK (vdp_sink);
    return;
  }
  GST_OBJECT_UNLOCK (vdp_sink);

  g_mutex_lock (vdp_sink->x_lock);

  g_object_unref (vdp_sink->device);
  vdp_sink->device = NULL;

  g_mutex_unlock (vdp_sink->x_lock);
}

static gboolean
gst_vdp_sink_stop (GstBaseSink * bsink)
{
  VdpSink *vdp_sink = GST_VDP_SINK (bsink);

  vdp_sink->running = FALSE;
  /* Wait for our event thread to finish before we clean up our stuff. */
  if (vdp_sink->event_thread)
    g_thread_join (vdp_sink->event_thread);

  if (vdp_sink->cur_image) {
    gst_buffer_unref (GST_BUFFER_CAST (vdp_sink->cur_image));
    vdp_sink->cur_image = NULL;
  }

  g_mutex_lock (vdp_sink->flow_lock);
  if (vdp_sink->window) {
    gst_vdp_sink_window_destroy (vdp_sink, vdp_sink->window);
    vdp_sink->window = NULL;
  }
  g_mutex_unlock (vdp_sink->flow_lock);

  gst_vdp_device_clear (vdp_sink);

  return TRUE;
}

/* Element stuff */

static GstCaps *
gst_vdp_sink_getcaps (GstBaseSink * bsink)
{
  VdpSink *vdp_sink;
  GstCaps *caps;

  vdp_sink = GST_VDP_SINK (bsink);

  if (vdp_sink->caps)
    caps = gst_caps_copy (vdp_sink->caps);
  else
    caps = gst_static_pad_template_get_caps (&sink_template);

  return caps;
}

static gboolean
gst_vdp_sink_setcaps (GstBaseSink * bsink, GstCaps * caps)
{
  VdpSink *vdp_sink;
  GstCaps *allowed_caps;
  gboolean ret = TRUE;
  GstStructure *structure;
  GstCaps *intersection;
  gint new_width, new_height;
  const GValue *fps;

  vdp_sink = GST_VDP_SINK (bsink);

  GST_OBJECT_LOCK (vdp_sink);
  if (!vdp_sink->device)
    return FALSE;
  GST_OBJECT_UNLOCK (vdp_sink);

  allowed_caps = gst_pad_get_caps (GST_BASE_SINK_PAD (bsink));
  GST_DEBUG_OBJECT (vdp_sink,
      "sinkconnect possible caps %" GST_PTR_FORMAT " with given caps %"
      GST_PTR_FORMAT, allowed_caps, caps);

  /* We intersect those caps with our template to make sure they are correct */
  intersection = gst_caps_intersect (allowed_caps, caps);
  gst_caps_unref (allowed_caps);

  GST_DEBUG_OBJECT (vdp_sink, "intersection returned %" GST_PTR_FORMAT,
      intersection);
  if (gst_caps_is_empty (intersection)) {
    gst_caps_unref (intersection);
    return FALSE;
  }

  gst_caps_unref (intersection);

  structure = gst_caps_get_structure (caps, 0);

  ret &= gst_structure_get_int (structure, "width", &new_width);
  ret &= gst_structure_get_int (structure, "height", &new_height);
  fps = gst_structure_get_value (structure, "framerate");
  ret &= (fps != NULL);
  if (!ret)
    return FALSE;

  GST_VIDEO_SINK_WIDTH (vdp_sink) = new_width;
  GST_VIDEO_SINK_HEIGHT (vdp_sink) = new_height;
  vdp_sink->fps_n = gst_value_get_fraction_numerator (fps);
  vdp_sink->fps_d = gst_value_get_fraction_denominator (fps);

  /* Notify application to set xwindow id now */
  g_mutex_lock (vdp_sink->flow_lock);
  if (!vdp_sink->window) {
    g_mutex_unlock (vdp_sink->flow_lock);
    gst_x_overlay_prepare_xwindow_id (GST_X_OVERLAY (vdp_sink));
  } else {
    g_mutex_unlock (vdp_sink->flow_lock);
  }

  /* Creating our window and our image */
  if (GST_VIDEO_SINK_WIDTH (vdp_sink) <= 0
      || GST_VIDEO_SINK_HEIGHT (vdp_sink) <= 0) {
    GST_ELEMENT_ERROR (vdp_sink, CORE, NEGOTIATION, (NULL),
        ("Invalid image size."));
    return FALSE;
  }

  g_mutex_lock (vdp_sink->flow_lock);
  if (!vdp_sink->window) {
    vdp_sink->window = gst_vdp_sink_window_new (vdp_sink,
        GST_VIDEO_SINK_WIDTH (vdp_sink), GST_VIDEO_SINK_HEIGHT (vdp_sink));
  }
  g_mutex_unlock (vdp_sink->flow_lock);

  return TRUE;
}

static void
gst_vdp_sink_get_times (GstBaseSink * bsink, GstBuffer * buf,
    GstClockTime * start, GstClockTime * end)
{
  VdpSink *vdp_sink;

  vdp_sink = GST_VDP_SINK (bsink);

  if (GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
    *start = GST_BUFFER_TIMESTAMP (buf);
    if (GST_BUFFER_DURATION_IS_VALID (buf)) {
      *end = *start + GST_BUFFER_DURATION (buf);
    } else {
      if (vdp_sink->fps_n > 0) {
        *end = *start +
            gst_util_uint64_scale_int (GST_SECOND, vdp_sink->fps_d,
            vdp_sink->fps_n);
      }
    }
  }
}

static GstFlowReturn
gst_vdp_sink_show_frame (GstBaseSink * bsink, GstBuffer * outbuf)
{
  VdpSink *vdp_sink = GST_VDP_SINK (bsink);
  VdpStatus status;
  GstVdpDevice *device;

  g_return_val_if_fail (GST_IS_VDP_SINK (vdp_sink), FALSE);

  /* We take the flow_lock. If expose is in there we don't want to run
     concurrently from the data flow thread */
  g_mutex_lock (vdp_sink->flow_lock);

  if (G_UNLIKELY (vdp_sink->window == NULL)) {
    g_mutex_unlock (vdp_sink->flow_lock);
    return GST_FLOW_ERROR;
  }

  device = vdp_sink->device;

  if (vdp_sink->cur_image) {
    VdpOutputSurface surface =
        GST_VDP_OUTPUT_BUFFER (vdp_sink->cur_image)->surface;
    VdpPresentationQueueStatus queue_status;
    VdpTime pres_time;

    g_mutex_lock (vdp_sink->x_lock);
    status =
        device->vdp_presentation_queue_query_surface_status (vdp_sink->
        window->queue, surface, &queue_status, &pres_time);
    g_mutex_unlock (vdp_sink->x_lock);

    if (queue_status == VDP_PRESENTATION_QUEUE_STATUS_QUEUED) {
      g_mutex_unlock (vdp_sink->flow_lock);
      return GST_FLOW_OK;
    }
  }

  /* Expose sends a NULL image, we take the latest frame */
  if (!outbuf) {
    if (vdp_sink->cur_image) {
      outbuf = vdp_sink->cur_image;
    } else {
      g_mutex_unlock (vdp_sink->flow_lock);
      return GST_FLOW_OK;
    }
  }

  gst_vdp_sink_window_update_geometry (vdp_sink, vdp_sink->window);

  g_mutex_lock (vdp_sink->x_lock);

  status = device->vdp_presentation_queue_display (vdp_sink->window->queue,
      GST_VDP_OUTPUT_BUFFER (outbuf)->surface, 0, 0, 0);
  if (status != VDP_STATUS_OK) {
    GST_ELEMENT_ERROR (vdp_sink, RESOURCE, READ,
        ("Could not display frame"),
        ("Error returned from vdpau was: %s",
            device->vdp_get_error_string (status)));

    g_mutex_unlock (vdp_sink->x_lock);
    g_mutex_unlock (vdp_sink->flow_lock);
    return GST_FLOW_ERROR;
  }


  if (!vdp_sink->cur_image)
    vdp_sink->cur_image = gst_buffer_ref (outbuf);

  else if (vdp_sink->cur_image != outbuf) {
    gst_buffer_unref (vdp_sink->cur_image);
    vdp_sink->cur_image = gst_buffer_ref (outbuf);
  }

  XSync (vdp_sink->device->display, FALSE);

  g_mutex_unlock (vdp_sink->x_lock);
  g_mutex_unlock (vdp_sink->flow_lock);

  return GST_FLOW_OK;
}


static gboolean
gst_vdp_sink_event (GstBaseSink * sink, GstEvent * event)
{
  VdpSink *vdp_sink = GST_VDP_SINK (sink);

  switch (GST_EVENT_TYPE (event)) {
    case GST_EVENT_TAG:{
      GstTagList *l;
      gchar *title = NULL;

      gst_event_parse_tag (event, &l);
      gst_tag_list_get_string (l, GST_TAG_TITLE, &title);

      if (title) {
        GST_DEBUG_OBJECT (vdp_sink, "got tags, title='%s'", title);
        gst_vdp_sink_window_set_title (vdp_sink, vdp_sink->window, title);

        g_free (title);
      }
      break;
    }
    default:
      break;
  }
  if (GST_BASE_SINK_CLASS (parent_class)->event)
    return GST_BASE_SINK_CLASS (parent_class)->event (sink, event);
  else
    return TRUE;
}

static GstFlowReturn
gst_vdp_sink_get_output_buffer (VdpSink * vdp_sink, GstCaps * caps,
    GstBuffer ** buf)
{
  GstStructure *structure;
  gint width, height;
  gint rgba_format;

  structure = gst_caps_get_structure (caps, 0);
  if (!gst_structure_get_int (structure, "width", &width) ||
      !gst_structure_get_int (structure, "height", &height) ||
      !gst_structure_get_int (structure, "rgba-format", &rgba_format)) {
    GST_WARNING_OBJECT (vdp_sink, "invalid caps for buffer allocation %"
        GST_PTR_FORMAT, caps);
    return GST_FLOW_ERROR;
  }

  *buf = GST_BUFFER (gst_vdp_output_buffer_new (vdp_sink->device,
          rgba_format, width, height, NULL));
  if (*buf == NULL) {
    return GST_FLOW_ERROR;
  }

  gst_buffer_set_caps (*buf, caps);

  return GST_FLOW_OK;
}

/* Buffer management
 *
 * The buffer_alloc function must either return a buffer with given size and
 * caps or create a buffer with different caps attached to the buffer. This
 * last option is called reverse negotiation, ie, where the sink suggests a
 * different format from the upstream peer. 
 *
 * We try to do reverse negotiation when our geometry changes and we like a
 * resized buffer.
 */
static GstFlowReturn
gst_vdp_sink_buffer_alloc (GstBaseSink * bsink, guint64 offset, guint size,
    GstCaps * caps, GstBuffer ** buf)
{
  VdpSink *vdp_sink;
  GstStructure *structure = NULL;
  GstFlowReturn ret = GST_FLOW_OK;
  GstCaps *alloc_caps;
  gboolean alloc_unref = FALSE;
  gint width, height;
  gint w_width, w_height;

  vdp_sink = GST_VDP_SINK (bsink);

  GST_LOG_OBJECT (vdp_sink,
      "a buffer of %d bytes was requested with caps %" GST_PTR_FORMAT
      " and offset %" G_GUINT64_FORMAT, size, caps, offset);

  /* assume we're going to alloc what was requested, keep track of
   * wheter we need to unref or not. When we suggest a new format 
   * upstream we will create a new caps that we need to unref. */
  alloc_caps = caps;
  alloc_unref = FALSE;

  /* get struct to see what is requested */
  structure = gst_caps_get_structure (caps, 0);
  if (!gst_structure_get_int (structure, "width", &width) ||
      !gst_structure_get_int (structure, "height", &height)) {
    GST_WARNING_OBJECT (vdp_sink, "invalid caps for buffer allocation %"
        GST_PTR_FORMAT, caps);
    ret = GST_FLOW_NOT_NEGOTIATED;
    goto beach;
  }

  /* We take the flow_lock because the window might go away */
  g_mutex_lock (vdp_sink->flow_lock);
  if (!vdp_sink->window) {
    g_mutex_unlock (vdp_sink->flow_lock);
    goto alloc;
  }

  /* What is our geometry */
  gst_vdp_sink_window_update_geometry (vdp_sink, vdp_sink->window);
  w_width = vdp_sink->window->width;
  w_height = vdp_sink->window->height;

  g_mutex_unlock (vdp_sink->flow_lock);

  /* We would like another geometry */
  if (width != w_width || height != w_height) {
    GstCaps *new_caps, *allowed_caps, *desired_caps;
    GstStructure *desired_struct;

    /* make a copy of the incomming caps to create the new
     * suggestion. We can't use make_writable because we might
     * then destroy the original caps which we still need when the
     * peer does not accept the suggestion. */
    new_caps = gst_caps_copy (caps);
    desired_struct = gst_caps_get_structure (new_caps, 0);

    GST_DEBUG ("we would love to receive a %dx%d video", w_width, w_height);
    gst_structure_set (desired_struct, "width", G_TYPE_INT, w_width, NULL);
    gst_structure_set (desired_struct, "height", G_TYPE_INT, w_height, NULL);

    allowed_caps = gst_pad_get_caps (GST_BASE_SINK_PAD (vdp_sink));
    desired_caps = gst_caps_intersect (new_caps, allowed_caps);

    gst_caps_unref (new_caps);
    gst_caps_unref (allowed_caps);

    /* see if peer accepts our new suggestion, if there is no peer, this 
     * function returns true. */
    if (gst_pad_peer_accept_caps (GST_VIDEO_SINK_PAD (vdp_sink), desired_caps)) {
      /* we will not alloc a buffer of the new suggested caps. Make sure
       * we also unref this new caps after we set it on the buffer. */
      alloc_caps = desired_caps;
      alloc_unref = TRUE;
      width = w_width;
      height = w_height;
      GST_DEBUG ("peer pad accepts our desired caps %" GST_PTR_FORMAT,
          desired_caps);
    } else {
      GST_DEBUG ("peer pad does not accept our desired caps %" GST_PTR_FORMAT,
          desired_caps);
      /* we alloc a buffer with the original incomming caps already in the
       * width and height variables */
    }
  }

alloc:
  ret = gst_vdp_sink_get_output_buffer (vdp_sink, alloc_caps, buf);

  /* could be our new reffed suggestion or the original unreffed caps */
  if (alloc_unref)
    gst_caps_unref (alloc_caps);

beach:
  return ret;
}

/* Interfaces stuff */

static gboolean
gst_vdp_sink_interface_supported (GstImplementsInterface * iface, GType type)
{
  g_assert (type == GST_TYPE_NAVIGATION || type == GST_TYPE_X_OVERLAY);
  return TRUE;
}

static void
gst_vdp_sink_interface_init (GstImplementsInterfaceClass * klass)
{
  klass->supported = gst_vdp_sink_interface_supported;
}

static void
gst_vdp_sink_navigation_send_event (GstNavigation * navigation,
    GstStructure * structure)
{
  VdpSink *vdp_sink = GST_VDP_SINK (navigation);
  GstEvent *event;
  gint x_offset, y_offset;
  gdouble x, y;
  GstPad *pad = NULL;

  event = gst_event_new_navigation (structure);

  /* We are not converting the pointer coordinates as there's no hardware
     scaling done here. The only possible scaling is done by videoscale and
     videoscale will have to catch those events and tranform the coordinates
     to match the applied scaling. So here we just add the offset if the image
     is centered in the window.  */

  /* We take the flow_lock while we look at the window */
  g_mutex_lock (vdp_sink->flow_lock);

  if (!vdp_sink->window) {
    g_mutex_unlock (vdp_sink->flow_lock);
    return;
  }

  x_offset = vdp_sink->window->width - GST_VIDEO_SINK_WIDTH (vdp_sink);
  y_offset = vdp_sink->window->height - GST_VIDEO_SINK_HEIGHT (vdp_sink);

  g_mutex_unlock (vdp_sink->flow_lock);

  if (x_offset > 0 && gst_structure_get_double (structure, "pointer_x", &x)) {
    x -= x_offset / 2;
    gst_structure_set (structure, "pointer_x", G_TYPE_DOUBLE, x, NULL);
  }
  if (y_offset > 0 && gst_structure_get_double (structure, "pointer_y", &y)) {
    y -= y_offset / 2;
    gst_structure_set (structure, "pointer_y", G_TYPE_DOUBLE, y, NULL);
  }

  pad = gst_pad_get_peer (GST_VIDEO_SINK_PAD (vdp_sink));

  if (GST_IS_PAD (pad) && GST_IS_EVENT (event)) {
    gst_pad_send_event (pad, event);

    gst_object_unref (pad);
  }
}

static void
gst_vdp_sink_navigation_init (GstNavigationInterface * iface)
{
  iface->send_event = gst_vdp_sink_navigation_send_event;
}

static void
gst_vdp_sink_set_xwindow_id (GstXOverlay * overlay, XID xwindow_id)
{
  VdpSink *vdp_sink = GST_VDP_SINK (overlay);
  GstVdpWindow *window = NULL;
  XWindowAttributes attr;

  /* We acquire the stream lock while setting this window in the element.
     We are basically cleaning tons of stuff replacing the old window, putting
     images while we do that would surely crash */
  g_mutex_lock (vdp_sink->flow_lock);

  /* If we already use that window return */
  if (vdp_sink->window && (xwindow_id == vdp_sink->window->win)) {
    g_mutex_unlock (vdp_sink->flow_lock);
    return;
  }

  /* If the element has not initialized the X11 context try to do so */
  if (!vdp_sink->device
      && !(vdp_sink->device = gst_vdp_sink_setup_device (vdp_sink))) {
    g_mutex_unlock (vdp_sink->flow_lock);
    /* we have thrown a GST_ELEMENT_ERROR now */
    return;
  }

  /* If a window is there already we destroy it */
  if (vdp_sink->window) {
    gst_vdp_sink_window_destroy (vdp_sink, vdp_sink->window);
    vdp_sink->window = NULL;
  }

  /* If the xid is 0 we go back to an internal window */
  if (xwindow_id == 0) {
    /* If no width/height caps nego did not happen window will be created
       during caps nego then */
    if (GST_VIDEO_SINK_WIDTH (vdp_sink) && GST_VIDEO_SINK_HEIGHT (vdp_sink)) {
      window = gst_vdp_sink_window_new (vdp_sink,
          GST_VIDEO_SINK_WIDTH (vdp_sink), GST_VIDEO_SINK_HEIGHT (vdp_sink));
    }
  } else {
    window = g_new0 (GstVdpWindow, 1);

    window->win = xwindow_id;

    /* We get window geometry, set the event we want to receive,
       and create a GC */
    g_mutex_lock (vdp_sink->x_lock);
    XGetWindowAttributes (vdp_sink->device->display, window->win, &attr);
    window->width = attr.width;
    window->height = attr.height;
    window->internal = FALSE;
    if (vdp_sink->handle_events) {
      XSelectInput (vdp_sink->device->display, window->win, ExposureMask |
          StructureNotifyMask | PointerMotionMask | KeyPressMask |
          KeyReleaseMask);
    }

    g_mutex_unlock (vdp_sink->x_lock);
  }

  if (window)
    vdp_sink->window = window;

  g_mutex_unlock (vdp_sink->flow_lock);
}

static void
gst_vdp_sink_expose (GstXOverlay * overlay)
{
  gst_vdp_sink_show_frame (GST_BASE_SINK (overlay), NULL);
}

static void
gst_vdp_sink_set_event_handling (GstXOverlay * overlay, gboolean handle_events)
{
  VdpSink *vdp_sink = GST_VDP_SINK (overlay);

  vdp_sink->handle_events = handle_events;

  g_mutex_lock (vdp_sink->flow_lock);

  if (G_UNLIKELY (!vdp_sink->window)) {
    g_mutex_unlock (vdp_sink->flow_lock);
    return;
  }

  g_mutex_lock (vdp_sink->x_lock);

  if (handle_events) {
    if (vdp_sink->window->internal) {
      XSelectInput (vdp_sink->device->display, vdp_sink->window->win,
          ExposureMask | StructureNotifyMask | PointerMotionMask |
          KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask);
    } else {
      XSelectInput (vdp_sink->device->display, vdp_sink->window->win,
          ExposureMask | StructureNotifyMask | PointerMotionMask |
          KeyPressMask | KeyReleaseMask);
    }
  } else {
    XSelectInput (vdp_sink->device->display, vdp_sink->window->win, 0);
  }

  g_mutex_unlock (vdp_sink->x_lock);

  g_mutex_unlock (vdp_sink->flow_lock);
}

static void
gst_vdp_sink_xoverlay_init (GstXOverlayClass * iface)
{
  iface->set_xwindow_id = gst_vdp_sink_set_xwindow_id;
  iface->expose = gst_vdp_sink_expose;
  iface->handle_events = gst_vdp_sink_set_event_handling;
}

/* =========================================== */
/*                                             */
/*              Init & Class init              */
/*                                             */
/* =========================================== */

static void
gst_vdp_sink_set_property (GObject * object, guint prop_id,
    const GValue * value, GParamSpec * pspec)
{
  VdpSink *vdp_sink;

  g_return_if_fail (GST_IS_VDP_SINK (object));

  vdp_sink = GST_VDP_SINK (object);

  switch (prop_id) {
    case PROP_DISPLAY:
      vdp_sink->display_name = g_strdup (g_value_get_string (value));
      break;
    case PROP_SYNCHRONOUS:
      vdp_sink->synchronous = g_value_get_boolean (value);
      if (vdp_sink->device) {
        GST_DEBUG_OBJECT (vdp_sink, "XSynchronize called with %s",
            vdp_sink->synchronous ? "TRUE" : "FALSE");
        g_mutex_lock (vdp_sink->x_lock);
        XSynchronize (vdp_sink->device->display, vdp_sink->synchronous);
        g_mutex_unlock (vdp_sink->x_lock);
      }
      break;
    case PROP_PIXEL_ASPECT_RATIO:
    {
      GValue *tmp;

      tmp = g_new0 (GValue, 1);
      g_value_init (tmp, GST_TYPE_FRACTION);

      if (!g_value_transform (value, tmp)) {
        GST_WARNING_OBJECT (vdp_sink,
            "Could not transform string to aspect ratio");
        g_free (tmp);
      } else {
        GST_DEBUG_OBJECT (vdp_sink, "set PAR to %d/%d",
            gst_value_get_fraction_numerator (tmp),
            gst_value_get_fraction_denominator (tmp));
        g_free (vdp_sink->par);
        vdp_sink->par = tmp;
      }
    }
      break;
    case PROP_HANDLE_EVENTS:
      gst_vdp_sink_set_event_handling (GST_X_OVERLAY (vdp_sink),
          g_value_get_boolean (value));
      break;
    case PROP_HANDLE_EXPOSE:
      vdp_sink->handle_expose = g_value_get_boolean (value);
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
}

static void
gst_vdp_sink_get_property (GObject * object, guint prop_id,
    GValue * value, GParamSpec * pspec)
{
  VdpSink *vdp_sink;

  g_return_if_fail (GST_IS_VDP_SINK (object));

  vdp_sink = GST_VDP_SINK (object);

  switch (prop_id) {
    case PROP_DISPLAY:
      g_value_set_string (value, vdp_sink->display_name);
      break;
    case PROP_SYNCHRONOUS:
      g_value_set_boolean (value, vdp_sink->synchronous);
      break;
    case PROP_PIXEL_ASPECT_RATIO:
      if (vdp_sink->par)
        g_value_transform (vdp_sink->par, value);
      break;
    case PROP_HANDLE_EVENTS:
      g_value_set_boolean (value, vdp_sink->handle_events);
      break;
    case PROP_HANDLE_EXPOSE:
      g_value_set_boolean (value, vdp_sink->handle_expose);
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
}

static void
gst_vdp_sink_finalize (GObject * object)
{
  VdpSink *vdp_sink;

  vdp_sink = GST_VDP_SINK (object);

  if (vdp_sink->display_name) {
    g_free (vdp_sink->display_name);
    vdp_sink->display_name = NULL;
  }
  if (vdp_sink->par) {
    g_free (vdp_sink->par);
    vdp_sink->par = NULL;
  }
  if (vdp_sink->x_lock) {
    g_mutex_free (vdp_sink->x_lock);
    vdp_sink->x_lock = NULL;
  }
  if (vdp_sink->flow_lock) {
    g_mutex_free (vdp_sink->flow_lock);
    vdp_sink->flow_lock = NULL;
  }

  g_free (vdp_sink->media_title);

  G_OBJECT_CLASS (parent_class)->finalize (object);
}

static void
gst_vdp_sink_init (VdpSink * vdp_sink)
{
  vdp_sink->device = NULL;

  vdp_sink->display_name = NULL;
  vdp_sink->par = NULL;

  vdp_sink->x_lock = g_mutex_new ();
  vdp_sink->flow_lock = g_mutex_new ();

  vdp_sink->synchronous = FALSE;
  vdp_sink->handle_events = TRUE;
  vdp_sink->handle_expose = TRUE;
}

static void
gst_vdp_sink_base_init (gpointer g_class)
{
  GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);

  gst_element_class_set_details_simple (element_class,
      "VDPAU Sink",
      "Sink/Video",
      "VDPAU Sink", "Carl-Anton Ingmarsson <ca.ingmarsson@gmail.com>");

  gst_element_class_add_pad_template (element_class,
      gst_static_pad_template_get (&sink_template));
}

static void
gst_vdp_sink_class_init (VdpSinkClass * klass)
{
  GObjectClass *gobject_class;
  GstElementClass *gstelement_class;
  GstBaseSinkClass *gstbasesink_class;

  gobject_class = (GObjectClass *) klass;
  gstelement_class = (GstElementClass *) klass;
  gstbasesink_class = (GstBaseSinkClass *) klass;

  parent_class = g_type_class_peek_parent (klass);

  gobject_class->finalize = gst_vdp_sink_finalize;
  gobject_class->set_property = gst_vdp_sink_set_property;
  gobject_class->get_property = gst_vdp_sink_get_property;

  g_object_class_install_property (gobject_class, PROP_DISPLAY,
      g_param_spec_string ("display", "Display", "X Display name",
          NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
  g_object_class_install_property (gobject_class, PROP_SYNCHRONOUS,
      g_param_spec_boolean ("synchronous", "Synchronous", "When enabled, runs "
          "the X display in synchronous mode. (used only for debugging)", FALSE,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
  g_object_class_install_property (gobject_class, PROP_PIXEL_ASPECT_RATIO,
      g_param_spec_string ("pixel-aspect-ratio", "Pixel Aspect Ratio",
          "The pixel aspect ratio of the device", "1/1",
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
  g_object_class_install_property (gobject_class, PROP_HANDLE_EVENTS,
      g_param_spec_boolean ("handle-events", "Handle XEvents",
          "When enabled, XEvents will be selected and handled", TRUE,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
  g_object_class_install_property (gobject_class, PROP_HANDLE_EXPOSE,
      g_param_spec_boolean ("handle-expose", "Handle expose",
          "When enabled, "
          "the current frame will always be drawn in response to X Expose "
          "events", TRUE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  gstbasesink_class->start = GST_DEBUG_FUNCPTR (gst_vdp_sink_start);
  gstbasesink_class->stop = GST_DEBUG_FUNCPTR (gst_vdp_sink_stop);
  gstbasesink_class->get_caps = GST_DEBUG_FUNCPTR (gst_vdp_sink_getcaps);
  gstbasesink_class->set_caps = GST_DEBUG_FUNCPTR (gst_vdp_sink_setcaps);
  gstbasesink_class->buffer_alloc =
      GST_DEBUG_FUNCPTR (gst_vdp_sink_buffer_alloc);
  gstbasesink_class->get_times = GST_DEBUG_FUNCPTR (gst_vdp_sink_get_times);
  gstbasesink_class->preroll = GST_DEBUG_FUNCPTR (gst_vdp_sink_show_frame);
  gstbasesink_class->render = GST_DEBUG_FUNCPTR (gst_vdp_sink_show_frame);
  gstbasesink_class->event = GST_DEBUG_FUNCPTR (gst_vdp_sink_event);
}

/* ============================================================= */
/*                                                               */
/*                       Public Methods                          */
/*                                                               */
/* ============================================================= */

/* =========================================== */
/*                                             */
/*          Object typing & Creation           */
/*                                             */
/* =========================================== */

GType
gst_vdp_sink_get_type (void)
{
  static GType vdp_sink_type = 0;

  if (!vdp_sink_type) {
    static const GTypeInfo vdp_sink_info = {
      sizeof (VdpSinkClass),
      gst_vdp_sink_base_init,
      NULL,
      (GClassInitFunc) gst_vdp_sink_class_init,
      NULL,
      NULL,
      sizeof (VdpSink),
      0,
      (GInstanceInitFunc) gst_vdp_sink_init,
    };
    static const GInterfaceInfo iface_info = {
      (GInterfaceInitFunc) gst_vdp_sink_interface_init,
      NULL,
      NULL,
    };
    static const GInterfaceInfo navigation_info = {
      (GInterfaceInitFunc) gst_vdp_sink_navigation_init,
      NULL,
      NULL,
    };
    static const GInterfaceInfo overlay_info = {
      (GInterfaceInitFunc) gst_vdp_sink_xoverlay_init,
      NULL,
      NULL,
    };

    vdp_sink_type = g_type_register_static (GST_TYPE_VIDEO_SINK,
        "VdpSink", &vdp_sink_info, 0);

    g_type_add_interface_static (vdp_sink_type, GST_TYPE_IMPLEMENTS_INTERFACE,
        &iface_info);
    g_type_add_interface_static (vdp_sink_type, GST_TYPE_NAVIGATION,
        &navigation_info);
    g_type_add_interface_static (vdp_sink_type, GST_TYPE_X_OVERLAY,
        &overlay_info);
  }

  DEBUG_INIT ();

  return vdp_sink_type;
}