summaryrefslogtreecommitdiff
path: root/gst-libs/gst/d3d11/gstd3d11memory.c
blob: 74137dd6a47ec0ba4ea0365ec8e51cbcad02f304 (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
/* GStreamer
 * Copyright (C) 2019 Seungha Yang <seungha.yang@navercorp.com>
 * Copyright (C) 2020 Seungha Yang <seungha@centricular.com>
 *
 * 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., 51 Franklin St, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

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

#include <string.h>
#include "gstd3d11memory.h"
#include "gstd3d11device.h"
#include "gstd3d11utils.h"

GST_DEBUG_CATEGORY_STATIC (gst_d3d11_allocator_debug);
#define GST_CAT_DEFAULT gst_d3d11_allocator_debug

static GstAllocator *_d3d11_memory_allocator;

/* GstD3D11AllocationParams */
static void gst_d3d11_allocation_params_init (GType type);
G_DEFINE_BOXED_TYPE_WITH_CODE (GstD3D11AllocationParams,
    gst_d3d11_allocation_params,
    (GBoxedCopyFunc) gst_d3d11_allocation_params_copy,
    (GBoxedFreeFunc) gst_d3d11_allocation_params_free,
    gst_d3d11_allocation_params_init (g_define_type_id));

/**
 * gst_d3d11_allocation_params_new:
 * @device: a #GstD3D11Device
 * @info: a #GstVideoInfo
 * @flags: a #GstD3D11AllocationFlags
 * @bind_flags: D3D11_BIND_FLAG value used for creating Direct3D11 texture
 *
 * Create #GstD3D11AllocationParams object which is used by #GstD3D11BufferPool
 * and #GstD3D11Allocator in order to allocate new ID3D11Texture2D
 * object with given configuration
 *
 * Returns: a #GstD3D11AllocationParams or %NULL if @info is not supported
 *
 * Since: 1.20
 */
GstD3D11AllocationParams *
gst_d3d11_allocation_params_new (GstD3D11Device * device, GstVideoInfo * info,
    GstD3D11AllocationFlags flags, guint bind_flags)
{
  GstD3D11AllocationParams *ret;
  const GstD3D11Format *d3d11_format;
  gint i;

  g_return_val_if_fail (info != NULL, NULL);

  d3d11_format = gst_d3d11_device_format_from_gst (device,
      GST_VIDEO_INFO_FORMAT (info));
  if (!d3d11_format) {
    GST_WARNING ("Couldn't get d3d11 format");
    return NULL;
  }

  ret = g_new0 (GstD3D11AllocationParams, 1);

  ret->info = *info;
  ret->aligned_info = *info;
  ret->d3d11_format = d3d11_format;

  /* Usage Flag
   * https://docs.microsoft.com/en-us/windows/win32/api/d3d11/ne-d3d11-d3d11_usage
   *
   * +----------------------------------------------------------+
   * | Resource Usage | Default | Dynamic | Immutable | Staging |
   * +----------------+---------+---------+-----------+---------+
   * | GPU-Read       | Yes     | Yes     | Yes       | Yes     |
   * | GPU-Write      | Yes     |         |           | Yes     |
   * | CPU-Read       |         |         |           | Yes     |
   * | CPU-Write      |         | Yes     |           | Yes     |
   * +----------------------------------------------------------+
   */

  /* If corresponding dxgi format is undefined, use resource format instead */
  if (d3d11_format->dxgi_format == DXGI_FORMAT_UNKNOWN) {
    for (i = 0; i < GST_VIDEO_INFO_N_PLANES (info); i++) {
      g_assert (d3d11_format->resource_format[i] != DXGI_FORMAT_UNKNOWN);

      ret->desc[i].Width = GST_VIDEO_INFO_COMP_WIDTH (info, i);
      ret->desc[i].Height = GST_VIDEO_INFO_COMP_HEIGHT (info, i);
      ret->desc[i].MipLevels = 1;
      ret->desc[i].ArraySize = 1;
      ret->desc[i].Format = d3d11_format->resource_format[i];
      ret->desc[i].SampleDesc.Count = 1;
      ret->desc[i].SampleDesc.Quality = 0;
      ret->desc[i].Usage = D3D11_USAGE_DEFAULT;
      ret->desc[i].BindFlags = bind_flags;
    }
  } else {
    ret->desc[0].Width = GST_VIDEO_INFO_WIDTH (info);
    ret->desc[0].Height = GST_VIDEO_INFO_HEIGHT (info);
    ret->desc[0].MipLevels = 1;
    ret->desc[0].ArraySize = 1;
    ret->desc[0].Format = d3d11_format->dxgi_format;
    ret->desc[0].SampleDesc.Count = 1;
    ret->desc[0].SampleDesc.Quality = 0;
    ret->desc[0].Usage = D3D11_USAGE_DEFAULT;
    ret->desc[0].BindFlags = bind_flags;
  }

  ret->flags = flags;

  return ret;
}

/**
 * gst_d3d11_allocation_params_alignment:
 * @params: a #GstD3D11AllocationParams
 * @align: a #GstVideoAlignment
 *
 * Adjust Width and Height fields of D3D11_TEXTURE2D_DESC with given
 * @align
 *
 * Returns: %TRUE if alignment could be applied
 *
 * Since: 1.20
 */
gboolean
gst_d3d11_allocation_params_alignment (GstD3D11AllocationParams * params,
    GstVideoAlignment * align)
{
  gint i;
  guint padding_width, padding_height;
  GstVideoInfo *info;
  GstVideoInfo new_info;

  g_return_val_if_fail (params != NULL, FALSE);
  g_return_val_if_fail (align != NULL, FALSE);

  /* d3d11 does not support stride align. Consider padding only */
  padding_width = align->padding_left + align->padding_right;
  padding_height = align->padding_top + align->padding_bottom;

  info = &params->info;

  if (!gst_video_info_set_format (&new_info, GST_VIDEO_INFO_FORMAT (info),
          GST_VIDEO_INFO_WIDTH (info) + padding_width,
          GST_VIDEO_INFO_HEIGHT (info) + padding_height)) {
    GST_WARNING ("Set format fail");
    return FALSE;
  }

  params->aligned_info = new_info;

  for (i = 0; i < GST_VIDEO_INFO_N_PLANES (info); i++) {
    params->desc[i].Width = GST_VIDEO_INFO_COMP_WIDTH (&new_info, i);
    params->desc[i].Height = GST_VIDEO_INFO_COMP_HEIGHT (&new_info, i);
  }

  return TRUE;
}

/**
 * gst_d3d11_allocation_params_copy:
 * @src: a #GstD3D11AllocationParams
 *
 * Returns: a copy of @src
 *
 * Since: 1.20
 */
GstD3D11AllocationParams *
gst_d3d11_allocation_params_copy (GstD3D11AllocationParams * src)
{
  GstD3D11AllocationParams *dst;

  g_return_val_if_fail (src != NULL, NULL);

  dst = g_new0 (GstD3D11AllocationParams, 1);
  memcpy (dst, src, sizeof (GstD3D11AllocationParams));

  return dst;
}

/**
 * gst_d3d11_allocation_params_free:
 * @params: a #GstD3D11AllocationParams
 *
 * Free @params
 *
 * Since: 1.20
 */
void
gst_d3d11_allocation_params_free (GstD3D11AllocationParams * params)
{
  g_free (params);
}

static gint
gst_d3d11_allocation_params_compare (const GstD3D11AllocationParams * p1,
    const GstD3D11AllocationParams * p2)
{
  g_return_val_if_fail (p1 != NULL, -1);
  g_return_val_if_fail (p2 != NULL, -1);

  if (p1 == p2)
    return 0;

  return -1;
}

static void
gst_d3d11_allocation_params_init (GType type)
{
  static GstValueTable table = {
    0, (GstValueCompareFunc) gst_d3d11_allocation_params_compare,
    NULL, NULL
  };

  table.type = type;
  gst_value_register (&table);
}

/* GstD3D11Memory */
#define GST_D3D11_MEMORY_GET_LOCK(m) (&(GST_D3D11_MEMORY_CAST(m)->priv->lock))
#define GST_D3D11_MEMORY_LOCK(m) G_STMT_START { \
  GST_TRACE("Locking %p from thread %p", (m), g_thread_self()); \
  g_mutex_lock(GST_D3D11_MEMORY_GET_LOCK(m)); \
  GST_TRACE("Locked %p from thread %p", (m), g_thread_self()); \
} G_STMT_END

#define GST_D3D11_MEMORY_UNLOCK(m) G_STMT_START { \
  GST_TRACE("Unlocking %p from thread %p", (m), g_thread_self()); \
  g_mutex_unlock(GST_D3D11_MEMORY_GET_LOCK(m)); \
} G_STMT_END

struct _GstD3D11MemoryPrivate
{
  ID3D11Texture2D *texture;
  ID3D11Texture2D *staging;

  D3D11_TEXTURE2D_DESC desc;

  guint subresource_index;

  ID3D11ShaderResourceView *shader_resource_view[GST_VIDEO_MAX_PLANES];
  guint num_shader_resource_views;

  ID3D11RenderTargetView *render_target_view[GST_VIDEO_MAX_PLANES];
  guint num_render_target_views;

  ID3D11VideoDecoderOutputView *decoder_output_view;
  ID3D11VideoProcessorInputView *processor_input_view;
  ID3D11VideoProcessorOutputView *processor_output_view;

  D3D11_MAPPED_SUBRESOURCE map;


  GMutex lock;
  gint cpu_map_count;
};

GST_DEFINE_MINI_OBJECT_TYPE (GstD3D11Memory, gst_d3d11_memory);

static inline D3D11_MAP
gst_d3d11_map_flags_to_d3d11 (GstMapFlags flags)
{
  if ((flags & GST_MAP_READWRITE) == GST_MAP_READWRITE)
    return D3D11_MAP_READ_WRITE;
  else if ((flags & GST_MAP_WRITE) == GST_MAP_WRITE)
    return D3D11_MAP_WRITE;
  else if ((flags & GST_MAP_READ) == GST_MAP_READ)
    return D3D11_MAP_READ;
  else
    g_assert_not_reached ();

  return D3D11_MAP_READ;
}

static ID3D11Texture2D *
gst_d3d11_allocate_staging_texture (GstD3D11Device * device,
    const D3D11_TEXTURE2D_DESC * ref)
{
  D3D11_TEXTURE2D_DESC desc = { 0, };
  ID3D11Texture2D *texture = NULL;
  ID3D11Device *device_handle = gst_d3d11_device_get_device_handle (device);
  HRESULT hr;

  desc.Width = ref->Width;
  desc.Height = ref->Height;
  desc.MipLevels = 1;
  desc.Format = ref->Format;
  desc.SampleDesc.Count = 1;
  desc.ArraySize = 1;
  desc.Usage = D3D11_USAGE_STAGING;
  desc.CPUAccessFlags = (D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE);

  hr = ID3D11Device_CreateTexture2D (device_handle, &desc, NULL, &texture);
  if (!gst_d3d11_result (hr, device)) {
    GST_ERROR_OBJECT (device, "Failed to create texture");
    return NULL;
  }

  return texture;
}

/* Must be called with d3d11 device lock */
static gboolean
gst_d3d11_memory_map_cpu_access (GstD3D11Memory * dmem, D3D11_MAP map_type)
{
  GstD3D11MemoryPrivate *priv = dmem->priv;
  HRESULT hr;
  ID3D11Resource *staging = (ID3D11Resource *) priv->staging;
  ID3D11DeviceContext *device_context =
      gst_d3d11_device_get_device_context_handle (dmem->device);

  hr = ID3D11DeviceContext_Map (device_context,
      staging, 0, map_type, 0, &priv->map);

  if (!gst_d3d11_result (hr, dmem->device)) {
    GST_ERROR_OBJECT (GST_MEMORY_CAST (dmem)->allocator,
        "Failed to map staging texture (0x%x)", (guint) hr);
    return FALSE;
  }

  return TRUE;
}

/* Must be called with d3d11 device lock */
static void
gst_d3d11_memory_upload (GstD3D11Memory * dmem)
{
  GstD3D11MemoryPrivate *priv = dmem->priv;
  ID3D11DeviceContext *device_context;

  if (!priv->staging || priv->staging == priv->texture ||
      !GST_MEMORY_FLAG_IS_SET (dmem, GST_D3D11_MEMORY_TRANSFER_NEED_UPLOAD))
    return;

  device_context = gst_d3d11_device_get_device_context_handle (dmem->device);
  ID3D11DeviceContext_CopySubresourceRegion (device_context,
      (ID3D11Resource *) priv->texture, priv->subresource_index, 0, 0, 0,
      (ID3D11Resource *) priv->staging, 0, NULL);
}

/* Must be called with d3d11 device lock */
static void
gst_d3d11_memory_download (GstD3D11Memory * dmem)
{
  GstD3D11MemoryPrivate *priv = dmem->priv;
  ID3D11DeviceContext *device_context;

  if (!priv->staging || priv->staging == priv->texture ||
      !GST_MEMORY_FLAG_IS_SET (dmem, GST_D3D11_MEMORY_TRANSFER_NEED_DOWNLOAD))
    return;

  device_context = gst_d3d11_device_get_device_context_handle (dmem->device);
  ID3D11DeviceContext_CopySubresourceRegion (device_context,
      (ID3D11Resource *) priv->staging, 0, 0, 0, 0,
      (ID3D11Resource *) priv->texture, priv->subresource_index, NULL);
}

static gpointer
gst_d3d11_memory_map_full (GstMemory * mem, GstMapInfo * info, gsize maxsize)
{
  GstD3D11Memory *dmem = GST_D3D11_MEMORY_CAST (mem);
  GstD3D11MemoryPrivate *priv = dmem->priv;
  GstMapFlags flags = info->flags;
  gpointer ret = NULL;

  gst_d3d11_device_lock (dmem->device);
  GST_D3D11_MEMORY_LOCK (dmem);

  if ((flags & GST_MAP_D3D11) == GST_MAP_D3D11) {
    gst_d3d11_memory_upload (dmem);
    GST_MEMORY_FLAG_UNSET (dmem, GST_D3D11_MEMORY_TRANSFER_NEED_UPLOAD);

    if ((flags & GST_MAP_WRITE) == GST_MAP_WRITE)
      GST_MINI_OBJECT_FLAG_SET (dmem, GST_D3D11_MEMORY_TRANSFER_NEED_DOWNLOAD);

    g_assert (priv->texture != NULL);
    ret = priv->texture;
    goto out;
  }

  if (priv->cpu_map_count == 0) {
    D3D11_MAP map_type;

    /* Allocate staging texture for CPU access */
    if (!priv->staging) {
      priv->staging = gst_d3d11_allocate_staging_texture (dmem->device,
          &priv->desc);
      if (!priv->staging) {
        GST_ERROR_OBJECT (mem->allocator, "Couldn't create staging texture");
        goto out;
      }

      /* first memory, always need download to staging */
      GST_MINI_OBJECT_FLAG_SET (mem, GST_D3D11_MEMORY_TRANSFER_NEED_DOWNLOAD);
    }

    gst_d3d11_memory_download (dmem);
    map_type = gst_d3d11_map_flags_to_d3d11 (flags);

    if (!gst_d3d11_memory_map_cpu_access (dmem, map_type)) {
      GST_ERROR_OBJECT (mem->allocator, "Couldn't map staging texture");
      goto out;
    }
  }

  if ((flags & GST_MAP_WRITE) == GST_MAP_WRITE) {
    GST_MINI_OBJECT_FLAG_SET (mem, GST_D3D11_MEMORY_TRANSFER_NEED_UPLOAD);
  }

  GST_MEMORY_FLAG_UNSET (mem, GST_D3D11_MEMORY_TRANSFER_NEED_DOWNLOAD);

  priv->cpu_map_count++;
  ret = dmem->priv->map.pData;

out:
  GST_D3D11_MEMORY_UNLOCK (dmem);
  gst_d3d11_device_unlock (dmem->device);

  return ret;
}

/* Must be called with d3d11 device lock */
static void
gst_d3d11_memory_unmap_cpu_access (GstD3D11Memory * dmem)
{
  GstD3D11MemoryPrivate *priv = dmem->priv;
  ID3D11Resource *staging = (ID3D11Resource *) priv->staging;
  ID3D11DeviceContext *device_context =
      gst_d3d11_device_get_device_context_handle (dmem->device);

  ID3D11DeviceContext_Unmap (device_context, staging, 0);
}

static void
gst_d3d11_memory_unmap_full (GstMemory * mem, GstMapInfo * info)
{
  GstD3D11Memory *dmem = GST_D3D11_MEMORY_CAST (mem);
  GstD3D11MemoryPrivate *priv = dmem->priv;

  gst_d3d11_device_lock (dmem->device);
  GST_D3D11_MEMORY_LOCK (dmem);

  if ((info->flags & GST_MAP_D3D11) == GST_MAP_D3D11) {
    if ((info->flags & GST_MAP_WRITE) == GST_MAP_WRITE)
      GST_MINI_OBJECT_FLAG_SET (mem, GST_D3D11_MEMORY_TRANSFER_NEED_DOWNLOAD);

    goto out;
  }

  if ((info->flags & GST_MAP_WRITE) == GST_MAP_WRITE)
    GST_MINI_OBJECT_FLAG_SET (mem, GST_D3D11_MEMORY_TRANSFER_NEED_UPLOAD);

  priv->cpu_map_count--;
  if (priv->cpu_map_count > 0)
    goto out;

  gst_d3d11_memory_unmap_cpu_access (dmem);

out:
  GST_D3D11_MEMORY_UNLOCK (dmem);
  gst_d3d11_device_unlock (dmem->device);
}

static GstMemory *
gst_d3d11_memory_share (GstMemory * mem, gssize offset, gssize size)
{
  /* TODO: impl. */
  return NULL;
}

static gboolean
gst_d3d11_memory_update_size (GstMemory * mem)
{
  GstD3D11Memory *dmem = GST_D3D11_MEMORY_CAST (mem);
  GstD3D11MemoryPrivate *priv = dmem->priv;
  gsize offset[GST_VIDEO_MAX_PLANES];
  gint stride[GST_VIDEO_MAX_PLANES];
  gsize size;
  D3D11_TEXTURE2D_DESC *desc = &priv->desc;
  gboolean ret = FALSE;

  if (!priv->staging) {
    priv->staging = gst_d3d11_allocate_staging_texture (dmem->device,
        &priv->desc);
    if (!priv->staging) {
      GST_ERROR_OBJECT (mem->allocator, "Couldn't create staging texture");
      return FALSE;
    }

    GST_MINI_OBJECT_FLAG_SET (mem, GST_D3D11_MEMORY_TRANSFER_NEED_DOWNLOAD);
  }

  gst_d3d11_device_lock (dmem->device);
  if (!gst_d3d11_memory_map_cpu_access (dmem, D3D11_MAP_READ_WRITE)) {
    GST_ERROR_OBJECT (mem->allocator, "Couldn't map staging texture");
    return FALSE;
  }

  gst_d3d11_memory_unmap_cpu_access (dmem);

  if (!gst_d3d11_dxgi_format_get_size (desc->Format, desc->Width, desc->Height,
          priv->map.RowPitch, offset, stride, &size)) {
    GST_ERROR_OBJECT (mem->allocator, "Couldn't calculate memory size");
    goto out;
  }

  mem->maxsize = mem->size = size;
  ret = TRUE;

out:
  gst_d3d11_device_unlock (dmem->device);
  return ret;
}

/**
 * gst_is_d3d11_memory:
 * @mem: a #GstMemory
 *
 * Returns: whether @mem is a #GstD3D11Memory
 *
 * Since: 1.20
 */
gboolean
gst_is_d3d11_memory (GstMemory * mem)
{
  return mem != NULL && mem->allocator != NULL &&
      (GST_IS_D3D11_ALLOCATOR (mem->allocator) ||
      GST_IS_D3D11_POOL_ALLOCATOR (mem->allocator));
}

/**
 * gst_d3d11_memory_init_once:
 *
 * Initializes the Direct3D11 Texture allocator. It is safe to call
 * this function multiple times. This must be called before any other
 * GstD3D11Memory operation.
 *
 * Since: 1.20
 */
void
gst_d3d11_memory_init_once (void)
{
  static gsize _init = 0;

  if (g_once_init_enter (&_init)) {

    GST_DEBUG_CATEGORY_INIT (gst_d3d11_allocator_debug, "d3d11allocator", 0,
        "Direct3D11 Texture Allocator");

    _d3d11_memory_allocator = g_object_new (GST_TYPE_D3D11_ALLOCATOR, NULL);
    gst_object_ref_sink (_d3d11_memory_allocator);

    gst_allocator_register (GST_D3D11_MEMORY_NAME, _d3d11_memory_allocator);
    g_once_init_leave (&_init, 1);
  }
}

/**
 * gst_d3d11_memory_get_texture_handle:
 * @mem: a #GstD3D11Memory
 *
 * Returns: (transfer none): a ID3D11Texture2D handle. Caller must not release
 * returned handle.
 *
 * Since: 1.20
 */
ID3D11Texture2D *
gst_d3d11_memory_get_texture_handle (GstD3D11Memory * mem)
{
  g_return_val_if_fail (gst_is_d3d11_memory (GST_MEMORY_CAST (mem)), NULL);

  return mem->priv->texture;
}

/**
 * gst_d3d11_memory_get_subresource_index:
 * @mem: a #GstD3D11Memory
 *
 * Returns: subresource index corresponding to @mem.
 *
 * Since: 1.20
 */
guint
gst_d3d11_memory_get_subresource_index (GstD3D11Memory * mem)
{
  g_return_val_if_fail (gst_is_d3d11_memory (GST_MEMORY_CAST (mem)), 0);

  return mem->priv->subresource_index;
}

/**
 * gst_d3d11_memory_get_texture_desc:
 * @mem: a #GstD3D11Memory
 * @desc: (out): a D3D11_TEXTURE2D_DESC
 *
 * Fill @desc with D3D11_TEXTURE2D_DESC for ID3D11Texture2D
 *
 * Returns: %TRUE if successeed
 *
 * Since: 1.20
 */
gboolean
gst_d3d11_memory_get_texture_desc (GstD3D11Memory * mem,
    D3D11_TEXTURE2D_DESC * desc)
{
  g_return_val_if_fail (gst_is_d3d11_memory (GST_MEMORY_CAST (mem)), FALSE);
  g_return_val_if_fail (desc != NULL, FALSE);

  *desc = mem->priv->desc;

  return TRUE;
}

gboolean
gst_d3d11_memory_get_texture_stride (GstD3D11Memory * mem, guint * stride)
{
  g_return_val_if_fail (gst_is_d3d11_memory (GST_MEMORY_CAST (mem)), FALSE);
  g_return_val_if_fail (stride != NULL, FALSE);

  *stride = mem->priv->map.RowPitch;

  return TRUE;
}

static gboolean
create_shader_resource_views (GstD3D11Memory * mem)
{
  GstD3D11MemoryPrivate *priv = mem->priv;
  gint i;
  HRESULT hr;
  guint num_views = 0;
  ID3D11Device *device_handle;
  D3D11_SHADER_RESOURCE_VIEW_DESC resource_desc = { 0, };
  DXGI_FORMAT formats[GST_VIDEO_MAX_PLANES] = { DXGI_FORMAT_UNKNOWN, };

  device_handle = gst_d3d11_device_get_device_handle (mem->device);

  switch (priv->desc.Format) {
    case DXGI_FORMAT_B8G8R8A8_UNORM:
    case DXGI_FORMAT_R8G8B8A8_UNORM:
    case DXGI_FORMAT_R10G10B10A2_UNORM:
    case DXGI_FORMAT_R8_UNORM:
    case DXGI_FORMAT_R8G8_UNORM:
    case DXGI_FORMAT_R16_UNORM:
    case DXGI_FORMAT_R16G16_UNORM:
    case DXGI_FORMAT_G8R8_G8B8_UNORM:
    case DXGI_FORMAT_R8G8_B8G8_UNORM:
    case DXGI_FORMAT_R16G16B16A16_UNORM:
      num_views = 1;
      formats[0] = priv->desc.Format;
      break;
    case DXGI_FORMAT_AYUV:
    case DXGI_FORMAT_YUY2:
      num_views = 1;
      formats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
      break;
    case DXGI_FORMAT_NV12:
      num_views = 2;
      formats[0] = DXGI_FORMAT_R8_UNORM;
      formats[1] = DXGI_FORMAT_R8G8_UNORM;
      break;
    case DXGI_FORMAT_P010:
    case DXGI_FORMAT_P016:
      num_views = 2;
      formats[0] = DXGI_FORMAT_R16_UNORM;
      formats[1] = DXGI_FORMAT_R16G16_UNORM;
      break;
    case DXGI_FORMAT_Y210:
      num_views = 1;
      formats[0] = DXGI_FORMAT_R16G16B16A16_UNORM;
      break;
    case DXGI_FORMAT_Y410:
      num_views = 1;
      formats[0] = DXGI_FORMAT_R10G10B10A2_UNORM;
      break;
    default:
      g_assert_not_reached ();
      return FALSE;
  }

  if ((priv->desc.BindFlags & D3D11_BIND_SHADER_RESOURCE) ==
      D3D11_BIND_SHADER_RESOURCE) {
    resource_desc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
    resource_desc.Texture2D.MipLevels = 1;

    for (i = 0; i < num_views; i++) {
      resource_desc.Format = formats[i];
      hr = ID3D11Device_CreateShaderResourceView (device_handle,
          (ID3D11Resource *) priv->texture, &resource_desc,
          &priv->shader_resource_view[i]);

      if (!gst_d3d11_result (hr, mem->device)) {
        GST_ERROR_OBJECT (GST_MEMORY_CAST (mem)->allocator,
            "Failed to create %dth resource view (0x%x)", i, (guint) hr);
        goto error;
      }
    }

    priv->num_shader_resource_views = num_views;

    return TRUE;
  }

  return FALSE;

error:
  for (i = 0; i < num_views; i++) {
    if (priv->shader_resource_view[i])
      ID3D11ShaderResourceView_Release (priv->shader_resource_view[i]);
    priv->shader_resource_view[i] = NULL;
  }

  priv->num_shader_resource_views = 0;

  return FALSE;
}

static gboolean
gst_d3d11_memory_ensure_shader_resource_view (GstD3D11Memory * mem)
{
  GstD3D11MemoryPrivate *priv = mem->priv;
  gboolean ret = FALSE;

  if (!(priv->desc.BindFlags & D3D11_BIND_SHADER_RESOURCE)) {
    GST_LOG_OBJECT (GST_MEMORY_CAST (mem)->allocator,
        "Need BindFlags, current flag 0x%x", priv->desc.BindFlags);
    return FALSE;
  }

  GST_D3D11_MEMORY_LOCK (mem);
  if (priv->num_shader_resource_views) {
    ret = TRUE;
    goto done;
  }

  ret = create_shader_resource_views (mem);

done:
  GST_D3D11_MEMORY_UNLOCK (mem);

  return ret;
}

/**
 * gst_d3d11_memory_get_shader_resource_view_size:
 * @mem: a #GstD3D11Memory
 *
 * Returns: the number of ID3D11ShaderResourceView that can be used
 * for processing GPU operation with @mem
 *
 * Since: 1.20
 */
guint
gst_d3d11_memory_get_shader_resource_view_size (GstD3D11Memory * mem)
{
  g_return_val_if_fail (gst_is_d3d11_memory (GST_MEMORY_CAST (mem)), 0);

  if (!gst_d3d11_memory_ensure_shader_resource_view (mem))
    return 0;

  return mem->priv->num_shader_resource_views;
}

/**
 * gst_d3d11_memory_get_shader_resource_view:
 * @mem: a #GstD3D11Memory
 * @index: the index of the ID3D11ShaderResourceView
 *
 * Returns: (transfer none) (nullable): a pointer to the
 * ID3D11ShaderResourceView or %NULL if ID3D11ShaderResourceView is unavailable
 * for @index
 *
 * Since: 1.20
 */
ID3D11ShaderResourceView *
gst_d3d11_memory_get_shader_resource_view (GstD3D11Memory * mem, guint index)
{
  GstD3D11MemoryPrivate *priv;

  g_return_val_if_fail (gst_is_d3d11_memory (GST_MEMORY_CAST (mem)), NULL);

  if (!gst_d3d11_memory_ensure_shader_resource_view (mem))
    return NULL;

  priv = mem->priv;

  if (index >= priv->num_shader_resource_views) {
    GST_ERROR ("Invalid SRV index %d", index);
    return NULL;
  }

  return priv->shader_resource_view[index];
}

static gboolean
create_render_target_views (GstD3D11Memory * mem)
{
  GstD3D11MemoryPrivate *priv = mem->priv;
  gint i;
  HRESULT hr;
  guint num_views = 0;
  ID3D11Device *device_handle;
  D3D11_RENDER_TARGET_VIEW_DESC render_desc = { 0, };
  DXGI_FORMAT formats[GST_VIDEO_MAX_PLANES] = { DXGI_FORMAT_UNKNOWN, };

  device_handle = gst_d3d11_device_get_device_handle (mem->device);

  switch (priv->desc.Format) {
    case DXGI_FORMAT_B8G8R8A8_UNORM:
    case DXGI_FORMAT_R8G8B8A8_UNORM:
    case DXGI_FORMAT_R10G10B10A2_UNORM:
    case DXGI_FORMAT_R8_UNORM:
    case DXGI_FORMAT_R8G8_UNORM:
    case DXGI_FORMAT_R16_UNORM:
    case DXGI_FORMAT_R16G16_UNORM:
      num_views = 1;
      formats[0] = priv->desc.Format;
      break;
    case DXGI_FORMAT_AYUV:
      num_views = 1;
      formats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
      break;
    case DXGI_FORMAT_NV12:
      num_views = 2;
      formats[0] = DXGI_FORMAT_R8_UNORM;
      formats[1] = DXGI_FORMAT_R8G8_UNORM;
      break;
    case DXGI_FORMAT_P010:
    case DXGI_FORMAT_P016:
      num_views = 2;
      formats[0] = DXGI_FORMAT_R16_UNORM;
      formats[1] = DXGI_FORMAT_R16G16_UNORM;
      break;
    default:
      g_assert_not_reached ();
      return FALSE;
  }

  if ((priv->desc.BindFlags & D3D11_BIND_RENDER_TARGET) ==
      D3D11_BIND_RENDER_TARGET) {
    render_desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
    render_desc.Texture2D.MipSlice = 0;

    for (i = 0; i < num_views; i++) {
      render_desc.Format = formats[i];

      hr = ID3D11Device_CreateRenderTargetView (device_handle,
          (ID3D11Resource *) priv->texture, &render_desc,
          &priv->render_target_view[i]);
      if (!gst_d3d11_result (hr, mem->device)) {
        GST_ERROR_OBJECT (GST_MEMORY_CAST (mem)->allocator,
            "Failed to create %dth render target view (0x%x)", i, (guint) hr);
        goto error;
      }
    }

    priv->num_render_target_views = num_views;

    return TRUE;
  }

  return FALSE;

error:
  for (i = 0; i < num_views; i++) {
    if (priv->render_target_view[i])
      ID3D11RenderTargetView_Release (priv->render_target_view[i]);
    priv->render_target_view[i] = NULL;
  }

  priv->num_render_target_views = 0;

  return FALSE;
}

static gboolean
gst_d3d11_memory_ensure_render_target_view (GstD3D11Memory * mem)
{
  GstD3D11MemoryPrivate *priv = mem->priv;
  gboolean ret = FALSE;

  if (!(priv->desc.BindFlags & D3D11_BIND_RENDER_TARGET)) {
    GST_WARNING_OBJECT (GST_MEMORY_CAST (mem)->allocator,
        "Need BindFlags, current flag 0x%x", priv->desc.BindFlags);
    return FALSE;
  }

  GST_D3D11_MEMORY_LOCK (mem);
  if (priv->num_render_target_views) {
    ret = TRUE;
    goto done;
  }

  ret = create_render_target_views (mem);

done:
  GST_D3D11_MEMORY_UNLOCK (mem);

  return ret;
}

/**
 * gst_d3d11_memory_get_render_target_view_size:
 * @mem: a #GstD3D11Memory
 *
 * Returns: the number of ID3D11RenderTargetView that can be used
 * for processing GPU operation with @mem
 *
 * Since: 1.20
 */
guint
gst_d3d11_memory_get_render_target_view_size (GstD3D11Memory * mem)
{
  g_return_val_if_fail (gst_is_d3d11_memory (GST_MEMORY_CAST (mem)), 0);

  if (!gst_d3d11_memory_ensure_render_target_view (mem))
    return 0;

  return mem->priv->num_render_target_views;
}

/**
 * gst_d3d11_memory_get_render_target_view:
 * @mem: a #GstD3D11Memory
 * @index: the index of the ID3D11RenderTargetView
 *
 * Returns: (transfer none) (nullable): a pointer to the
 * ID3D11RenderTargetView or %NULL if ID3D11RenderTargetView is unavailable
 * for @index
 *
 * Since: 1.20
 */
ID3D11RenderTargetView *
gst_d3d11_memory_get_render_target_view (GstD3D11Memory * mem, guint index)
{
  GstD3D11MemoryPrivate *priv;

  g_return_val_if_fail (gst_is_d3d11_memory (GST_MEMORY_CAST (mem)), NULL);

  if (!gst_d3d11_memory_ensure_render_target_view (mem))
    return NULL;

  priv = mem->priv;

  if (index >= priv->num_render_target_views) {
    GST_ERROR ("Invalid RTV index %d", index);
    return NULL;
  }

  return priv->render_target_view[index];
}

static gboolean
gst_d3d11_memory_ensure_decoder_output_view (GstD3D11Memory * mem,
    ID3D11VideoDevice * video_device, GUID * decoder_profile)
{
  GstD3D11MemoryPrivate *dmem_priv = mem->priv;
  GstD3D11Allocator *allocator;
  D3D11_VIDEO_DECODER_OUTPUT_VIEW_DESC desc;
  HRESULT hr;
  gboolean ret = FALSE;

  allocator = GST_D3D11_ALLOCATOR (GST_MEMORY_CAST (mem)->allocator);

  if (!(dmem_priv->desc.BindFlags & D3D11_BIND_DECODER)) {
    GST_LOG_OBJECT (allocator,
        "Need BindFlags, current flag 0x%x", dmem_priv->desc.BindFlags);
    return FALSE;
  }

  GST_D3D11_MEMORY_LOCK (mem);
  if (dmem_priv->decoder_output_view) {
    ID3D11VideoDecoderOutputView_GetDesc (dmem_priv->decoder_output_view,
        &desc);
    if (IsEqualGUID (&desc.DecodeProfile, decoder_profile)) {
      goto succeeded;
    } else {
      /* Shouldn't happen, but try again anyway */
      GST_WARNING_OBJECT (allocator,
          "Existing view has different decoder profile");
      ID3D11VideoDecoderOutputView_Release (dmem_priv->decoder_output_view);
      dmem_priv->decoder_output_view = NULL;
    }
  }

  if (dmem_priv->decoder_output_view)
    goto succeeded;

  desc.DecodeProfile = *decoder_profile;
  desc.ViewDimension = D3D11_VDOV_DIMENSION_TEXTURE2D;
  desc.Texture2D.ArraySlice = dmem_priv->subresource_index;

  hr = ID3D11VideoDevice_CreateVideoDecoderOutputView (video_device,
      (ID3D11Resource *) dmem_priv->texture, &desc,
      &dmem_priv->decoder_output_view);
  if (!gst_d3d11_result (hr, mem->device)) {
    GST_ERROR_OBJECT (allocator,
        "Could not create decoder output view, hr: 0x%x", (guint) hr);
    goto done;
  }

succeeded:
  ret = TRUE;

done:
  GST_D3D11_MEMORY_UNLOCK (mem);

  return ret;
}

/**
 * gst_d3d11_memory_get_decoder_output_view:
 * @mem: a #GstD3D11Memory
 *
 * Returns: (transfer none) (nullable): a pointer to the
 * ID3D11VideoDecoderOutputView or %NULL if ID3D11VideoDecoderOutputView is
 * unavailable
 *
 * Since: 1.20
 */
ID3D11VideoDecoderOutputView *
gst_d3d11_memory_get_decoder_output_view (GstD3D11Memory * mem,
    ID3D11VideoDevice * video_device, GUID * decoder_profile)
{
  g_return_val_if_fail (gst_is_d3d11_memory (GST_MEMORY_CAST (mem)), NULL);
  g_return_val_if_fail (video_device != NULL, NULL);
  g_return_val_if_fail (decoder_profile != NULL, NULL);

  if (!gst_d3d11_memory_ensure_decoder_output_view (mem,
          video_device, decoder_profile))
    return NULL;

  return mem->priv->decoder_output_view;
}

static gboolean
check_bind_flags_for_processor_input_view (guint bind_flags)
{
  static const guint compatible_flags = (D3D11_BIND_DECODER |
      D3D11_BIND_VIDEO_ENCODER | D3D11_BIND_RENDER_TARGET |
      D3D11_BIND_UNORDERED_ACCESS);

  if (bind_flags == 0)
    return TRUE;

  if ((bind_flags & compatible_flags) != 0)
    return TRUE;

  return FALSE;
}

static gboolean
gst_d3d11_memory_ensure_processor_input_view (GstD3D11Memory * mem,
    ID3D11VideoDevice * video_device,
    ID3D11VideoProcessorEnumerator * enumerator)
{
  GstD3D11MemoryPrivate *dmem_priv = mem->priv;
  GstD3D11Allocator *allocator;
  D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC desc;
  HRESULT hr;
  gboolean ret = FALSE;

  allocator = GST_D3D11_ALLOCATOR (GST_MEMORY_CAST (mem)->allocator);

  if (!check_bind_flags_for_processor_input_view (dmem_priv->desc.BindFlags)) {
    GST_LOG_OBJECT (allocator,
        "Need BindFlags, current flag 0x%x", dmem_priv->desc.BindFlags);
    return FALSE;
  }

  GST_D3D11_MEMORY_LOCK (mem);
  if (dmem_priv->processor_input_view)
    goto succeeded;

  desc.FourCC = 0;
  desc.ViewDimension = D3D11_VPIV_DIMENSION_TEXTURE2D;
  desc.Texture2D.MipSlice = 0;
  desc.Texture2D.ArraySlice = dmem_priv->subresource_index;

  hr = ID3D11VideoDevice_CreateVideoProcessorInputView (video_device,
      (ID3D11Resource *) dmem_priv->texture, enumerator, &desc,
      &dmem_priv->processor_input_view);
  if (!gst_d3d11_result (hr, mem->device)) {
    GST_ERROR_OBJECT (allocator,
        "Could not create processor input view, hr: 0x%x", (guint) hr);
    goto done;
  }

succeeded:
  ret = TRUE;

done:
  GST_D3D11_MEMORY_UNLOCK (mem);

  return ret;
}

/**
 * gst_d3d11_memory_get_processor_input_view:
 * @mem: a #GstD3D11Memory
 * @video_device: a #ID3D11VideoDevice
 * @enumerator: a #ID3D11VideoProcessorEnumerator
 *
 * Returns: (transfer none) (nullable): a pointer to the
 * ID3D11VideoProcessorInputView or %NULL if ID3D11VideoProcessorInputView is
 * unavailable
 *
 * Since: 1.20
 */
ID3D11VideoProcessorInputView *
gst_d3d11_memory_get_processor_input_view (GstD3D11Memory * mem,
    ID3D11VideoDevice * video_device,
    ID3D11VideoProcessorEnumerator * enumerator)
{
  g_return_val_if_fail (gst_is_d3d11_memory (GST_MEMORY_CAST (mem)), NULL);
  g_return_val_if_fail (video_device != NULL, NULL);
  g_return_val_if_fail (enumerator != NULL, NULL);

  if (!gst_d3d11_memory_ensure_processor_input_view (mem, video_device,
          enumerator))
    return NULL;

  return mem->priv->processor_input_view;
}

static gboolean
gst_d3d11_memory_ensure_processor_output_view (GstD3D11Memory * mem,
    ID3D11VideoDevice * video_device,
    ID3D11VideoProcessorEnumerator * enumerator)
{
  GstD3D11MemoryPrivate *priv = mem->priv;
  GstD3D11Allocator *allocator;
  D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC desc = { 0, };
  HRESULT hr;
  gboolean ret;

  allocator = GST_D3D11_ALLOCATOR (GST_MEMORY_CAST (mem)->allocator);

  if (!(priv->desc.BindFlags & D3D11_BIND_RENDER_TARGET)) {
    GST_LOG_OBJECT (allocator,
        "Need BindFlags, current flag 0x%x", priv->desc.BindFlags);
    return FALSE;
  }

  /* FIXME: texture array should be supported at some point */
  if (priv->subresource_index != 0) {
    GST_FIXME_OBJECT (allocator,
        "Texture array is not suppoted for processor output view");
    return FALSE;
  }

  GST_D3D11_MEMORY_LOCK (mem);
  if (priv->processor_output_view)
    goto succeeded;

  desc.ViewDimension = D3D11_VPOV_DIMENSION_TEXTURE2D;
  desc.Texture2D.MipSlice = 0;

  hr = ID3D11VideoDevice_CreateVideoProcessorOutputView (video_device,
      (ID3D11Resource *) priv->texture, enumerator, &desc,
      &priv->processor_output_view);
  if (!gst_d3d11_result (hr, mem->device)) {
    GST_ERROR_OBJECT (allocator,
        "Could not create processor input view, hr: 0x%x", (guint) hr);
    goto done;
  }

succeeded:
  ret = TRUE;

done:
  GST_D3D11_MEMORY_UNLOCK (mem);

  return ret;
}

/**
 * gst_d3d11_memory_get_processor_output_view:
 * @mem: a #GstD3D11Memory
 * @video_device: a #ID3D11VideoDevice
 * @enumerator: a #ID3D11VideoProcessorEnumerator
 *
 * Returns: (transfer none) (nullable): a pointer to the
 * ID3D11VideoProcessorOutputView or %NULL if ID3D11VideoProcessorOutputView is
 * unavailable
 *
 * Since: 1.20
 */
ID3D11VideoProcessorOutputView *
gst_d3d11_memory_get_processor_output_view (GstD3D11Memory * mem,
    ID3D11VideoDevice * video_device,
    ID3D11VideoProcessorEnumerator * enumerator)
{
  g_return_val_if_fail (gst_is_d3d11_memory (GST_MEMORY_CAST (mem)), NULL);
  g_return_val_if_fail (video_device != NULL, NULL);
  g_return_val_if_fail (enumerator != NULL, NULL);

  if (!gst_d3d11_memory_ensure_processor_output_view (mem, video_device,
          enumerator))
    return NULL;

  return mem->priv->processor_output_view;
}

/* GstD3D11Allocator */
#define gst_d3d11_allocator_parent_class alloc_parent_class
G_DEFINE_TYPE (GstD3D11Allocator, gst_d3d11_allocator, GST_TYPE_ALLOCATOR);

static GstMemory *gst_d3d11_allocator_dummy_alloc (GstAllocator * allocator,
    gsize size, GstAllocationParams * params);
static void gst_d3d11_allocator_free (GstAllocator * allocator,
    GstMemory * mem);

static void
gst_d3d11_allocator_class_init (GstD3D11AllocatorClass * klass)
{
  GstAllocatorClass *allocator_class = GST_ALLOCATOR_CLASS (klass);

  allocator_class->alloc = gst_d3d11_allocator_dummy_alloc;
  allocator_class->free = gst_d3d11_allocator_free;
}

static void
gst_d3d11_allocator_init (GstD3D11Allocator * allocator)
{
  GstAllocator *alloc = GST_ALLOCATOR_CAST (allocator);

  alloc->mem_type = GST_D3D11_MEMORY_NAME;
  alloc->mem_map_full = gst_d3d11_memory_map_full;
  alloc->mem_unmap_full = gst_d3d11_memory_unmap_full;
  alloc->mem_share = gst_d3d11_memory_share;
  /* fallback copy */

  GST_OBJECT_FLAG_SET (alloc, GST_ALLOCATOR_FLAG_CUSTOM_ALLOC);
}

static GstMemory *
gst_d3d11_allocator_dummy_alloc (GstAllocator * allocator, gsize size,
    GstAllocationParams * params)
{
  g_return_val_if_reached (NULL);
}

static void
gst_d3d11_allocator_free (GstAllocator * allocator, GstMemory * mem)
{
  GstD3D11Memory *dmem = GST_D3D11_MEMORY_CAST (mem);
  GstD3D11MemoryPrivate *dmem_priv = dmem->priv;
  gint i;

  GST_LOG_OBJECT (allocator, "Free memory %p", mem);

  for (i = 0; i < GST_VIDEO_MAX_PLANES; i++) {
    if (dmem_priv->render_target_view[i])
      ID3D11RenderTargetView_Release (dmem_priv->render_target_view[i]);

    if (dmem_priv->shader_resource_view[i])
      ID3D11ShaderResourceView_Release (dmem_priv->shader_resource_view[i]);
  }

  if (dmem_priv->decoder_output_view)
    ID3D11VideoDecoderOutputView_Release (dmem_priv->decoder_output_view);

  if (dmem_priv->processor_input_view)
    ID3D11VideoProcessorInputView_Release (dmem_priv->processor_input_view);

  if (dmem_priv->processor_output_view)
    ID3D11VideoProcessorOutputView_Release (dmem_priv->processor_output_view);

  if (dmem_priv->texture)
    ID3D11Texture2D_Release (dmem_priv->texture);

  if (dmem_priv->staging)
    ID3D11Texture2D_Release (dmem_priv->staging);

  gst_clear_object (&dmem->device);
  g_mutex_clear (&dmem_priv->lock);
  g_free (dmem->priv);
  g_free (dmem);
}

static GstMemory *
gst_d3d11_allocator_alloc_wrapped (GstD3D11Allocator * self,
    GstD3D11Device * device, const D3D11_TEXTURE2D_DESC * desc,
    ID3D11Texture2D * texture)
{
  GstD3D11Memory *mem;

  mem = g_new0 (GstD3D11Memory, 1);
  mem->priv = g_new0 (GstD3D11MemoryPrivate, 1);

  gst_memory_init (GST_MEMORY_CAST (mem),
      0, GST_ALLOCATOR_CAST (self), NULL, 0, 0, 0, 0);
  g_mutex_init (&mem->priv->lock);
  mem->priv->texture = texture;
  mem->priv->desc = *desc;
  mem->device = gst_object_ref (device);

  /* This is staging texture as well */
  if (desc->Usage == D3D11_USAGE_STAGING) {
    mem->priv->staging = texture;
    ID3D11Texture2D_AddRef (texture);
  }

  return GST_MEMORY_CAST (mem);
}

static GstMemory *
gst_d3d11_allocator_alloc_internal (GstD3D11Allocator * self,
    GstD3D11Device * device, const D3D11_TEXTURE2D_DESC * desc)
{
  ID3D11Texture2D *texture = NULL;
  ID3D11Device *device_handle;
  HRESULT hr;

  device_handle = gst_d3d11_device_get_device_handle (device);

  hr = ID3D11Device_CreateTexture2D (device_handle, desc, NULL, &texture);
  if (!gst_d3d11_result (hr, device)) {
    GST_ERROR_OBJECT (self, "Couldn't create texture");
    return NULL;
  }

  return gst_d3d11_allocator_alloc_wrapped (self, device, desc, texture);
}

/**
 * gst_d3d11_allocator_alloc:
 * @allocator: a #GstD3D11Allocator
 * @device: a #GstD3D11Device
 * @desc: a D3D11_TEXTURE2D_DESC struct
 *
 * Returns: a newly allocated #GstD3D11Memory with given parameters.
 *
 * Since: 1.20
 */
GstMemory *
gst_d3d11_allocator_alloc (GstD3D11Allocator * allocator,
    GstD3D11Device * device, const D3D11_TEXTURE2D_DESC * desc)
{
  GstMemory *mem;

  g_return_val_if_fail (GST_IS_D3D11_ALLOCATOR (allocator), NULL);
  g_return_val_if_fail (GST_IS_D3D11_DEVICE (device), NULL);
  g_return_val_if_fail (desc != NULL, NULL);

  mem = gst_d3d11_allocator_alloc_internal (allocator, device, desc);
  if (!mem)
    return NULL;

  if (!gst_d3d11_memory_update_size (mem)) {
    GST_ERROR_OBJECT (allocator, "Failed to calculate size");
    gst_memory_unref (mem);
    return NULL;
  }

  return mem;
}

gboolean
gst_d3d11_allocator_set_active (GstD3D11Allocator * allocator, gboolean active)
{
  GstD3D11AllocatorClass *klass;

  g_return_val_if_fail (GST_IS_D3D11_ALLOCATOR (allocator), FALSE);

  klass = GST_D3D11_ALLOCATOR_GET_CLASS (allocator);
  if (klass->set_actvie)
    return klass->set_actvie (allocator, active);

  return TRUE;
}

/* GstD3D11PoolAllocator */
#define GST_D3D11_POOL_ALLOCATOR_LOCK(alloc)   (g_rec_mutex_lock(&alloc->priv->lock))
#define GST_D3D11_POOL_ALLOCATOR_UNLOCK(alloc) (g_rec_mutex_unlock(&alloc->priv->lock))
#define GST_D3D11_POOL_ALLOCATOR_IS_FLUSHING(alloc)  (g_atomic_int_get (&alloc->priv->flushing))

struct _GstD3D11PoolAllocatorPrivate
{
  /* parent texture when array typed memory is used */
  ID3D11Texture2D *texture;
  D3D11_TEXTURE2D_DESC desc;

  /* All below member variables are analogous to that of GstBufferPool */
  GstAtomicQueue *queue;
  GstPoll *poll;

  /* This lock will protect all below variables apart from atomic ones
   * (identical to GstBufferPool::priv::rec_lock) */
  GRecMutex lock;
  gboolean started;
  gboolean active;

  /* atomic */
  gint outstanding;
  guint max_mems;
  guint cur_mems;
  gboolean flushing;

  /* Calculated memory size, based on Direct3D11 staging texture map.
   * Note that, we cannot know the actually staging texture memory size prior
   * to map the staging texture because driver will likely require padding */
  gsize mem_size;
};

static void gst_d3d11_pool_allocator_dispose (GObject * object);
static void gst_d3d11_pool_allocator_finalize (GObject * object);

static gboolean
gst_d3d11_pool_allocator_set_active (GstD3D11Allocator * allocator,
    gboolean active);

static gboolean gst_d3d11_pool_allocator_start (GstD3D11PoolAllocator * self);
static gboolean gst_d3d11_pool_allocator_stop (GstD3D11PoolAllocator * self);
static gboolean gst_d3d11_memory_release (GstMiniObject * mini_object);

#define gst_d3d11_pool_allocator_parent_class pool_alloc_parent_class
G_DEFINE_TYPE_WITH_PRIVATE (GstD3D11PoolAllocator,
    gst_d3d11_pool_allocator, GST_TYPE_D3D11_ALLOCATOR);

static void
gst_d3d11_pool_allocator_class_init (GstD3D11PoolAllocatorClass * klass)
{
  GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
  GstD3D11AllocatorClass *d3d11alloc_class = GST_D3D11_ALLOCATOR_CLASS (klass);

  gobject_class->dispose = gst_d3d11_pool_allocator_dispose;
  gobject_class->finalize = gst_d3d11_pool_allocator_finalize;

  d3d11alloc_class->set_actvie = gst_d3d11_pool_allocator_set_active;
}

static void
gst_d3d11_pool_allocator_init (GstD3D11PoolAllocator * allocator)
{
  GstD3D11PoolAllocatorPrivate *priv;

  priv = allocator->priv =
      gst_d3d11_pool_allocator_get_instance_private (allocator);
  g_rec_mutex_init (&priv->lock);

  priv->poll = gst_poll_new_timer ();
  priv->queue = gst_atomic_queue_new (16);
  priv->flushing = 1;
  priv->active = FALSE;
  priv->started = FALSE;

  /* 1 control write for flushing - the flush token */
  gst_poll_write_control (priv->poll);
  /* 1 control write for marking that we are not waiting for poll - the wait token */
  gst_poll_write_control (priv->poll);
}

static void
gst_d3d11_pool_allocator_dispose (GObject * object)
{
  GstD3D11PoolAllocator *self = GST_D3D11_POOL_ALLOCATOR (object);

  gst_clear_object (&self->device);

  G_OBJECT_CLASS (pool_alloc_parent_class)->dispose (object);
}

static void
gst_d3d11_pool_allocator_finalize (GObject * object)
{
  GstD3D11PoolAllocator *self = GST_D3D11_POOL_ALLOCATOR (object);
  GstD3D11PoolAllocatorPrivate *priv = self->priv;

  GST_DEBUG_OBJECT (self, "Finalize");

  gst_d3d11_pool_allocator_stop (self);
  gst_atomic_queue_unref (priv->queue);
  gst_poll_free (priv->poll);
  g_rec_mutex_clear (&priv->lock);

  if (priv->texture)
    ID3D11Texture2D_Release (priv->texture);

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

static gboolean
gst_d3d11_pool_allocator_start (GstD3D11PoolAllocator * self)
{
  GstD3D11PoolAllocatorPrivate *priv = self->priv;
  ID3D11Device *device_handle;
  HRESULT hr;
  guint i;

  if (priv->started)
    return TRUE;

  /* Nothing to do */
  if (priv->desc.ArraySize == 1) {
    priv->started = TRUE;
    return TRUE;
  }

  device_handle = gst_d3d11_device_get_device_handle (self->device);

  if (!priv->texture) {
    hr = ID3D11Device_CreateTexture2D (device_handle, &priv->desc, NULL,
        &priv->texture);
    if (!gst_d3d11_result (hr, self->device)) {
      GST_ERROR_OBJECT (self, "Failed to allocate texture");
      return FALSE;
    }
  }

  /* Pre-allocate memory objects */
  for (i = 0; i < priv->desc.ArraySize; i++) {
    GstMemory *mem;

    ID3D11Texture2D_AddRef (priv->texture);
    mem =
        gst_d3d11_allocator_alloc_wrapped (GST_D3D11_ALLOCATOR_CAST
        (_d3d11_memory_allocator), self->device, &priv->desc, priv->texture);

    if (i == 0) {
      if (!gst_d3d11_memory_update_size (mem)) {
        GST_ERROR_OBJECT (self, "Failed to calculate memory size");
        gst_memory_unref (mem);
        return FALSE;
      }

      priv->mem_size = mem->size;
    } else {
      mem->size = mem->maxsize = priv->mem_size;
    }

    GST_D3D11_MEMORY_CAST (mem)->priv->subresource_index = i;

    g_atomic_int_add (&priv->cur_mems, 1);
    gst_atomic_queue_push (priv->queue, mem);
    gst_poll_write_control (priv->poll);
  }

  priv->started = TRUE;

  return TRUE;
}

static void
gst_d3d11_pool_allocator_do_set_flushing (GstD3D11PoolAllocator * self,
    gboolean flushing)
{
  GstD3D11PoolAllocatorPrivate *priv = self->priv;

  if (GST_D3D11_POOL_ALLOCATOR_IS_FLUSHING (self) == flushing)
    return;

  if (flushing) {
    g_atomic_int_set (&priv->flushing, 1);
    /* Write the flush token to wake up any waiters */
    gst_poll_write_control (priv->poll);
  } else {
    while (!gst_poll_read_control (priv->poll)) {
      if (errno == EWOULDBLOCK) {
        /* This should not really happen unless flushing and unflushing
         * happens on different threads. Let's wait a bit to get back flush
         * token from the thread that was setting it to flushing */
        g_thread_yield ();
        continue;
      } else {
        /* Critical error but GstPoll already complained */
        break;
      }
    }

    g_atomic_int_set (&priv->flushing, 0);
  }
}

static gboolean
gst_d3d11_pool_allocator_set_active (GstD3D11Allocator * allocator,
    gboolean active)
{
  GstD3D11PoolAllocator *self = GST_D3D11_POOL_ALLOCATOR (allocator);
  GstD3D11PoolAllocatorPrivate *priv = self->priv;

  GST_LOG_OBJECT (self, "active %d", active);

  GST_D3D11_POOL_ALLOCATOR_LOCK (self);
  /* just return if we are already in the right state */
  if (priv->active == active)
    goto was_ok;

  if (active) {
    if (!gst_d3d11_pool_allocator_start (self))
      goto start_failed;

    /* flush_stop may release memory objects, setting to active to avoid running
     * do_stop while activating the pool */
    priv->active = TRUE;

    gst_d3d11_pool_allocator_do_set_flushing (self, FALSE);
  } else {
    gint outstanding;

    /* set to flushing first */
    gst_d3d11_pool_allocator_do_set_flushing (self, TRUE);

    /* when all memory objects are in the pool, free them. Else they will be
     * freed when they are released */
    outstanding = g_atomic_int_get (&priv->outstanding);
    GST_LOG_OBJECT (self, "outstanding memories %d, (in queue %d)",
        outstanding, gst_atomic_queue_length (priv->queue));
    if (outstanding == 0) {
      if (!gst_d3d11_pool_allocator_stop (self))
        goto stop_failed;
    }

    priv->active = FALSE;
  }

  GST_D3D11_POOL_ALLOCATOR_UNLOCK (self);

  return TRUE;

was_ok:
  {
    GST_DEBUG_OBJECT (self, "allocator was in the right state");
    GST_D3D11_POOL_ALLOCATOR_UNLOCK (self);
    return TRUE;
  }
start_failed:
  {
    GST_ERROR_OBJECT (self, "start failed");
    GST_D3D11_POOL_ALLOCATOR_UNLOCK (self);
    return FALSE;
  }
stop_failed:
  {
    GST_ERROR_OBJECT (self, "stop failed");
    GST_D3D11_POOL_ALLOCATOR_UNLOCK (self);
    return FALSE;
  }
}

static void
gst_d3d11_pool_allocator_free_memory (GstD3D11PoolAllocator * self,
    GstMemory * mem)
{
  GstD3D11PoolAllocatorPrivate *priv = self->priv;

  g_atomic_int_add (&priv->cur_mems, -1);
  GST_LOG_OBJECT (self, "freeing memory %p (%u left)", mem, priv->cur_mems);

  GST_MINI_OBJECT_CAST (mem)->dispose = NULL;
  gst_memory_unref (mem);
}

/* must be called with the lock */
static gboolean
gst_d3d11_pool_allocator_clear_queue (GstD3D11PoolAllocator * self)
{
  GstD3D11PoolAllocatorPrivate *priv = self->priv;
  GstMemory *memory;

  GST_LOG_OBJECT (self, "Clearing queue");

  /* clear the pool */
  while ((memory = gst_atomic_queue_pop (priv->queue))) {
    while (!gst_poll_read_control (priv->poll)) {
      if (errno == EWOULDBLOCK) {
        /* We put the memory into the queue but did not finish writing control
         * yet, let's wait a bit and retry */
        g_thread_yield ();
        continue;
      } else {
        /* Critical error but GstPoll already complained */
        break;
      }
    }
    gst_d3d11_pool_allocator_free_memory (self, memory);
  }

  GST_LOG_OBJECT (self, "Clear done");

  return priv->cur_mems == 0;
}

/* must be called with the lock */
static gboolean
gst_d3d11_pool_allocator_stop (GstD3D11PoolAllocator * self)
{
  GstD3D11PoolAllocatorPrivate *priv = self->priv;

  GST_DEBUG_OBJECT (self, "Stop");

  if (priv->started) {
    if (!gst_d3d11_pool_allocator_clear_queue (self))
      return FALSE;

    priv->started = FALSE;
  } else {
    GST_DEBUG_OBJECT (self, "Wasn't started");
  }

  return TRUE;
}

static inline void
dec_outstanding (GstD3D11PoolAllocator * self)
{
  if (g_atomic_int_dec_and_test (&self->priv->outstanding)) {
    /* all memory objects are returned to the pool, see if we need to free them */
    if (GST_D3D11_POOL_ALLOCATOR_IS_FLUSHING (self)) {
      /* take the lock so that set_active is not run concurrently */
      GST_D3D11_POOL_ALLOCATOR_LOCK (self);
      /* now that we have the lock, check if we have been de-activated with
       * outstanding buffers */
      if (!self->priv->active)
        gst_d3d11_pool_allocator_stop (self);

      GST_D3D11_POOL_ALLOCATOR_UNLOCK (self);
    }
  }
}

static void
gst_d3d11_pool_allocator_release_memory (GstD3D11PoolAllocator * self,
    GstMemory * mem)
{
  GST_LOG_OBJECT (self, "Released memory %p", mem);

  GST_MINI_OBJECT_CAST (mem)->dispose = NULL;
  mem->allocator = gst_object_ref (_d3d11_memory_allocator);
  gst_object_unref (self);

  /* keep it around in our queue */
  gst_atomic_queue_push (self->priv->queue, mem);
  gst_poll_write_control (self->priv->poll);
  dec_outstanding (self);
}

static gboolean
gst_d3d11_memory_release (GstMiniObject * mini_object)
{
  GstMemory *mem = GST_MEMORY_CAST (mini_object);
  GstD3D11PoolAllocator *alloc;

  g_assert (mem->allocator != NULL);

  if (!GST_IS_D3D11_POOL_ALLOCATOR (mem->allocator)) {
    GST_LOG_OBJECT (mem->allocator, "Not our memory, free");
    return TRUE;
  }

  alloc = GST_D3D11_POOL_ALLOCATOR (mem->allocator);
  /* if flushing, free this memory */
  if (GST_D3D11_POOL_ALLOCATOR_IS_FLUSHING (alloc)) {
    GST_LOG_OBJECT (alloc, "allocator is flushing, free %p", mem);
    return TRUE;
  }

  /* return the memory to the allocator */
  gst_memory_ref (mem);
  gst_d3d11_pool_allocator_release_memory (alloc, mem);

  return FALSE;
}

static GstFlowReturn
gst_d3d11_pool_allocator_alloc (GstD3D11PoolAllocator * self, GstMemory ** mem)
{
  GstD3D11PoolAllocatorPrivate *priv = self->priv;
  GstMemory *new_mem;

  /* we allcates texture array during start */
  if (priv->desc.ArraySize > 1)
    return GST_FLOW_EOS;

  /* increment the allocation counter */
  g_atomic_int_add (&priv->cur_mems, 1);
  new_mem =
      gst_d3d11_allocator_alloc_internal (GST_D3D11_ALLOCATOR_CAST
      (_d3d11_memory_allocator), self->device, &priv->desc);
  if (!new_mem) {
    GST_ERROR_OBJECT (self, "Failed to allocate new memory");
    g_atomic_int_add (&priv->cur_mems, -1);
    return GST_FLOW_ERROR;
  }

  if (!priv->mem_size) {
    if (!gst_d3d11_memory_update_size (new_mem)) {
      GST_ERROR_OBJECT (self, "Failed to calculate size");
      gst_memory_unref (new_mem);
      g_atomic_int_add (&priv->cur_mems, -1);

      return GST_FLOW_ERROR;
    }

    priv->mem_size = new_mem->size;
  }

  new_mem->size = new_mem->maxsize = priv->mem_size;

  *mem = new_mem;

  return GST_FLOW_OK;
}

static GstFlowReturn
gst_d3d11_pool_allocator_acquire_memory_internal (GstD3D11PoolAllocator * self,
    GstMemory ** memory)
{
  GstFlowReturn result;
  GstD3D11PoolAllocatorPrivate *priv = self->priv;

  while (TRUE) {
    if (G_UNLIKELY (GST_D3D11_POOL_ALLOCATOR_IS_FLUSHING (self)))
      goto flushing;

    /* try to get a memory from the queue */
    *memory = gst_atomic_queue_pop (priv->queue);
    if (G_LIKELY (*memory)) {
      while (!gst_poll_read_control (priv->poll)) {
        if (errno == EWOULDBLOCK) {
          /* We put the memory into the queue but did not finish writing control
           * yet, let's wait a bit and retry */
          g_thread_yield ();
          continue;
        } else {
          /* Critical error but GstPoll already complained */
          break;
        }
      }
      result = GST_FLOW_OK;
      GST_LOG_OBJECT (self, "acquired memory %p", *memory);
      break;
    }

    /* no memory, try to allocate some more */
    GST_LOG_OBJECT (self, "no memory, trying to allocate");
    result = gst_d3d11_pool_allocator_alloc (self, memory);
    if (G_LIKELY (result == GST_FLOW_OK))
      /* we have a memory, return it */
      break;

    if (G_UNLIKELY (result != GST_FLOW_EOS))
      /* something went wrong, return error */
      break;

    /* now we release the control socket, we wait for a memory release or
     * flushing */
    if (!gst_poll_read_control (priv->poll)) {
      if (errno == EWOULDBLOCK) {
        /* This means that we have two threads trying to allocate memory
         * already, and the other one already got the wait token. This
         * means that we only have to wait for the poll now and not write the
         * token afterwards: we will be woken up once the other thread is
         * woken up and that one will write the wait token it removed */
        GST_LOG_OBJECT (self, "waiting for free memory or flushing");
        gst_poll_wait (priv->poll, GST_CLOCK_TIME_NONE);
      } else {
        /* This is a critical error, GstPoll already gave a warning */
        result = GST_FLOW_ERROR;
        break;
      }
    } else {
      /* We're the first thread waiting, we got the wait token and have to
       * write it again later
       * OR
       * We're a second thread and just consumed the flush token and block all
       * other threads, in which case we must not wait and give it back
       * immediately */
      if (!GST_D3D11_POOL_ALLOCATOR_IS_FLUSHING (self)) {
        GST_LOG_OBJECT (self, "waiting for free memory or flushing");
        gst_poll_wait (priv->poll, GST_CLOCK_TIME_NONE);
      }
      gst_poll_write_control (priv->poll);
    }
  }

  return result;

  /* ERRORS */
flushing:
  {
    GST_DEBUG_OBJECT (self, "we are flushing");
    return GST_FLOW_FLUSHING;
  }
}

/**
 * gst_d3d11_pool_allocator_new:
 * @device: a #GstD3D11Device
 * @desc: a D3D11_TEXTURE2D_DESC for texture allocation
 *
 * Creates a new #GstD3D11PoolAllocator instance.
 *
 * Returns: (transfer full): a new #GstD3D11PoolAllocator instance
 */
GstD3D11PoolAllocator *
gst_d3d11_pool_allocator_new (GstD3D11Device * device,
    const D3D11_TEXTURE2D_DESC * desc)
{
  GstD3D11PoolAllocator *self;

  g_return_val_if_fail (GST_IS_D3D11_DEVICE (device), NULL);
  g_return_val_if_fail (desc != NULL, NULL);

  gst_d3d11_memory_init_once ();

  self = g_object_new (GST_TYPE_D3D11_POOL_ALLOCATOR, NULL);
  gst_object_ref_sink (self);

  self->device = gst_object_ref (device);
  self->priv->desc = *desc;

  return self;
}

/**
 * gst_d3d11_pool_allocator_acquire_memory:
 * @allocator: a #GstD3D11PoolAllocator
 * @memory: (transfer full): a #GstMemory
 *
 * Acquires a #GstMemory from @allocator. @memory should point to a memory
 * location that can hold a pointer to the new #GstMemory.
 *
 * Returns: a #GstFlowReturn such as %GST_FLOW_FLUSHING when the allocator is
 * inactive.
 */
GstFlowReturn
gst_d3d11_pool_allocator_acquire_memory (GstD3D11PoolAllocator * allocator,
    GstMemory ** memory)
{
  GstD3D11PoolAllocatorPrivate *priv;
  GstFlowReturn result;

  g_return_val_if_fail (GST_IS_D3D11_POOL_ALLOCATOR (allocator),
      GST_FLOW_ERROR);
  g_return_val_if_fail (memory != NULL, FALSE);

  priv = allocator->priv;

  /* assume we'll have one more outstanding buffer we need to do that so
   * that concurrent set_active doesn't clear the buffers */
  g_atomic_int_inc (&priv->outstanding);
  result = gst_d3d11_pool_allocator_acquire_memory_internal (allocator, memory);

  if (result == GST_FLOW_OK) {
    GstMemory *mem = *memory;
    /* Replace default allocator with ours */
    gst_object_unref (mem->allocator);
    mem->allocator = gst_object_ref (allocator);
    GST_MINI_OBJECT_CAST (mem)->dispose = gst_d3d11_memory_release;
  } else {
    dec_outstanding (allocator);
  }

  return result;
}

/**
 * gst_d3d11_pool_allocator_get_pool_size:
 * @allocator: a #GstD3D11PoolAllocator
 * @max_size: (out) (optional): the max size of pool
 * @outstanding_size: (out) (optional): the number of outstanding memory
 *
 * Returns: %TRUE if the size of memory pool is known
 *
 * Since: 1.20
 */
gboolean
gst_d3d11_pool_allocator_get_pool_size (GstD3D11PoolAllocator * allocator,
    guint * max_size, guint * outstanding_size)
{
  GstD3D11PoolAllocatorPrivate *priv;

  g_return_val_if_fail (GST_IS_D3D11_POOL_ALLOCATOR (allocator), FALSE);

  priv = allocator->priv;

  if (max_size) {
    if (priv->desc.ArraySize > 1) {
      *max_size = priv->desc.ArraySize;
    } else {
      /* For non-texture-array memory, we don't have any limit yet */
      *max_size = 0;
    }
  }

  if (outstanding_size)
    *outstanding_size = g_atomic_int_get (&priv->outstanding);

  return TRUE;
}