summaryrefslogtreecommitdiff
path: root/sys/xvimage/xvimagesink.c
blob: 51f145d59e06bc259c5c7473846fabc490a85652 (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
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
/* GStreamer
 * Copyright (C) <2005> Julien Moutte <julien@moutte.net>
 *               <2009>,<2010> Stefan Kost <stefan.kost@nokia.com>
 * Copyright (C) 2012, 2013 Samsung Electronics Co., Ltd.
 *
 * 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.
 *
 * * Modifications by Samsung Electronics Co., Ltd.
 * 1. Add display related properties
 * 2. Support samsung extension format to improve performance
 * 3. Support video texture overlay of OSP layer
 */

/**
 * SECTION:element-xvimagesink
 *
 * XvImageSink renders video frames to a drawable (XWindow) on a local display
 * using the XVideo extension. Rendering to a remote display is theoretically
 * possible but i doubt that the XVideo extension is actually available when
 * connecting to a remote display. This element can receive a Window ID from the
 * application through the XOverlay interface and will then render video frames
 * in this drawable. If no Window ID was provided by the application, the
 * element will create its own internal window and render into it.
 *
 * <refsect2>
 * <title>Scaling</title>
 * <para>
 * The XVideo extension, when it's available, handles hardware accelerated
 * scaling of video frames. This means that the element will just accept
 * incoming video frames no matter their geometry and will then put them to the
 * drawable scaling them on the fly. Using the #GstXvImageSink:force-aspect-ratio
 * property it is possible to enforce scaling with a constant aspect ratio,
 * which means drawing black borders around the video frame.
 * </para>
 * </refsect2>
 * <refsect2>
 * <title>Events</title>
 * <para>
 * XvImageSink creates a thread to handle events coming from the drawable. There
 * are several kind of events that can be grouped in 2 big categories: input
 * events and window state related events. Input events will be translated to
 * navigation events and pushed upstream for other elements to react on them.
 * This includes events such as pointer moves, key press/release, clicks etc...
 * Other events are used to handle the drawable appearance even when the data
 * is not flowing (GST_STATE_PAUSED). That means that even when the element is
 * paused, it will receive expose events from the drawable and draw the latest
 * frame with correct borders/aspect-ratio.
 * </para>
 * </refsect2>
 * <refsect2>
 * <title>Pixel aspect ratio</title>
 * <para>
 * When changing state to GST_STATE_READY, XvImageSink will open a connection to
 * the display specified in the #GstXvImageSink:display property or the
 * default display if nothing specified. Once this connection is open it will
 * inspect the display configuration including the physical display geometry and
 * then calculate the pixel aspect ratio. When receiving video frames with a
 * different pixel aspect ratio, XvImageSink will use hardware scaling to
 * display the video frames correctly on display's pixel aspect ratio.
 * Sometimes the calculated pixel aspect ratio can be wrong, it is
 * then possible to enforce a specific pixel aspect ratio using the
 * #GstXvImageSink:pixel-aspect-ratio property.
 * </para>
 * </refsect2>
 * <refsect2>
 * <title>Examples</title>
 * |[
 * gst-launch -v videotestsrc ! xvimagesink
 * ]| A pipeline to test hardware scaling.
 * When the test video signal appears you can resize the window and see that
 * video frames are scaled through hardware (no extra CPU cost).
 * |[
 * gst-launch -v videotestsrc ! xvimagesink force-aspect-ratio=true
 * ]| Same pipeline with #GstXvImageSink:force-aspect-ratio property set to true
 * You can observe the borders drawn around the scaled image respecting aspect
 * ratio.
 * |[
 * gst-launch -v videotestsrc ! navigationtest ! xvimagesink
 * ]| A pipeline to test navigation events.
 * While moving the mouse pointer over the test signal you will see a black box
 * following the mouse pointer. If you press the mouse button somewhere on the
 * video and release it somewhere else a green box will appear where you pressed
 * the button and a red one where you released it. (The navigationtest element
 * is part of gst-plugins-good.) You can observe here that even if the images
 * are scaled through hardware the pointer coordinates are converted back to the
 * original video frame geometry so that the box can be drawn to the correct
 * position. This also handles borders correctly, limiting coordinates to the
 * image area
 * |[
 * gst-launch -v videotestsrc ! video/x-raw-yuv, pixel-aspect-ratio=(fraction)4/3 ! xvimagesink
 * ]| This is faking a 4/3 pixel aspect ratio caps on video frames produced by
 * videotestsrc, in most cases the pixel aspect ratio of the display will be
 * 1/1. This means that XvImageSink will have to do the scaling to convert
 * incoming frames to a size that will match the display pixel aspect ratio
 * (from 320x240 to 320x180 in this case). Note that you might have to escape
 * some characters for your shell like '\(fraction\)'.
 * |[
 * gst-launch -v videotestsrc ! xvimagesink hue=100 saturation=-100 brightness=100
 * ]| Demonstrates how to use the colorbalance interface.
 * </refsect2>
 */

/* for developers: there are two useful tools : xvinfo and xvattr */

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

/* Our interfaces */
#include <gst/interfaces/navigation.h>
#include <gst/interfaces/xoverlay.h>
#include <gst/interfaces/colorbalance.h>
#include <gst/interfaces/propertyprobe.h>
/* Helper functions */
#include <gst/video/video.h>

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

#ifdef GST_EXT_XV_ENHANCEMENT
/* Samsung extension headers */
/* For xv extension header for buffer transfer (output) */
#include "xv_types.h"

/* headers for drm */
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <unistd.h>
#include <xf86drm.h>
#include <xf86drmMode.h>
#include <X11/Xmd.h>
#include <dri2/dri2.h>

typedef enum {
	BUF_SHARE_METHOD_PADDR = 0,
	BUF_SHARE_METHOD_FD
} buf_share_method_t;

/* max channel count *********************************************************/
#define SCMN_IMGB_MAX_PLANE         (4)

/* image buffer definition ***************************************************

    +------------------------------------------+ ---
    |                                          |  ^
    |     a[], p[]                             |  |
    |     +---------------------------+ ---    |  |
    |     |                           |  ^     |  |
    |     |<---------- w[] ---------->|  |     |  |
    |     |                           |  |     |  |
    |     |                           |        |
    |     |                           |  h[]   |  e[]
    |     |                           |        |
    |     |                           |  |     |  |
    |     |                           |  |     |  |
    |     |                           |  v     |  |
    |     +---------------------------+ ---    |  |
    |                                          |  v
    +------------------------------------------+ ---

    |<----------------- s[] ------------------>|
*/

typedef struct
{
	/* width of each image plane */
	int      w[SCMN_IMGB_MAX_PLANE];
	/* height of each image plane */
	int      h[SCMN_IMGB_MAX_PLANE];
	/* stride of each image plane */
	int      s[SCMN_IMGB_MAX_PLANE];
	/* elevation of each image plane */
	int      e[SCMN_IMGB_MAX_PLANE];
	/* user space address of each image plane */
	void   * a[SCMN_IMGB_MAX_PLANE];
	/* physical address of each image plane, if needs */
	void   * p[SCMN_IMGB_MAX_PLANE];
	/* color space type of image */
	int      cs;
	/* left postion, if needs */
	int      x;
	/* top position, if needs */
	int      y;
	/* to align memory */
	int      __dummy2;
	/* arbitrary data */
	int      data[16];
	/* dma buf fd */
	int dmabuf_fd[SCMN_IMGB_MAX_PLANE];
	/* buffer share method */
	int buf_share_method;
} SCMN_IMGB;
#endif /* GST_EXT_XV_ENHANCEMENT */

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

#include "gst/glib-compat-private.h"

GST_DEBUG_CATEGORY_STATIC (gst_debug_xvimagesink);
#define GST_CAT_DEFAULT gst_debug_xvimagesink
GST_DEBUG_CATEGORY_STATIC (GST_CAT_PERFORMANCE);

#ifdef GST_EXT_XV_ENHANCEMENT
#define GST_TYPE_XVIMAGESINK_DISPLAY_MODE (gst_xvimagesink_display_mode_get_type())

static GType
gst_xvimagesink_display_mode_get_type(void)
{
	static GType xvimagesink_display_mode_type = 0;
	static const GEnumValue display_mode_type[] = {
		{ 0, "Default mode", "DEFAULT"},
		{ 1, "Primary video ON and Secondary video FULL SCREEN mode", "PRI_VIDEO_ON_AND_SEC_VIDEO_FULL_SCREEN"},
		{ 2, "Primary video OFF and Secondary video FULL SCREEN mode", "PRI_VIDEO_OFF_AND_SEC_VIDEO_FULL_SCREEN"},
		{ 3, NULL, NULL},
	};

	if (!xvimagesink_display_mode_type) {
		xvimagesink_display_mode_type = g_enum_register_static("GstXVImageSinkDisplayModeType", display_mode_type);
	}

	return xvimagesink_display_mode_type;
}

enum {
    DEGREE_0,
    DEGREE_90,
    DEGREE_180,
    DEGREE_270,
    DEGREE_NUM,
};

#define GST_TYPE_XVIMAGESINK_ROTATE_ANGLE (gst_xvimagesink_rotate_angle_get_type())

static GType
gst_xvimagesink_rotate_angle_get_type(void)
{
	static GType xvimagesink_rotate_angle_type = 0;
	static const GEnumValue rotate_angle_type[] = {
		{ 0, "No rotate", "DEGREE_0"},
		{ 1, "Rotate 90 degree", "DEGREE_90"},
		{ 2, "Rotate 180 degree", "DEGREE_180"},
		{ 3, "Rotate 270 degree", "DEGREE_270"},
		{ 4, NULL, NULL},
	};

	if (!xvimagesink_rotate_angle_type) {
		xvimagesink_rotate_angle_type = g_enum_register_static("GstXVImageSinkRotateAngleType", rotate_angle_type);
	}

	return xvimagesink_rotate_angle_type;
}

enum {
    DISP_GEO_METHOD_LETTER_BOX = 0,
    DISP_GEO_METHOD_ORIGIN_SIZE,
    DISP_GEO_METHOD_FULL_SCREEN,
    DISP_GEO_METHOD_CROPPED_FULL_SCREEN,
    DISP_GEO_METHOD_ORIGIN_SIZE_OR_LETTER_BOX,
    DISP_GEO_METHOD_CUSTOM_ROI,
    DISP_GEO_METHOD_NUM,
};
#define DEF_DISPLAY_GEOMETRY_METHOD DISP_GEO_METHOD_LETTER_BOX

enum {
    FLIP_NONE = 0,
    FLIP_HORIZONTAL,
    FLIP_VERTICAL,
    FLIP_BOTH,
    FLIP_NUM,
};
#define DEF_DISPLAY_FLIP            FLIP_NONE

#define GST_TYPE_XVIMAGESINK_DISPLAY_GEOMETRY_METHOD (gst_xvimagesink_display_geometry_method_get_type())
#define GST_TYPE_XVIMAGESINK_FLIP                    (gst_xvimagesink_flip_get_type())

static GType
gst_xvimagesink_display_geometry_method_get_type(void)
{
	static GType xvimagesink_display_geometry_method_type = 0;
	static const GEnumValue display_geometry_method_type[] = {
		{ 0, "Letter box", "LETTER_BOX"},
		{ 1, "Origin size", "ORIGIN_SIZE"},
		{ 2, "Full-screen", "FULL_SCREEN"},
		{ 3, "Cropped full-screen", "CROPPED_FULL_SCREEN"},
		{ 4, "Origin size(if screen size is larger than video size(width/height)) or Letter box(if video size(width/height) is larger than screen size)", "ORIGIN_SIZE_OR_LETTER_BOX"},
		{ 5, "Explicitly described destination ROI", "CUSTOM_ROI"},
		{ 6, NULL, NULL},
	};

	if (!xvimagesink_display_geometry_method_type) {
		xvimagesink_display_geometry_method_type = g_enum_register_static("GstXVImageSinkDisplayGeometryMethodType", display_geometry_method_type);
	}

	return xvimagesink_display_geometry_method_type;
}

static GType
gst_xvimagesink_flip_get_type(void)
{
	static GType xvimagesink_flip_type = 0;
	static const GEnumValue flip_type[] = {
		{ FLIP_NONE,       "Flip NONE", "FLIP_NONE"},
		{ FLIP_HORIZONTAL, "Flip HORIZONTAL", "FLIP_HORIZONTAL"},
		{ FLIP_VERTICAL,   "Flip VERTICAL", "FLIP_VERTICAL"},
		{ FLIP_BOTH,       "Flip BOTH", "FLIP_BOTH"},
		{ FLIP_NUM, NULL, NULL},
	};

	if (!xvimagesink_flip_type) {
		xvimagesink_flip_type = g_enum_register_static("GstXVImageSinkFlipType", flip_type);
	}

	return xvimagesink_flip_type;
}

#define g_marshal_value_peek_pointer(v)  (v)->data[0].v_pointer
void
gst_xvimagesink_BOOLEAN__POINTER (GClosure         *closure,
                                     GValue         *return_value G_GNUC_UNUSED,
                                     guint          n_param_values,
                                     const GValue   *param_values,
                                     gpointer       invocation_hint G_GNUC_UNUSED,
                                     gpointer       marshal_data)
{
  typedef gboolean (*GMarshalFunc_BOOLEAN__POINTER) (gpointer     data1,
                                                     gpointer     arg_1,
                                                     gpointer     data2);
  register GMarshalFunc_BOOLEAN__POINTER callback;
  register GCClosure *cc = (GCClosure*) closure;
  register gpointer data1, data2;

  gboolean v_return;

  g_return_if_fail (return_value != NULL);
  g_return_if_fail (n_param_values == 2);

  if (G_CCLOSURE_SWAP_DATA (closure)) {
    data1 = closure->data;
    data2 = g_value_peek_pointer (param_values + 0);
  } else {
    data1 = g_value_peek_pointer (param_values + 0);
    data2 = closure->data;
  }
  callback = (GMarshalFunc_BOOLEAN__POINTER) (marshal_data ? marshal_data : cc->callback);

  v_return = callback (data1,
                      g_marshal_value_peek_pointer (param_values + 1),
                      data2);

  g_value_set_boolean (return_value, v_return);
}

enum
{
    SIGNAL_FRAME_RENDER_ERROR,
    LAST_SIGNAL
};
static guint gst_xvimagesink_signals[LAST_SIGNAL] = { 0 };

#endif /* GST_EXT_XV_ENHANCEMENT */

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_xvimagesink_reset (GstXvImageSink * xvimagesink);

static GstBufferClass *xvimage_buffer_parent_class = NULL;
static void gst_xvimage_buffer_finalize (GstXvImageBuffer * xvimage);

static void gst_xvimagesink_xwindow_update_geometry (GstXvImageSink *
    xvimagesink);
static gint gst_xvimagesink_get_format_from_caps (GstXvImageSink * xvimagesink,
    GstCaps * caps);
static void gst_xvimagesink_expose (GstXOverlay * overlay);

#ifdef GST_EXT_XV_ENHANCEMENT
static XImage *make_transparent_image(Display *d, Window win, int w, int h);
static gboolean set_display_mode(GstXContext *xcontext, int set_mode);
static void drm_close_gem(GstXvImageSink *xvimagesink, unsigned int *gem_handle);
static void gst_xvimagesink_set_pixmap_handle (GstXOverlay * overlay, guintptr id);
#endif /* GST_EXT_XV_ENHANCEMENT */

/* Default template - initiated with class struct to allow gst-register to work
   without X running */
static GstStaticPadTemplate gst_xvimagesink_sink_template_factory =
    GST_STATIC_PAD_TEMPLATE ("sink",
    GST_PAD_SINK,
    GST_PAD_ALWAYS,
    GST_STATIC_CAPS ("video/x-raw-rgb, "
        "framerate = (fraction) [ 0, MAX ], "
        "width = (int) [ 1, MAX ], "
        "height = (int) [ 1, MAX ]; "
        "video/x-raw-yuv, "
        "framerate = (fraction) [ 0, MAX ], "
        "width = (int) [ 1, MAX ], " "height = (int) [ 1, MAX ]")
    );

enum
{
  PROP_0,
  PROP_CONTRAST,
  PROP_BRIGHTNESS,
  PROP_HUE,
  PROP_SATURATION,
  PROP_DISPLAY,
  PROP_SYNCHRONOUS,
  PROP_PIXEL_ASPECT_RATIO,
  PROP_FORCE_ASPECT_RATIO,
  PROP_HANDLE_EVENTS,
  PROP_DEVICE,
  PROP_DEVICE_NAME,
  PROP_HANDLE_EXPOSE,
  PROP_DOUBLE_BUFFER,
  PROP_AUTOPAINT_COLORKEY,
  PROP_COLORKEY,
  PROP_DRAW_BORDERS,
  PROP_WINDOW_WIDTH,
  PROP_WINDOW_HEIGHT,
#ifdef GST_EXT_XV_ENHANCEMENT
  PROP_DISPLAY_MODE,
  PROP_ROTATE_ANGLE,
  PROP_FLIP,
  PROP_DISPLAY_GEOMETRY_METHOD,
  PROP_VISIBLE,
  PROP_ZOOM,
  PROP_DST_ROI_X,
  PROP_DST_ROI_Y,
  PROP_DST_ROI_W,
  PROP_DST_ROI_H,
  PROP_STOP_VIDEO,
  PROP_PIXMAP_CB,
  PROP_PIXMAP_CB_USER_DATA,
#endif /* GST_EXT_XV_ENHANCEMENT */
};

static void gst_xvimagesink_init_interfaces (GType type);

GST_BOILERPLATE_FULL (GstXvImageSink, gst_xvimagesink, GstVideoSink,
    GST_TYPE_VIDEO_SINK, gst_xvimagesink_init_interfaces);


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

/* xvimage buffers */

#define GST_TYPE_XVIMAGE_BUFFER (gst_xvimage_buffer_get_type())

#define GST_IS_XVIMAGE_BUFFER(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), GST_TYPE_XVIMAGE_BUFFER))
#define GST_XVIMAGE_BUFFER(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), GST_TYPE_XVIMAGE_BUFFER, GstXvImageBuffer))
#define GST_XVIMAGE_BUFFER_CAST(obj) ((GstXvImageBuffer *)(obj))

/* This function destroys a GstXvImage handling XShm availability */
static void
gst_xvimage_buffer_destroy (GstXvImageBuffer * xvimage)
{
  GstXvImageSink *xvimagesink;

  GST_DEBUG_OBJECT (xvimage, "Destroying buffer");

  xvimagesink = xvimage->xvimagesink;
  if (G_UNLIKELY (xvimagesink == NULL))
    goto no_sink;

  g_return_if_fail (GST_IS_XVIMAGESINK (xvimagesink));

  GST_OBJECT_LOCK (xvimagesink);

  /* If the destroyed image is the current one we destroy our reference too */
  if (xvimagesink->cur_image == xvimage)
    xvimagesink->cur_image = NULL;

  /* We might have some buffers destroyed after changing state to NULL */
  if (xvimagesink->xcontext == NULL) {
    GST_DEBUG_OBJECT (xvimagesink, "Destroying XvImage after Xcontext");
#ifdef HAVE_XSHM
    /* Need to free the shared memory segment even if the x context
     * was already cleaned up */
    if (xvimage->SHMInfo.shmaddr != ((void *) -1)) {
      shmdt (xvimage->SHMInfo.shmaddr);
    }
#endif
    goto beach;
  }

  g_mutex_lock (xvimagesink->x_lock);

#ifdef HAVE_XSHM
  if (xvimagesink->xcontext->use_xshm) {
    if (xvimage->SHMInfo.shmaddr != ((void *) -1)) {
      GST_DEBUG_OBJECT (xvimagesink, "XServer ShmDetaching from 0x%x id 0x%lx",
          xvimage->SHMInfo.shmid, xvimage->SHMInfo.shmseg);
      XShmDetach (xvimagesink->xcontext->disp, &xvimage->SHMInfo);
      XSync (xvimagesink->xcontext->disp, FALSE);

      shmdt (xvimage->SHMInfo.shmaddr);
    }
    if (xvimage->xvimage)
      XFree (xvimage->xvimage);
  } else
#endif /* HAVE_XSHM */
  {
    if (xvimage->xvimage) {
      if (xvimage->xvimage->data) {
        g_free (xvimage->xvimage->data);
      }
      XFree (xvimage->xvimage);
    }
  }

  XSync (xvimagesink->xcontext->disp, FALSE);

  g_mutex_unlock (xvimagesink->x_lock);

beach:
  GST_OBJECT_UNLOCK (xvimagesink);
  xvimage->xvimagesink = NULL;
  gst_object_unref (xvimagesink);

  GST_MINI_OBJECT_CLASS (xvimage_buffer_parent_class)->finalize (GST_MINI_OBJECT
      (xvimage));

  return;

no_sink:
  {
    GST_WARNING ("no sink found");
    return;
  }
}

static void
gst_xvimage_buffer_finalize (GstXvImageBuffer * xvimage)
{
  GstXvImageSink *xvimagesink;
  gboolean running;

  xvimagesink = xvimage->xvimagesink;
  if (G_UNLIKELY (xvimagesink == NULL))
    goto no_sink;

  g_return_if_fail (GST_IS_XVIMAGESINK (xvimagesink));

  GST_OBJECT_LOCK (xvimagesink);
  running = xvimagesink->running;
  GST_OBJECT_UNLOCK (xvimagesink);

  /* If our geometry changed we can't reuse that image. */
  if (running == FALSE) {
    GST_LOG_OBJECT (xvimage, "destroy image as sink is shutting down");
    gst_xvimage_buffer_destroy (xvimage);
  } else if ((xvimage->width != xvimagesink->video_width) ||
      (xvimage->height != xvimagesink->video_height)) {
    GST_LOG_OBJECT (xvimage,
        "destroy image as its size changed %dx%d vs current %dx%d",
        xvimage->width, xvimage->height,
        xvimagesink->video_width, xvimagesink->video_height);
    gst_xvimage_buffer_destroy (xvimage);
  } else {
    /* In that case we can reuse the image and add it to our image pool. */
    GST_LOG_OBJECT (xvimage, "recycling image in pool");
    /* need to increment the refcount again to recycle */
    gst_buffer_ref (GST_BUFFER_CAST (xvimage));
    g_mutex_lock (xvimagesink->pool_lock);
    xvimagesink->image_pool = g_slist_prepend (xvimagesink->image_pool,
        xvimage);
    g_mutex_unlock (xvimagesink->pool_lock);
  }
  return;

no_sink:
  {
    GST_WARNING ("no sink found");
    return;
  }
}

static void
gst_xvimage_buffer_free (GstXvImageBuffer * xvimage)
{
  /* make sure it is not recycled */
  xvimage->width = -1;
  xvimage->height = -1;
  gst_buffer_unref (GST_BUFFER (xvimage));
}

static void
gst_xvimage_buffer_init (GstXvImageBuffer * xvimage, gpointer g_class)
{
#ifdef HAVE_XSHM
  xvimage->SHMInfo.shmaddr = ((void *) -1);
  xvimage->SHMInfo.shmid = -1;
#endif
}

static void
gst_xvimage_buffer_class_init (gpointer g_class, gpointer class_data)
{
  GstMiniObjectClass *mini_object_class = GST_MINI_OBJECT_CLASS (g_class);

  xvimage_buffer_parent_class = g_type_class_peek_parent (g_class);

  mini_object_class->finalize = (GstMiniObjectFinalizeFunction)
      gst_xvimage_buffer_finalize;
}

static GType
gst_xvimage_buffer_get_type (void)
{
  static GType _gst_xvimage_buffer_type;

  if (G_UNLIKELY (_gst_xvimage_buffer_type == 0)) {
    static const GTypeInfo xvimage_buffer_info = {
      sizeof (GstBufferClass),
      NULL,
      NULL,
      gst_xvimage_buffer_class_init,
      NULL,
      NULL,
      sizeof (GstXvImageBuffer),
      0,
      (GInstanceInitFunc) gst_xvimage_buffer_init,
      NULL
    };
    _gst_xvimage_buffer_type = g_type_register_static (GST_TYPE_BUFFER,
        "GstXvImageBuffer", &xvimage_buffer_info, 0);
  }
  return _gst_xvimage_buffer_type;
}

/* X11 stuff */

static gboolean error_caught = FALSE;

static int
gst_xvimagesink_handle_xerror (Display * display, XErrorEvent * xevent)
{
  char error_msg[1024];

  XGetErrorText (display, xevent->error_code, error_msg, 1024);
  GST_DEBUG ("xvimagesink triggered an XError. error: %s", error_msg);
  error_caught = TRUE;
  return 0;
}

#ifdef HAVE_XSHM
/* This function checks that it is actually really possible to create an image
   using XShm */
static gboolean
gst_xvimagesink_check_xshm_calls (GstXContext * xcontext)
{
  XvImage *xvimage;
  XShmSegmentInfo SHMInfo;
  gint size;
  int (*handler) (Display *, XErrorEvent *);
  gboolean result = FALSE;
  gboolean did_attach = FALSE;

  g_return_val_if_fail (xcontext != NULL, FALSE);

  /* Sync to ensure any older errors are already processed */
  XSync (xcontext->disp, FALSE);

  /* Set defaults so we don't free these later unnecessarily */
  SHMInfo.shmaddr = ((void *) -1);
  SHMInfo.shmid = -1;

  /* Setting an error handler to catch failure */
  error_caught = FALSE;
  handler = XSetErrorHandler (gst_xvimagesink_handle_xerror);

  /* Trying to create a 1x1 picture */
  GST_DEBUG ("XvShmCreateImage of 1x1");
  xvimage = XvShmCreateImage (xcontext->disp, xcontext->xv_port_id,
      xcontext->im_format, NULL, 1, 1, &SHMInfo);

  /* Might cause an error, sync to ensure it is noticed */
  XSync (xcontext->disp, FALSE);
  if (!xvimage || error_caught) {
    GST_WARNING ("could not XvShmCreateImage a 1x1 image");
    goto beach;
  }
  size = xvimage->data_size;

  SHMInfo.shmid = shmget (IPC_PRIVATE, size, IPC_CREAT | 0777);
  if (SHMInfo.shmid == -1) {
    GST_WARNING ("could not get shared memory of %d bytes", size);
    goto beach;
  }

  SHMInfo.shmaddr = shmat (SHMInfo.shmid, NULL, 0);
  if (SHMInfo.shmaddr == ((void *) -1)) {
    GST_WARNING ("Failed to shmat: %s", g_strerror (errno));
    /* Clean up the shared memory segment */
    shmctl (SHMInfo.shmid, IPC_RMID, NULL);
    goto beach;
  }

  xvimage->data = SHMInfo.shmaddr;
  SHMInfo.readOnly = FALSE;

  if (XShmAttach (xcontext->disp, &SHMInfo) == 0) {
    GST_WARNING ("Failed to XShmAttach");
    /* Clean up the shared memory segment */
    shmctl (SHMInfo.shmid, IPC_RMID, NULL);
    goto beach;
  }

  /* Sync to ensure we see any errors we caused */
  XSync (xcontext->disp, FALSE);

  /* Delete the shared memory segment as soon as everyone is attached.
   * This way, it will be deleted as soon as we detach later, and not
   * leaked if we crash. */
  shmctl (SHMInfo.shmid, IPC_RMID, NULL);

  if (!error_caught) {
    GST_DEBUG ("XServer ShmAttached to 0x%x, id 0x%lx", SHMInfo.shmid,
        SHMInfo.shmseg);

    did_attach = TRUE;
    /* store whether we succeeded in result */
    result = TRUE;
  } else {
    GST_WARNING ("MIT-SHM extension check failed at XShmAttach. "
        "Not using shared memory.");
  }

beach:
  /* Sync to ensure we swallow any errors we caused and reset error_caught */
  XSync (xcontext->disp, FALSE);

  error_caught = FALSE;
  XSetErrorHandler (handler);

  if (did_attach) {
    GST_DEBUG ("XServer ShmDetaching from 0x%x id 0x%lx",
        SHMInfo.shmid, SHMInfo.shmseg);
    XShmDetach (xcontext->disp, &SHMInfo);
    XSync (xcontext->disp, FALSE);
  }
  if (SHMInfo.shmaddr != ((void *) -1))
    shmdt (SHMInfo.shmaddr);
  if (xvimage)
    XFree (xvimage);
  return result;
}
#endif /* HAVE_XSHM */

/* This function handles GstXvImage creation depending on XShm availability */
static GstXvImageBuffer *
gst_xvimagesink_xvimage_new (GstXvImageSink * xvimagesink, GstCaps * caps)
{
  GstXvImageBuffer *xvimage = NULL;
  GstStructure *structure = NULL;
  gboolean succeeded = FALSE;
  int (*handler) (Display *, XErrorEvent *);

  g_return_val_if_fail (GST_IS_XVIMAGESINK (xvimagesink), NULL);

  if (caps == NULL)
    return NULL;

  xvimage = (GstXvImageBuffer *) gst_mini_object_new (GST_TYPE_XVIMAGE_BUFFER);
  GST_DEBUG_OBJECT (xvimage, "Creating new XvImageBuffer");

  structure = gst_caps_get_structure (caps, 0);

  if (!gst_structure_get_int (structure, "width", &xvimage->width) ||
      !gst_structure_get_int (structure, "height", &xvimage->height)) {
    GST_WARNING ("failed getting geometry from caps %" GST_PTR_FORMAT, caps);
  }

  GST_LOG_OBJECT (xvimagesink, "creating %dx%d", xvimage->width,
      xvimage->height);
#ifdef GST_EXT_XV_ENHANCEMENT
  GST_LOG_OBJECT(xvimagesink, "aligned size %dx%d",
                               xvimagesink->aligned_width, xvimagesink->aligned_height);
  if (xvimagesink->aligned_width == 0 || xvimagesink->aligned_height == 0) {
    GST_INFO_OBJECT(xvimagesink, "aligned size is zero. set size of caps.");
    xvimagesink->aligned_width = xvimage->width;
    xvimagesink->aligned_height = xvimage->height;
  }
#endif /* GST_EXT_XV_ENHANCEMENT */

  xvimage->im_format = gst_xvimagesink_get_format_from_caps (xvimagesink, caps);
  if (xvimage->im_format == -1) {
    GST_WARNING_OBJECT (xvimagesink, "failed to get format from caps %"
        GST_PTR_FORMAT, caps);
    GST_ELEMENT_ERROR (xvimagesink, RESOURCE, WRITE,
        ("Failed to create output image buffer of %dx%d pixels",
            xvimage->width, xvimage->height), ("Invalid input caps"));
    goto beach_unlocked;
  }
  xvimage->xvimagesink = gst_object_ref (xvimagesink);

  g_mutex_lock (xvimagesink->x_lock);

#ifdef GST_EXT_XV_ENHANCEMENT
  XSync (xvimagesink->xcontext->disp, FALSE);
#endif /* GST_EXT_XV_ENHANCEMENT */
  /* Setting an error handler to catch failure */
  error_caught = FALSE;
  handler = XSetErrorHandler (gst_xvimagesink_handle_xerror);

#ifdef HAVE_XSHM
  if (xvimagesink->xcontext->use_xshm) {
    int expected_size;

    xvimage->xvimage = XvShmCreateImage (xvimagesink->xcontext->disp,
        xvimagesink->xcontext->xv_port_id,
        xvimage->im_format, NULL,
#ifdef GST_EXT_XV_ENHANCEMENT
        xvimagesink->aligned_width, xvimagesink->aligned_height, &xvimage->SHMInfo);
#else /* GST_EXT_XV_ENHANCEMENT */
        xvimage->width, xvimage->height, &xvimage->SHMInfo);
#endif /* GST_EXT_XV_ENHANCEMENT */
    if (!xvimage->xvimage || error_caught) {
      g_mutex_unlock (xvimagesink->x_lock);

      /* Reset error flag */
      error_caught = FALSE;

      /* Push a warning */
      GST_ELEMENT_WARNING (xvimagesink, RESOURCE, WRITE,
          ("Failed to create output image buffer of %dx%d pixels",
              xvimage->width, xvimage->height),
          ("could not XvShmCreateImage a %dx%d image",
              xvimage->width, xvimage->height));

#ifdef GST_EXT_XV_ENHANCEMENT
      goto beach_unlocked;
#else /* GST_EXT_XV_ENHANCEMENT */
      /* Retry without XShm */
      xvimagesink->xcontext->use_xshm = FALSE;

      /* Hold X mutex again to try without XShm */
      g_mutex_lock (xvimagesink->x_lock);
      goto no_xshm;
#endif /* GST_EXT_XV_ENHANCEMENT */
    }

    /* we have to use the returned data_size for our shm size */
    xvimage->size = xvimage->xvimage->data_size;
    GST_LOG_OBJECT (xvimagesink, "XShm image size is %" G_GSIZE_FORMAT,
        xvimage->size);

    /* calculate the expected size.  This is only for sanity checking the
     * number we get from X. */
    switch (xvimage->im_format) {
      case GST_MAKE_FOURCC ('I', '4', '2', '0'):
      case GST_MAKE_FOURCC ('Y', 'V', '1', '2'):
      {
        gint pitches[3];
        gint offsets[3];
        guint plane;

        offsets[0] = 0;
        pitches[0] = GST_ROUND_UP_4 (xvimage->width);
        offsets[1] = offsets[0] + pitches[0] * GST_ROUND_UP_2 (xvimage->height);
        pitches[1] = GST_ROUND_UP_8 (xvimage->width) / 2;
        offsets[2] =
            offsets[1] + pitches[1] * GST_ROUND_UP_2 (xvimage->height) / 2;
        pitches[2] = GST_ROUND_UP_8 (pitches[0]) / 2;

        expected_size =
            offsets[2] + pitches[2] * GST_ROUND_UP_2 (xvimage->height) / 2;

        for (plane = 0; plane < xvimage->xvimage->num_planes; plane++) {
          GST_DEBUG_OBJECT (xvimagesink,
              "Plane %u has a expected pitch of %d bytes, " "offset of %d",
              plane, pitches[plane], offsets[plane]);
        }
        break;
      }
      case GST_MAKE_FOURCC ('Y', 'U', 'Y', '2'):
      case GST_MAKE_FOURCC ('U', 'Y', 'V', 'Y'):
        expected_size = xvimage->height * GST_ROUND_UP_4 (xvimage->width * 2);
        break;

#ifdef GST_EXT_XV_ENHANCEMENT
      case GST_MAKE_FOURCC ('S', 'T', '1', '2'):
      case GST_MAKE_FOURCC ('S', 'N', '1', '2'):
      case GST_MAKE_FOURCC ('S', 'N', '2', '1'):
      case GST_MAKE_FOURCC ('S', 'U', 'Y', 'V'):
      case GST_MAKE_FOURCC ('S', 'U', 'Y', '2'):
      case GST_MAKE_FOURCC ('S', '4', '2', '0'):
      case GST_MAKE_FOURCC ('S', 'Y', 'V', 'Y'):
        expected_size = sizeof(SCMN_IMGB);
        break;
#endif /* GST_EXT_XV_ENHANCEMENT */
      default:
        expected_size = 0;
        break;
    }
    if (expected_size != 0 && xvimage->size != expected_size) {
      GST_WARNING_OBJECT (xvimagesink,
          "unexpected XShm image size (got %" G_GSIZE_FORMAT ", expected %d)",
          xvimage->size, expected_size);
    }

    /* Be verbose about our XvImage stride */
    {
      guint plane;

      for (plane = 0; plane < xvimage->xvimage->num_planes; plane++) {
        GST_DEBUG_OBJECT (xvimagesink, "Plane %u has a pitch of %d bytes, "
            "offset of %d", plane, xvimage->xvimage->pitches[plane],
            xvimage->xvimage->offsets[plane]);
      }
    }

    xvimage->SHMInfo.shmid = shmget (IPC_PRIVATE, xvimage->size,
        IPC_CREAT | 0777);
    if (xvimage->SHMInfo.shmid == -1) {
      g_mutex_unlock (xvimagesink->x_lock);
      GST_ELEMENT_ERROR (xvimagesink, RESOURCE, WRITE,
          ("Failed to create output image buffer of %dx%d pixels",
              xvimage->width, xvimage->height),
          ("could not get shared memory of %" G_GSIZE_FORMAT " bytes",
              xvimage->size));
      goto beach_unlocked;
    }

    xvimage->SHMInfo.shmaddr = shmat (xvimage->SHMInfo.shmid, NULL, 0);
    if (xvimage->SHMInfo.shmaddr == ((void *) -1)) {
      g_mutex_unlock (xvimagesink->x_lock);
      GST_ELEMENT_ERROR (xvimagesink, RESOURCE, WRITE,
          ("Failed to create output image buffer of %dx%d pixels",
              xvimage->width, xvimage->height),
          ("Failed to shmat: %s", g_strerror (errno)));
      /* Clean up the shared memory segment */
      shmctl (xvimage->SHMInfo.shmid, IPC_RMID, NULL);
      goto beach_unlocked;
    }

    xvimage->xvimage->data = xvimage->SHMInfo.shmaddr;
    xvimage->SHMInfo.readOnly = FALSE;

    if (XShmAttach (xvimagesink->xcontext->disp, &xvimage->SHMInfo) == 0) {
      /* Clean up the shared memory segment */
      shmctl (xvimage->SHMInfo.shmid, IPC_RMID, NULL);

      g_mutex_unlock (xvimagesink->x_lock);
      GST_ELEMENT_ERROR (xvimagesink, RESOURCE, WRITE,
          ("Failed to create output image buffer of %dx%d pixels",
              xvimage->width, xvimage->height), ("Failed to XShmAttach"));
      goto beach_unlocked;
    }

    XSync (xvimagesink->xcontext->disp, FALSE);

    /* Delete the shared memory segment as soon as we everyone is attached.
     * This way, it will be deleted as soon as we detach later, and not
     * leaked if we crash. */
    shmctl (xvimage->SHMInfo.shmid, IPC_RMID, NULL);

    GST_DEBUG_OBJECT (xvimagesink, "XServer ShmAttached to 0x%x, id 0x%lx",
        xvimage->SHMInfo.shmid, xvimage->SHMInfo.shmseg);
  } else
  no_xshm:
#endif /* HAVE_XSHM */
  {
    xvimage->xvimage = XvCreateImage (xvimagesink->xcontext->disp,
        xvimagesink->xcontext->xv_port_id,
#ifdef GST_EXT_XV_ENHANCEMENT
        xvimage->im_format, NULL, xvimagesink->aligned_width, xvimagesink->aligned_height);
#else /* GST_EXT_XV_ENHANCEMENT */
        xvimage->im_format, NULL, xvimage->width, xvimage->height);
#endif /* GST_EXT_XV_ENHANCEMENT */
    if (!xvimage->xvimage || error_caught) {
      g_mutex_unlock (xvimagesink->x_lock);
      /* Reset error handler */
      error_caught = FALSE;
      XSetErrorHandler (handler);
      /* Push an error */
      GST_ELEMENT_ERROR (xvimagesink, RESOURCE, WRITE,
          ("Failed to create outputimage buffer of %dx%d pixels",
              xvimage->width, xvimage->height),
          ("could not XvCreateImage a %dx%d image",
              xvimage->width, xvimage->height));
      goto beach_unlocked;
    }

    /* we have to use the returned data_size for our image size */
    xvimage->size = xvimage->xvimage->data_size;
    xvimage->xvimage->data = g_malloc (xvimage->size);

    XSync (xvimagesink->xcontext->disp, FALSE);
  }

  /* Reset error handler */
  error_caught = FALSE;
  XSetErrorHandler (handler);

  succeeded = TRUE;

  GST_BUFFER_DATA (xvimage) = (guchar *) xvimage->xvimage->data;
  GST_BUFFER_SIZE (xvimage) = xvimage->size;

  g_mutex_unlock (xvimagesink->x_lock);

beach_unlocked:
  if (!succeeded) {
    gst_xvimage_buffer_free (xvimage);
    xvimage = NULL;
  }

  return xvimage;
}

/* We are called with the x_lock taken */
static void
gst_xvimagesink_xwindow_draw_borders (GstXvImageSink * xvimagesink,
    GstXWindow * xwindow, GstVideoRectangle rect)
{
  gint t1, t2;

  g_return_if_fail (GST_IS_XVIMAGESINK (xvimagesink));
  g_return_if_fail (xwindow != NULL);

  XSetForeground (xvimagesink->xcontext->disp, xwindow->gc,
      xvimagesink->xcontext->black);

  /* Left border */
  if (rect.x > xvimagesink->render_rect.x) {
    XFillRectangle (xvimagesink->xcontext->disp, xwindow->win, xwindow->gc,
        xvimagesink->render_rect.x, xvimagesink->render_rect.y,
        rect.x - xvimagesink->render_rect.x, xvimagesink->render_rect.h);
  }

  /* Right border */
  t1 = rect.x + rect.w;
  t2 = xvimagesink->render_rect.x + xvimagesink->render_rect.w;
  if (t1 < t2) {
    XFillRectangle (xvimagesink->xcontext->disp, xwindow->win, xwindow->gc,
        t1, xvimagesink->render_rect.y, t2 - t1, xvimagesink->render_rect.h);
  }

  /* Top border */
  if (rect.y > xvimagesink->render_rect.y) {
    XFillRectangle (xvimagesink->xcontext->disp, xwindow->win, xwindow->gc,
        xvimagesink->render_rect.x, xvimagesink->render_rect.y,
        xvimagesink->render_rect.w, rect.y - xvimagesink->render_rect.y);
  }

  /* Bottom border */
  t1 = rect.y + rect.h;
  t2 = xvimagesink->render_rect.y + xvimagesink->render_rect.h;
  if (t1 < t2) {
    XFillRectangle (xvimagesink->xcontext->disp, xwindow->win, xwindow->gc,
        xvimagesink->render_rect.x, t1, xvimagesink->render_rect.w, t2 - t1);
  }
}

/* This function puts a GstXvImage on a GstXvImageSink's window. Returns FALSE
 * if no window was available  */
static gboolean
gst_xvimagesink_xvimage_put (GstXvImageSink * xvimagesink,
    GstXvImageBuffer * xvimage)
{
  GstVideoRectangle result;
  gboolean draw_border = FALSE;

#ifdef GST_EXT_XV_ENHANCEMENT
  static Atom atom_rotation = None;
  static Atom atom_hflip = None;
  static Atom atom_vflip = None;
  gboolean set_hflip = FALSE;
  gboolean set_vflip = FALSE;

  GstVideoRectangle src_origin = { 0, 0, 0, 0};
  GstVideoRectangle src_input  = { 0, 0, 0, 0};
  GstVideoRectangle src = { 0, 0, 0, 0};
  GstVideoRectangle dst = { 0, 0, 0, 0};

  int rotate        = 0;
  int ret           = 0;
  int idx           = 0;
  int (*handler) (Display *, XErrorEvent *);
  gboolean res = FALSE;
#endif /* GST_EXT_XV_ENHANCEMENT */

  /* 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 (xvimagesink->flow_lock);

#ifdef GST_EXT_XV_ENHANCEMENT
  if (xvimagesink->xid_updated) {
    if (xvimage && xvimagesink->xvimage == NULL) {
      GST_WARNING_OBJECT (xvimagesink, "set xvimage to NULL, new xid was set right after creation of new xvimage");
      xvimage = NULL;
    }
    xvimagesink->xid_updated = FALSE;
  }
#endif /* GST_EXT_XV_ENHANCEMENT */

  if (G_UNLIKELY (xvimagesink->xwindow == NULL)) {
#ifdef GST_EXT_XV_ENHANCEMENT
    if (xvimagesink->get_pixmap_cb) {
      GST_INFO_OBJECT( xvimagesink, "xwindow is NULL, but it has get_pixmap_cb(0x%x), keep going..",xvimagesink->get_pixmap_cb );
    } else {
      GST_INFO_OBJECT( xvimagesink, "xwindow is NULL. Skip xvimage_put." );
#endif /* GST_EXT_XV_ENHANCEMENT */
    g_mutex_unlock (xvimagesink->flow_lock);
    return FALSE;
#ifdef GST_EXT_XV_ENHANCEMENT
    }
#endif /* GST_EXT_XV_ENHANCEMENT */
  }

#ifdef GST_EXT_XV_ENHANCEMENT
  if (xvimagesink->visible == FALSE) {
    GST_INFO_OBJECT(xvimagesink, "visible is FALSE. Skip xvimage_put.");
    g_mutex_unlock(xvimagesink->flow_lock);
    return TRUE;
  }
#endif /* GST_EXT_XV_ENHANCEMENT */

  /* Draw borders when displaying the first frame. After this
     draw borders only on expose event or after a size change. */
  if (!xvimagesink->cur_image || xvimagesink->redraw_border) {
    draw_border = TRUE;
  }

  /* Store a reference to the last image we put, lose the previous one */
  if (xvimage && xvimagesink->cur_image != xvimage) {
    if (xvimagesink->cur_image) {
      GST_LOG_OBJECT (xvimagesink, "unreffing %p", xvimagesink->cur_image);
      gst_buffer_unref (GST_BUFFER_CAST (xvimagesink->cur_image));
    }
    GST_LOG_OBJECT (xvimagesink, "reffing %p as our current image", xvimage);
    xvimagesink->cur_image =
        GST_XVIMAGE_BUFFER_CAST (gst_buffer_ref (GST_BUFFER_CAST (xvimage)));
  }

  /* Expose sends a NULL image, we take the latest frame */
  if (!xvimage) {
    if (xvimagesink->cur_image) {
      draw_border = TRUE;
      xvimage = xvimagesink->cur_image;
    } else {
#ifdef GST_EXT_XV_ENHANCEMENT
      GST_INFO_OBJECT(xvimagesink, "cur_image is NULL. Skip xvimage_put.");
#endif /* GST_EXT_XV_ENHANCEMENT */
      g_mutex_unlock (xvimagesink->flow_lock);
      return TRUE;
    }
  }

#ifdef GST_EXT_XV_ENHANCEMENT
  if (!xvimagesink->get_pixmap_cb) {
    gst_xvimagesink_xwindow_update_geometry( xvimagesink );
  } else {
    /* for multi-pixmap usage for the video texture */
    gst_xvimagesink_set_pixmap_handle ((GstXOverlay *)xvimagesink, xvimagesink->get_pixmap_cb(xvimagesink->get_pixmap_cb_user_data));
    idx = xvimagesink->current_pixmap_idx;
    if (idx == -1) {
      g_mutex_unlock (xvimagesink->flow_lock);
      return FALSE;
    } else if (idx == -2) {
      GST_WARNING_OBJECT(xvimagesink, "Skip putImage().");
      g_mutex_unlock (xvimagesink->flow_lock);
      return TRUE;
    }
  }

  src.x = src.y = 0;
  src_origin.x = src_origin.y = src_input.x = src_input.y = 0;

  src_input.w = src_origin.w = xvimagesink->video_width;
  src_input.h = src_origin.h = xvimagesink->video_height;

  if (xvimagesink->rotate_angle == DEGREE_0 ||
      xvimagesink->rotate_angle == DEGREE_180) {
    src.w = src_origin.w;
    src.h = src_origin.h;
  } else {
    src.w = src_origin.h;
    src.h = src_origin.w;
  }

  dst.w = xvimagesink->render_rect.w;
  dst.h = xvimagesink->render_rect.h;

  switch (xvimagesink->display_geometry_method)
  {
    case DISP_GEO_METHOD_LETTER_BOX:
      gst_video_sink_center_rect (src, dst, &result, TRUE);
      result.x += xvimagesink->render_rect.x;
      result.y += xvimagesink->render_rect.y;
      break;

    case DISP_GEO_METHOD_ORIGIN_SIZE_OR_LETTER_BOX:
      GST_WARNING_OBJECT(xvimagesink, "not supported API, set ORIGIN_SIZE mode");
    case DISP_GEO_METHOD_ORIGIN_SIZE:
      gst_video_sink_center_rect (src, dst, &result, FALSE);
      gst_video_sink_center_rect (dst, src, &src_input, FALSE);

      if (xvimagesink->rotate_angle == DEGREE_90 ||
          xvimagesink->rotate_angle == DEGREE_270) {
        src_input.x = src_input.x ^ src_input.y;
        src_input.y = src_input.x ^ src_input.y;
        src_input.x = src_input.x ^ src_input.y;

        src_input.w = src_input.w ^ src_input.h;
        src_input.h = src_input.w ^ src_input.h;
        src_input.w = src_input.w ^ src_input.h;
      }
      break;

   case DISP_GEO_METHOD_FULL_SCREEN:
      result.x = result.y = 0;
      if (!xvimagesink->get_pixmap_cb) {
        result.w = xvimagesink->xwindow->width;
        result.h = xvimagesink->xwindow->height;
      } else {
        result.w = xvimagesink->xpixmap[idx]->width;
        result.h = xvimagesink->xpixmap[idx]->height;
      }
      break;

   case DISP_GEO_METHOD_CROPPED_FULL_SCREEN:
      gst_video_sink_center_rect(dst, src, &src_input, TRUE);

      result.x = result.y = 0;
      result.w = dst.w;
      result.h = dst.h;

      if (xvimagesink->rotate_angle == DEGREE_90 ||
          xvimagesink->rotate_angle == DEGREE_270) {
        src_input.x = src_input.x ^ src_input.y;
        src_input.y = src_input.x ^ src_input.y;
        src_input.x = src_input.x ^ src_input.y;

        src_input.w = src_input.w ^ src_input.h;
        src_input.h = src_input.w ^ src_input.h;
        src_input.w = src_input.w ^ src_input.h;
      }
      break;

    case DISP_GEO_METHOD_CUSTOM_ROI:
#ifdef GST_EXT_XV_ENHANCEMENT_ROI_MODE
      switch (xvimagesink->rotate_angle) {
      case DEGREE_90:
        result.w = xvimagesink->dst_roi.h;
        result.h = xvimagesink->dst_roi.w;

        result.x = xvimagesink->dst_roi.y;
        if (!xvimagesink->get_pixmap_cb) {
          result.y = xvimagesink->xwindow->height - xvimagesink->dst_roi.x - xvimagesink->dst_roi.w;
        } else {
          result.y = xvimagesink->xpixmap[idx]->height - xvimagesink->dst_roi.x - xvimagesink->dst_roi.w;
        }
        break;
      case DEGREE_180:
        result.w = xvimagesink->dst_roi.w;
        result.h = xvimagesink->dst_roi.h;

        if (!xvimagesink->get_pixmap_cb) {
          result.x = xvimagesink->xwindow->width - result.w - xvimagesink->dst_roi.x;
          result.y = xvimagesink->xwindow->height - result.h - xvimagesink->dst_roi.y;
        } else {
          result.x = xvimagesink->xpixmap[idx]->width - result.w - xvimagesink->dst_roi.x;
          result.y = xvimagesink->xpixmap[idx]->height - result.h - xvimagesink->dst_roi.y;
        }
        break;
      case DEGREE_270:
        result.w = xvimagesink->dst_roi.h;
        result.h = xvimagesink->dst_roi.w;

        if (!xvimagesink->get_pixmap_cb) {
          result.x = xvimagesink->xwindow->width - xvimagesink->dst_roi.y - xvimagesink->dst_roi.h;
        } else {
          result.x = xvimagesink->xpixmap[idx]->width - xvimagesink->dst_roi.y - xvimagesink->dst_roi.h;
        }
        result.y = xvimagesink->dst_roi.x;
        break;
      default:
        result.x = xvimagesink->dst_roi.x;
        result.y = xvimagesink->dst_roi.y;
        result.w = xvimagesink->dst_roi.w;
        result.h = xvimagesink->dst_roi.h;
        break;
      }

      GST_LOG_OBJECT(xvimagesink, "rotate[%d], ROI input[%d,%d,%dx%d] > result[%d,%d,%dx%d]",
                     xvimagesink->rotate_angle,
                     xvimagesink->dst_roi.x, xvimagesink->dst_roi.y, xvimagesink->dst_roi.w, xvimagesink->dst_roi.h,
                     result.x, result.y, result.w, result.h);
#else /* GST_EXT_XV_ENHANCEMENT_ROI_MODE */
      result.x = xvimagesink->dst_roi.x;
      result.y = xvimagesink->dst_roi.y;
      result.w = xvimagesink->dst_roi.w;
      result.h = xvimagesink->dst_roi.h;

      if (xvimagesink->rotate_angle == DEGREE_90 ||
          xvimagesink->rotate_angle == DEGREE_270) {
        result.w = xvimagesink->dst_roi.h;
        result.h = xvimagesink->dst_roi.w;
      }
#endif /* GST_EXT_XV_ENHANCEMENT_ROI_MODE */
      break;

    default:
      break;
  }

  if (xvimagesink->zoom > 1 && xvimagesink->zoom < 10) {
    src_input.x += (src_input.w-(src_input.w/xvimagesink->zoom))>>1;
    src_input.y += (src_input.h-(src_input.h/xvimagesink->zoom))>>1;
    src_input.w /= xvimagesink->zoom;
    src_input.h /= xvimagesink->zoom;
  }

#else /* GST_EXT_XV_ENHANCEMENT */
  if (xvimagesink->keep_aspect) {
    GstVideoRectangle src, dst;

    /* We use the calculated geometry from _setcaps as a source to respect
       source and screen pixel aspect ratios. */
    src.w = GST_VIDEO_SINK_WIDTH (xvimagesink);
    src.h = GST_VIDEO_SINK_HEIGHT (xvimagesink);
    dst.w = xvimagesink->render_rect.w;
    dst.h = xvimagesink->render_rect.h;

    gst_video_sink_center_rect (src, dst, &result, TRUE);
    result.x += xvimagesink->render_rect.x;
    result.y += xvimagesink->render_rect.y;
  } else {
    memcpy (&result, &xvimagesink->render_rect, sizeof (GstVideoRectangle));
  }
#endif /* GST_EXT_XV_ENHANCEMENT */

  g_mutex_lock (xvimagesink->x_lock);

#ifdef GST_EXT_XV_ENHANCEMENT
  if (draw_border && xvimagesink->draw_borders && !xvimagesink->get_pixmap_cb) {
#else
  if (draw_border && xvimagesink->draw_borders) {
#endif /* GST_EXT_XV_ENHANCEMENT */
    gst_xvimagesink_xwindow_draw_borders (xvimagesink, xvimagesink->xwindow,
        result);
    xvimagesink->redraw_border = FALSE;
  }

  /* We scale to the window's geometry */
#ifdef HAVE_XSHM
  if (xvimagesink->xcontext->use_xshm) {
    GST_LOG_OBJECT (xvimagesink,
        "XvShmPutImage with image %dx%d and window %dx%d, from xvimage %"
        GST_PTR_FORMAT,
        xvimage->width, xvimage->height,
        xvimagesink->render_rect.w, xvimagesink->render_rect.h, xvimage);

#ifdef GST_EXT_XV_ENHANCEMENT
    switch( xvimagesink->rotate_angle )
    {
      /* There's slightly weired code (CCW? CW?) */
      case DEGREE_0:
        break;
      case DEGREE_90:
        rotate = 270;
        break;
      case DEGREE_180:
        rotate = 180;
        break;
      case DEGREE_270:
        rotate = 90;
        break;
      default:
        GST_WARNING_OBJECT( xvimagesink, "Unsupported rotation [%d]... set DEGREE 0.",
          xvimagesink->rotate_angle );
        break;
    }

    /* Trim as proper size */
    if (src_input.w % 2 == 1) {
        src_input.w += 1;
    }
    if (src_input.h % 2 == 1) {
        src_input.h += 1;
    }

    if (!xvimagesink->get_pixmap_cb) {
      GST_LOG_OBJECT( xvimagesink, "screen[%dx%d],window[%d,%d,%dx%d],method[%d],rotate[%d],zoom[%d],dp_mode[%d],src[%dx%d],dst[%d,%d,%dx%d],input[%d,%d,%dx%d],result[%d,%d,%dx%d]",
        xvimagesink->scr_w, xvimagesink->scr_h,
        xvimagesink->xwindow->x, xvimagesink->xwindow->y, xvimagesink->xwindow->width, xvimagesink->xwindow->height,
        xvimagesink->display_geometry_method, rotate, xvimagesink->zoom, xvimagesink->display_mode,
        src_origin.w, src_origin.h,
        dst.x, dst.y, dst.w, dst.h,
        src_input.x, src_input.y, src_input.w, src_input.h,
        result.x, result.y, result.w, result.h );
    } else {
      GST_LOG_OBJECT( xvimagesink, "pixmap[%d,%d,%dx%d],method[%d],rotate[%d],zoom[%d],dp_mode[%d],src[%dx%d],dst[%d,%d,%dx%d],input[%d,%d,%dx%d],result[%d,%d,%dx%d]",
      xvimagesink->xpixmap[idx]->x, xvimagesink->xpixmap[idx]->y, xvimagesink->xpixmap[idx]->width, xvimagesink->xpixmap[idx]->height,
      xvimagesink->display_geometry_method, rotate, xvimagesink->zoom, xvimagesink->display_mode,
      src_origin.w, src_origin.h,
      dst.x, dst.y, dst.w, dst.h,
      src_input.x, src_input.y, src_input.w, src_input.h,
      result.x, result.y, result.w, result.h );
    }

    /* set display rotation */
    if (atom_rotation == None) {
      atom_rotation = XInternAtom(xvimagesink->xcontext->disp,
                                  "_USER_WM_PORT_ATTRIBUTE_ROTATION", False);
    }

    ret = XvSetPortAttribute(xvimagesink->xcontext->disp, xvimagesink->xcontext->xv_port_id, atom_rotation, rotate);
    if (ret != Success) {
      GST_ERROR_OBJECT( xvimagesink, "XvSetPortAttribute failed[%d]. disp[%x],xv_port_id[%d],atom[%x],rotate[%d]",
        ret, xvimagesink->xcontext->disp, xvimagesink->xcontext->xv_port_id, atom_rotation, rotate );
      return FALSE;
    }

    /* set display flip */
    if (atom_hflip == None) {
      atom_hflip = XInternAtom(xvimagesink->xcontext->disp,
                               "_USER_WM_PORT_ATTRIBUTE_HFLIP", False);
    }
    if (atom_vflip == None) {
      atom_vflip = XInternAtom(xvimagesink->xcontext->disp,
                               "_USER_WM_PORT_ATTRIBUTE_VFLIP", False);
    }

    switch (xvimagesink->flip) {
    case FLIP_HORIZONTAL:
      set_hflip = TRUE;
      set_vflip = FALSE;
      break;
    case FLIP_VERTICAL:
      set_hflip = FALSE;
      set_vflip = TRUE;
      break;
    case FLIP_BOTH:
      set_hflip = TRUE;
      set_vflip = TRUE;
      break;
    case FLIP_NONE:
    default:
      set_hflip = FALSE;
      set_vflip = FALSE;
      break;
    }

    ret = XvSetPortAttribute(xvimagesink->xcontext->disp, xvimagesink->xcontext->xv_port_id, atom_hflip, set_hflip);
    if (ret != Success) {
      GST_WARNING("set HFLIP failed[%d]. disp[%x],xv_port_id[%d],atom[%x],hflip[%d]",
                  ret, xvimagesink->xcontext->disp, xvimagesink->xcontext->xv_port_id, atom_hflip, set_hflip);
    }
    ret = XvSetPortAttribute(xvimagesink->xcontext->disp, xvimagesink->xcontext->xv_port_id, atom_vflip, set_vflip);
    if (ret != Success) {
      GST_WARNING("set VFLIP failed[%d]. disp[%x],xv_port_id[%d],atom[%x],vflip[%d]",
                  ret, xvimagesink->xcontext->disp, xvimagesink->xcontext->xv_port_id, atom_vflip, set_vflip);
    }

    /* set error handler */
    error_caught = FALSE;
    handler = XSetErrorHandler(gst_xvimagesink_handle_xerror);

    /* src input indicates the status when degree is 0 */
    /* dst input indicates the area that src will be shown regardless of rotate */
    if (xvimagesink->visible && !xvimagesink->is_hided) {
      if (xvimagesink->xim_transparenter) {
        GST_LOG_OBJECT( xvimagesink, "Transparent related issue." );
        XPutImage(xvimagesink->xcontext->disp,
          xvimagesink->xwindow->win,
          xvimagesink->xwindow->gc,
          xvimagesink->xim_transparenter,
          0, 0,
          result.x, result.y, result.w, result.h);
      }

      if (xvimagesink->get_pixmap_cb) {
        gint idx = xvimagesink->current_pixmap_idx;
        ret = XvShmPutImage (xvimagesink->xcontext->disp,
          xvimagesink->xcontext->xv_port_id,
          xvimagesink->xpixmap[idx]->pixmap,
          xvimagesink->xpixmap[idx]->gc, xvimage->xvimage,
          src_input.x, src_input.y, src_input.w, src_input.h,
          result.x, result.y, result.w, result.h, FALSE);
        GST_LOG_OBJECT(xvimagesink, "pixmap[%d]->pixmap = %d", idx, xvimagesink->xpixmap[idx]->pixmap);
      } else {
        ret = XvShmPutImage (xvimagesink->xcontext->disp,
          xvimagesink->xcontext->xv_port_id,
          xvimagesink->xwindow->win,
          xvimagesink->xwindow->gc, xvimage->xvimage,
          src_input.x, src_input.y, src_input.w, src_input.h,
          result.x, result.y, result.w, result.h, FALSE);
      }
      GST_LOG_OBJECT( xvimagesink, "XvShmPutImage return value [%d]", ret );
    } else {
      GST_LOG_OBJECT( xvimagesink, "visible is FALSE. skip this image..." );
    }
#else /* GST_EXT_XV_ENHANCEMENT */
    XvShmPutImage (xvimagesink->xcontext->disp,
        xvimagesink->xcontext->xv_port_id,
        xvimagesink->xwindow->win,
        xvimagesink->xwindow->gc, xvimage->xvimage,
        xvimagesink->disp_x, xvimagesink->disp_y,
        xvimagesink->disp_width, xvimagesink->disp_height,
        result.x, result.y, result.w, result.h, FALSE);
#endif /* GST_EXT_XV_ENHANCEMENT */
  } else
#endif /* HAVE_XSHM */
  {
    XvPutImage (xvimagesink->xcontext->disp,
        xvimagesink->xcontext->xv_port_id,
        xvimagesink->xwindow->win,
        xvimagesink->xwindow->gc, xvimage->xvimage,
        xvimagesink->disp_x, xvimagesink->disp_y,
        xvimagesink->disp_width, xvimagesink->disp_height,
        result.x, result.y, result.w, result.h);
  }

  XSync (xvimagesink->xcontext->disp, FALSE);

#ifdef HAVE_XSHM
#ifdef GST_EXT_XV_ENHANCEMENT
  if (xvimagesink->get_pixmap_cb) {
    if (error_caught) {
      g_signal_emit (G_OBJECT (xvimagesink),
                     gst_xvimagesink_signals[SIGNAL_FRAME_RENDER_ERROR],
                     0,
                     &xvimagesink->xpixmap[idx]->pixmap,
                     &res);
      GST_WARNING_OBJECT( xvimagesink, "pixmap cb case, putimage error_caught" );
    }
  }
  /* Reset error handler */
  error_caught = FALSE;
  XSetErrorHandler (handler);
#endif /* GST_EXT_XV_ENHANCEMENT */
#endif /* HAVE_XSHM */

  g_mutex_unlock (xvimagesink->x_lock);

  g_mutex_unlock (xvimagesink->flow_lock);

  return TRUE;
}

static gboolean
gst_xvimagesink_xwindow_decorate (GstXvImageSink * xvimagesink,
    GstXWindow * window)
{
  Atom hints_atom = None;
  MotifWmHints *hints;

  g_return_val_if_fail (GST_IS_XVIMAGESINK (xvimagesink), FALSE);
  g_return_val_if_fail (window != NULL, FALSE);

  g_mutex_lock (xvimagesink->x_lock);

  hints_atom = XInternAtom (xvimagesink->xcontext->disp, "_MOTIF_WM_HINTS",
      True);
  if (hints_atom == None) {
    g_mutex_unlock (xvimagesink->x_lock);
    return FALSE;
  }

  hints = g_malloc0 (sizeof (MotifWmHints));

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

  XChangeProperty (xvimagesink->xcontext->disp, window->win,
      hints_atom, hints_atom, 32, PropModeReplace,
      (guchar *) hints, sizeof (MotifWmHints) / sizeof (long));

  XSync (xvimagesink->xcontext->disp, FALSE);

  g_mutex_unlock (xvimagesink->x_lock);

  g_free (hints);

  return TRUE;
}

static void
gst_xvimagesink_xwindow_set_title (GstXvImageSink * xvimagesink,
    GstXWindow * xwindow, const gchar * media_title)
{
  if (media_title) {
    g_free (xvimagesink->media_title);
    xvimagesink->media_title = g_strdup (media_title);
  }
  if (xwindow) {
    /* we have a window */
    if (xwindow->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 && xvimagesink->media_title) {
        title = title_mem = g_strconcat (xvimagesink->media_title, " : ",
            app_name, NULL);
      } else if (app_name) {
        title = app_name;
      } else if (xvimagesink->media_title) {
        title = xvimagesink->media_title;
      }

      if (title) {
        if ((XStringListToTextProperty (((char **) &title), 1,
                    &xproperty)) != 0) {
          XSetWMName (xvimagesink->xcontext->disp, xwindow->win, &xproperty);
          XFree (xproperty.value);
        }

        g_free (title_mem);
      }
    }
  }
}

#ifdef GST_EXT_XV_ENHANCEMENT
static XImage *make_transparent_image(Display *d, Window win, int w, int h)
{
  XImage *xim;

  /* create a normal ximage */
  xim = XCreateImage(d, DefaultVisualOfScreen(DefaultScreenOfDisplay(d)),  24, ZPixmap, 0, NULL, w, h, 32, 0);

  GST_INFO("ximage %p", xim);

  /* allocate data for it */
  if (xim) {
    xim->data = (char *)malloc(xim->bytes_per_line * xim->height);
    if (xim->data) {
      memset(xim->data, 0x00, xim->bytes_per_line * xim->height);
      return xim;
    } else {
      GST_ERROR("failed to alloc data - size %d", xim->bytes_per_line * xim->height);
    }

    XDestroyImage(xim);
  }

  GST_ERROR("failed to create Ximage");

  return NULL;
}


static gboolean set_display_mode(GstXContext *xcontext, int set_mode)
{
  int ret = 0;
  static gboolean is_exist = FALSE;
  static XvPortID current_port_id = -1;
  Atom atom_output = None;

  if (xcontext == NULL) {
    GST_WARNING("xcontext is NULL");
    return FALSE;
  }

  /* check once per one xv_port_id */
  if (current_port_id != xcontext->xv_port_id) {
    /* check whether _USER_WM_PORT_ATTRIBUTE_OUTPUT attribute is existed */
    int i = 0;
    int count = 0;
    XvAttribute *const attr = XvQueryPortAttributes(xcontext->disp,
                                                    xcontext->xv_port_id, &count);
    if (attr) {
      current_port_id = xcontext->xv_port_id;
      for (i = 0 ; i < count ; i++) {
        if (!strcmp(attr[i].name, "_USER_WM_PORT_ATTRIBUTE_OUTPUT")) {
          is_exist = TRUE;
          GST_INFO("_USER_WM_PORT_ATTRIBUTE_OUTPUT[index %d] found", i);
          break;
        }
      }
      XFree(attr);
    } else {
      GST_WARNING("XvQueryPortAttributes disp:%d, port_id:%d failed",
                  xcontext->disp, xcontext->xv_port_id);
    }
  }

  if (is_exist) {
    GST_INFO("set display mode %d", set_mode);
    atom_output = XInternAtom(xcontext->disp,
                              "_USER_WM_PORT_ATTRIBUTE_OUTPUT", False);
    ret = XvSetPortAttribute(xcontext->disp, xcontext->xv_port_id,
                             atom_output, set_mode);
    if (ret == Success) {
      return TRUE;
    } else {
      GST_WARNING("display mode[%d] set failed.", set_mode);
    }
  } else {
    GST_WARNING("_USER_WM_PORT_ATTRIBUTE_OUTPUT is not existed");
  }

  return FALSE;
}

static void drm_init(GstXvImageSink *xvimagesink)
{
	Display *dpy;
	int i = 0;
	int eventBase = 0;
	int errorBase = 0;
	int dri2Major = 0;
	int dri2Minor = 0;
	char *driverName = NULL;
	char *deviceName = NULL;
	struct drm_auth auth_arg = {0};

	xvimagesink->drm_fd = -1;

	dpy = XOpenDisplay(0);
	if (!dpy) {
		GST_ERROR("XOpenDisplay failed errno:%d", errno);
		return;
	}

	GST_INFO("START");

	/* DRI2 */
	if (!DRI2QueryExtension(dpy, &eventBase, &errorBase)) {
		GST_ERROR("DRI2QueryExtension !!");
		goto DRM_INIT_ERROR;
	}

	if (!DRI2QueryVersion(dpy, &dri2Major, &dri2Minor)) {
		GST_ERROR("DRI2QueryVersion !!");
		goto DRM_INIT_ERROR;
	}

	if (!DRI2Connect(dpy, RootWindow(dpy, DefaultScreen(dpy)), &driverName, &deviceName)) {
		GST_ERROR("DRI2Connect !!");
		goto DRM_INIT_ERROR;
	}

	if (!driverName || !deviceName) {
		GST_ERROR("driverName or deviceName is not valid");
		goto DRM_INIT_ERROR;
	}

	GST_INFO("Open drm device : %s", deviceName);

	/* get the drm_fd though opening the deviceName */
	xvimagesink->drm_fd = open(deviceName, O_RDWR);
	if (xvimagesink->drm_fd < 0) {
		GST_ERROR("cannot open drm device (%s)", deviceName);
		goto DRM_INIT_ERROR;
	}

	/* get magic from drm to authentication */
	if (ioctl(xvimagesink->drm_fd, DRM_IOCTL_GET_MAGIC, &auth_arg)) {
		GST_ERROR("cannot get drm auth magic");
		goto DRM_INIT_ERROR;
	}

	if (!DRI2Authenticate(dpy, RootWindow(dpy, DefaultScreen(dpy)), auth_arg.magic)) {
		GST_ERROR("cannot get drm authentication from X");
		goto DRM_INIT_ERROR;
	}

	/* init gem handle */
	for (i = 0 ; i < MAX_PLANE_NUM ; i++) {
		xvimagesink->gem_handle[i] = 0;
	}

	XCloseDisplay(dpy);
	free(driverName);
	free(deviceName);

	GST_INFO("DONE");

	return;

DRM_INIT_ERROR:
	if (xvimagesink->drm_fd >= 0) {
		close(xvimagesink->drm_fd);
		xvimagesink->drm_fd = -1;
	}
	if (dpy) {
		XCloseDisplay(dpy);
	}
	if (driverName) {
		free(driverName);
	}
	if (deviceName) {
		free(deviceName);
	}

	return;
}

static void drm_fini(GstXvImageSink *xvimagesink)
{
	GST_INFO("START");

	if (xvimagesink->drm_fd >= 0) {
		GST_INFO("close drm_fd %d", xvimagesink->drm_fd);
		close(xvimagesink->drm_fd);
		xvimagesink->drm_fd = -1;
	} else {
		GST_INFO("DRM device is NOT opened");
	}

	GST_INFO("DONE");
}

static unsigned int drm_convert_dmabuf_gemname(GstXvImageSink *xvimagesink, int dmabuf_fd, int *gem_handle)
{
	int i = 0;
	int ret = 0;

	struct drm_prime_handle prime_arg = {0,};
	struct drm_gem_flink flink_arg = {0,};

	if (!xvimagesink || !gem_handle) {
		GST_ERROR("handle[%p,%p] is NULL", xvimagesink, gem_handle);
		return 0;
	}

	GST_LOG("START - fd : %d", dmabuf_fd);

	if (xvimagesink->drm_fd < 0) {
		GST_ERROR("DRM is not opened");
		return 0;
	}

	if (dmabuf_fd <= 0) {
		GST_LOG("Ignore wrong dmabuf fd(%d)", dmabuf_fd);
		return 0;
	}

	prime_arg.fd = dmabuf_fd;
	ret = ioctl(xvimagesink->drm_fd, DRM_IOCTL_PRIME_FD_TO_HANDLE, &prime_arg);
	if (ret) {
		GST_ERROR("DRM_IOCTL_PRIME_FD_TO_HANDLE failed. ret %d, dmabuf fd : %d", ret, dmabuf_fd);
		return 0;
	}

	GST_LOG("gem handle %u", prime_arg.handle);

	*gem_handle = prime_arg.handle;
	flink_arg.handle = prime_arg.handle;
	ret = ioctl(xvimagesink->drm_fd, DRM_IOCTL_GEM_FLINK, &flink_arg);
	if (ret) {
		GST_ERROR("DRM_IOCTL_GEM_FLINK failed. ret %d, gem_handle %u, gem_name %u", ret, *gem_handle, flink_arg.name);
		return 0;
	}

	GST_LOG("DONE converted GEM name %u", flink_arg.name);

	return flink_arg.name;
}

static void drm_close_gem(GstXvImageSink *xvimagesink, unsigned int *gem_handle)
{
	struct drm_gem_close close_arg = {0,};

	if (xvimagesink->drm_fd < 0 || !gem_handle) {
		GST_ERROR("DRM is not opened");
		return;
	}

	if (*gem_handle <= 0) {
		GST_DEBUG("invalid gem handle %d", *gem_handle);
		return;
	}

	GST_DEBUG("Call DRM_IOCTL_GEM_CLOSE");

	close_arg.handle = *gem_handle;
	if (ioctl(xvimagesink->drm_fd, DRM_IOCTL_GEM_CLOSE, &close_arg)) {
		GST_ERROR("cannot close drm gem handle %d", gem_handle);
		return;
	}

	GST_DEBUG("close gem handle %d done", *gem_handle);

	*gem_handle = 0;

	return;
}
#endif /* GST_EXT_XV_ENHANCEMENT */

/* This function handles a GstXWindow creation
 * The width and height are the actual pixel size on the display */
static GstXWindow *
gst_xvimagesink_xwindow_new (GstXvImageSink * xvimagesink,
    gint width, gint height)
{
  GstXWindow *xwindow = NULL;
  XGCValues values;
#ifdef GST_EXT_XV_ENHANCEMENT
  XSetWindowAttributes win_attr;
  XWindowAttributes root_attr;
#endif /* GST_EXT_XV_ENHANCEMENT */

  g_return_val_if_fail (GST_IS_XVIMAGESINK (xvimagesink), NULL);

  xwindow = g_new0 (GstXWindow, 1);

  xvimagesink->render_rect.x = xvimagesink->render_rect.y = 0;
#ifdef GST_EXT_XV_ENHANCEMENT
  /* 0 or 180 */
  if (xvimagesink->rotate_angle == 0 || xvimagesink->rotate_angle == 2) {
    xvimagesink->render_rect.w = xwindow->width = width;
    xvimagesink->render_rect.h = xwindow->height = height;
  /* 90 or 270 */
  } else {
    xvimagesink->render_rect.w = xwindow->width = height;
    xvimagesink->render_rect.h = xwindow->height = width;
  }

  XGetWindowAttributes(xvimagesink->xcontext->disp, xvimagesink->xcontext->root, &root_attr);

  if (xwindow->width > root_attr.width) {
    GST_INFO_OBJECT(xvimagesink, "Width[%d] is bigger than Max width. Set Max[%d].",
                                 xwindow->width, root_attr.width);
    xvimagesink->render_rect.w = xwindow->width = root_attr.width;
  }
  if (xwindow->height > root_attr.height) {
    GST_INFO_OBJECT(xvimagesink, "Height[%d] is bigger than Max Height. Set Max[%d].",
                                 xwindow->height, root_attr.height);
    xvimagesink->render_rect.h = xwindow->height = root_attr.height;
  }
  xwindow->internal = TRUE;

  g_mutex_lock (xvimagesink->x_lock);

  GST_DEBUG_OBJECT( xvimagesink, "window create [%dx%d]", xwindow->width, xwindow->height );

  xwindow->win = XCreateSimpleWindow(xvimagesink->xcontext->disp,
                                     xvimagesink->xcontext->root,
                                     0, 0, xwindow->width, xwindow->height,
                                     0, 0, 0);

  xvimagesink->xim_transparenter = make_transparent_image(xvimagesink->xcontext->disp,
                                                          xvimagesink->xcontext->root,
                                                          xwindow->width, xwindow->height);

  /* Make window manager not to change window size as Full screen */
  win_attr.override_redirect = True;
  XChangeWindowAttributes(xvimagesink->xcontext->disp, xwindow->win, CWOverrideRedirect, &win_attr);
#else /* GST_EXT_XV_ENHANCEMENT */
  xvimagesink->render_rect.w = width;
  xvimagesink->render_rect.h = height;

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

  g_mutex_lock (xvimagesink->x_lock);

  xwindow->win = XCreateSimpleWindow (xvimagesink->xcontext->disp,
      xvimagesink->xcontext->root,
      0, 0, width, height, 0, 0, xvimagesink->xcontext->black);
#endif /* GST_EXT_XV_ENHANCEMENT */

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

  /* set application name as a title */
  gst_xvimagesink_xwindow_set_title (xvimagesink, xwindow, NULL);

  if (xvimagesink->handle_events) {
    Atom wm_delete;

    XSelectInput (xvimagesink->xcontext->disp, xwindow->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 (xvimagesink->xcontext->disp,
        "WM_DELETE_WINDOW", True);
    if (wm_delete != None) {
      (void) XSetWMProtocols (xvimagesink->xcontext->disp, xwindow->win,
          &wm_delete, 1);
    }
  }

  xwindow->gc = XCreateGC (xvimagesink->xcontext->disp,
      xwindow->win, 0, &values);

  XMapRaised (xvimagesink->xcontext->disp, xwindow->win);

  XSync (xvimagesink->xcontext->disp, FALSE);

  g_mutex_unlock (xvimagesink->x_lock);

  gst_xvimagesink_xwindow_decorate (xvimagesink, xwindow);

  gst_x_overlay_got_window_handle (GST_X_OVERLAY (xvimagesink), xwindow->win);

  return xwindow;
}

/* This function destroys a GstXWindow */
static void
gst_xvimagesink_xwindow_destroy (GstXvImageSink * xvimagesink,
    GstXWindow * xwindow)
{
  g_return_if_fail (xwindow != NULL);
  g_return_if_fail (GST_IS_XVIMAGESINK (xvimagesink));

  g_mutex_lock (xvimagesink->x_lock);

  /* If we did not create that window we just free the GC and let it live */
  if (xwindow->internal) {
    XDestroyWindow (xvimagesink->xcontext->disp, xwindow->win);
    if (xvimagesink->xim_transparenter) {
      XDestroyImage(xvimagesink->xim_transparenter);
      xvimagesink->xim_transparenter = NULL;
    }
  } else {
    XSelectInput (xvimagesink->xcontext->disp, xwindow->win, 0);
  }

  XFreeGC (xvimagesink->xcontext->disp, xwindow->gc);

  XSync (xvimagesink->xcontext->disp, FALSE);

  g_mutex_unlock (xvimagesink->x_lock);

  g_free (xwindow);
}

#ifdef GST_EXT_XV_ENHANCEMENT
/* This function destroys a GstXWindow */
static void
gst_xvimagesink_xpixmap_destroy (GstXvImageSink * xvimagesink,
    GstXPixmap * xpixmap)
{
  g_return_if_fail (xpixmap != NULL);
  g_return_if_fail (GST_IS_XVIMAGESINK (xvimagesink));

  g_mutex_lock (xvimagesink->x_lock);

  XSelectInput (xvimagesink->xcontext->disp, xpixmap->pixmap, 0);

  XFreeGC (xvimagesink->xcontext->disp, xpixmap->gc);

  XSync (xvimagesink->xcontext->disp, FALSE);

  g_mutex_unlock (xvimagesink->x_lock);

  g_free (xpixmap);
}
#endif /* GST_EXT_XV_ENHANCEMENT */

static void
gst_xvimagesink_xwindow_update_geometry (GstXvImageSink * xvimagesink)
{
#ifdef GST_EXT_XV_ENHANCEMENT
  Window root_window, child_window;
  XWindowAttributes root_attr;

  int cur_win_x = 0;
  int cur_win_y = 0;
  unsigned int cur_win_width = 0;
  unsigned int cur_win_height = 0;
  unsigned int cur_win_border_width = 0;
  unsigned int cur_win_depth = 0;
#else /* GST_EXT_XV_ENHANCEMENT */
  XWindowAttributes attr;
#endif /* GST_EXT_XV_ENHANCEMENT */

  g_return_if_fail (GST_IS_XVIMAGESINK (xvimagesink));

  /* Update the window geometry */
  g_mutex_lock (xvimagesink->x_lock);
  if (G_UNLIKELY (xvimagesink->xwindow == NULL)) {
    g_mutex_unlock (xvimagesink->x_lock);
    return;
  }

#ifdef GST_EXT_XV_ENHANCEMENT
  /* Get root window and size of current window */
  XGetGeometry( xvimagesink->xcontext->disp, xvimagesink->xwindow->win, &root_window,
    &cur_win_x, &cur_win_y, /* relative x, y */
    &cur_win_width, &cur_win_height,
    &cur_win_border_width, &cur_win_depth );

  xvimagesink->xwindow->width = cur_win_width;
  xvimagesink->xwindow->height = cur_win_height;

  /* Get absolute coordinates of current window */
  XTranslateCoordinates( xvimagesink->xcontext->disp,
    xvimagesink->xwindow->win,
    root_window,
    0, 0,
    &cur_win_x, &cur_win_y, // relative x, y to root window == absolute x, y
    &child_window );

  xvimagesink->xwindow->x = cur_win_x;
  xvimagesink->xwindow->y = cur_win_y;

  /* Get size of root window == size of screen */
  XGetWindowAttributes(xvimagesink->xcontext->disp, root_window, &root_attr);

  xvimagesink->scr_w = root_attr.width;
  xvimagesink->scr_h = root_attr.height;

  if (!xvimagesink->have_render_rect) {
    xvimagesink->render_rect.x = xvimagesink->render_rect.y = 0;
    xvimagesink->render_rect.w = cur_win_width;
    xvimagesink->render_rect.h = cur_win_height;
  }

  GST_LOG_OBJECT(xvimagesink, "screen size %dx%d, current window geometry %d,%d,%dx%d, render_rect %d,%d,%dx%d",
    xvimagesink->scr_w, xvimagesink->scr_h,
    xvimagesink->xwindow->x, xvimagesink->xwindow->y,
    xvimagesink->xwindow->width, xvimagesink->xwindow->height,
    xvimagesink->render_rect.x, xvimagesink->render_rect.y,
    xvimagesink->render_rect.w, xvimagesink->render_rect.h);
#else /* GST_EXT_XV_ENHANCEMENT */
  XGetWindowAttributes (xvimagesink->xcontext->disp,
      xvimagesink->xwindow->win, &attr);

  xvimagesink->xwindow->width = attr.width;
  xvimagesink->xwindow->height = attr.height;

  if (!xvimagesink->have_render_rect) {
    xvimagesink->render_rect.x = xvimagesink->render_rect.y = 0;
    xvimagesink->render_rect.w = attr.width;
    xvimagesink->render_rect.h = attr.height;
  }
#endif /* GST_EXT_XV_ENHANCEMENT */

  g_mutex_unlock (xvimagesink->x_lock);
}

static void
gst_xvimagesink_xwindow_clear (GstXvImageSink * xvimagesink,
    GstXWindow * xwindow)
{
  g_return_if_fail (xwindow != NULL);
  g_return_if_fail (GST_IS_XVIMAGESINK (xvimagesink));

  g_mutex_lock (xvimagesink->x_lock);

  XvStopVideo (xvimagesink->xcontext->disp, xvimagesink->xcontext->xv_port_id,
      xwindow->win);
#ifndef GST_EXT_XV_ENHANCEMENT
  /* Preview area is not updated before other UI is updated in the screen. */
  XSetForeground (xvimagesink->xcontext->disp, xwindow->gc,
      xvimagesink->xcontext->black);

  XFillRectangle (xvimagesink->xcontext->disp, xwindow->win, xwindow->gc,
      xvimagesink->render_rect.x, xvimagesink->render_rect.y,
      xvimagesink->render_rect.w, xvimagesink->render_rect.h);
#endif /* GST_EXT_XV_ENHANCEMENT */

  XSync (xvimagesink->xcontext->disp, FALSE);

  g_mutex_unlock (xvimagesink->x_lock);
}

/* This function commits our internal colorbalance settings to our grabbed Xv
   port. If the xcontext is not initialized yet it simply returns */
static void
gst_xvimagesink_update_colorbalance (GstXvImageSink * xvimagesink)
{
  GList *channels = NULL;

  g_return_if_fail (GST_IS_XVIMAGESINK (xvimagesink));

  /* If we haven't initialized the X context we can't update anything */
  if (xvimagesink->xcontext == NULL)
    return;

  /* Don't set the attributes if they haven't been changed, to avoid
   * rounding errors changing the values */
  if (!xvimagesink->cb_changed)
    return;

  /* For each channel of the colorbalance we calculate the correct value
     doing range conversion and then set the Xv port attribute to match our
     values. */
  channels = xvimagesink->xcontext->channels_list;

  while (channels) {
    if (channels->data && GST_IS_COLOR_BALANCE_CHANNEL (channels->data)) {
      GstColorBalanceChannel *channel = NULL;
      Atom prop_atom;
      gint value = 0;
      gdouble convert_coef;

      channel = GST_COLOR_BALANCE_CHANNEL (channels->data);
      g_object_ref (channel);

      /* Our range conversion coef */
      convert_coef = (channel->max_value - channel->min_value) / 2000.0;

      if (g_ascii_strcasecmp (channel->label, "XV_HUE") == 0) {
        value = xvimagesink->hue;
      } else if (g_ascii_strcasecmp (channel->label, "XV_SATURATION") == 0) {
        value = xvimagesink->saturation;
      } else if (g_ascii_strcasecmp (channel->label, "XV_CONTRAST") == 0) {
        value = xvimagesink->contrast;
      } else if (g_ascii_strcasecmp (channel->label, "XV_BRIGHTNESS") == 0) {
        value = xvimagesink->brightness;
      } else {
        g_warning ("got an unknown channel %s", channel->label);
        g_object_unref (channel);
        return;
      }

      /* Committing to Xv port */
      g_mutex_lock (xvimagesink->x_lock);
      prop_atom =
          XInternAtom (xvimagesink->xcontext->disp, channel->label, True);
      if (prop_atom != None) {
        int xv_value;
        xv_value =
            floor (0.5 + (value + 1000) * convert_coef + channel->min_value);
        XvSetPortAttribute (xvimagesink->xcontext->disp,
            xvimagesink->xcontext->xv_port_id, prop_atom, xv_value);
      }
      g_mutex_unlock (xvimagesink->x_lock);

      g_object_unref (channel);
    }
    channels = g_list_next (channels);
  }
}

/* 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. It will also listen for configure events on the window to
   trigger caps renegotiation so on the fly software scaling can work. */
static void
gst_xvimagesink_handle_xevents (GstXvImageSink * xvimagesink)
{
  XEvent e;
  guint pointer_x = 0, pointer_y = 0;
  gboolean pointer_moved = FALSE;
  gboolean exposed = FALSE, configured = FALSE;

  g_return_if_fail (GST_IS_XVIMAGESINK (xvimagesink));

  /* Handle Interaction, produces navigation events */

  /* We get all pointer motion events, only the last position is
     interesting. */
  g_mutex_lock (xvimagesink->flow_lock);
  g_mutex_lock (xvimagesink->x_lock);
  while (XCheckWindowEvent (xvimagesink->xcontext->disp,
          xvimagesink->xwindow->win, PointerMotionMask, &e)) {
    g_mutex_unlock (xvimagesink->x_lock);
    g_mutex_unlock (xvimagesink->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 (xvimagesink->flow_lock);
    g_mutex_lock (xvimagesink->x_lock);
  }
  if (pointer_moved) {
    g_mutex_unlock (xvimagesink->x_lock);
    g_mutex_unlock (xvimagesink->flow_lock);

    GST_DEBUG ("xvimagesink pointer moved over window at %d,%d",
        pointer_x, pointer_y);
    gst_navigation_send_mouse_event (GST_NAVIGATION (xvimagesink),
        "mouse-move", 0, e.xbutton.x, e.xbutton.y);

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

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

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

    switch (e.type) {
      case ButtonPress:
        /* Mouse button pressed over our window. We send upstream
           events for interactivity/navigation */
        GST_DEBUG ("xvimagesink button %d pressed over window at %d,%d",
            e.xbutton.button, e.xbutton.x, e.xbutton.y);
        gst_navigation_send_mouse_event (GST_NAVIGATION (xvimagesink),
            "mouse-button-press", e.xbutton.button, e.xbutton.x, e.xbutton.y);
        break;
      case ButtonRelease:
        /* Mouse button released over our window. We send upstream
           events for interactivity/navigation */
        GST_DEBUG ("xvimagesink button %d released over window at %d,%d",
            e.xbutton.button, e.xbutton.x, e.xbutton.y);
        gst_navigation_send_mouse_event (GST_NAVIGATION (xvimagesink),
            "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 ("xvimagesink key %d pressed over window at %d,%d",
            e.xkey.keycode, e.xkey.x, e.xkey.y);
        g_mutex_lock (xvimagesink->x_lock);
        keysym = XKeycodeToKeysym (xvimagesink->xcontext->disp,
            e.xkey.keycode, 0);
        g_mutex_unlock (xvimagesink->x_lock);
        if (keysym != NoSymbol) {
          char *key_str = NULL;

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

  /* Handle Expose */
  while (XCheckWindowEvent (xvimagesink->xcontext->disp,
          xvimagesink->xwindow->win, ExposureMask | StructureNotifyMask, &e)) {
    switch (e.type) {
      case Expose:
        exposed = TRUE;
        break;
      case ConfigureNotify:
        g_mutex_unlock (xvimagesink->x_lock);
#ifdef GST_EXT_XV_ENHANCEMENT
        GST_INFO_OBJECT (xvimagesink, "Call gst_xvimagesink_xwindow_update_geometry!");
#endif /* GST_EXT_XV_ENHANCEMENT */
        gst_xvimagesink_xwindow_update_geometry (xvimagesink);
        g_mutex_lock (xvimagesink->x_lock);
        configured = TRUE;
        break;
      default:
        break;
    }
  }

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

    gst_xvimagesink_expose (GST_X_OVERLAY (xvimagesink));

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

  /* Handle Display events */
  while (XPending (xvimagesink->xcontext->disp)) {
    XNextEvent (xvimagesink->xcontext->disp, &e);

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

        wm_delete = XInternAtom (xvimagesink->xcontext->disp,
            "WM_DELETE_WINDOW", True);
        if (wm_delete != None && wm_delete == (Atom) e.xclient.data.l[0]) {
          /* Handle window deletion by posting an error on the bus */
          GST_ELEMENT_ERROR (xvimagesink, RESOURCE, NOT_FOUND,
              ("Output window was closed"), (NULL));

          g_mutex_unlock (xvimagesink->x_lock);
          gst_xvimagesink_xwindow_destroy (xvimagesink, xvimagesink->xwindow);
          xvimagesink->xwindow = NULL;
          g_mutex_lock (xvimagesink->x_lock);
        }
        break;
      }
#ifdef GST_EXT_XV_ENHANCEMENT
      case VisibilityNotify:
        if (e.xvisibility.window == xvimagesink->xwindow->win) {
          if (e.xvisibility.state == VisibilityFullyObscured) {
            Atom atom_stream;

            GST_INFO_OBJECT(xvimagesink, "current window is FULLY HIDED");

            xvimagesink->is_hided = TRUE;
            atom_stream = XInternAtom(xvimagesink->xcontext->disp,
                                      "_USER_WM_PORT_ATTRIBUTE_STREAM_OFF", False);
            if (atom_stream != None) {
              if (XvSetPortAttribute(xvimagesink->xcontext->disp,
                                     xvimagesink->xcontext->xv_port_id,
                                     atom_stream, 0) != Success) {
                GST_WARNING_OBJECT(xvimagesink, "STREAM OFF failed");
              }
              XSync(xvimagesink->xcontext->disp, FALSE);
            } else {
              GST_WARNING_OBJECT(xvimagesink, "atom_stream is NONE");
            }
          } else {
            GST_INFO_OBJECT(xvimagesink, "current window is SHOWN");

            if (xvimagesink->is_hided) {
              g_mutex_unlock(xvimagesink->x_lock);
              g_mutex_unlock(xvimagesink->flow_lock);

              xvimagesink->is_hided = FALSE;
              gst_xvimagesink_expose(GST_X_OVERLAY(xvimagesink));

              g_mutex_lock(xvimagesink->flow_lock);
              g_mutex_lock(xvimagesink->x_lock);
            } else {
              GST_INFO_OBJECT(xvimagesink, "current window is not HIDED, skip this event");
            }
          }
        }
        break;
#endif /* GST_EXT_XV_ENHANCEMENT */
      default:
        break;
    }
  }

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

static void
gst_lookup_xv_port_from_adaptor (GstXContext * xcontext,
    XvAdaptorInfo * adaptors, int adaptor_no)
{
  gint j;
  gint res;

  /* Do we support XvImageMask ? */
  if (!(adaptors[adaptor_no].type & XvImageMask)) {
    GST_DEBUG ("XV Adaptor %s has no support for XvImageMask",
        adaptors[adaptor_no].name);
    return;
  }

  /* We found such an adaptor, looking for an available port */
  for (j = 0; j < adaptors[adaptor_no].num_ports && !xcontext->xv_port_id; j++) {
    /* We try to grab the port */
    res = XvGrabPort (xcontext->disp, adaptors[adaptor_no].base_id + j, 0);
    if (Success == res) {
      xcontext->xv_port_id = adaptors[adaptor_no].base_id + j;
      GST_DEBUG ("XV Adaptor %s with %ld ports", adaptors[adaptor_no].name,
          adaptors[adaptor_no].num_ports);
    } else {
      GST_DEBUG ("GrabPort %d for XV Adaptor %s failed: %d", j,
          adaptors[adaptor_no].name, res);
    }
  }
}

/* This function generates a caps with all supported format by the first
   Xv grabable port we find. We store each one of the supported formats in a
   format list and append the format to a newly created caps that we return
   If this function does not return NULL because of an error, it also grabs
   the port via XvGrabPort */
static GstCaps *
gst_xvimagesink_get_xv_support (GstXvImageSink * xvimagesink,
    GstXContext * xcontext)
{
  gint i;
  XvAdaptorInfo *adaptors;
  gint nb_formats;
  XvImageFormatValues *formats = NULL;
  guint nb_encodings;
  XvEncodingInfo *encodings = NULL;
  gulong max_w = G_MAXINT, max_h = G_MAXINT;
  GstCaps *caps = NULL;
  GstCaps *rgb_caps = NULL;

  g_return_val_if_fail (xcontext != NULL, NULL);

  /* First let's check that XVideo extension is available */
  if (!XQueryExtension (xcontext->disp, "XVideo", &i, &i, &i)) {
    GST_ELEMENT_ERROR (xvimagesink, RESOURCE, SETTINGS,
        ("Could not initialise Xv output"),
        ("XVideo extension is not available"));
    return NULL;
  }

  /* Then we get adaptors list */
  if (Success != XvQueryAdaptors (xcontext->disp, xcontext->root,
          &xcontext->nb_adaptors, &adaptors)) {
    GST_ELEMENT_ERROR (xvimagesink, RESOURCE, SETTINGS,
        ("Could not initialise Xv output"),
        ("Failed getting XV adaptors list"));
    return NULL;
  }

  xcontext->xv_port_id = 0;

  GST_DEBUG ("Found %u XV adaptor(s)", xcontext->nb_adaptors);

  xcontext->adaptors =
      (gchar **) g_malloc0 (xcontext->nb_adaptors * sizeof (gchar *));

  /* Now fill up our adaptor name array */
  for (i = 0; i < xcontext->nb_adaptors; i++) {
    xcontext->adaptors[i] = g_strdup (adaptors[i].name);
  }

  if (xvimagesink->adaptor_no >= 0 &&
      xvimagesink->adaptor_no < xcontext->nb_adaptors) {
    /* Find xv port from user defined adaptor */
    gst_lookup_xv_port_from_adaptor (xcontext, adaptors,
        xvimagesink->adaptor_no);
  }

  if (!xcontext->xv_port_id) {
    /* Now search for an adaptor that supports XvImageMask */
    for (i = 0; i < xcontext->nb_adaptors && !xcontext->xv_port_id; i++) {
      gst_lookup_xv_port_from_adaptor (xcontext, adaptors, i);
      xvimagesink->adaptor_no = i;
    }
  }

  XvFreeAdaptorInfo (adaptors);

  if (!xcontext->xv_port_id) {
    xvimagesink->adaptor_no = -1;
    GST_ELEMENT_ERROR (xvimagesink, RESOURCE, BUSY,
        ("Could not initialise Xv output"), ("No port available"));
    return NULL;
  }

  /* Set XV_AUTOPAINT_COLORKEY and XV_DOUBLE_BUFFER and XV_COLORKEY */
  {
    int count, todo = 3;
    XvAttribute *const attr = XvQueryPortAttributes (xcontext->disp,
        xcontext->xv_port_id, &count);
    static const char autopaint[] = "XV_AUTOPAINT_COLORKEY";
    static const char dbl_buffer[] = "XV_DOUBLE_BUFFER";
    static const char colorkey[] = "XV_COLORKEY";

    GST_DEBUG_OBJECT (xvimagesink, "Checking %d Xv port attributes", count);

    xvimagesink->have_autopaint_colorkey = FALSE;
    xvimagesink->have_double_buffer = FALSE;
    xvimagesink->have_colorkey = FALSE;

    for (i = 0; ((i < count) && todo); i++)
      if (!strcmp (attr[i].name, autopaint)) {
        const Atom atom = XInternAtom (xcontext->disp, autopaint, False);

        /* turn on autopaint colorkey */
        XvSetPortAttribute (xcontext->disp, xcontext->xv_port_id, atom,
            (xvimagesink->autopaint_colorkey ? 1 : 0));
        todo--;
        xvimagesink->have_autopaint_colorkey = TRUE;
      } else if (!strcmp (attr[i].name, dbl_buffer)) {
        const Atom atom = XInternAtom (xcontext->disp, dbl_buffer, False);

        XvSetPortAttribute (xcontext->disp, xcontext->xv_port_id, atom,
            (xvimagesink->double_buffer ? 1 : 0));
        todo--;
        xvimagesink->have_double_buffer = TRUE;
      } else if (!strcmp (attr[i].name, colorkey)) {
        /* Set the colorkey, default is something that is dark but hopefully
         * won't randomly appear on the screen elsewhere (ie not black or greys)
         * can be overridden by setting "colorkey" property
         */
        const Atom atom = XInternAtom (xcontext->disp, colorkey, False);
        guint32 ckey = 0;
        gboolean set_attr = TRUE;
        guint cr, cg, cb;

        /* set a colorkey in the right format RGB565/RGB888
         * We only handle these 2 cases, because they're the only types of
         * devices we've encountered. If we don't recognise it, leave it alone
         */
        cr = (xvimagesink->colorkey >> 16);
        cg = (xvimagesink->colorkey >> 8) & 0xFF;
        cb = (xvimagesink->colorkey) & 0xFF;
        switch (xcontext->depth) {
          case 16:             /* RGB 565 */
            cr >>= 3;
            cg >>= 2;
            cb >>= 3;
            ckey = (cr << 11) | (cg << 5) | cb;
            break;
          case 24:
          case 32:             /* RGB 888 / ARGB 8888 */
            ckey = (cr << 16) | (cg << 8) | cb;
            break;
          default:
            GST_DEBUG_OBJECT (xvimagesink,
                "Unknown bit depth %d for Xv Colorkey - not adjusting",
                xcontext->depth);
            set_attr = FALSE;
            break;
        }

        if (set_attr) {
          ckey = CLAMP (ckey, (guint32) attr[i].min_value,
              (guint32) attr[i].max_value);
          GST_LOG_OBJECT (xvimagesink,
              "Setting color key for display depth %d to 0x%x",
              xcontext->depth, ckey);

          XvSetPortAttribute (xcontext->disp, xcontext->xv_port_id, atom,
              (gint) ckey);
        }
        todo--;
        xvimagesink->have_colorkey = TRUE;
      }

    XFree (attr);
  }

  /* Get the list of encodings supported by the adapter and look for the
   * XV_IMAGE encoding so we can determine the maximum width and height
   * supported */
  XvQueryEncodings (xcontext->disp, xcontext->xv_port_id, &nb_encodings,
      &encodings);

  for (i = 0; i < nb_encodings; i++) {
    GST_LOG_OBJECT (xvimagesink,
        "Encoding %d, name %s, max wxh %lux%lu rate %d/%d",
        i, encodings[i].name, encodings[i].width, encodings[i].height,
        encodings[i].rate.numerator, encodings[i].rate.denominator);
    if (strcmp (encodings[i].name, "XV_IMAGE") == 0) {
      max_w = encodings[i].width;
      max_h = encodings[i].height;
#ifdef GST_EXT_XV_ENHANCEMENT
      xvimagesink->scr_w = max_w;
      xvimagesink->scr_h = max_h;
#endif /* GST_EXT_XV_ENHANCEMENT */
    }
  }

  XvFreeEncodingInfo (encodings);

  /* We get all image formats supported by our port */
  formats = XvListImageFormats (xcontext->disp,
      xcontext->xv_port_id, &nb_formats);
  caps = gst_caps_new_empty ();
  for (i = 0; i < nb_formats; i++) {
    GstCaps *format_caps = NULL;
    gboolean is_rgb_format = FALSE;

    /* We set the image format of the xcontext to an existing one. This
       is just some valid image format for making our xshm calls check before
       caps negotiation really happens. */
    xcontext->im_format = formats[i].id;

    switch (formats[i].type) {
      case XvRGB:
      {
        XvImageFormatValues *fmt = &(formats[i]);
        gint endianness = G_BIG_ENDIAN;

        if (fmt->byte_order == LSBFirst) {
          /* our caps system handles 24/32bpp RGB as big-endian. */
          if (fmt->bits_per_pixel == 24 || fmt->bits_per_pixel == 32) {
            fmt->red_mask = GUINT32_TO_BE (fmt->red_mask);
            fmt->green_mask = GUINT32_TO_BE (fmt->green_mask);
            fmt->blue_mask = GUINT32_TO_BE (fmt->blue_mask);

            if (fmt->bits_per_pixel == 24) {
              fmt->red_mask >>= 8;
              fmt->green_mask >>= 8;
              fmt->blue_mask >>= 8;
            }
          } else
            endianness = G_LITTLE_ENDIAN;
        }

        format_caps = gst_caps_new_simple ("video/x-raw-rgb",
            "endianness", G_TYPE_INT, endianness,
            "depth", G_TYPE_INT, fmt->depth,
            "bpp", G_TYPE_INT, fmt->bits_per_pixel,
            "red_mask", G_TYPE_INT, fmt->red_mask,
            "green_mask", G_TYPE_INT, fmt->green_mask,
            "blue_mask", G_TYPE_INT, fmt->blue_mask,
            "width", GST_TYPE_INT_RANGE, 1, max_w,
            "height", GST_TYPE_INT_RANGE, 1, max_h,
            "framerate", GST_TYPE_FRACTION_RANGE, 0, 1, G_MAXINT, 1, NULL);

        is_rgb_format = TRUE;
        break;
      }
      case XvYUV:
        format_caps = gst_caps_new_simple ("video/x-raw-yuv",
            "format", GST_TYPE_FOURCC, formats[i].id,
            "width", GST_TYPE_INT_RANGE, 1, max_w,
            "height", GST_TYPE_INT_RANGE, 1, max_h,
            "framerate", GST_TYPE_FRACTION_RANGE, 0, 1, G_MAXINT, 1, NULL);
        break;
      default:
        g_assert_not_reached ();
        break;
    }

    if (format_caps) {
      GstXvImageFormat *format = NULL;

      format = g_new0 (GstXvImageFormat, 1);
      if (format) {
        format->format = formats[i].id;
        format->caps = gst_caps_copy (format_caps);
        xcontext->formats_list = g_list_append (xcontext->formats_list, format);
      }

      if (is_rgb_format) {
        if (rgb_caps == NULL)
          rgb_caps = format_caps;
        else
          gst_caps_append (rgb_caps, format_caps);
      } else
        gst_caps_append (caps, format_caps);
    }
  }

  /* Collected all caps into either the caps or rgb_caps structures.
   * Append rgb_caps on the end of YUV, so that YUV is always preferred */
  if (rgb_caps)
    gst_caps_append (caps, rgb_caps);

  if (formats)
    XFree (formats);

  GST_DEBUG ("Generated the following caps: %" GST_PTR_FORMAT, caps);

  if (gst_caps_is_empty (caps)) {
    gst_caps_unref (caps);
    XvUngrabPort (xcontext->disp, xcontext->xv_port_id, 0);
    GST_ELEMENT_ERROR (xvimagesink, STREAM, WRONG_TYPE, (NULL),
        ("No supported format found"));
    return NULL;
  }

  return caps;
}

static gpointer
gst_xvimagesink_event_thread (GstXvImageSink * xvimagesink)
{
  g_return_val_if_fail (GST_IS_XVIMAGESINK (xvimagesink), NULL);

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

    if (xvimagesink->xwindow) {
      gst_xvimagesink_handle_xevents (xvimagesink);
    }
    /* FIXME: do we want to align this with the framerate or anything else? */
    g_usleep (G_USEC_PER_SEC / 20);

    GST_OBJECT_LOCK (xvimagesink);
  }
  GST_OBJECT_UNLOCK (xvimagesink);

  return NULL;
}

static void
gst_xvimagesink_manage_event_thread (GstXvImageSink * xvimagesink)
{
  GThread *thread = NULL;

  /* don't start the thread too early */
  if (xvimagesink->xcontext == NULL) {
    return;
  }

  GST_OBJECT_LOCK (xvimagesink);
  if (xvimagesink->handle_expose || xvimagesink->handle_events) {
    if (!xvimagesink->event_thread) {
      /* Setup our event listening thread */
      GST_DEBUG_OBJECT (xvimagesink, "run xevent thread, expose %d, events %d",
          xvimagesink->handle_expose, xvimagesink->handle_events);
      xvimagesink->running = TRUE;
#if !GLIB_CHECK_VERSION (2, 31, 0)
      xvimagesink->event_thread = g_thread_create (
          (GThreadFunc) gst_xvimagesink_event_thread, xvimagesink, TRUE, NULL);
#else
      xvimagesink->event_thread = g_thread_try_new ("xvimagesink-events",
          (GThreadFunc) gst_xvimagesink_event_thread, xvimagesink, NULL);
#endif
    }
  } else {
    if (xvimagesink->event_thread) {
      GST_DEBUG_OBJECT (xvimagesink, "stop xevent thread, expose %d, events %d",
          xvimagesink->handle_expose, xvimagesink->handle_events);
      xvimagesink->running = FALSE;
      /* grab thread and mark it as NULL */
      thread = xvimagesink->event_thread;
      xvimagesink->event_thread = NULL;
    }
  }
  GST_OBJECT_UNLOCK (xvimagesink);

  /* Wait for our event thread to finish */
  if (thread)
    g_thread_join (thread);

}


#ifdef GST_EXT_XV_ENHANCEMENT
/**
 * gst_xvimagesink_prepare_xid:
 * @overlay: a #GstXOverlay which does not yet have an XWindow or XPixmap.
 *
 * This will post a "prepare-xid" element message with video size and display size on the bus
 * to give applications an opportunity to call
 * gst_x_overlay_set_xwindow_id() before a plugin creates its own
 * window or pixmap.
 *
 * This function should only be used by video overlay plugin developers.
 */
static void
gst_xvimagesink_prepare_xid (GstXOverlay * overlay)
{
  GstStructure *s;
  GstMessage *msg;

  g_return_if_fail (overlay != NULL);
  g_return_if_fail (GST_IS_X_OVERLAY (overlay));

  GstXvImageSink *xvimagesink;
  xvimagesink = GST_XVIMAGESINK (GST_OBJECT (overlay));

  GST_DEBUG ("post \"prepare-xid\" element message with video-width(%d), video-height(%d), display-width(%d), display-height(%d)",
        GST_VIDEO_SINK_WIDTH (xvimagesink), GST_VIDEO_SINK_HEIGHT (xvimagesink), xvimagesink->xcontext->width, xvimagesink->xcontext->height);

  GST_LOG_OBJECT (GST_OBJECT (overlay), "prepare xid");
  s = gst_structure_new ("prepare-xid",
        "video-width", G_TYPE_INT, GST_VIDEO_SINK_WIDTH (xvimagesink),
        "video-height", G_TYPE_INT, GST_VIDEO_SINK_HEIGHT (xvimagesink),
        "display-width", G_TYPE_INT, xvimagesink->xcontext->width,
        "display-height", G_TYPE_INT, xvimagesink->xcontext->height,
        NULL);
  msg = gst_message_new_element (GST_OBJECT (overlay), s);
  gst_element_post_message (GST_ELEMENT (overlay), msg);
}
#endif /* GST_EXT_XV_ENHANCEMENT */


/* This function calculates the pixel aspect ratio based on the properties
 * in the xcontext structure and stores it there. */
static void
gst_xvimagesink_calculate_pixel_aspect_ratio (GstXContext * xcontext)
{
  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 i;
  gint index;
  gdouble ratio;
  gdouble delta;

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

  /* 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) (xcontext->widthmm * xcontext->height)
      / (xcontext->heightmm * xcontext->width);

  /* DirectFB's X in 720x576 reports the physical dimensions wrong, so
   * override here */
  if (xcontext->width == 720 && xcontext->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]);

  g_free (xcontext->par);
  xcontext->par = g_new0 (GValue, 1);
  g_value_init (xcontext->par, GST_TYPE_FRACTION);
  gst_value_set_fraction (xcontext->par, par[index][0], par[index][1]);
  GST_DEBUG ("set xcontext PAR to %d/%d",
      gst_value_get_fraction_numerator (xcontext->par),
      gst_value_get_fraction_denominator (xcontext->par));
}

/* This function gets the X Display and global info about it. Everything is
   stored in our object and will be cleaned when the object is disposed. Note
   here that caps for supported format are generated without any window or
   image creation */
static GstXContext *
gst_xvimagesink_xcontext_get (GstXvImageSink * xvimagesink)
{
  GstXContext *xcontext = NULL;
  XPixmapFormatValues *px_formats = NULL;
  gint nb_formats = 0, i, j, N_attr;
  XvAttribute *xv_attr;
  Atom prop_atom;
  const char *channels[4] = { "XV_HUE", "XV_SATURATION",
    "XV_BRIGHTNESS", "XV_CONTRAST"
  };

  g_return_val_if_fail (GST_IS_XVIMAGESINK (xvimagesink), NULL);

  xcontext = g_new0 (GstXContext, 1);
  xcontext->im_format = 0;

  g_mutex_lock (xvimagesink->x_lock);

  xcontext->disp = XOpenDisplay (xvimagesink->display_name);

  if (!xcontext->disp) {
    g_mutex_unlock (xvimagesink->x_lock);
    g_free (xcontext);
    GST_ELEMENT_ERROR (xvimagesink, RESOURCE, WRITE,
        ("Could not initialise Xv output"), ("Could not open display"));
    return NULL;
  }

  xcontext->screen = DefaultScreenOfDisplay (xcontext->disp);
  xcontext->screen_num = DefaultScreen (xcontext->disp);
  xcontext->visual = DefaultVisual (xcontext->disp, xcontext->screen_num);
  xcontext->root = DefaultRootWindow (xcontext->disp);
  xcontext->white = XWhitePixel (xcontext->disp, xcontext->screen_num);
  xcontext->black = XBlackPixel (xcontext->disp, xcontext->screen_num);
  xcontext->depth = DefaultDepthOfScreen (xcontext->screen);

  xcontext->width = DisplayWidth (xcontext->disp, xcontext->screen_num);
  xcontext->height = DisplayHeight (xcontext->disp, xcontext->screen_num);
  xcontext->widthmm = DisplayWidthMM (xcontext->disp, xcontext->screen_num);
  xcontext->heightmm = DisplayHeightMM (xcontext->disp, xcontext->screen_num);

  GST_DEBUG_OBJECT (xvimagesink, "X reports %dx%d pixels and %d mm x %d mm",
      xcontext->width, xcontext->height, xcontext->widthmm, xcontext->heightmm);

  gst_xvimagesink_calculate_pixel_aspect_ratio (xcontext);
  /* We get supported pixmap formats at supported depth */
  px_formats = XListPixmapFormats (xcontext->disp, &nb_formats);

  if (!px_formats) {
    XCloseDisplay (xcontext->disp);
    g_mutex_unlock (xvimagesink->x_lock);
    g_free (xcontext->par);
    g_free (xcontext);
    GST_ELEMENT_ERROR (xvimagesink, RESOURCE, SETTINGS,
        ("Could not initialise Xv output"), ("Could not get pixel formats"));
    return NULL;
  }

  /* We get bpp value corresponding to our running depth */
  for (i = 0; i < nb_formats; i++) {
    if (px_formats[i].depth == xcontext->depth)
      xcontext->bpp = px_formats[i].bits_per_pixel;
  }

  XFree (px_formats);

  xcontext->endianness =
      (ImageByteOrder (xcontext->disp) ==
      LSBFirst) ? G_LITTLE_ENDIAN : G_BIG_ENDIAN;

  /* our caps system handles 24/32bpp RGB as big-endian. */
  if ((xcontext->bpp == 24 || xcontext->bpp == 32) &&
      xcontext->endianness == G_LITTLE_ENDIAN) {
    xcontext->endianness = G_BIG_ENDIAN;
    xcontext->visual->red_mask = GUINT32_TO_BE (xcontext->visual->red_mask);
    xcontext->visual->green_mask = GUINT32_TO_BE (xcontext->visual->green_mask);
    xcontext->visual->blue_mask = GUINT32_TO_BE (xcontext->visual->blue_mask);
    if (xcontext->bpp == 24) {
      xcontext->visual->red_mask >>= 8;
      xcontext->visual->green_mask >>= 8;
      xcontext->visual->blue_mask >>= 8;
    }
  }

  xcontext->caps = gst_xvimagesink_get_xv_support (xvimagesink, xcontext);

  if (!xcontext->caps) {
    XCloseDisplay (xcontext->disp);
    g_mutex_unlock (xvimagesink->x_lock);
    g_free (xcontext->par);
    g_free (xcontext);
    /* GST_ELEMENT_ERROR is thrown by gst_xvimagesink_get_xv_support */
    return NULL;
  }
#ifdef HAVE_XSHM
  /* Search for XShm extension support */
  if (XShmQueryExtension (xcontext->disp) &&
      gst_xvimagesink_check_xshm_calls (xcontext)) {
    xcontext->use_xshm = TRUE;
    GST_DEBUG ("xvimagesink is using XShm extension");
  } else
#endif /* HAVE_XSHM */
  {
    xcontext->use_xshm = FALSE;
    GST_DEBUG ("xvimagesink is not using XShm extension");
  }

  xv_attr = XvQueryPortAttributes (xcontext->disp,
      xcontext->xv_port_id, &N_attr);


  /* Generate the channels list */
  for (i = 0; i < (sizeof (channels) / sizeof (char *)); i++) {
    XvAttribute *matching_attr = NULL;

    /* Retrieve the property atom if it exists. If it doesn't exist,
     * the attribute itself must not either, so we can skip */
    prop_atom = XInternAtom (xcontext->disp, channels[i], True);
    if (prop_atom == None)
      continue;

    if (xv_attr != NULL) {
      for (j = 0; j < N_attr && matching_attr == NULL; ++j)
        if (!g_ascii_strcasecmp (channels[i], xv_attr[j].name))
          matching_attr = xv_attr + j;
    }

    if (matching_attr) {
      GstColorBalanceChannel *channel;

      channel = g_object_new (GST_TYPE_COLOR_BALANCE_CHANNEL, NULL);
      channel->label = g_strdup (channels[i]);
      channel->min_value = matching_attr->min_value;
      channel->max_value = matching_attr->max_value;

      xcontext->channels_list = g_list_append (xcontext->channels_list,
          channel);

      /* If the colorbalance settings have not been touched we get Xv values
         as defaults and update our internal variables */
      if (!xvimagesink->cb_changed) {
        gint val;

        XvGetPortAttribute (xcontext->disp, xcontext->xv_port_id,
            prop_atom, &val);
        /* Normalize val to [-1000, 1000] */
        val = floor (0.5 + -1000 + 2000 * (val - channel->min_value) /
            (double) (channel->max_value - channel->min_value));

        if (!g_ascii_strcasecmp (channels[i], "XV_HUE"))
          xvimagesink->hue = val;
        else if (!g_ascii_strcasecmp (channels[i], "XV_SATURATION"))
          xvimagesink->saturation = val;
        else if (!g_ascii_strcasecmp (channels[i], "XV_BRIGHTNESS"))
          xvimagesink->brightness = val;
        else if (!g_ascii_strcasecmp (channels[i], "XV_CONTRAST"))
          xvimagesink->contrast = val;
      }
    }
  }

  if (xv_attr)
    XFree (xv_attr);

#ifdef GST_EXT_XV_ENHANCEMENT
  set_display_mode(xcontext, xvimagesink->display_mode);
#endif /* GST_EXT_XV_ENHANCEMENT */

  g_mutex_unlock (xvimagesink->x_lock);

  return xcontext;
}

/* This function cleans the X context. Closing the Display, releasing the XV
   port and unrefing the caps for supported formats. */
static void
gst_xvimagesink_xcontext_clear (GstXvImageSink * xvimagesink)
{
  GList *formats_list, *channels_list;
  GstXContext *xcontext;
  gint i = 0;

  g_return_if_fail (GST_IS_XVIMAGESINK (xvimagesink));

  GST_OBJECT_LOCK (xvimagesink);
  if (xvimagesink->xcontext == NULL) {
    GST_OBJECT_UNLOCK (xvimagesink);
    return;
  }

  /* Take the XContext from the sink and clean it up */
  xcontext = xvimagesink->xcontext;
  xvimagesink->xcontext = NULL;

  GST_OBJECT_UNLOCK (xvimagesink);


  formats_list = xcontext->formats_list;

  while (formats_list) {
    GstXvImageFormat *format = formats_list->data;

    gst_caps_unref (format->caps);
    g_free (format);
    formats_list = g_list_next (formats_list);
  }

  if (xcontext->formats_list)
    g_list_free (xcontext->formats_list);

  channels_list = xcontext->channels_list;

  while (channels_list) {
    GstColorBalanceChannel *channel = channels_list->data;

    g_object_unref (channel);
    channels_list = g_list_next (channels_list);
  }

  if (xcontext->channels_list)
    g_list_free (xcontext->channels_list);

  gst_caps_unref (xcontext->caps);
  if (xcontext->last_caps)
    gst_caps_replace (&xcontext->last_caps, NULL);

  for (i = 0; i < xcontext->nb_adaptors; i++) {
    g_free (xcontext->adaptors[i]);
  }

  g_free (xcontext->adaptors);

  g_free (xcontext->par);

  g_mutex_lock (xvimagesink->x_lock);

  GST_DEBUG_OBJECT (xvimagesink, "Closing display and freeing X Context");

  XvUngrabPort (xcontext->disp, xcontext->xv_port_id, 0);

  XCloseDisplay (xcontext->disp);

  g_mutex_unlock (xvimagesink->x_lock);

  g_free (xcontext);
}

static void
gst_xvimagesink_imagepool_clear (GstXvImageSink * xvimagesink)
{
  g_mutex_lock (xvimagesink->pool_lock);

  while (xvimagesink->image_pool) {
    GstXvImageBuffer *xvimage = xvimagesink->image_pool->data;

    xvimagesink->image_pool = g_slist_delete_link (xvimagesink->image_pool,
        xvimagesink->image_pool);
    gst_xvimage_buffer_free (xvimage);
  }

  g_mutex_unlock (xvimagesink->pool_lock);
}

/* Element stuff */

/* This function tries to get a format matching with a given caps in the
   supported list of formats we generated in gst_xvimagesink_get_xv_support */
static gint
gst_xvimagesink_get_format_from_caps (GstXvImageSink * xvimagesink,
    GstCaps * caps)
{
  GList *list = NULL;

  g_return_val_if_fail (GST_IS_XVIMAGESINK (xvimagesink), 0);

  list = xvimagesink->xcontext->formats_list;

  while (list) {
    GstXvImageFormat *format = list->data;

    if (format) {
      if (gst_caps_can_intersect (caps, format->caps)) {
        return format->format;
      }
    }
    list = g_list_next (list);
  }

  return -1;
}

static GstCaps *
gst_xvimagesink_getcaps (GstBaseSink * bsink)
{
  GstXvImageSink *xvimagesink;

  xvimagesink = GST_XVIMAGESINK (bsink);

  if (xvimagesink->xcontext)
    return gst_caps_ref (xvimagesink->xcontext->caps);

  return
      gst_caps_copy (gst_pad_get_pad_template_caps (GST_VIDEO_SINK_PAD
          (xvimagesink)));
}

static gboolean
gst_xvimagesink_setcaps (GstBaseSink * bsink, GstCaps * caps)
{
  GstXvImageSink *xvimagesink;
  GstStructure *structure;
  guint32 im_format = 0;
  gboolean ret;
  gint video_width, video_height;
  gint disp_x, disp_y;
  gint disp_width, disp_height;
  gint video_par_n, video_par_d;        /* video's PAR */
  gint display_par_n, display_par_d;    /* display's PAR */
  const GValue *caps_par;
  const GValue *caps_disp_reg;
  const GValue *fps;
  guint num, den;
#ifdef GST_EXT_XV_ENHANCEMENT
  gboolean enable_last_buffer;
#endif /* #ifdef GST_EXT_XV_ENHANCEMENT */

  xvimagesink = GST_XVIMAGESINK (bsink);

  GST_DEBUG_OBJECT (xvimagesink,
      "In setcaps. Possible caps %" GST_PTR_FORMAT ", setting caps %"
      GST_PTR_FORMAT, xvimagesink->xcontext->caps, caps);

  if (!gst_caps_can_intersect (xvimagesink->xcontext->caps, caps))
    goto incompatible_caps;

  structure = gst_caps_get_structure (caps, 0);
  ret = gst_structure_get_int (structure, "width", &video_width);
  ret &= gst_structure_get_int (structure, "height", &video_height);
  fps = gst_structure_get_value (structure, "framerate");
  ret &= (fps != NULL);

  if (!ret)
    goto incomplete_caps;

#ifdef GST_EXT_XV_ENHANCEMENT
  xvimagesink->aligned_width = video_width;
  xvimagesink->aligned_height = video_height;

  /* get enable-last-buffer */
  g_object_get(G_OBJECT(xvimagesink), "enable-last-buffer", &enable_last_buffer, NULL);
  GST_INFO_OBJECT(xvimagesink, "current enable-last-buffer : %d", enable_last_buffer);

  /* flush if enable-last-buffer is TRUE */
  if (enable_last_buffer) {
    GST_INFO_OBJECT(xvimagesink, "flush last-buffer");
    g_object_set(G_OBJECT(xvimagesink), "enable-last-buffer", FALSE, NULL);
    g_object_set(G_OBJECT(xvimagesink), "enable-last-buffer", TRUE, NULL);
  }
#endif /* GST_EXT_XV_ENHANCEMENT */

  xvimagesink->fps_n = gst_value_get_fraction_numerator (fps);
  xvimagesink->fps_d = gst_value_get_fraction_denominator (fps);

  xvimagesink->video_width = video_width;
  xvimagesink->video_height = video_height;

  im_format = gst_xvimagesink_get_format_from_caps (xvimagesink, caps);
  if (im_format == -1)
    goto invalid_format;

  /* get aspect ratio from caps if it's present, and
   * convert video width and height to a display width and height
   * using wd / hd = wv / hv * PARv / PARd */

  /* get video's PAR */
  caps_par = gst_structure_get_value (structure, "pixel-aspect-ratio");
  if (caps_par) {
    video_par_n = gst_value_get_fraction_numerator (caps_par);
    video_par_d = gst_value_get_fraction_denominator (caps_par);
  } else {
    video_par_n = 1;
    video_par_d = 1;
  }
  /* get display's PAR */
  if (xvimagesink->par) {
    display_par_n = gst_value_get_fraction_numerator (xvimagesink->par);
    display_par_d = gst_value_get_fraction_denominator (xvimagesink->par);
  } else {
    display_par_n = 1;
    display_par_d = 1;
  }

  /* get the display region */
  caps_disp_reg = gst_structure_get_value (structure, "display-region");
  if (caps_disp_reg) {
    disp_x = g_value_get_int (gst_value_array_get_value (caps_disp_reg, 0));
    disp_y = g_value_get_int (gst_value_array_get_value (caps_disp_reg, 1));
    disp_width = g_value_get_int (gst_value_array_get_value (caps_disp_reg, 2));
    disp_height =
        g_value_get_int (gst_value_array_get_value (caps_disp_reg, 3));
  } else {
    disp_x = disp_y = 0;
    disp_width = video_width;
    disp_height = video_height;
  }

  if (!gst_video_calculate_display_ratio (&num, &den, video_width,
          video_height, video_par_n, video_par_d, display_par_n, display_par_d))
    goto no_disp_ratio;

  xvimagesink->disp_x = disp_x;
  xvimagesink->disp_y = disp_y;
  xvimagesink->disp_width = disp_width;
  xvimagesink->disp_height = disp_height;

  GST_DEBUG_OBJECT (xvimagesink,
      "video width/height: %dx%d, calculated display ratio: %d/%d",
      video_width, video_height, num, den);

  /* now find a width x height that respects this display ratio.
   * prefer those that have one of w/h the same as the incoming video
   * using wd / hd = num / den */

  /* start with same height, because of interlaced video */
  /* check hd / den is an integer scale factor, and scale wd with the PAR */
  if (video_height % den == 0) {
    GST_DEBUG_OBJECT (xvimagesink, "keeping video height");
    GST_VIDEO_SINK_WIDTH (xvimagesink) = (guint)
        gst_util_uint64_scale_int (video_height, num, den);
    GST_VIDEO_SINK_HEIGHT (xvimagesink) = video_height;
  } else if (video_width % num == 0) {
    GST_DEBUG_OBJECT (xvimagesink, "keeping video width");
    GST_VIDEO_SINK_WIDTH (xvimagesink) = video_width;
    GST_VIDEO_SINK_HEIGHT (xvimagesink) = (guint)
        gst_util_uint64_scale_int (video_width, den, num);
  } else {
    GST_DEBUG_OBJECT (xvimagesink, "approximating while keeping video height");
    GST_VIDEO_SINK_WIDTH (xvimagesink) = (guint)
        gst_util_uint64_scale_int (video_height, num, den);
    GST_VIDEO_SINK_HEIGHT (xvimagesink) = video_height;
  }
  GST_DEBUG_OBJECT (xvimagesink, "scaling to %dx%d",
      GST_VIDEO_SINK_WIDTH (xvimagesink), GST_VIDEO_SINK_HEIGHT (xvimagesink));

  /* Notify application to set xwindow id now */
  g_mutex_lock (xvimagesink->flow_lock);
#ifdef GST_EXT_XV_ENHANCEMENT
  if (!xvimagesink->xwindow && !xvimagesink->get_pixmap_cb) {
    g_mutex_unlock (xvimagesink->flow_lock);
    gst_xvimagesink_prepare_xid (GST_X_OVERLAY (xvimagesink));
#else
  if (!xvimagesink->xwindow) {
    g_mutex_unlock (xvimagesink->flow_lock);
    gst_x_overlay_prepare_xwindow_id (GST_X_OVERLAY (xvimagesink));
#endif
  } else {
    g_mutex_unlock (xvimagesink->flow_lock);
  }

  /* Creating our window and our image with the display size in pixels */
  if (GST_VIDEO_SINK_WIDTH (xvimagesink) <= 0 ||
      GST_VIDEO_SINK_HEIGHT (xvimagesink) <= 0)
    goto no_display_size;

  g_mutex_lock (xvimagesink->flow_lock);
#ifdef GST_EXT_XV_ENHANCEMENT
  if (!xvimagesink->xwindow && !xvimagesink->get_pixmap_cb) {
    GST_DEBUG_OBJECT (xvimagesink, "xwindow is null and not multi-pixmaps usage case");
#else
  if (!xvimagesink->xwindow) {
#endif
    xvimagesink->xwindow = gst_xvimagesink_xwindow_new (xvimagesink,
        GST_VIDEO_SINK_WIDTH (xvimagesink),
        GST_VIDEO_SINK_HEIGHT (xvimagesink));
  }

  /* After a resize, we want to redraw the borders in case the new frame size
   * doesn't cover the same area */
  xvimagesink->redraw_border = TRUE;

  /* We renew our xvimage only if size or format changed;
   * the xvimage is the same size as the video pixel size */
  if ((xvimagesink->xvimage) &&
      ((im_format != xvimagesink->xvimage->im_format) ||
          (video_width != xvimagesink->xvimage->width) ||
          (video_height != xvimagesink->xvimage->height))) {
    GST_DEBUG_OBJECT (xvimagesink,
        "old format %" GST_FOURCC_FORMAT ", new format %" GST_FOURCC_FORMAT,
        GST_FOURCC_ARGS (xvimagesink->xvimage->im_format),
        GST_FOURCC_ARGS (im_format));
    GST_DEBUG_OBJECT (xvimagesink, "renewing xvimage");
    gst_buffer_unref (GST_BUFFER (xvimagesink->xvimage));
    xvimagesink->xvimage = NULL;
  }

  g_mutex_unlock (xvimagesink->flow_lock);

  return TRUE;

  /* ERRORS */
incompatible_caps:
  {
    GST_ERROR_OBJECT (xvimagesink, "caps incompatible");
    return FALSE;
  }
incomplete_caps:
  {
    GST_DEBUG_OBJECT (xvimagesink, "Failed to retrieve either width, "
        "height or framerate from intersected caps");
    return FALSE;
  }
invalid_format:
  {
    GST_DEBUG_OBJECT (xvimagesink,
        "Could not locate image format from caps %" GST_PTR_FORMAT, caps);
    return FALSE;
  }
no_disp_ratio:
  {
    GST_ELEMENT_ERROR (xvimagesink, CORE, NEGOTIATION, (NULL),
        ("Error calculating the output display ratio of the video."));
    return FALSE;
  }
no_display_size:
  {
    GST_ELEMENT_ERROR (xvimagesink, CORE, NEGOTIATION, (NULL),
        ("Error calculating the output display ratio of the video."));
    return FALSE;
  }
}

static GstStateChangeReturn
gst_xvimagesink_change_state (GstElement * element, GstStateChange transition)
{
  GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
  GstXvImageSink *xvimagesink;
  GstXContext *xcontext = NULL;
#ifdef GST_EXT_XV_ENHANCEMENT
  Atom atom_preemption = None;
#endif /* GST_EXT_XV_ENHANCEMENT */

  xvimagesink = GST_XVIMAGESINK (element);

  switch (transition) {
    case GST_STATE_CHANGE_NULL_TO_READY:
      /* Initializing the XContext */
      if (xvimagesink->xcontext == NULL) {
        xcontext = gst_xvimagesink_xcontext_get (xvimagesink);
        if (xcontext == NULL)
          return GST_STATE_CHANGE_FAILURE;
        GST_OBJECT_LOCK (xvimagesink);
        if (xcontext)
          xvimagesink->xcontext = xcontext;
        GST_OBJECT_UNLOCK (xvimagesink);
      }

      /* update object's par with calculated one if not set yet */
      if (!xvimagesink->par) {
        xvimagesink->par = g_new0 (GValue, 1);
        gst_value_init_and_copy (xvimagesink->par, xvimagesink->xcontext->par);
        GST_DEBUG_OBJECT (xvimagesink, "set calculated PAR on object's PAR");
      }
      /* call XSynchronize with the current value of synchronous */
      GST_DEBUG_OBJECT (xvimagesink, "XSynchronize called with %s",
          xvimagesink->synchronous ? "TRUE" : "FALSE");
      XSynchronize (xvimagesink->xcontext->disp, xvimagesink->synchronous);
      gst_xvimagesink_update_colorbalance (xvimagesink);
      gst_xvimagesink_manage_event_thread (xvimagesink);
      break;
    case GST_STATE_CHANGE_READY_TO_PAUSED:
      g_mutex_lock (xvimagesink->pool_lock);
      xvimagesink->pool_invalid = FALSE;
      g_mutex_unlock (xvimagesink->pool_lock);
      break;
    case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
#ifdef GST_EXT_XV_ENHANCEMENT
      g_mutex_lock (xvimagesink->x_lock);
      atom_preemption = XInternAtom( xvimagesink->xcontext->disp,
                                     "_USER_WM_PORT_ATTRIBUTE_PREEMPTION", False );
      if (atom_preemption != None) {
         if (XvSetPortAttribute(xvimagesink->xcontext->disp,
                                xvimagesink->xcontext->xv_port_id,
                                atom_preemption, 1 ) != Success) {
            GST_ERROR_OBJECT(xvimagesink, "%d: XvSetPortAttribute: preemption failed.\n", atom_preemption);
         }
         XSync (xvimagesink->xcontext->disp, FALSE);
      }
      g_mutex_unlock (xvimagesink->x_lock);
#endif /* GST_EXT_XV_ENHANCEMENT */
      break;
    case GST_STATE_CHANGE_PAUSED_TO_READY:
      g_mutex_lock (xvimagesink->pool_lock);
      xvimagesink->pool_invalid = TRUE;
      g_mutex_unlock (xvimagesink->pool_lock);
      break;
    default:
      break;
  }

  ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);

  switch (transition) {
    case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
#ifdef GST_EXT_XV_ENHANCEMENT
      xvimagesink->rotate_changed = TRUE;
      g_mutex_lock (xvimagesink->x_lock);
      atom_preemption = XInternAtom( xvimagesink->xcontext->disp,
                                     "_USER_WM_PORT_ATTRIBUTE_PREEMPTION", False );
      if (atom_preemption != None) {
         if (XvSetPortAttribute(xvimagesink->xcontext->disp,
                                xvimagesink->xcontext->xv_port_id,
                                atom_preemption, 0 ) != Success) {
            GST_ERROR_OBJECT(xvimagesink, "%d: XvSetPortAttribute: preemption failed.\n", atom_preemption);
         }
         XSync (xvimagesink->xcontext->disp, FALSE);
      }
      g_mutex_unlock (xvimagesink->x_lock);
#endif /* GST_EXT_XV_ENHANCEMENT */
      break;
    case GST_STATE_CHANGE_PAUSED_TO_READY:
      xvimagesink->fps_n = 0;
      xvimagesink->fps_d = 1;
      GST_VIDEO_SINK_WIDTH (xvimagesink) = 0;
      GST_VIDEO_SINK_HEIGHT (xvimagesink) = 0;
#ifdef GST_EXT_XV_ENHANCEMENT
      /* close drm */
      drm_fini(xvimagesink);
#endif /* GST_EXT_XV_ENHANCEMENT */
      break;
    case GST_STATE_CHANGE_READY_TO_NULL:
      gst_xvimagesink_reset (xvimagesink);
      break;
    default:
      break;
  }

  return ret;
}

static void
gst_xvimagesink_get_times (GstBaseSink * bsink, GstBuffer * buf,
    GstClockTime * start, GstClockTime * end)
{
  GstXvImageSink *xvimagesink;

  xvimagesink = GST_XVIMAGESINK (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 (xvimagesink->fps_n > 0) {
        *end = *start +
            gst_util_uint64_scale_int (GST_SECOND, xvimagesink->fps_d,
            xvimagesink->fps_n);
      }
    }
  }
}

static GstFlowReturn
gst_xvimagesink_show_frame (GstVideoSink * vsink, GstBuffer * buf)
{
  GstXvImageSink *xvimagesink;

#ifdef GST_EXT_XV_ENHANCEMENT
  XV_PUTIMAGE_DATA_PTR img_data = NULL;
  SCMN_IMGB *scmn_imgb = NULL;
  gint format = 0;
  gboolean ret = FALSE;
#endif /* GST_EXT_XV_ENHANCEMENT */

  xvimagesink = GST_XVIMAGESINK (vsink);

#ifdef GST_EXT_XV_ENHANCEMENT
  if (xvimagesink->stop_video) {
    GST_INFO( "Stop video is TRUE. so skip show frame..." );
    return GST_FLOW_OK;
  }
#endif /* GST_EXT_XV_ENHANCEMENT */

  /* If this buffer has been allocated using our buffer management we simply
     put the ximage which is in the PRIVATE pointer */
  if (GST_IS_XVIMAGE_BUFFER (buf)) {
    GST_LOG_OBJECT (xvimagesink, "fast put of bufferpool buffer %p", buf);
#ifdef GST_EXT_XV_ENHANCEMENT
    xvimagesink->xid_updated = FALSE;
#endif /* GST_EXT_XV_ENHANCEMENT */
    if (!gst_xvimagesink_xvimage_put (xvimagesink,
            GST_XVIMAGE_BUFFER_CAST (buf)))
      goto no_window;
  } else {
    GST_CAT_LOG_OBJECT (GST_CAT_PERFORMANCE, xvimagesink,
        "slow copy into bufferpool buffer %p", buf);
    /* Else we have to copy the data into our private image, */
    /* if we have one... */
#ifdef GST_EXT_XV_ENHANCEMENT
    g_mutex_lock (xvimagesink->flow_lock);
#endif /* GST_EXT_XV_ENHANCEMENT */
    if (!xvimagesink->xvimage) {
      GST_DEBUG_OBJECT (xvimagesink, "creating our xvimage");

#ifdef GST_EXT_XV_ENHANCEMENT
      format = gst_xvimagesink_get_format_from_caps(xvimagesink, GST_BUFFER_CAPS(buf));
      switch (format) {
        case GST_MAKE_FOURCC('S', 'T', '1', '2'):
        case GST_MAKE_FOURCC('S', 'N', '1', '2'):
        case GST_MAKE_FOURCC('S', 'N', '2', '1'):
        case GST_MAKE_FOURCC('S', '4', '2', '0'):
        case GST_MAKE_FOURCC('S', 'U', 'Y', '2'):
        case GST_MAKE_FOURCC('S', 'U', 'Y', 'V'):
        case GST_MAKE_FOURCC('S', 'Y', 'V', 'Y'):
          scmn_imgb = (SCMN_IMGB *)GST_BUFFER_MALLOCDATA(buf);
          if(scmn_imgb == NULL) {
            GST_DEBUG_OBJECT( xvimagesink, "scmn_imgb is NULL. Skip xvimage put..." );
            g_mutex_unlock (xvimagesink->flow_lock);
            return GST_FLOW_OK;
          }

          /* skip buffer if aligned size is smaller than size of caps */
          if (scmn_imgb->s[0] < xvimagesink->video_width ||
              scmn_imgb->e[0] < xvimagesink->video_height) {
            GST_WARNING_OBJECT(xvimagesink, "invalid size[caps:%dx%d,aligned:%dx%d]. Skip this buffer...",
                                            xvimagesink->video_width, xvimagesink->video_height,
                                            scmn_imgb->s[0], scmn_imgb->e[0]);
            g_mutex_unlock (xvimagesink->flow_lock);
            return GST_FLOW_OK;
          }

          xvimagesink->aligned_width = scmn_imgb->s[0];
          xvimagesink->aligned_height = scmn_imgb->e[0];
          GST_INFO_OBJECT(xvimagesink, "Use aligned width,height[%dx%d]",
                                       xvimagesink->aligned_width, xvimagesink->aligned_height);
          break;
        default:
          GST_INFO_OBJECT(xvimagesink, "Use original width,height of caps");
          break;
      }
#endif /* GST_EXT_XV_ENHANCEMENT */

      xvimagesink->xvimage = gst_xvimagesink_xvimage_new (xvimagesink,
          GST_BUFFER_CAPS (buf));

      if (!xvimagesink->xvimage)
        /* The create method should have posted an informative error */
        goto no_image;

      if (xvimagesink->xvimage->size < GST_BUFFER_SIZE (buf)) {
        GST_ELEMENT_ERROR (xvimagesink, RESOURCE, WRITE,
            ("Failed to create output image buffer of %dx%d pixels",
                xvimagesink->xvimage->width, xvimagesink->xvimage->height),
            ("XServer allocated buffer size did not match input buffer"));

        gst_xvimage_buffer_destroy (xvimagesink->xvimage);
        xvimagesink->xvimage = NULL;
        goto no_image;
      }
    }

#ifdef GST_EXT_XV_ENHANCEMENT
    switch (xvimagesink->xvimage->im_format) {
      /* Cases for specified formats of Samsung extension */
      case GST_MAKE_FOURCC('S', 'T', '1', '2'):
      case GST_MAKE_FOURCC('S', 'N', '1', '2'):
      case GST_MAKE_FOURCC('S', 'N', '2', '1'):
      case GST_MAKE_FOURCC('S', '4', '2', '0'):
      case GST_MAKE_FOURCC('S', 'U', 'Y', '2'):
      case GST_MAKE_FOURCC('S', 'U', 'Y', 'V'):
      case GST_MAKE_FOURCC('S', 'Y', 'V', 'Y'):
      case GST_MAKE_FOURCC('I', 'T', 'L', 'V'):
      {
        GST_LOG("Samsung EXT format - fourcc:%c%c%c%c, display mode:%d, Rotate angle:%d",
                xvimagesink->xvimage->im_format, xvimagesink->xvimage->im_format>>8,
                xvimagesink->xvimage->im_format>>16, xvimagesink->xvimage->im_format>>24,
                xvimagesink->display_mode, xvimagesink->rotate_angle);

        if (xvimagesink->xvimage->xvimage->data) {
          img_data = (XV_PUTIMAGE_DATA_PTR) xvimagesink->xvimage->xvimage->data;
          memset(img_data, 0x0, sizeof(XV_PUTIMAGE_DATA));
          XV_PUTIMAGE_INIT_DATA(img_data);

          scmn_imgb = (SCMN_IMGB *)GST_BUFFER_MALLOCDATA(buf);
          if (scmn_imgb == NULL) {
            GST_DEBUG_OBJECT( xvimagesink, "scmn_imgb is NULL. Skip xvimage put..." );
            g_mutex_unlock (xvimagesink->flow_lock);
            return GST_FLOW_OK;
          }

          if (scmn_imgb->buf_share_method == BUF_SHARE_METHOD_PADDR) {
            img_data->YBuf = (unsigned int)scmn_imgb->p[0];
            img_data->CbBuf = (unsigned int)scmn_imgb->p[1];
            img_data->CrBuf = (unsigned int)scmn_imgb->p[2];
            img_data->BufType = XV_BUF_TYPE_LEGACY;
          } else if (scmn_imgb->buf_share_method == BUF_SHARE_METHOD_FD) {
            /* open drm to use gem */
            if (xvimagesink->drm_fd < 0) {
              drm_init(xvimagesink);
            }

            /* convert dma-buf fd into drm gem name */
            img_data->YBuf = drm_convert_dmabuf_gemname(xvimagesink, (int)scmn_imgb->dmabuf_fd[0], &xvimagesink->gem_handle[0]);
            img_data->CbBuf = drm_convert_dmabuf_gemname(xvimagesink, (int)scmn_imgb->dmabuf_fd[1], &xvimagesink->gem_handle[1]);
            img_data->CrBuf = drm_convert_dmabuf_gemname(xvimagesink, (int)scmn_imgb->dmabuf_fd[2], &xvimagesink->gem_handle[2]);
            img_data->BufType = XV_BUF_TYPE_DMABUF;
          } else {
            GST_WARNING("unknown buf_share_method type [%d]. skip xvimage put...",
                        scmn_imgb->buf_share_method);
            g_mutex_unlock (xvimagesink->flow_lock);
            return GST_FLOW_OK;
          }

          GST_LOG_OBJECT(xvimagesink, "YBuf[%d], CbBuf[%d], CrBuf[%d]",
                                      img_data->YBuf, img_data->CbBuf, img_data->CrBuf );
        } else {
          GST_WARNING_OBJECT( xvimagesink, "xvimage->data is NULL. skip xvimage put..." );
          g_mutex_unlock (xvimagesink->flow_lock);
          return GST_FLOW_OK;
        }
        break;
      }
      default:
      {
        GST_DEBUG("Normal format activated. fourcc = %d", xvimagesink->xvimage->im_format);
        memcpy (xvimagesink->xvimage->xvimage->data,
        GST_BUFFER_DATA (buf),
        MIN (GST_BUFFER_SIZE (buf), xvimagesink->xvimage->size));
        break;
      }
    }

    g_mutex_unlock (xvimagesink->flow_lock);
    ret = gst_xvimagesink_xvimage_put(xvimagesink, xvimagesink->xvimage);

    /* close gem handle */
    if (xvimagesink->drm_fd >= 0 ) {
      drm_close_gem(xvimagesink, &xvimagesink->gem_handle[0]);
      drm_close_gem(xvimagesink, &xvimagesink->gem_handle[1]);
      drm_close_gem(xvimagesink, &xvimagesink->gem_handle[2]);
    }

    if (!ret) {
      goto no_window;
    }
#else /* GST_EXT_XV_ENHANCEMENT */
    memcpy (xvimagesink->xvimage->xvimage->data,
        GST_BUFFER_DATA (buf),
        MIN (GST_BUFFER_SIZE (buf), xvimagesink->xvimage->size));

    if (!gst_xvimagesink_xvimage_put (xvimagesink, xvimagesink->xvimage))
      goto no_window;
#endif /* GST_EXT_XV_ENHANCEMENT */
  }

  return GST_FLOW_OK;

  /* ERRORS */
no_image:
  {
    /* No image available. That's very bad ! */
    GST_WARNING_OBJECT (xvimagesink, "could not create image");
#ifdef GST_EXT_XV_ENHANCEMENT
    g_mutex_unlock (xvimagesink->flow_lock);
#endif
    return GST_FLOW_ERROR;
  }
no_window:
  {
    /* No Window available to put our image into */
    GST_WARNING_OBJECT (xvimagesink, "could not output image - no window");
    return GST_FLOW_ERROR;
  }
}

static gboolean
gst_xvimagesink_event (GstBaseSink * sink, GstEvent * event)
{
  GstXvImageSink *xvimagesink = GST_XVIMAGESINK (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) {
#ifdef GST_EXT_XV_ENHANCEMENT
        if (!xvimagesink->get_pixmap_cb) {
#endif
        GST_DEBUG_OBJECT (xvimagesink, "got tags, title='%s'", title);
        gst_xvimagesink_xwindow_set_title (xvimagesink, xvimagesink->xwindow,
            title);

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

/* Buffer management */

static GstCaps *
gst_xvimage_sink_different_size_suggestion (GstXvImageSink * xvimagesink,
    GstCaps * caps)
{
  GstCaps *intersection;
  GstCaps *new_caps;
  GstStructure *s;
  gint width, height;
  gint par_n = 1, par_d = 1;
  gint dar_n, dar_d;
  gint w, h;

  new_caps = gst_caps_copy (caps);

  s = gst_caps_get_structure (new_caps, 0);

  gst_structure_get_int (s, "width", &width);
  gst_structure_get_int (s, "height", &height);
  gst_structure_get_fraction (s, "pixel-aspect-ratio", &par_n, &par_d);

  gst_structure_remove_field (s, "width");
  gst_structure_remove_field (s, "height");
  gst_structure_remove_field (s, "pixel-aspect-ratio");

  intersection = gst_caps_intersect (xvimagesink->xcontext->caps, new_caps);
  gst_caps_unref (new_caps);

  if (gst_caps_is_empty (intersection))
    return intersection;

  s = gst_caps_get_structure (intersection, 0);

  gst_util_fraction_multiply (width, height, par_n, par_d, &dar_n, &dar_d);

  /* xvimagesink supports all PARs */

  gst_structure_fixate_field_nearest_int (s, "width", width);
  gst_structure_fixate_field_nearest_int (s, "height", height);
  gst_structure_get_int (s, "width", &w);
  gst_structure_get_int (s, "height", &h);

  gst_util_fraction_multiply (h, w, dar_n, dar_d, &par_n, &par_d);
  gst_structure_set (s, "pixel-aspect-ratio", GST_TYPE_FRACTION, par_n, par_d,
      NULL);

  return intersection;
}

static GstFlowReturn
gst_xvimagesink_buffer_alloc (GstBaseSink * bsink, guint64 offset, guint size,
    GstCaps * caps, GstBuffer ** buf)
{
  GstFlowReturn ret = GST_FLOW_OK;
  GstXvImageSink *xvimagesink;
  GstXvImageBuffer *xvimage = NULL;
  GstCaps *intersection = NULL;
  GstStructure *structure = NULL;
  gint width, height, image_format;

  xvimagesink = GST_XVIMAGESINK (bsink);

  if (G_UNLIKELY (!caps))
    goto no_caps;

  g_mutex_lock (xvimagesink->pool_lock);
  if (G_UNLIKELY (xvimagesink->pool_invalid))
    goto invalid;

  if (G_LIKELY (xvimagesink->xcontext->last_caps &&
          gst_caps_is_equal (caps, xvimagesink->xcontext->last_caps))) {
    GST_LOG_OBJECT (xvimagesink,
        "buffer alloc for same last_caps, reusing caps");
    intersection = gst_caps_ref (caps);
    image_format = xvimagesink->xcontext->last_format;
    width = xvimagesink->xcontext->last_width;
    height = xvimagesink->xcontext->last_height;

    goto reuse_last_caps;
  }

  GST_DEBUG_OBJECT (xvimagesink, "buffer alloc requested size %d with caps %"
      GST_PTR_FORMAT ", intersecting with our caps %" GST_PTR_FORMAT, size,
      caps, xvimagesink->xcontext->caps);

  /* Check the caps against our xcontext */
  intersection = gst_caps_intersect (xvimagesink->xcontext->caps, caps);

  GST_DEBUG_OBJECT (xvimagesink, "intersection in buffer alloc returned %"
      GST_PTR_FORMAT, intersection);

  if (gst_caps_is_empty (intersection)) {
    GstCaps *new_caps;

    gst_caps_unref (intersection);

    /* So we don't support this kind of buffer, let's define one we'd like */
    new_caps = gst_caps_copy (caps);

    structure = gst_caps_get_structure (new_caps, 0);
    if (!gst_structure_has_field (structure, "width") ||
        !gst_structure_has_field (structure, "height")) {
      gst_caps_unref (new_caps);
      goto invalid;
    }

    /* Try different dimensions */
    intersection =
        gst_xvimage_sink_different_size_suggestion (xvimagesink, new_caps);

    if (gst_caps_is_empty (intersection)) {
      /* Try with different YUV formats first */
      gst_structure_set_name (structure, "video/x-raw-yuv");

      /* Remove format specific fields */
      gst_structure_remove_field (structure, "format");
      gst_structure_remove_field (structure, "endianness");
      gst_structure_remove_field (structure, "depth");
      gst_structure_remove_field (structure, "bpp");
      gst_structure_remove_field (structure, "red_mask");
      gst_structure_remove_field (structure, "green_mask");
      gst_structure_remove_field (structure, "blue_mask");
      gst_structure_remove_field (structure, "alpha_mask");

      /* Reuse intersection with Xcontext */
      intersection = gst_caps_intersect (xvimagesink->xcontext->caps, new_caps);
    }

    if (gst_caps_is_empty (intersection)) {
      /* Try with different dimensions and YUV formats */
      intersection =
          gst_xvimage_sink_different_size_suggestion (xvimagesink, new_caps);
    }

    if (gst_caps_is_empty (intersection)) {
      /* Now try with RGB */
      gst_structure_set_name (structure, "video/x-raw-rgb");
      /* And interset again */
      gst_caps_unref (intersection);
      intersection = gst_caps_intersect (xvimagesink->xcontext->caps, new_caps);
    }

    if (gst_caps_is_empty (intersection)) {
      /* Try with different dimensions and RGB formats */
      intersection =
          gst_xvimage_sink_different_size_suggestion (xvimagesink, new_caps);
    }

    /* Clean this copy */
    gst_caps_unref (new_caps);

    if (gst_caps_is_empty (intersection))
      goto incompatible;
  }

  /* Ensure the returned caps are fixed */
  gst_caps_truncate (intersection);

  GST_DEBUG_OBJECT (xvimagesink, "allocating a buffer with caps %"
      GST_PTR_FORMAT, intersection);
  if (gst_caps_is_equal (intersection, caps)) {
    /* Things work better if we return a buffer with the same caps ptr
     * as was asked for when we can */
    gst_caps_replace (&intersection, caps);
  }

  /* Get image format from caps */
  image_format = gst_xvimagesink_get_format_from_caps (xvimagesink,
      intersection);

  /* Get geometry from caps */
  structure = gst_caps_get_structure (intersection, 0);
  if (!gst_structure_get_int (structure, "width", &width) ||
      !gst_structure_get_int (structure, "height", &height) ||
      image_format == -1)
    goto invalid_caps;

  /* Store our caps and format as the last_caps to avoid expensive
   * caps intersection next time */
  gst_caps_replace (&xvimagesink->xcontext->last_caps, intersection);
  xvimagesink->xcontext->last_format = image_format;
  xvimagesink->xcontext->last_width = width;
  xvimagesink->xcontext->last_height = height;

reuse_last_caps:

  /* Walking through the pool cleaning unusable images and searching for a
     suitable one */
  while (xvimagesink->image_pool) {
    xvimage = xvimagesink->image_pool->data;

    if (xvimage) {
      /* Removing from the pool */
      xvimagesink->image_pool = g_slist_delete_link (xvimagesink->image_pool,
          xvimagesink->image_pool);

      /* We check for geometry or image format changes */
      if ((xvimage->width != width) ||
          (xvimage->height != height) || (xvimage->im_format != image_format)) {
        /* This image is unusable. Destroying... */
        gst_xvimage_buffer_free (xvimage);
        xvimage = NULL;
      } else {
        /* We found a suitable image */
        GST_LOG_OBJECT (xvimagesink, "found usable image in pool");
        break;
      }
    }
  }

  if (!xvimage) {
    /* We found no suitable image in the pool. Creating... */
    GST_DEBUG_OBJECT (xvimagesink, "no usable image in pool, creating xvimage");
    xvimage = gst_xvimagesink_xvimage_new (xvimagesink, intersection);
  }
  g_mutex_unlock (xvimagesink->pool_lock);

  if (xvimage) {
    /* Make sure the buffer is cleared of any previously used flags */
    GST_MINI_OBJECT_CAST (xvimage)->flags = 0;
    gst_buffer_set_caps (GST_BUFFER_CAST (xvimage), intersection);
  }

  *buf = GST_BUFFER_CAST (xvimage);

beach:
  if (intersection) {
    gst_caps_unref (intersection);
  }

  return ret;

  /* ERRORS */
invalid:
  {
    GST_DEBUG_OBJECT (xvimagesink, "the pool is flushing");
    ret = GST_FLOW_WRONG_STATE;
    g_mutex_unlock (xvimagesink->pool_lock);
    goto beach;
  }
incompatible:
  {
    GST_WARNING_OBJECT (xvimagesink, "we were requested a buffer with "
        "caps %" GST_PTR_FORMAT ", but our xcontext caps %" GST_PTR_FORMAT
        " are completely incompatible with those caps", caps,
        xvimagesink->xcontext->caps);
    ret = GST_FLOW_NOT_NEGOTIATED;
    g_mutex_unlock (xvimagesink->pool_lock);
    goto beach;
  }
invalid_caps:
  {
    GST_WARNING_OBJECT (xvimagesink, "invalid caps for buffer allocation %"
        GST_PTR_FORMAT, intersection);
    ret = GST_FLOW_NOT_NEGOTIATED;
    g_mutex_unlock (xvimagesink->pool_lock);
    goto beach;
  }
no_caps:
  {
    GST_WARNING_OBJECT (xvimagesink, "have no caps, doing fallback allocation");
    *buf = NULL;
    ret = GST_FLOW_OK;
    goto beach;
  }
}

/* Interfaces stuff */

static gboolean
gst_xvimagesink_interface_supported (GstImplementsInterface * iface, GType type)
{
  if (type == GST_TYPE_NAVIGATION || type == GST_TYPE_X_OVERLAY ||
      type == GST_TYPE_COLOR_BALANCE || type == GST_TYPE_PROPERTY_PROBE)
    return TRUE;
  else
    return FALSE;
}

static void
gst_xvimagesink_interface_init (GstImplementsInterfaceClass * klass)
{
  klass->supported = gst_xvimagesink_interface_supported;
}

static void
gst_xvimagesink_navigation_send_event (GstNavigation * navigation,
    GstStructure * structure)
{
  GstXvImageSink *xvimagesink = GST_XVIMAGESINK (navigation);
  GstPad *peer;

  if ((peer = gst_pad_get_peer (GST_VIDEO_SINK_PAD (xvimagesink)))) {
    GstEvent *event;
    GstVideoRectangle src, dst, result;
    gdouble x, y, xscale = 1.0, yscale = 1.0;

    event = gst_event_new_navigation (structure);

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

    if (!xvimagesink->xwindow) {
      g_mutex_unlock (xvimagesink->flow_lock);
      return;
    }

    if (xvimagesink->keep_aspect) {
      /* We get the frame position using the calculated geometry from _setcaps
         that respect pixel aspect ratios */
      src.w = GST_VIDEO_SINK_WIDTH (xvimagesink);
      src.h = GST_VIDEO_SINK_HEIGHT (xvimagesink);
      dst.w = xvimagesink->render_rect.w;
      dst.h = xvimagesink->render_rect.h;

      gst_video_sink_center_rect (src, dst, &result, TRUE);
      result.x += xvimagesink->render_rect.x;
      result.y += xvimagesink->render_rect.y;
    } else {
      memcpy (&result, &xvimagesink->render_rect, sizeof (GstVideoRectangle));
    }

    g_mutex_unlock (xvimagesink->flow_lock);

    /* We calculate scaling using the original video frames geometry to include
       pixel aspect ratio scaling. */
    xscale = (gdouble) xvimagesink->video_width / result.w;
    yscale = (gdouble) xvimagesink->video_height / result.h;

    /* Converting pointer coordinates to the non scaled geometry */
    if (gst_structure_get_double (structure, "pointer_x", &x)) {
      x = MIN (x, result.x + result.w);
      x = MAX (x - result.x, 0);
      gst_structure_set (structure, "pointer_x", G_TYPE_DOUBLE,
          (gdouble) x * xscale, NULL);
    }
    if (gst_structure_get_double (structure, "pointer_y", &y)) {
      y = MIN (y, result.y + result.h);
      y = MAX (y - result.y, 0);
      gst_structure_set (structure, "pointer_y", G_TYPE_DOUBLE,
          (gdouble) y * yscale, NULL);
    }

    gst_pad_send_event (peer, event);
    gst_object_unref (peer);
  }
}

static void
gst_xvimagesink_navigation_init (GstNavigationInterface * iface)
{
  iface->send_event = gst_xvimagesink_navigation_send_event;
}

#ifdef GST_EXT_XV_ENHANCEMENT
static void
gst_xvimagesink_set_pixmap_handle (GstXOverlay * overlay, guintptr id)
{
  XID pixmap_id = id;
  int i = 0;
  GstXvImageSink *xvimagesink = GST_XVIMAGESINK (overlay);
  GstXPixmap *xpixmap = NULL;

  g_return_if_fail (GST_IS_XVIMAGESINK (xvimagesink));

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

  gst_xvimagesink_update_colorbalance (xvimagesink);

  GST_DEBUG_OBJECT( xvimagesink, "pixmap id : %d", pixmap_id );

  /* if the returned pixmap_id is 0, set current pixmap index to -2 to skip putImage() */
  if (pixmap_id == 0) {
    xvimagesink->current_pixmap_idx = -2;
    return;
  }

  g_mutex_lock (xvimagesink->x_lock);

  for (i = 0; i < MAX_PIXMAP_NUM; i++) {
    if (!xvimagesink->xpixmap[i]) {
      Window root_window;
      int cur_win_x = 0;
      int cur_win_y = 0;
      unsigned int cur_win_width = 0;
      unsigned int cur_win_height = 0;
      unsigned int cur_win_border_width = 0;
      unsigned int cur_win_depth = 0;

      GST_INFO_OBJECT( xvimagesink, "xpixmap[%d] is empty, create it with pixmap_id(%d)", i, pixmap_id );

      xpixmap = g_new0 (GstXPixmap, 1);
      if (xpixmap) {
        xpixmap->pixmap = pixmap_id;

        /* Get root window and size of current window */
        XGetGeometry(xvimagesink->xcontext->disp, xpixmap->pixmap, &root_window,
                     &cur_win_x, &cur_win_y, /* relative x, y */
                     &cur_win_width, &cur_win_height,
                     &cur_win_border_width, &cur_win_depth);
        if (!cur_win_width || !cur_win_height) {
          GST_INFO_OBJECT( xvimagesink, "cur_win_width(%d) or cur_win_height(%d) is null..", cur_win_width, cur_win_height );
          g_mutex_unlock (xvimagesink->x_lock);
          return;
        }
        xpixmap->width = cur_win_width;
        xpixmap->height = cur_win_height;

        if (!xvimagesink->render_rect.w)
          xvimagesink->render_rect.w = cur_win_width;
        if (!xvimagesink->render_rect.h)
          xvimagesink->render_rect.h = cur_win_height;

        /* Create a GC */
        xpixmap->gc = XCreateGC (xvimagesink->xcontext->disp, xpixmap->pixmap, 0, NULL);

        xvimagesink->xpixmap[i] = xpixmap;
        xvimagesink->current_pixmap_idx = i;
      } else {
        GST_ERROR("failed to create xpixmap errno: %d", errno);
      }

      g_mutex_unlock (xvimagesink->x_lock);
      return;

    } else if (xvimagesink->xpixmap[i]->pixmap == pixmap_id) {
      GST_DEBUG_OBJECT( xvimagesink, "found xpixmap[%d]->pixmap : %d", i, pixmap_id );
      xvimagesink->current_pixmap_idx = i;

      g_mutex_unlock (xvimagesink->x_lock);
      return;

    } else {
      continue;
    }
  }

  GST_ERROR_OBJECT( xvimagesink, "could not find the pixmap id(%d) in xpixmap array", pixmap_id );
  xvimagesink->current_pixmap_idx = -1;

  g_mutex_unlock (xvimagesink->x_lock);
  return;
}
#endif /* GST_EXT_XV_ENHANCEMENT */

static void
gst_xvimagesink_set_window_handle (GstXOverlay * overlay, guintptr id)
{
  XID xwindow_id = id;
  GstXvImageSink *xvimagesink = GST_XVIMAGESINK (overlay);
  GstXWindow *xwindow = NULL;

  g_return_if_fail (GST_IS_XVIMAGESINK (xvimagesink));

  g_mutex_lock (xvimagesink->flow_lock);

#ifdef GST_EXT_XV_ENHANCEMENT
  GST_INFO_OBJECT( xvimagesink, "ENTER, id : %d", xwindow_id );
#endif /* GST_EXT_XV_ENHANCEMENT */

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

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

  gst_xvimagesink_update_colorbalance (xvimagesink);

  /* Clear image pool as the images are unusable anyway */
  gst_xvimagesink_imagepool_clear (xvimagesink);

  /* Clear the xvimage */
  if (xvimagesink->xvimage) {
    gst_xvimage_buffer_free (xvimagesink->xvimage);
    xvimagesink->xvimage = NULL;
  }

  /* If a window is there already we destroy it */
  if (xvimagesink->xwindow) {
    gst_xvimagesink_xwindow_destroy (xvimagesink, xvimagesink->xwindow);
    xvimagesink->xwindow = 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 */
#ifdef GST_EXT_XV_ENHANCEMENT
  GST_INFO_OBJECT( xvimagesink, "xid is 0. create window[%dx%d]",
    GST_VIDEO_SINK_WIDTH (xvimagesink), GST_VIDEO_SINK_HEIGHT (xvimagesink) );
#endif /* GST_EXT_XV_ENHANCEMENT */
    if (GST_VIDEO_SINK_WIDTH (xvimagesink)
        && GST_VIDEO_SINK_HEIGHT (xvimagesink)) {
      xwindow =
          gst_xvimagesink_xwindow_new (xvimagesink,
          GST_VIDEO_SINK_WIDTH (xvimagesink),
          GST_VIDEO_SINK_HEIGHT (xvimagesink));
    }
  } else {
    XWindowAttributes attr;

    xwindow = g_new0 (GstXWindow, 1);
    xwindow->win = xwindow_id;

    /* Set the event we want to receive and create a GC */
    g_mutex_lock (xvimagesink->x_lock);

    XGetWindowAttributes (xvimagesink->xcontext->disp, xwindow->win, &attr);

    xwindow->width = attr.width;
    xwindow->height = attr.height;
    xwindow->internal = FALSE;
    if (!xvimagesink->have_render_rect) {
      xvimagesink->render_rect.x = xvimagesink->render_rect.y = 0;
      xvimagesink->render_rect.w = attr.width;
      xvimagesink->render_rect.h = attr.height;
    }
    if (xvimagesink->handle_events) {
      XSelectInput (xvimagesink->xcontext->disp, xwindow->win, ExposureMask |
          StructureNotifyMask | PointerMotionMask | KeyPressMask |
          KeyReleaseMask);
    }

    xwindow->gc = XCreateGC (xvimagesink->xcontext->disp,
        xwindow->win, 0, NULL);
    g_mutex_unlock (xvimagesink->x_lock);
  }

  if (xwindow)
    xvimagesink->xwindow = xwindow;

#ifdef GST_EXT_XV_ENHANCEMENT
  xvimagesink->xid_updated = TRUE;
#endif /* GST_EXT_XV_ENHANCEMENT */

  g_mutex_unlock (xvimagesink->flow_lock);
}

static void
gst_xvimagesink_expose (GstXOverlay * overlay)
{
  GstXvImageSink *xvimagesink = GST_XVIMAGESINK (overlay);

  gst_xvimagesink_xwindow_update_geometry (xvimagesink);
#ifdef GST_EXT_XV_ENHANCEMENT
  GST_INFO_OBJECT( xvimagesink, "Overlay window exposed. update it");
  gst_xvimagesink_xvimage_put (xvimagesink, xvimagesink->xvimage);
#else /* GST_EXT_XV_ENHANCEMENT */
  gst_xvimagesink_xvimage_put (xvimagesink, NULL);
#endif /* GST_EXT_XV_ENHANCEMENT */
}

static void
gst_xvimagesink_set_event_handling (GstXOverlay * overlay,
    gboolean handle_events)
{
  GstXvImageSink *xvimagesink = GST_XVIMAGESINK (overlay);

  xvimagesink->handle_events = handle_events;

  g_mutex_lock (xvimagesink->flow_lock);

  if (G_UNLIKELY (!xvimagesink->xwindow)) {
    g_mutex_unlock (xvimagesink->flow_lock);
    return;
  }

  g_mutex_lock (xvimagesink->x_lock);

  if (handle_events) {
    if (xvimagesink->xwindow->internal) {
      XSelectInput (xvimagesink->xcontext->disp, xvimagesink->xwindow->win,
#ifdef GST_EXT_XV_ENHANCEMENT
          ExposureMask | StructureNotifyMask | PointerMotionMask | VisibilityChangeMask |
#else /* GST_EXT_XV_ENHANCEMENT */
          ExposureMask | StructureNotifyMask | PointerMotionMask |
#endif /* GST_EXT_XV_ENHANCEMENT */
          KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask);
    } else {
      XSelectInput (xvimagesink->xcontext->disp, xvimagesink->xwindow->win,
#ifdef GST_EXT_XV_ENHANCEMENT
          ExposureMask | StructureNotifyMask | PointerMotionMask | VisibilityChangeMask |
#else /* GST_EXT_XV_ENHANCEMENT */
          ExposureMask | StructureNotifyMask | PointerMotionMask |
#endif /* GST_EXT_XV_ENHANCEMENT */
          KeyPressMask | KeyReleaseMask);
    }
  } else {
    XSelectInput (xvimagesink->xcontext->disp, xvimagesink->xwindow->win, 0);
  }

  g_mutex_unlock (xvimagesink->x_lock);

  g_mutex_unlock (xvimagesink->flow_lock);
}

static void
gst_xvimagesink_set_render_rectangle (GstXOverlay * overlay, gint x, gint y,
    gint width, gint height)
{
  GstXvImageSink *xvimagesink = GST_XVIMAGESINK (overlay);

  /* FIXME: how about some locking? */
  if (width >= 0 && height >= 0) {
    xvimagesink->render_rect.x = x;
    xvimagesink->render_rect.y = y;
    xvimagesink->render_rect.w = width;
    xvimagesink->render_rect.h = height;
    xvimagesink->have_render_rect = TRUE;
  } else {
    xvimagesink->render_rect.x = 0;
    xvimagesink->render_rect.y = 0;
    xvimagesink->render_rect.w = xvimagesink->xwindow->width;
    xvimagesink->render_rect.h = xvimagesink->xwindow->height;
    xvimagesink->have_render_rect = FALSE;
  }
}

static void
gst_xvimagesink_xoverlay_init (GstXOverlayClass * iface)
{
  iface->set_window_handle = gst_xvimagesink_set_window_handle;
  iface->expose = gst_xvimagesink_expose;
  iface->handle_events = gst_xvimagesink_set_event_handling;
  iface->set_render_rectangle = gst_xvimagesink_set_render_rectangle;
}

static const GList *
gst_xvimagesink_colorbalance_list_channels (GstColorBalance * balance)
{
  GstXvImageSink *xvimagesink = GST_XVIMAGESINK (balance);

  g_return_val_if_fail (GST_IS_XVIMAGESINK (xvimagesink), NULL);

  if (xvimagesink->xcontext)
    return xvimagesink->xcontext->channels_list;
  else
    return NULL;
}

static void
gst_xvimagesink_colorbalance_set_value (GstColorBalance * balance,
    GstColorBalanceChannel * channel, gint value)
{
  GstXvImageSink *xvimagesink = GST_XVIMAGESINK (balance);

  g_return_if_fail (GST_IS_XVIMAGESINK (xvimagesink));
  g_return_if_fail (channel->label != NULL);

  xvimagesink->cb_changed = TRUE;

  /* Normalize val to [-1000, 1000] */
  value = floor (0.5 + -1000 + 2000 * (value - channel->min_value) /
      (double) (channel->max_value - channel->min_value));

  if (g_ascii_strcasecmp (channel->label, "XV_HUE") == 0) {
    xvimagesink->hue = value;
  } else if (g_ascii_strcasecmp (channel->label, "XV_SATURATION") == 0) {
    xvimagesink->saturation = value;
  } else if (g_ascii_strcasecmp (channel->label, "XV_CONTRAST") == 0) {
    xvimagesink->contrast = value;
  } else if (g_ascii_strcasecmp (channel->label, "XV_BRIGHTNESS") == 0) {
    xvimagesink->brightness = value;
  } else {
    g_warning ("got an unknown channel %s", channel->label);
    return;
  }

  gst_xvimagesink_update_colorbalance (xvimagesink);
}

static gint
gst_xvimagesink_colorbalance_get_value (GstColorBalance * balance,
    GstColorBalanceChannel * channel)
{
  GstXvImageSink *xvimagesink = GST_XVIMAGESINK (balance);
  gint value = 0;

  g_return_val_if_fail (GST_IS_XVIMAGESINK (xvimagesink), 0);
  g_return_val_if_fail (channel->label != NULL, 0);

  if (g_ascii_strcasecmp (channel->label, "XV_HUE") == 0) {
    value = xvimagesink->hue;
  } else if (g_ascii_strcasecmp (channel->label, "XV_SATURATION") == 0) {
    value = xvimagesink->saturation;
  } else if (g_ascii_strcasecmp (channel->label, "XV_CONTRAST") == 0) {
    value = xvimagesink->contrast;
  } else if (g_ascii_strcasecmp (channel->label, "XV_BRIGHTNESS") == 0) {
    value = xvimagesink->brightness;
  } else {
    g_warning ("got an unknown channel %s", channel->label);
  }

  /* Normalize val to [channel->min_value, channel->max_value] */
  value = channel->min_value + (channel->max_value - channel->min_value) *
      (value + 1000) / 2000;

  return value;
}

static void
gst_xvimagesink_colorbalance_init (GstColorBalanceClass * iface)
{
  GST_COLOR_BALANCE_TYPE (iface) = GST_COLOR_BALANCE_HARDWARE;
  iface->list_channels = gst_xvimagesink_colorbalance_list_channels;
  iface->set_value = gst_xvimagesink_colorbalance_set_value;
  iface->get_value = gst_xvimagesink_colorbalance_get_value;
}

static const GList *
gst_xvimagesink_probe_get_properties (GstPropertyProbe * probe)
{
  GObjectClass *klass = G_OBJECT_GET_CLASS (probe);
  static GList *list = NULL;

  if (!list) {
    list = g_list_append (NULL, g_object_class_find_property (klass, "device"));
    list =
        g_list_append (list, g_object_class_find_property (klass,
            "autopaint-colorkey"));
    list =
        g_list_append (list, g_object_class_find_property (klass,
            "double-buffer"));
    list =
        g_list_append (list, g_object_class_find_property (klass, "colorkey"));
  }

  return list;
}

static void
gst_xvimagesink_probe_probe_property (GstPropertyProbe * probe,
    guint prop_id, const GParamSpec * pspec)
{
  GstXvImageSink *xvimagesink = GST_XVIMAGESINK (probe);

  switch (prop_id) {
    case PROP_DEVICE:
    case PROP_AUTOPAINT_COLORKEY:
    case PROP_DOUBLE_BUFFER:
    case PROP_COLORKEY:
      GST_DEBUG_OBJECT (xvimagesink,
          "probing device list and get capabilities");
      if (!xvimagesink->xcontext) {
        GST_DEBUG_OBJECT (xvimagesink, "generating xcontext");
        xvimagesink->xcontext = gst_xvimagesink_xcontext_get (xvimagesink);
      }
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (probe, prop_id, pspec);
      break;
  }
}

static gboolean
gst_xvimagesink_probe_needs_probe (GstPropertyProbe * probe,
    guint prop_id, const GParamSpec * pspec)
{
  GstXvImageSink *xvimagesink = GST_XVIMAGESINK (probe);
  gboolean ret = FALSE;

  switch (prop_id) {
    case PROP_DEVICE:
    case PROP_AUTOPAINT_COLORKEY:
    case PROP_DOUBLE_BUFFER:
    case PROP_COLORKEY:
      if (xvimagesink->xcontext != NULL) {
        ret = FALSE;
      } else {
        ret = TRUE;
      }
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (probe, prop_id, pspec);
      break;
  }

  return ret;
}

static GValueArray *
gst_xvimagesink_probe_get_values (GstPropertyProbe * probe,
    guint prop_id, const GParamSpec * pspec)
{
  GstXvImageSink *xvimagesink = GST_XVIMAGESINK (probe);
  GValueArray *array = NULL;

  if (G_UNLIKELY (!xvimagesink->xcontext)) {
    GST_WARNING_OBJECT (xvimagesink, "we don't have any xcontext, can't "
        "get values");
    goto beach;
  }

  switch (prop_id) {
    case PROP_DEVICE:
    {
      guint i;
      GValue value = { 0 };

      array = g_value_array_new (xvimagesink->xcontext->nb_adaptors);
      g_value_init (&value, G_TYPE_STRING);

      for (i = 0; i < xvimagesink->xcontext->nb_adaptors; i++) {
        gchar *adaptor_id_s = g_strdup_printf ("%u", i);

        g_value_set_string (&value, adaptor_id_s);
        g_value_array_append (array, &value);
        g_free (adaptor_id_s);
      }
      g_value_unset (&value);
      break;
    }
    case PROP_AUTOPAINT_COLORKEY:
      if (xvimagesink->have_autopaint_colorkey) {
        GValue value = { 0 };

        array = g_value_array_new (2);
        g_value_init (&value, G_TYPE_BOOLEAN);
        g_value_set_boolean (&value, FALSE);
        g_value_array_append (array, &value);
        g_value_set_boolean (&value, TRUE);
        g_value_array_append (array, &value);
        g_value_unset (&value);
      }
      break;
    case PROP_DOUBLE_BUFFER:
      if (xvimagesink->have_double_buffer) {
        GValue value = { 0 };

        array = g_value_array_new (2);
        g_value_init (&value, G_TYPE_BOOLEAN);
        g_value_set_boolean (&value, FALSE);
        g_value_array_append (array, &value);
        g_value_set_boolean (&value, TRUE);
        g_value_array_append (array, &value);
        g_value_unset (&value);
      }
      break;
    case PROP_COLORKEY:
      if (xvimagesink->have_colorkey) {
        GValue value = { 0 };

        array = g_value_array_new (1);
        g_value_init (&value, GST_TYPE_INT_RANGE);
        gst_value_set_int_range (&value, 0, 0xffffff);
        g_value_array_append (array, &value);
        g_value_unset (&value);
      }
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (probe, prop_id, pspec);
      break;
  }

beach:
  return array;
}

static void
gst_xvimagesink_property_probe_interface_init (GstPropertyProbeInterface *
    iface)
{
  iface->get_properties = gst_xvimagesink_probe_get_properties;
  iface->probe_property = gst_xvimagesink_probe_probe_property;
  iface->needs_probe = gst_xvimagesink_probe_needs_probe;
  iface->get_values = gst_xvimagesink_probe_get_values;
}

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

static void
gst_xvimagesink_set_property (GObject * object, guint prop_id,
    const GValue * value, GParamSpec * pspec)
{
  GstXvImageSink *xvimagesink;

  g_return_if_fail (GST_IS_XVIMAGESINK (object));

  xvimagesink = GST_XVIMAGESINK (object);

  switch (prop_id) {
    case PROP_HUE:
      xvimagesink->hue = g_value_get_int (value);
      xvimagesink->cb_changed = TRUE;
      gst_xvimagesink_update_colorbalance (xvimagesink);
      break;
    case PROP_CONTRAST:
      xvimagesink->contrast = g_value_get_int (value);
      xvimagesink->cb_changed = TRUE;
      gst_xvimagesink_update_colorbalance (xvimagesink);
      break;
    case PROP_BRIGHTNESS:
      xvimagesink->brightness = g_value_get_int (value);
      xvimagesink->cb_changed = TRUE;
      gst_xvimagesink_update_colorbalance (xvimagesink);
      break;
    case PROP_SATURATION:
      xvimagesink->saturation = g_value_get_int (value);
      xvimagesink->cb_changed = TRUE;
      gst_xvimagesink_update_colorbalance (xvimagesink);
      break;
    case PROP_DISPLAY:
      xvimagesink->display_name = g_strdup (g_value_get_string (value));
      break;
    case PROP_SYNCHRONOUS:
      xvimagesink->synchronous = g_value_get_boolean (value);
      if (xvimagesink->xcontext) {
        XSynchronize (xvimagesink->xcontext->disp, xvimagesink->synchronous);
        GST_DEBUG_OBJECT (xvimagesink, "XSynchronize called with %s",
            xvimagesink->synchronous ? "TRUE" : "FALSE");
      }
      break;
    case PROP_PIXEL_ASPECT_RATIO:
      g_free (xvimagesink->par);
      xvimagesink->par = g_new0 (GValue, 1);
      g_value_init (xvimagesink->par, GST_TYPE_FRACTION);
      if (!g_value_transform (value, xvimagesink->par)) {
        g_warning ("Could not transform string to aspect ratio");
        gst_value_set_fraction (xvimagesink->par, 1, 1);
      }
      GST_DEBUG_OBJECT (xvimagesink, "set PAR to %d/%d",
          gst_value_get_fraction_numerator (xvimagesink->par),
          gst_value_get_fraction_denominator (xvimagesink->par));
      break;
    case PROP_FORCE_ASPECT_RATIO:
      xvimagesink->keep_aspect = g_value_get_boolean (value);
      break;
    case PROP_HANDLE_EVENTS:
      gst_xvimagesink_set_event_handling (GST_X_OVERLAY (xvimagesink),
          g_value_get_boolean (value));
      gst_xvimagesink_manage_event_thread (xvimagesink);
      break;
    case PROP_DEVICE:
      xvimagesink->adaptor_no = atoi (g_value_get_string (value));
      break;
    case PROP_HANDLE_EXPOSE:
      xvimagesink->handle_expose = g_value_get_boolean (value);
      gst_xvimagesink_manage_event_thread (xvimagesink);
      break;
    case PROP_DOUBLE_BUFFER:
      xvimagesink->double_buffer = g_value_get_boolean (value);
      break;
    case PROP_AUTOPAINT_COLORKEY:
      xvimagesink->autopaint_colorkey = g_value_get_boolean (value);
      break;
    case PROP_COLORKEY:
      xvimagesink->colorkey = g_value_get_int (value);
      break;
    case PROP_DRAW_BORDERS:
      xvimagesink->draw_borders = g_value_get_boolean (value);
      break;
#ifdef GST_EXT_XV_ENHANCEMENT
    case PROP_DISPLAY_MODE:
    {
      int set_mode = g_value_get_enum (value);

      g_mutex_lock(xvimagesink->flow_lock);
      g_mutex_lock(xvimagesink->x_lock);

      if (xvimagesink->display_mode != set_mode) {
        if (xvimagesink->xcontext) {
          /* set display mode */
          if (set_display_mode(xvimagesink->xcontext, set_mode)) {
            xvimagesink->display_mode = set_mode;
          } else {
            GST_WARNING_OBJECT(xvimagesink, "display mode[%d] set failed.", set_mode);
          }
        } else {
          /* "xcontext" is not created yet. It will be applied when xcontext is created. */
          GST_INFO_OBJECT(xvimagesink, "xcontext is NULL. display-mode will be set later.");
          xvimagesink->display_mode = set_mode;
        }
      } else {
        GST_INFO_OBJECT(xvimagesink, "skip display mode %d, because current mode is same", set_mode);
      }

      g_mutex_unlock(xvimagesink->x_lock);
      g_mutex_unlock(xvimagesink->flow_lock);
    }
      break;
    case PROP_DISPLAY_GEOMETRY_METHOD:
      xvimagesink->display_geometry_method = g_value_get_enum (value);
      GST_LOG("Overlay geometry changed. update it");
      gst_xvimagesink_xvimage_put (xvimagesink, xvimagesink->xvimage);
      break;
    case PROP_FLIP:
      xvimagesink->flip = g_value_get_enum(value);
      break;
    case PROP_ROTATE_ANGLE:
      xvimagesink->rotate_angle = g_value_get_enum (value);
      xvimagesink->rotate_changed = TRUE;
      break;
    case PROP_VISIBLE:
      g_mutex_lock( xvimagesink->flow_lock );
      g_mutex_lock( xvimagesink->x_lock );

      if (xvimagesink->visible && (g_value_get_boolean(value) == FALSE)) {
        Atom atom_stream = XInternAtom( xvimagesink->xcontext->disp,
                                        "_USER_WM_PORT_ATTRIBUTE_STREAM_OFF", False );
        if (atom_stream != None) {
          if (XvSetPortAttribute(xvimagesink->xcontext->disp,
                                 xvimagesink->xcontext->xv_port_id,
                                 atom_stream, 0 ) != Success) {
            GST_WARNING_OBJECT( xvimagesink, "Set visible FALSE failed" );
          }

          XSync( xvimagesink->xcontext->disp, FALSE );
        }
      } else if (!xvimagesink->visible && (g_value_get_boolean(value) == TRUE)) {
        g_mutex_unlock( xvimagesink->x_lock );
        g_mutex_unlock( xvimagesink->flow_lock );
        GST_INFO_OBJECT( xvimagesink, "Set visible as TRUE. Update it." );
        gst_xvimagesink_xvimage_put (xvimagesink, xvimagesink->xvimage);
        g_mutex_lock( xvimagesink->flow_lock );
        g_mutex_lock( xvimagesink->x_lock );
      }

      xvimagesink->visible = g_value_get_boolean (value);

      g_mutex_unlock( xvimagesink->x_lock );
      g_mutex_unlock( xvimagesink->flow_lock );
      break;
    case PROP_ZOOM:
      xvimagesink->zoom = g_value_get_int (value);
      break;
    case PROP_DST_ROI_X:
      xvimagesink->dst_roi.x = g_value_get_int (value);
      break;
    case PROP_DST_ROI_Y:
      xvimagesink->dst_roi.y = g_value_get_int (value);
      break;
    case PROP_DST_ROI_W:
      xvimagesink->dst_roi.w = g_value_get_int (value);
      break;
    case PROP_DST_ROI_H:
      xvimagesink->dst_roi.h = g_value_get_int (value);
      break;
    case PROP_STOP_VIDEO:
      xvimagesink->stop_video = g_value_get_int (value);
      g_mutex_lock( xvimagesink->flow_lock );

      if( xvimagesink->stop_video )
      {
        if ( xvimagesink->get_pixmap_cb ) {
          if (xvimagesink->xpixmap[0] && xvimagesink->xpixmap[0]->pixmap) {
            g_mutex_lock (xvimagesink->x_lock);
            GST_INFO_OBJECT( xvimagesink, "calling XvStopVideo()" );
            XvStopVideo (xvimagesink->xcontext->disp, xvimagesink->xcontext->xv_port_id, xvimagesink->xpixmap[0]->pixmap);
            g_mutex_unlock (xvimagesink->x_lock);
          }
        } else {
          GST_INFO_OBJECT( xvimagesink, "Xwindow CLEAR when set video-stop property" );
          gst_xvimagesink_xwindow_clear (xvimagesink, xvimagesink->xwindow);
        }
      }

      g_mutex_unlock( xvimagesink->flow_lock );
      break;
    case PROP_PIXMAP_CB:
    {
      void *cb_func;
      cb_func = g_value_get_pointer(value);
      if (cb_func) {
        xvimagesink->get_pixmap_cb = cb_func;
        GST_INFO_OBJECT (xvimagesink, "Set callback(0x%x) for getting pixmap id", xvimagesink->get_pixmap_cb);
      }
      break;
    }
    case PROP_PIXMAP_CB_USER_DATA:
    {
      void *user_data;
      user_data = g_value_get_pointer(value);
      if (user_data) {
        xvimagesink->get_pixmap_cb_user_data = user_data;
        GST_INFO_OBJECT (xvimagesink, "Set user data(0x%x) for getting pixmap id", xvimagesink->get_pixmap_cb_user_data);
      }
      break;
    }
#endif /* GST_EXT_XV_ENHANCEMENT */
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
}

static void
gst_xvimagesink_get_property (GObject * object, guint prop_id,
    GValue * value, GParamSpec * pspec)
{
  GstXvImageSink *xvimagesink;

  g_return_if_fail (GST_IS_XVIMAGESINK (object));

  xvimagesink = GST_XVIMAGESINK (object);

  switch (prop_id) {
    case PROP_HUE:
      g_value_set_int (value, xvimagesink->hue);
      break;
    case PROP_CONTRAST:
      g_value_set_int (value, xvimagesink->contrast);
      break;
    case PROP_BRIGHTNESS:
      g_value_set_int (value, xvimagesink->brightness);
      break;
    case PROP_SATURATION:
      g_value_set_int (value, xvimagesink->saturation);
      break;
    case PROP_DISPLAY:
      g_value_set_string (value, xvimagesink->display_name);
      break;
    case PROP_SYNCHRONOUS:
      g_value_set_boolean (value, xvimagesink->synchronous);
      break;
    case PROP_PIXEL_ASPECT_RATIO:
      if (xvimagesink->par)
        g_value_transform (xvimagesink->par, value);
      break;
    case PROP_FORCE_ASPECT_RATIO:
      g_value_set_boolean (value, xvimagesink->keep_aspect);
      break;
    case PROP_HANDLE_EVENTS:
      g_value_set_boolean (value, xvimagesink->handle_events);
      break;
    case PROP_DEVICE:
    {
      char *adaptor_no_s = g_strdup_printf ("%u", xvimagesink->adaptor_no);

      g_value_set_string (value, adaptor_no_s);
      g_free (adaptor_no_s);
      break;
    }
    case PROP_DEVICE_NAME:
      if (xvimagesink->xcontext && xvimagesink->xcontext->adaptors) {
        g_value_set_string (value,
            xvimagesink->xcontext->adaptors[xvimagesink->adaptor_no]);
      } else {
        g_value_set_string (value, NULL);
      }
      break;
    case PROP_HANDLE_EXPOSE:
      g_value_set_boolean (value, xvimagesink->handle_expose);
      break;
    case PROP_DOUBLE_BUFFER:
      g_value_set_boolean (value, xvimagesink->double_buffer);
      break;
    case PROP_AUTOPAINT_COLORKEY:
      g_value_set_boolean (value, xvimagesink->autopaint_colorkey);
      break;
    case PROP_COLORKEY:
      g_value_set_int (value, xvimagesink->colorkey);
      break;
    case PROP_DRAW_BORDERS:
      g_value_set_boolean (value, xvimagesink->draw_borders);
      break;
    case PROP_WINDOW_WIDTH:
      if (xvimagesink->xwindow)
        g_value_set_uint64 (value, xvimagesink->xwindow->width);
      else
        g_value_set_uint64 (value, 0);
      break;
    case PROP_WINDOW_HEIGHT:
      if (xvimagesink->xwindow)
        g_value_set_uint64 (value, xvimagesink->xwindow->height);
      else
        g_value_set_uint64 (value, 0);
      break;
#ifdef GST_EXT_XV_ENHANCEMENT
    case PROP_DISPLAY_MODE:
      g_value_set_enum (value, xvimagesink->display_mode);
      break;
    case PROP_DISPLAY_GEOMETRY_METHOD:
      g_value_set_enum (value, xvimagesink->display_geometry_method);
      break;
    case PROP_FLIP:
      g_value_set_enum(value, xvimagesink->flip);
      break;
    case PROP_ROTATE_ANGLE:
      g_value_set_enum (value, xvimagesink->rotate_angle);
      break;
    case PROP_VISIBLE:
      g_value_set_boolean (value, xvimagesink->visible);
      break;
    case PROP_ZOOM:
      g_value_set_int (value, xvimagesink->zoom);
      break;
    case PROP_DST_ROI_X:
      g_value_set_int (value, xvimagesink->dst_roi.x);
      break;
    case PROP_DST_ROI_Y:
      g_value_set_int (value, xvimagesink->dst_roi.y);
      break;
    case PROP_DST_ROI_W:
      g_value_set_int (value, xvimagesink->dst_roi.w);
      break;
    case PROP_DST_ROI_H:
      g_value_set_int (value, xvimagesink->dst_roi.h);
      break;
    case PROP_STOP_VIDEO:
      g_value_set_int (value, xvimagesink->stop_video);
      break;
    case PROP_PIXMAP_CB:
      g_value_set_pointer (value, xvimagesink->get_pixmap_cb);
      break;
    case PROP_PIXMAP_CB_USER_DATA:
      g_value_set_pointer (value, xvimagesink->get_pixmap_cb_user_data);
      break;
#endif /* GST_EXT_XV_ENHANCEMENT */
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
}

static void
gst_xvimagesink_reset (GstXvImageSink * xvimagesink)
{
  GThread *thread;

  GST_OBJECT_LOCK (xvimagesink);
  xvimagesink->running = FALSE;
  /* grab thread and mark it as NULL */
  thread = xvimagesink->event_thread;
  xvimagesink->event_thread = NULL;
  GST_OBJECT_UNLOCK (xvimagesink);

  /* invalidate the pool, current allocations continue, new buffer_alloc fails
   * with wrong_state */
  g_mutex_lock (xvimagesink->pool_lock);
  xvimagesink->pool_invalid = TRUE;
  g_mutex_unlock (xvimagesink->pool_lock);

  /* Wait for our event thread to finish before we clean up our stuff. */
  if (thread)
    g_thread_join (thread);

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

  gst_xvimagesink_imagepool_clear (xvimagesink);

  if (xvimagesink->xwindow) {
    gst_xvimagesink_xwindow_clear (xvimagesink, xvimagesink->xwindow);
    gst_xvimagesink_xwindow_destroy (xvimagesink, xvimagesink->xwindow);
    xvimagesink->xwindow = NULL;
  }
#ifdef GST_EXT_XV_ENHANCEMENT
  if (xvimagesink->get_pixmap_cb) {
    int i = 0;
    if (xvimagesink->xpixmap[0] && xvimagesink->xpixmap[0]->pixmap) {
      g_mutex_lock (xvimagesink->x_lock);
      GST_INFO_OBJECT( xvimagesink, "calling XvStopVideo()" );
      XvStopVideo (xvimagesink->xcontext->disp, xvimagesink->xcontext->xv_port_id, xvimagesink->xpixmap[0]->pixmap);
      g_mutex_unlock (xvimagesink->x_lock);
    }
    for (i = 0; i < MAX_PIXMAP_NUM; i++) {
      if (xvimagesink->xpixmap[i]) {
        gst_xvimagesink_xpixmap_destroy (xvimagesink, xvimagesink->xpixmap[i]);
        xvimagesink->xpixmap[i] = NULL;
      }
    }
    xvimagesink->get_pixmap_cb = NULL;
    xvimagesink->get_pixmap_cb_user_data = NULL;
  }
#endif /* GST_EXT_XV_ENHANCEMENT */
  xvimagesink->render_rect.x = xvimagesink->render_rect.y =
      xvimagesink->render_rect.w = xvimagesink->render_rect.h = 0;
  xvimagesink->have_render_rect = FALSE;

  gst_xvimagesink_xcontext_clear (xvimagesink);
}

/* Finalize is called only once, dispose can be called multiple times.
 * We use mutexes and don't reset stuff to NULL here so let's register
 * as a finalize. */
static void
gst_xvimagesink_finalize (GObject * object)
{
  GstXvImageSink *xvimagesink;

  xvimagesink = GST_XVIMAGESINK (object);

  gst_xvimagesink_reset (xvimagesink);

  if (xvimagesink->display_name) {
    g_free (xvimagesink->display_name);
    xvimagesink->display_name = NULL;
  }

  if (xvimagesink->par) {
    g_free (xvimagesink->par);
    xvimagesink->par = NULL;
  }
  if (xvimagesink->x_lock) {
    g_mutex_free (xvimagesink->x_lock);
    xvimagesink->x_lock = NULL;
  }
  if (xvimagesink->flow_lock) {
    g_mutex_free (xvimagesink->flow_lock);
    xvimagesink->flow_lock = NULL;
  }
  if (xvimagesink->pool_lock) {
    g_mutex_free (xvimagesink->pool_lock);
    xvimagesink->pool_lock = NULL;
  }

  g_free (xvimagesink->media_title);

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

static void
gst_xvimagesink_init (GstXvImageSink * xvimagesink,
    GstXvImageSinkClass * xvimagesinkclass)
{
  xvimagesink->display_name = NULL;
  xvimagesink->adaptor_no = 0;
  xvimagesink->xcontext = NULL;
  xvimagesink->xwindow = NULL;
  xvimagesink->xvimage = NULL;
  xvimagesink->cur_image = NULL;

  xvimagesink->hue = xvimagesink->saturation = 0;
  xvimagesink->contrast = xvimagesink->brightness = 0;
  xvimagesink->cb_changed = FALSE;

  xvimagesink->fps_n = 0;
  xvimagesink->fps_d = 0;
  xvimagesink->video_width = 0;
  xvimagesink->video_height = 0;

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

  xvimagesink->image_pool = NULL;
  xvimagesink->pool_lock = g_mutex_new ();

  xvimagesink->synchronous = FALSE;
  xvimagesink->double_buffer = TRUE;
  xvimagesink->running = FALSE;
  xvimagesink->keep_aspect = FALSE;
  xvimagesink->handle_events = TRUE;
  xvimagesink->par = NULL;
  xvimagesink->handle_expose = TRUE;
  xvimagesink->autopaint_colorkey = TRUE;

  /* on 16bit displays this becomes r,g,b = 1,2,3
   * on 24bit displays this becomes r,g,b = 8,8,16
   * as a port atom value
   */
  xvimagesink->colorkey = (8 << 16) | (8 << 8) | 16;
  xvimagesink->draw_borders = TRUE;

#ifdef GST_EXT_XV_ENHANCEMENT
  xvimagesink->xid_updated = FALSE;
  xvimagesink->display_mode = DISPLAY_MODE_DEFAULT;
  xvimagesink->rotate_changed = TRUE;
  xvimagesink->display_geometry_method = DEF_DISPLAY_GEOMETRY_METHOD;
  xvimagesink->flip = DEF_DISPLAY_FLIP;
  xvimagesink->rotate_angle = DEGREE_270;
  xvimagesink->visible = TRUE;
  xvimagesink->zoom = 1;
  xvimagesink->rotation = -1;
  xvimagesink->dst_roi.x = 0;
  xvimagesink->dst_roi.y = 0;
  xvimagesink->dst_roi.w = 0;
  xvimagesink->dst_roi.h = 0;
  xvimagesink->xim_transparenter = NULL;
  xvimagesink->scr_w = 0;
  xvimagesink->scr_h = 0;
  xvimagesink->aligned_width = 0;
  xvimagesink->aligned_height = 0;
  xvimagesink->stop_video = FALSE;
  xvimagesink->is_hided = FALSE;
  xvimagesink->drm_fd = -1;
  xvimagesink->current_pixmap_idx = -1;
  xvimagesink->get_pixmap_cb = NULL;
  xvimagesink->get_pixmap_cb_user_data = NULL;
#endif /* GST_EXT_XV_ENHANCEMENT */
}

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

  gst_element_class_set_details_simple (element_class,
      "Video sink", "Sink/Video",
      "A Xv based videosink", "Julien Moutte <julien@moutte.net>");

  gst_element_class_add_static_pad_template (element_class,
      &gst_xvimagesink_sink_template_factory);
}

static void
gst_xvimagesink_class_init (GstXvImageSinkClass * klass)
{
  GObjectClass *gobject_class;
  GstElementClass *gstelement_class;
  GstBaseSinkClass *gstbasesink_class;
  GstVideoSinkClass *videosink_class;

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

  gobject_class->set_property = gst_xvimagesink_set_property;
  gobject_class->get_property = gst_xvimagesink_get_property;

  g_object_class_install_property (gobject_class, PROP_CONTRAST,
      g_param_spec_int ("contrast", "Contrast", "The contrast of the video",
          -1000, 1000, 0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
  g_object_class_install_property (gobject_class, PROP_BRIGHTNESS,
      g_param_spec_int ("brightness", "Brightness",
          "The brightness of the video", -1000, 1000, 0,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
  g_object_class_install_property (gobject_class, PROP_HUE,
      g_param_spec_int ("hue", "Hue", "The hue of the video", -1000, 1000, 0,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
  g_object_class_install_property (gobject_class, PROP_SATURATION,
      g_param_spec_int ("saturation", "Saturation",
          "The saturation of the video", -1000, 1000, 0,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
  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. "
          "(unrelated to A/V sync, 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_FORCE_ASPECT_RATIO,
      g_param_spec_boolean ("force-aspect-ratio", "Force aspect ratio",
          "When enabled, scaling will respect original aspect ratio", FALSE,
          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_DEVICE,
      g_param_spec_string ("device", "Adaptor number",
          "The number of the video adaptor", "0",
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
  g_object_class_install_property (gobject_class, PROP_DEVICE_NAME,
      g_param_spec_string ("device-name", "Adaptor name",
          "The name of the video adaptor", NULL,
          G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
  /**
   * GstXvImageSink:handle-expose
   *
   * When enabled, the current frame will always be drawn in response to X
   * Expose.
   *
   * Since: 0.10.14
   */
  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));

  /**
   * GstXvImageSink:double-buffer
   *
   * Whether to double-buffer the output.
   *
   * Since: 0.10.14
   */
  g_object_class_install_property (gobject_class, PROP_DOUBLE_BUFFER,
      g_param_spec_boolean ("double-buffer", "Double-buffer",
          "Whether to double-buffer the output", TRUE,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
  /**
   * GstXvImageSink:autopaint-colorkey
   *
   * Whether to autofill overlay with colorkey
   *
   * Since: 0.10.21
   */
  g_object_class_install_property (gobject_class, PROP_AUTOPAINT_COLORKEY,
      g_param_spec_boolean ("autopaint-colorkey", "Autofill with colorkey",
          "Whether to autofill overlay with colorkey", TRUE,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
  /**
   * GstXvImageSink:colorkey
   *
   * Color to use for the overlay mask.
   *
   * Since: 0.10.21
   */
  g_object_class_install_property (gobject_class, PROP_COLORKEY,
      g_param_spec_int ("colorkey", "Colorkey",
          "Color to use for the overlay mask", G_MININT, G_MAXINT, 0,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  /**
   * GstXvImageSink:draw-borders
   *
   * Draw black borders when using GstXvImageSink:force-aspect-ratio to fill
   * unused parts of the video area.
   *
   * Since: 0.10.21
   */
  g_object_class_install_property (gobject_class, PROP_DRAW_BORDERS,
      g_param_spec_boolean ("draw-borders", "Colorkey",
          "Draw black borders to fill unused area in force-aspect-ratio mode",
          TRUE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  /**
   * GstXvImageSink:window-width
   *
   * Actual width of the video window.
   *
   * Since: 0.10.32
   */
  g_object_class_install_property (gobject_class, PROP_WINDOW_WIDTH,
      g_param_spec_uint64 ("window-width", "window-width",
          "Width of the window", 0, G_MAXUINT64, 0,
          G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));

  /**
   * GstXvImageSink:window-height
   *
   * Actual height of the video window.
   *
   * Since: 0.10.32
   */
  g_object_class_install_property (gobject_class, PROP_WINDOW_HEIGHT,
      g_param_spec_uint64 ("window-height", "window-height",
          "Height of the window", 0, G_MAXUINT64, 0,
          G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));

#ifdef GST_EXT_XV_ENHANCEMENT
  /**
   * GstXvImageSink:display-mode
   *
   * select display mode
   */
  g_object_class_install_property(gobject_class, PROP_DISPLAY_MODE,
    g_param_spec_enum("display-mode", "Display Mode",
      "Display device setting",
      GST_TYPE_XVIMAGESINK_DISPLAY_MODE, DISPLAY_MODE_DEFAULT,
      G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  /**
   * GstXvImageSink:display-geometry-method
   *
   * Display geometrical method setting
   */
  g_object_class_install_property(gobject_class, PROP_DISPLAY_GEOMETRY_METHOD,
    g_param_spec_enum("display-geometry-method", "Display geometry method",
      "Geometrical method for display",
      GST_TYPE_XVIMAGESINK_DISPLAY_GEOMETRY_METHOD, DEF_DISPLAY_GEOMETRY_METHOD,
      G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  /**
   * GstXvImageSink:display-flip
   *
   * Display flip setting
   */
  g_object_class_install_property(gobject_class, PROP_FLIP,
    g_param_spec_enum("flip", "Display flip",
      "Flip for display",
      GST_TYPE_XVIMAGESINK_FLIP, DEF_DISPLAY_FLIP,
      G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  /**
   * GstXvImageSink:rotate
   *
   * Draw rotation angle setting
   */
  g_object_class_install_property(gobject_class, PROP_ROTATE_ANGLE,
    g_param_spec_enum("rotate", "Rotate angle",
      "Rotate angle of display output",
      GST_TYPE_XVIMAGESINK_ROTATE_ANGLE, DEGREE_270,
      G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  /**
   * GstXvImageSink:visible
   *
   * Whether reserve original src size or not
   */
  g_object_class_install_property (gobject_class, PROP_VISIBLE,
      g_param_spec_boolean ("visible", "Visible",
          "Draws screen or blacks out, true means visible, false blacks out",
          TRUE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  /**
   * GstXvImageSink:zoom
   *
   * Scale small area of screen to 2X, 3X, ... , 9X
   */
  g_object_class_install_property (gobject_class, PROP_ZOOM,
      g_param_spec_int ("zoom", "Zoom",
          "Zooms screen as nX", 1, 9, 1,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  /**
   * GstXvImageSink:dst-roi-x
   *
   * X value of Destination ROI
   */
  g_object_class_install_property (gobject_class, PROP_DST_ROI_X,
      g_param_spec_int ("dst-roi-x", "Dst-ROI-X",
          "X value of Destination ROI(only effective \"CUSTOM_ROI\")", 0, XV_SCREEN_SIZE_WIDTH, 0,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  /**
   * GstXvImageSink:dst-roi-y
   *
   * Y value of Destination ROI
   */
  g_object_class_install_property (gobject_class, PROP_DST_ROI_Y,
      g_param_spec_int ("dst-roi-y", "Dst-ROI-Y",
          "Y value of Destination ROI(only effective \"CUSTOM_ROI\")", 0, XV_SCREEN_SIZE_HEIGHT, 0,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  /**
   * GstXvImageSink:dst-roi-w
   *
   * W value of Destination ROI
   */
  g_object_class_install_property (gobject_class, PROP_DST_ROI_W,
      g_param_spec_int ("dst-roi-w", "Dst-ROI-W",
          "W value of Destination ROI(only effective \"CUSTOM_ROI\")", 0, XV_SCREEN_SIZE_WIDTH, 0,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  /**
   * GstXvImageSink:dst-roi-h
   *
   * H value of Destination ROI
   */
  g_object_class_install_property (gobject_class, PROP_DST_ROI_H,
      g_param_spec_int ("dst-roi-h", "Dst-ROI-H",
          "H value of Destination ROI(only effective \"CUSTOM_ROI\")", 0, XV_SCREEN_SIZE_HEIGHT, 0,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  /**
   * GstXvImageSink:stop-video
   *
   * Stop video for releasing video source buffer
   */
  g_object_class_install_property (gobject_class, PROP_STOP_VIDEO,
      g_param_spec_int ("stop-video", "Stop-Video",
          "Stop video for releasing video source buffer", 0, 1, 0,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  g_object_class_install_property (gobject_class, PROP_PIXMAP_CB,
      g_param_spec_pointer("pixmap-id-callback", "Pixmap-Id-Callback",
          "pointer of callback function for getting pixmap id", G_PARAM_READWRITE));

  g_object_class_install_property (gobject_class, PROP_PIXMAP_CB_USER_DATA,
      g_param_spec_pointer("pixmap-id-callback-userdata", "Pixmap-Id-Callback-Userdata",
          "pointer of user data of callback function for getting pixmap id", G_PARAM_READWRITE));

  /**
   * GstXvImageSink::frame-render-error
   */
  gst_xvimagesink_signals[SIGNAL_FRAME_RENDER_ERROR] = g_signal_new (
          "frame-render-error",
          G_TYPE_FROM_CLASS (klass),
          G_SIGNAL_RUN_LAST,
          0,
          NULL,
          NULL,
          gst_xvimagesink_BOOLEAN__POINTER,
          G_TYPE_BOOLEAN,
          1,
          G_TYPE_POINTER);

#endif /* GST_EXT_XV_ENHANCEMENT */

  gobject_class->finalize = gst_xvimagesink_finalize;

  gstelement_class->change_state =
      GST_DEBUG_FUNCPTR (gst_xvimagesink_change_state);

  gstbasesink_class->get_caps = GST_DEBUG_FUNCPTR (gst_xvimagesink_getcaps);
  gstbasesink_class->set_caps = GST_DEBUG_FUNCPTR (gst_xvimagesink_setcaps);
  gstbasesink_class->buffer_alloc =
      GST_DEBUG_FUNCPTR (gst_xvimagesink_buffer_alloc);
  gstbasesink_class->get_times = GST_DEBUG_FUNCPTR (gst_xvimagesink_get_times);
  gstbasesink_class->event = GST_DEBUG_FUNCPTR (gst_xvimagesink_event);

  videosink_class->show_frame = GST_DEBUG_FUNCPTR (gst_xvimagesink_show_frame);
}

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

/* =========================================== */
/*                                             */
/*          Object typing & Creation           */
/*                                             */
/* =========================================== */
static void
gst_xvimagesink_init_interfaces (GType type)
{
  static const GInterfaceInfo iface_info = {
    (GInterfaceInitFunc) gst_xvimagesink_interface_init,
    NULL,
    NULL,
  };
  static const GInterfaceInfo navigation_info = {
    (GInterfaceInitFunc) gst_xvimagesink_navigation_init,
    NULL,
    NULL,
  };
  static const GInterfaceInfo overlay_info = {
    (GInterfaceInitFunc) gst_xvimagesink_xoverlay_init,
    NULL,
    NULL,
  };
  static const GInterfaceInfo colorbalance_info = {
    (GInterfaceInitFunc) gst_xvimagesink_colorbalance_init,
    NULL,
    NULL,
  };
  static const GInterfaceInfo propertyprobe_info = {
    (GInterfaceInitFunc) gst_xvimagesink_property_probe_interface_init,
    NULL,
    NULL,
  };

  g_type_add_interface_static (type,
      GST_TYPE_IMPLEMENTS_INTERFACE, &iface_info);
  g_type_add_interface_static (type, GST_TYPE_NAVIGATION, &navigation_info);
  g_type_add_interface_static (type, GST_TYPE_X_OVERLAY, &overlay_info);
  g_type_add_interface_static (type, GST_TYPE_COLOR_BALANCE,
      &colorbalance_info);
  g_type_add_interface_static (type, GST_TYPE_PROPERTY_PROBE,
      &propertyprobe_info);

  /* register type and create class in a more safe place instead of at
   * runtime since the type registration and class creation is not
   * threadsafe. */
  g_type_class_ref (gst_xvimage_buffer_get_type ());
}

static gboolean
plugin_init (GstPlugin * plugin)
{
  if (!gst_element_register (plugin, "xvimagesink",
          GST_RANK_PRIMARY, GST_TYPE_XVIMAGESINK))
    return FALSE;

  GST_DEBUG_CATEGORY_INIT (gst_debug_xvimagesink, "xvimagesink", 0,
      "xvimagesink element");
  GST_DEBUG_CATEGORY_GET (GST_CAT_PERFORMANCE, "GST_PERFORMANCE");

  return TRUE;
}

GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
    GST_VERSION_MINOR,
    "xvimagesink",
    "XFree86 video output plugin using Xv extension",
    plugin_init, VERSION, GST_LICENSE, GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)