d3d11: Define enum and flags types manually
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-bad / gst-libs / gst / d3d11 / gstd3d11memory.cpp
1 /* GStreamer
2  * Copyright (C) 2019 Seungha Yang <seungha.yang@navercorp.com>
3  * Copyright (C) 2020 Seungha Yang <seungha@centricular.com>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
18  * Boston, MA 02110-1301, USA.
19  */
20
21 #ifdef HAVE_CONFIG_H
22 #include "config.h"
23 #endif
24
25 #include <string.h>
26 #include "gstd3d11memory.h"
27 #include "gstd3d11device.h"
28 #include "gstd3d11utils.h"
29 #include "gstd3d11_private.h"
30
31 GST_DEBUG_CATEGORY_STATIC (gst_d3d11_allocator_debug);
32 #define GST_CAT_DEFAULT gst_d3d11_allocator_debug
33
34 static GstAllocator *_d3d11_memory_allocator;
35
36 GType
37 gst_d3d11_allocation_flags_get_type (void)
38 {
39   static gsize type = 0;
40   static const GFlagsValue values[] = {
41     {GST_D3D11_ALLOCATION_FLAG_DEFAULT, "GST_D3D11_ALLOCATION_FLAG_DEFAULT",
42         "default"},
43     {GST_D3D11_ALLOCATION_FLAG_TEXTURE_ARRAY,
44         "GST_D3D11_ALLOCATION_FLAG_TEXTURE_ARRAY", "texture-array"},
45     {0, nullptr, nullptr}
46   };
47
48   if (g_once_init_enter (&type)) {
49     GType tmp = g_flags_register_static ("GstD3D11AllocationFlags", values);
50     g_once_init_leave (&type, tmp);
51   }
52
53   return (GType) type;
54 }
55
56 GType
57 gst_d3d11_memory_transfer_get_type (void)
58 {
59   static gsize type = 0;
60   static const GFlagsValue values[] = {
61     {GST_D3D11_MEMORY_TRANSFER_NEED_DOWNLOAD,
62         "GST_D3D11_MEMORY_TRANSFER_NEED_DOWNLOAD", "need-download"},
63     {GST_D3D11_MEMORY_TRANSFER_NEED_UPLOAD,
64         "GST_D3D11_MEMORY_TRANSFER_NEED_UPLOAD", "need-upload"},
65     {0, nullptr, nullptr}
66   };
67
68   if (g_once_init_enter (&type)) {
69     GType tmp = g_flags_register_static ("GstD3D11MemoryTransfer", values);
70     g_once_init_leave (&type, tmp);
71   }
72
73   return (GType) type;
74 }
75
76 GType
77 gst_d3d11_memory_native_type_get_type (void)
78 {
79   static gsize type = 0;
80   static const GEnumValue values[] = {
81     {GST_D3D11_MEMORY_NATIVE_TYPE_INVALID,
82         "GST_D3D11_MEMORY_NATIVE_TYPE_INVALID", "invalid"},
83     {GST_D3D11_MEMORY_NATIVE_TYPE_BUFFER, "GST_D3D11_MEMORY_NATIVE_TYPE_BUFFER",
84         "buffer"},
85     {GST_D3D11_MEMORY_NATIVE_TYPE_TEXTURE_2D,
86         "GST_D3D11_MEMORY_NATIVE_TYPE_TEXTURE_2D", "texture-2d"},
87     {0, nullptr, nullptr}
88   };
89
90   if (g_once_init_enter (&type)) {
91     GType tmp = g_enum_register_static ("GstD3D11MemoryNativeType", values);
92     g_once_init_leave (&type, tmp);
93   }
94
95   return (GType) type;
96 }
97
98 /* GstD3D11AllocationParams */
99 static void gst_d3d11_allocation_params_init (GType type);
100 G_DEFINE_BOXED_TYPE_WITH_CODE (GstD3D11AllocationParams,
101     gst_d3d11_allocation_params,
102     (GBoxedCopyFunc) gst_d3d11_allocation_params_copy,
103     (GBoxedFreeFunc) gst_d3d11_allocation_params_free,
104     gst_d3d11_allocation_params_init (g_define_type_id));
105
106 /**
107  * gst_d3d11_allocation_params_new:
108  * @device: a #GstD3D11Device
109  * @info: a #GstVideoInfo
110  * @flags: a #GstD3D11AllocationFlags
111  * @bind_flags: D3D11_BIND_FLAG value used for creating texture
112  * @misc_flags: D3D11_RESOURCE_MISC_FLAG value used for creating texture
113  *
114  * Create #GstD3D11AllocationParams object which is used by #GstD3D11BufferPool
115  * and #GstD3D11Allocator in order to allocate new ID3D11Texture2D
116  * object with given configuration
117  *
118  * Returns: a #GstD3D11AllocationParams or %NULL if @info is not supported
119  *
120  * Since: 1.22
121  */
122 GstD3D11AllocationParams *
123 gst_d3d11_allocation_params_new (GstD3D11Device * device,
124     const GstVideoInfo * info, GstD3D11AllocationFlags flags, guint bind_flags,
125     guint misc_flags)
126 {
127   GstD3D11AllocationParams *ret;
128   GstD3D11Format d3d11_format;
129   guint i;
130
131   g_return_val_if_fail (info != NULL, NULL);
132
133   if (!gst_d3d11_device_get_format (device, GST_VIDEO_INFO_FORMAT (info),
134           &d3d11_format)) {
135     GST_WARNING ("Couldn't get d3d11 format");
136     return NULL;
137   }
138
139   ret = g_new0 (GstD3D11AllocationParams, 1);
140
141   ret->info = *info;
142   ret->aligned_info = *info;
143   ret->d3d11_format = d3d11_format;
144
145   /* Usage Flag
146    * https://docs.microsoft.com/en-us/windows/win32/api/d3d11/ne-d3d11-d3d11_usage
147    *
148    * +----------------------------------------------------------+
149    * | Resource Usage | Default | Dynamic | Immutable | Staging |
150    * +----------------+---------+---------+-----------+---------+
151    * | GPU-Read       | Yes     | Yes     | Yes       | Yes     |
152    * | GPU-Write      | Yes     |         |           | Yes     |
153    * | CPU-Read       |         |         |           | Yes     |
154    * | CPU-Write      |         | Yes     |           | Yes     |
155    * +----------------------------------------------------------+
156    */
157
158   /* If corresponding dxgi format is undefined, use resource format instead */
159   if (d3d11_format.dxgi_format == DXGI_FORMAT_UNKNOWN) {
160     for (i = 0; i < GST_VIDEO_INFO_N_PLANES (info); i++) {
161       g_assert (d3d11_format.resource_format[i] != DXGI_FORMAT_UNKNOWN);
162
163       ret->desc[i].Width = GST_VIDEO_INFO_COMP_WIDTH (info, i);
164       ret->desc[i].Height = GST_VIDEO_INFO_COMP_HEIGHT (info, i);
165       ret->desc[i].MipLevels = 1;
166       ret->desc[i].ArraySize = 1;
167       ret->desc[i].Format = d3d11_format.resource_format[i];
168       ret->desc[i].SampleDesc.Count = 1;
169       ret->desc[i].SampleDesc.Quality = 0;
170       ret->desc[i].Usage = D3D11_USAGE_DEFAULT;
171       ret->desc[i].BindFlags = bind_flags;
172       ret->desc[i].MiscFlags = misc_flags;
173     }
174   } else {
175     ret->desc[0].Width = GST_VIDEO_INFO_WIDTH (info);
176     ret->desc[0].Height = GST_VIDEO_INFO_HEIGHT (info);
177     ret->desc[0].MipLevels = 1;
178     ret->desc[0].ArraySize = 1;
179     ret->desc[0].Format = d3d11_format.dxgi_format;
180     ret->desc[0].SampleDesc.Count = 1;
181     ret->desc[0].SampleDesc.Quality = 0;
182     ret->desc[0].Usage = D3D11_USAGE_DEFAULT;
183     ret->desc[0].BindFlags = bind_flags;
184     ret->desc[0].MiscFlags = misc_flags;
185   }
186
187   ret->flags = flags;
188
189   return ret;
190 }
191
192 /**
193  * gst_d3d11_allocation_params_alignment:
194  * @params: a #GstD3D11AllocationParams
195  * @align: a #GstVideoAlignment
196  *
197  * Adjust Width and Height fields of D3D11_TEXTURE2D_DESC with given
198  * @align
199  *
200  * Returns: %TRUE if alignment could be applied
201  *
202  * Since: 1.22
203  */
204 gboolean
205 gst_d3d11_allocation_params_alignment (GstD3D11AllocationParams * params,
206     const GstVideoAlignment * align)
207 {
208   guint i;
209   guint padding_width, padding_height;
210   GstVideoInfo *info;
211   GstVideoInfo new_info;
212
213   g_return_val_if_fail (params != NULL, FALSE);
214   g_return_val_if_fail (align != NULL, FALSE);
215
216   /* d3d11 does not support stride align. Consider padding only */
217   padding_width = align->padding_left + align->padding_right;
218   padding_height = align->padding_top + align->padding_bottom;
219
220   info = &params->info;
221
222   if (!gst_video_info_set_format (&new_info, GST_VIDEO_INFO_FORMAT (info),
223           GST_VIDEO_INFO_WIDTH (info) + padding_width,
224           GST_VIDEO_INFO_HEIGHT (info) + padding_height)) {
225     GST_WARNING ("Set format fail");
226     return FALSE;
227   }
228
229   params->aligned_info = new_info;
230
231   for (i = 0; i < GST_VIDEO_INFO_N_PLANES (info); i++) {
232     params->desc[i].Width = GST_VIDEO_INFO_COMP_WIDTH (&new_info, i);
233     params->desc[i].Height = GST_VIDEO_INFO_COMP_HEIGHT (&new_info, i);
234   }
235
236   return TRUE;
237 }
238
239 /**
240  * gst_d3d11_allocation_params_copy:
241  * @src: a #GstD3D11AllocationParams
242  *
243  * Returns: a copy of @src
244  *
245  * Since: 1.22
246  */
247 GstD3D11AllocationParams *
248 gst_d3d11_allocation_params_copy (GstD3D11AllocationParams * src)
249 {
250   GstD3D11AllocationParams *dst;
251
252   g_return_val_if_fail (src != NULL, NULL);
253
254   dst = g_new0 (GstD3D11AllocationParams, 1);
255   memcpy (dst, src, sizeof (GstD3D11AllocationParams));
256
257   return dst;
258 }
259
260 /**
261  * gst_d3d11_allocation_params_free:
262  * @params: a #GstD3D11AllocationParams
263  *
264  * Free @params
265  *
266  * Since: 1.22
267  */
268 void
269 gst_d3d11_allocation_params_free (GstD3D11AllocationParams * params)
270 {
271   g_free (params);
272 }
273
274 static gint
275 gst_d3d11_allocation_params_compare (const GstD3D11AllocationParams * p1,
276     const GstD3D11AllocationParams * p2)
277 {
278   g_return_val_if_fail (p1 != NULL, -1);
279   g_return_val_if_fail (p2 != NULL, -1);
280
281   if (p1 == p2)
282     return 0;
283
284   return -1;
285 }
286
287 static void
288 gst_d3d11_allocation_params_init (GType type)
289 {
290   static GstValueTable table = {
291     0, (GstValueCompareFunc) gst_d3d11_allocation_params_compare,
292     NULL, NULL
293   };
294
295   table.type = type;
296   gst_value_register (&table);
297 }
298
299 /* GstD3D11Memory */
300 #define GST_D3D11_MEMORY_GET_LOCK(m) (&(GST_D3D11_MEMORY_CAST(m)->priv->lock))
301 #define GST_D3D11_MEMORY_LOCK(m) G_STMT_START { \
302   GST_TRACE("Locking %p from thread %p", (m), g_thread_self()); \
303   g_mutex_lock(GST_D3D11_MEMORY_GET_LOCK(m)); \
304   GST_TRACE("Locked %p from thread %p", (m), g_thread_self()); \
305 } G_STMT_END
306
307 #define GST_D3D11_MEMORY_UNLOCK(m) G_STMT_START { \
308   GST_TRACE("Unlocking %p from thread %p", (m), g_thread_self()); \
309   g_mutex_unlock(GST_D3D11_MEMORY_GET_LOCK(m)); \
310 } G_STMT_END
311
312 struct _GstD3D11MemoryPrivate
313 {
314   ID3D11Texture2D *texture;
315   ID3D11Buffer *buffer;
316
317   ID3D11Resource *staging;
318
319   D3D11_TEXTURE2D_DESC desc;
320   D3D11_BUFFER_DESC buffer_desc;
321
322   guint subresource_index;
323
324   ID3D11ShaderResourceView *shader_resource_view[GST_VIDEO_MAX_PLANES];
325   guint num_shader_resource_views;
326
327   ID3D11RenderTargetView *render_target_view[GST_VIDEO_MAX_PLANES];
328   guint num_render_target_views;
329
330   ID3D11VideoDecoderOutputView *decoder_output_view;
331   ID3D11VideoDecoder *decoder_handle;
332
333   ID3D11VideoProcessorInputView *processor_input_view;
334   ID3D11VideoProcessorOutputView *processor_output_view;
335
336   D3D11_MAPPED_SUBRESOURCE map;
337
338   GstD3D11MemoryNativeType native_type;
339
340   GMutex lock;
341   gint cpu_map_count;
342
343   GDestroyNotify notify;
344   gpointer user_data;
345 };
346
347 static inline D3D11_MAP
348 gst_d3d11_map_flags_to_d3d11 (GstMapFlags flags)
349 {
350   if ((flags & GST_MAP_READWRITE) == GST_MAP_READWRITE)
351     return D3D11_MAP_READ_WRITE;
352   else if ((flags & GST_MAP_WRITE) == GST_MAP_WRITE)
353     return D3D11_MAP_WRITE;
354   else if ((flags & GST_MAP_READ) == GST_MAP_READ)
355     return D3D11_MAP_READ;
356   else
357     g_assert_not_reached ();
358
359   return D3D11_MAP_READ;
360 }
361
362 static ID3D11Texture2D *
363 gst_d3d11_allocate_staging_texture (GstD3D11Device * device,
364     const D3D11_TEXTURE2D_DESC * ref)
365 {
366   D3D11_TEXTURE2D_DESC desc = { 0, };
367   ID3D11Texture2D *texture = NULL;
368   ID3D11Device *device_handle = gst_d3d11_device_get_device_handle (device);
369   HRESULT hr;
370
371   desc.Width = ref->Width;
372   desc.Height = ref->Height;
373   desc.MipLevels = 1;
374   desc.Format = ref->Format;
375   desc.SampleDesc.Count = 1;
376   desc.ArraySize = 1;
377   desc.Usage = D3D11_USAGE_STAGING;
378   desc.CPUAccessFlags = (D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE);
379
380   hr = device_handle->CreateTexture2D (&desc, NULL, &texture);
381   if (!gst_d3d11_result (hr, device)) {
382     GST_ERROR_OBJECT (device, "Failed to create texture");
383     return NULL;
384   }
385
386   return texture;
387 }
388
389 /* Must be called with d3d11 device lock */
390 static gboolean
391 gst_d3d11_memory_map_cpu_access (GstD3D11Memory * dmem, D3D11_MAP map_type)
392 {
393   GstD3D11MemoryPrivate *priv = dmem->priv;
394   HRESULT hr;
395   ID3D11DeviceContext *device_context =
396       gst_d3d11_device_get_device_context_handle (dmem->device);
397
398   hr = device_context->Map (priv->staging, 0, map_type, 0, &priv->map);
399
400   if (!gst_d3d11_result (hr, dmem->device)) {
401     GST_ERROR_OBJECT (GST_MEMORY_CAST (dmem)->allocator,
402         "Failed to map staging texture (0x%x)", (guint) hr);
403     return FALSE;
404   }
405
406   return TRUE;
407 }
408
409 /* Must be called with d3d11 device lock */
410 static void
411 gst_d3d11_memory_upload (GstD3D11Memory * dmem)
412 {
413   GstD3D11MemoryPrivate *priv = dmem->priv;
414   ID3D11DeviceContext *device_context;
415
416   if (!priv->staging ||
417       !GST_MEMORY_FLAG_IS_SET (dmem, GST_D3D11_MEMORY_TRANSFER_NEED_UPLOAD))
418     return;
419
420   device_context = gst_d3d11_device_get_device_context_handle (dmem->device);
421   device_context->CopySubresourceRegion (priv->texture, priv->subresource_index,
422       0, 0, 0, priv->staging, 0, NULL);
423 }
424
425 /* Must be called with d3d11 device lock */
426 static void
427 gst_d3d11_memory_download (GstD3D11Memory * dmem)
428 {
429   GstD3D11MemoryPrivate *priv = dmem->priv;
430   ID3D11DeviceContext *device_context;
431
432   if (!priv->staging ||
433       !GST_MEMORY_FLAG_IS_SET (dmem, GST_D3D11_MEMORY_TRANSFER_NEED_DOWNLOAD))
434     return;
435
436   device_context = gst_d3d11_device_get_device_context_handle (dmem->device);
437   device_context->CopySubresourceRegion (priv->staging, 0, 0, 0, 0,
438       priv->texture, priv->subresource_index, NULL);
439 }
440
441 static gpointer
442 gst_d3d11_memory_map_full (GstMemory * mem, GstMapInfo * info, gsize maxsize)
443 {
444   GstD3D11Memory *dmem = GST_D3D11_MEMORY_CAST (mem);
445   GstD3D11MemoryPrivate *priv = dmem->priv;
446   GstMapFlags flags = info->flags;
447   gpointer ret = NULL;
448   GstD3D11DeviceLockGuard lk (dmem->device);
449
450   GST_D3D11_MEMORY_LOCK (dmem);
451
452   memset (info->user_data, 0, sizeof (info->user_data));
453   info->user_data[0] = GUINT_TO_POINTER (dmem->priv->subresource_index);
454
455   if ((flags & GST_MAP_D3D11) == GST_MAP_D3D11) {
456     if (priv->native_type == GST_D3D11_MEMORY_NATIVE_TYPE_BUFFER) {
457       /* FIXME: handle non-staging buffer */
458       g_assert (priv->buffer != nullptr);
459       ret = priv->buffer;
460     } else {
461       gst_d3d11_memory_upload (dmem);
462       GST_MEMORY_FLAG_UNSET (dmem, GST_D3D11_MEMORY_TRANSFER_NEED_UPLOAD);
463
464       if ((flags & GST_MAP_WRITE) == GST_MAP_WRITE)
465         GST_MINI_OBJECT_FLAG_SET (dmem,
466             GST_D3D11_MEMORY_TRANSFER_NEED_DOWNLOAD);
467
468       g_assert (priv->texture != NULL);
469       ret = priv->texture;
470       goto out;
471     }
472   }
473
474   if (priv->cpu_map_count == 0) {
475     D3D11_MAP map_type;
476
477     /* FIXME: handle non-staging buffer */
478     if (priv->native_type == GST_D3D11_MEMORY_NATIVE_TYPE_TEXTURE_2D) {
479       /* Allocate staging texture for CPU access */
480       if (!priv->staging) {
481         priv->staging = gst_d3d11_allocate_staging_texture (dmem->device,
482             &priv->desc);
483         if (!priv->staging) {
484           GST_ERROR_OBJECT (mem->allocator, "Couldn't create staging texture");
485           goto out;
486         }
487
488         /* first memory, always need download to staging */
489         GST_MINI_OBJECT_FLAG_SET (mem, GST_D3D11_MEMORY_TRANSFER_NEED_DOWNLOAD);
490       }
491
492       gst_d3d11_memory_download (dmem);
493     }
494
495     map_type = gst_d3d11_map_flags_to_d3d11 (flags);
496     if (!gst_d3d11_memory_map_cpu_access (dmem, map_type)) {
497       GST_ERROR_OBJECT (mem->allocator, "Couldn't map staging texture");
498       goto out;
499     }
500   }
501
502   if ((flags & GST_MAP_WRITE) == GST_MAP_WRITE) {
503     GST_MINI_OBJECT_FLAG_SET (mem, GST_D3D11_MEMORY_TRANSFER_NEED_UPLOAD);
504   }
505
506   GST_MEMORY_FLAG_UNSET (mem, GST_D3D11_MEMORY_TRANSFER_NEED_DOWNLOAD);
507
508   priv->cpu_map_count++;
509   ret = dmem->priv->map.pData;
510
511 out:
512   GST_D3D11_MEMORY_UNLOCK (dmem);
513
514   return ret;
515 }
516
517 /* Must be called with d3d11 device lock */
518 static void
519 gst_d3d11_memory_unmap_cpu_access (GstD3D11Memory * dmem)
520 {
521   GstD3D11MemoryPrivate *priv = dmem->priv;
522   ID3D11DeviceContext *device_context =
523       gst_d3d11_device_get_device_context_handle (dmem->device);
524
525   device_context->Unmap (priv->staging, 0);
526 }
527
528 static void
529 gst_d3d11_memory_unmap_full (GstMemory * mem, GstMapInfo * info)
530 {
531   GstD3D11Memory *dmem = GST_D3D11_MEMORY_CAST (mem);
532   GstD3D11MemoryPrivate *priv = dmem->priv;
533   GstD3D11DeviceLockGuard lk (dmem->device);
534
535   GST_D3D11_MEMORY_LOCK (dmem);
536
537   if ((info->flags & GST_MAP_D3D11) == GST_MAP_D3D11) {
538     if ((info->flags & GST_MAP_WRITE) == GST_MAP_WRITE)
539       GST_MINI_OBJECT_FLAG_SET (mem, GST_D3D11_MEMORY_TRANSFER_NEED_DOWNLOAD);
540
541     goto out;
542   }
543
544   if ((info->flags & GST_MAP_WRITE) == GST_MAP_WRITE)
545     GST_MINI_OBJECT_FLAG_SET (mem, GST_D3D11_MEMORY_TRANSFER_NEED_UPLOAD);
546
547   priv->cpu_map_count--;
548   if (priv->cpu_map_count > 0)
549     goto out;
550
551   gst_d3d11_memory_unmap_cpu_access (dmem);
552
553 out:
554   GST_D3D11_MEMORY_UNLOCK (dmem);
555 }
556
557 static GstMemory *
558 gst_d3d11_memory_share (GstMemory * mem, gssize offset, gssize size)
559 {
560   /* TODO: impl. */
561   return NULL;
562 }
563
564 static gboolean
565 gst_d3d11_memory_update_size (GstMemory * mem)
566 {
567   GstD3D11Memory *dmem = GST_D3D11_MEMORY_CAST (mem);
568   GstD3D11MemoryPrivate *priv = dmem->priv;
569   gsize offset[GST_VIDEO_MAX_PLANES];
570   gint stride[GST_VIDEO_MAX_PLANES];
571   gsize size;
572   D3D11_TEXTURE2D_DESC *desc = &priv->desc;
573   gboolean ret = FALSE;
574
575   if (!priv->staging) {
576     priv->staging = gst_d3d11_allocate_staging_texture (dmem->device,
577         &priv->desc);
578     if (!priv->staging) {
579       GST_ERROR_OBJECT (mem->allocator, "Couldn't create staging texture");
580       return FALSE;
581     }
582   }
583
584   GstD3D11DeviceLockGuard lk (dmem->device);
585
586   if (!gst_d3d11_memory_map_cpu_access (dmem, D3D11_MAP_READ_WRITE)) {
587     GST_ERROR_OBJECT (mem->allocator, "Couldn't map staging texture");
588     return FALSE;
589   }
590
591   gst_d3d11_memory_unmap_cpu_access (dmem);
592
593   if (!gst_d3d11_dxgi_format_get_size (desc->Format, desc->Width, desc->Height,
594           priv->map.RowPitch, offset, stride, &size)) {
595     GST_ERROR_OBJECT (mem->allocator, "Couldn't calculate memory size");
596     goto out;
597   }
598
599   mem->maxsize = mem->size = size;
600   ret = TRUE;
601
602 out:
603   GST_D3D11_CLEAR_COM (priv->staging);
604
605   return ret;
606 }
607
608 /**
609  * gst_is_d3d11_memory:
610  * @mem: a #GstMemory
611  *
612  * Returns: whether @mem is a #GstD3D11Memory
613  *
614  * Since: 1.22
615  */
616 gboolean
617 gst_is_d3d11_memory (GstMemory * mem)
618 {
619   return mem != NULL && mem->allocator != NULL &&
620       (GST_IS_D3D11_ALLOCATOR (mem->allocator) ||
621       GST_IS_D3D11_POOL_ALLOCATOR (mem->allocator));
622 }
623
624 /**
625  * gst_d3d11_memory_get_native_type:
626  * @mem: a #GstD3D11Memory
627  *
628  * Returns: a #GstD3D11MemoryNativeType
629  *
630  * Since: 1.22
631  */
632 GstD3D11MemoryNativeType
633 gst_d3d11_memory_get_native_type (GstD3D11Memory * mem)
634 {
635   if (!gst_is_d3d11_memory (GST_MEMORY_CAST (mem)))
636     return GST_D3D11_MEMORY_NATIVE_TYPE_INVALID;
637
638   return mem->priv->native_type;
639 }
640
641 /**
642  * gst_d3d11_memory_init_once:
643  *
644  * Initializes the Direct3D11 Texture allocator. It is safe to call
645  * this function multiple times. This must be called before any other
646  * GstD3D11Memory operation.
647  *
648  * Since: 1.22
649  */
650 void
651 gst_d3d11_memory_init_once (void)
652 {
653   static gsize _init = 0;
654
655   if (g_once_init_enter (&_init)) {
656
657     GST_DEBUG_CATEGORY_INIT (gst_d3d11_allocator_debug, "d3d11allocator", 0,
658         "Direct3D11 Texture Allocator");
659
660     _d3d11_memory_allocator =
661         (GstAllocator *) g_object_new (GST_TYPE_D3D11_ALLOCATOR, NULL);
662     gst_object_ref_sink (_d3d11_memory_allocator);
663
664     gst_allocator_register (GST_D3D11_MEMORY_NAME, _d3d11_memory_allocator);
665     g_once_init_leave (&_init, 1);
666   }
667 }
668
669 /**
670  * gst_d3d11_memory_get_resource_handle:
671  * @mem: a #GstD3D11Memory
672  *
673  * Returns: (transfer none): a ID3D11Resource handle. Caller must not release
674  * returned handle.
675  *
676  * Since: 1.22
677  */
678 ID3D11Resource *
679 gst_d3d11_memory_get_resource_handle (GstD3D11Memory * mem)
680 {
681   g_return_val_if_fail (gst_is_d3d11_memory (GST_MEMORY_CAST (mem)), NULL);
682
683   switch (mem->priv->native_type) {
684     case GST_D3D11_MEMORY_NATIVE_TYPE_BUFFER:
685       return mem->priv->buffer;
686     case GST_D3D11_MEMORY_NATIVE_TYPE_TEXTURE_2D:
687       return mem->priv->texture;
688     default:
689       break;
690   }
691
692   return nullptr;
693 }
694
695 /**
696  * gst_d3d11_memory_get_subresource_index:
697  * @mem: a #GstD3D11Memory
698  *
699  * Returns: subresource index corresponding to @mem.
700  *
701  * Since: 1.22
702  */
703 guint
704 gst_d3d11_memory_get_subresource_index (GstD3D11Memory * mem)
705 {
706   g_return_val_if_fail (gst_is_d3d11_memory (GST_MEMORY_CAST (mem)), 0);
707
708   if (mem->priv->native_type != GST_D3D11_MEMORY_NATIVE_TYPE_TEXTURE_2D)
709     return 0;
710
711   return mem->priv->subresource_index;
712 }
713
714 /**
715  * gst_d3d11_memory_get_texture_desc:
716  * @mem: a #GstD3D11Memory
717  * @desc: (out): a D3D11_TEXTURE2D_DESC
718  *
719  * Fill @desc with D3D11_TEXTURE2D_DESC for ID3D11Texture2D
720  *
721  * Returns: %TRUE if successeed
722  *
723  * Since: 1.22
724  */
725 gboolean
726 gst_d3d11_memory_get_texture_desc (GstD3D11Memory * mem,
727     D3D11_TEXTURE2D_DESC * desc)
728 {
729   g_return_val_if_fail (gst_is_d3d11_memory (GST_MEMORY_CAST (mem)), FALSE);
730   g_return_val_if_fail (desc != NULL, FALSE);
731
732   if (mem->priv->native_type != GST_D3D11_MEMORY_NATIVE_TYPE_TEXTURE_2D)
733     return FALSE;
734
735   *desc = mem->priv->desc;
736
737   return TRUE;
738 }
739
740 /**
741  * gst_d3d11_memory_get_buffer_desc:
742  * @mem: a #GstD3D11Memory
743  * @desc: (out): a D3D11_BUFFER_DESC
744  *
745  * Fill @desc with D3D11_BUFFER_DESC for ID3D11Buffer
746  *
747  * Returns: %TRUE if successeed
748  *
749  * Since: 1.22
750  */
751 gboolean
752 gst_d3d11_memory_get_buffer_desc (GstD3D11Memory * mem,
753     D3D11_BUFFER_DESC * desc)
754 {
755   g_return_val_if_fail (gst_is_d3d11_memory (GST_MEMORY_CAST (mem)), FALSE);
756   g_return_val_if_fail (desc != NULL, FALSE);
757
758   if (mem->priv->native_type != GST_D3D11_MEMORY_NATIVE_TYPE_BUFFER)
759     return FALSE;
760
761   *desc = mem->priv->buffer_desc;
762
763   return TRUE;
764 }
765
766 /**
767  * gst_d3d11_memory_get_resource_stride:
768  * @mem: a #GstD3D11Memory
769  * @stride: (out): stride of resource
770  *
771  * Returns: %TRUE if successeed
772  *
773  * Since: 1.22
774  */
775 gboolean
776 gst_d3d11_memory_get_resource_stride (GstD3D11Memory * mem, guint * stride)
777 {
778   g_return_val_if_fail (gst_is_d3d11_memory (GST_MEMORY_CAST (mem)), FALSE);
779   g_return_val_if_fail (stride != NULL, FALSE);
780
781   *stride = mem->priv->map.RowPitch;
782
783   return TRUE;
784 }
785
786 static gboolean
787 create_shader_resource_views (GstD3D11Memory * mem)
788 {
789   GstD3D11MemoryPrivate *priv = mem->priv;
790   guint i;
791   HRESULT hr;
792   guint num_views = 0;
793   ID3D11Device *device_handle;
794   D3D11_SHADER_RESOURCE_VIEW_DESC resource_desc;
795   DXGI_FORMAT formats[GST_VIDEO_MAX_PLANES] = { DXGI_FORMAT_UNKNOWN, };
796
797   memset (&resource_desc, 0, sizeof (D3D11_SHADER_RESOURCE_VIEW_DESC));
798
799   device_handle = gst_d3d11_device_get_device_handle (mem->device);
800
801   num_views = gst_d3d11_dxgi_format_get_resource_format (priv->desc.Format,
802       formats);
803   if (!num_views) {
804     GST_ERROR_OBJECT (GST_MEMORY_CAST (mem)->allocator,
805         "Unknown resource formats for DXGI format %s (%d)",
806         gst_d3d11_dxgi_format_to_string (priv->desc.Format), priv->desc.Format);
807     return FALSE;
808   }
809
810   if ((priv->desc.BindFlags & D3D11_BIND_SHADER_RESOURCE) != 0) {
811     resource_desc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
812     resource_desc.Texture2D.MipLevels = 1;
813
814     for (i = 0; i < num_views; i++) {
815       resource_desc.Format = formats[i];
816       hr = device_handle->CreateShaderResourceView (priv->texture,
817           &resource_desc, &priv->shader_resource_view[i]);
818
819       if (!gst_d3d11_result (hr, mem->device)) {
820         GST_ERROR_OBJECT (GST_MEMORY_CAST (mem)->allocator,
821             "Failed to create resource DXGI format %s (%d) for plane %d"
822             " view (0x%x)", gst_d3d11_dxgi_format_to_string (formats[i]),
823             formats[i], i, (guint) hr);
824         goto error;
825       }
826     }
827
828     priv->num_shader_resource_views = num_views;
829
830     return TRUE;
831   }
832
833   return FALSE;
834
835 error:
836   for (i = 0; i < num_views; i++)
837     GST_D3D11_CLEAR_COM (priv->shader_resource_view[i]);
838
839   priv->num_shader_resource_views = 0;
840
841   return FALSE;
842 }
843
844 static gboolean
845 gst_d3d11_memory_ensure_shader_resource_view (GstD3D11Memory * mem)
846 {
847   GstD3D11MemoryPrivate *priv = mem->priv;
848   gboolean ret = FALSE;
849
850   if (mem->priv->native_type != GST_D3D11_MEMORY_NATIVE_TYPE_TEXTURE_2D)
851     return FALSE;
852
853   if (!(priv->desc.BindFlags & D3D11_BIND_SHADER_RESOURCE)) {
854     GST_LOG_OBJECT (GST_MEMORY_CAST (mem)->allocator,
855         "Need BindFlags, current flag 0x%x", priv->desc.BindFlags);
856     return FALSE;
857   }
858
859   GST_D3D11_MEMORY_LOCK (mem);
860   if (priv->num_shader_resource_views) {
861     ret = TRUE;
862     goto done;
863   }
864
865   ret = create_shader_resource_views (mem);
866
867 done:
868   GST_D3D11_MEMORY_UNLOCK (mem);
869
870   return ret;
871 }
872
873 /**
874  * gst_d3d11_memory_get_shader_resource_view_size:
875  * @mem: a #GstD3D11Memory
876  *
877  * Returns: the number of ID3D11ShaderResourceView that can be used
878  * for processing GPU operation with @mem
879  *
880  * Since: 1.22
881  */
882 guint
883 gst_d3d11_memory_get_shader_resource_view_size (GstD3D11Memory * mem)
884 {
885   g_return_val_if_fail (gst_is_d3d11_memory (GST_MEMORY_CAST (mem)), 0);
886
887   if (!gst_d3d11_memory_ensure_shader_resource_view (mem))
888     return 0;
889
890   return mem->priv->num_shader_resource_views;
891 }
892
893 /**
894  * gst_d3d11_memory_get_shader_resource_view:
895  * @mem: a #GstD3D11Memory
896  * @index: the index of the ID3D11ShaderResourceView
897  *
898  * Returns: (transfer none) (nullable): a pointer to the
899  * ID3D11ShaderResourceView or %NULL if ID3D11ShaderResourceView is unavailable
900  * for @index
901  *
902  * Since: 1.22
903  */
904 ID3D11ShaderResourceView *
905 gst_d3d11_memory_get_shader_resource_view (GstD3D11Memory * mem, guint index)
906 {
907   GstD3D11MemoryPrivate *priv;
908
909   g_return_val_if_fail (gst_is_d3d11_memory (GST_MEMORY_CAST (mem)), NULL);
910
911   if (!gst_d3d11_memory_ensure_shader_resource_view (mem))
912     return NULL;
913
914   priv = mem->priv;
915
916   if (index >= priv->num_shader_resource_views) {
917     GST_ERROR ("Invalid SRV index %d", index);
918     return NULL;
919   }
920
921   return priv->shader_resource_view[index];
922 }
923
924 static gboolean
925 create_render_target_views (GstD3D11Memory * mem)
926 {
927   GstD3D11MemoryPrivate *priv = mem->priv;
928   guint i;
929   HRESULT hr;
930   guint num_views = 0;
931   ID3D11Device *device_handle;
932   D3D11_RENDER_TARGET_VIEW_DESC render_desc;
933   DXGI_FORMAT formats[GST_VIDEO_MAX_PLANES] = { DXGI_FORMAT_UNKNOWN, };
934
935   memset (&render_desc, 0, sizeof (D3D11_RENDER_TARGET_VIEW_DESC));
936
937   device_handle = gst_d3d11_device_get_device_handle (mem->device);
938
939   num_views = gst_d3d11_dxgi_format_get_resource_format (priv->desc.Format,
940       formats);
941   if (!num_views) {
942     GST_ERROR_OBJECT (GST_MEMORY_CAST (mem)->allocator,
943         "Unknown resource formats for DXGI format %s (%d)",
944         gst_d3d11_dxgi_format_to_string (priv->desc.Format), priv->desc.Format);
945     return FALSE;
946   }
947
948   if ((priv->desc.BindFlags & D3D11_BIND_RENDER_TARGET) != 0) {
949     render_desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
950     render_desc.Texture2D.MipSlice = 0;
951
952     for (i = 0; i < num_views; i++) {
953       render_desc.Format = formats[i];
954
955       hr = device_handle->CreateRenderTargetView (priv->texture, &render_desc,
956           &priv->render_target_view[i]);
957       if (!gst_d3d11_result (hr, mem->device)) {
958         GST_ERROR_OBJECT (GST_MEMORY_CAST (mem)->allocator,
959             "Failed to create resource DXGI format %s (%d) for plane %d"
960             " view (0x%x)", gst_d3d11_dxgi_format_to_string (formats[i]),
961             formats[i], i, (guint) hr);
962         goto error;
963       }
964     }
965
966     priv->num_render_target_views = num_views;
967
968     return TRUE;
969   }
970
971   return FALSE;
972
973 error:
974   for (i = 0; i < num_views; i++)
975     GST_D3D11_CLEAR_COM (priv->render_target_view[i]);
976
977   priv->num_render_target_views = 0;
978
979   return FALSE;
980 }
981
982 static gboolean
983 gst_d3d11_memory_ensure_render_target_view (GstD3D11Memory * mem)
984 {
985   GstD3D11MemoryPrivate *priv = mem->priv;
986   gboolean ret = FALSE;
987
988   if (mem->priv->native_type != GST_D3D11_MEMORY_NATIVE_TYPE_TEXTURE_2D)
989     return FALSE;
990
991   if (!(priv->desc.BindFlags & D3D11_BIND_RENDER_TARGET)) {
992     GST_WARNING_OBJECT (GST_MEMORY_CAST (mem)->allocator,
993         "Need BindFlags, current flag 0x%x", priv->desc.BindFlags);
994     return FALSE;
995   }
996
997   GST_D3D11_MEMORY_LOCK (mem);
998   if (priv->num_render_target_views) {
999     ret = TRUE;
1000     goto done;
1001   }
1002
1003   ret = create_render_target_views (mem);
1004
1005 done:
1006   GST_D3D11_MEMORY_UNLOCK (mem);
1007
1008   return ret;
1009 }
1010
1011 /**
1012  * gst_d3d11_memory_get_render_target_view_size:
1013  * @mem: a #GstD3D11Memory
1014  *
1015  * Returns: the number of ID3D11RenderTargetView that can be used
1016  * for processing GPU operation with @mem
1017  *
1018  * Since: 1.22
1019  */
1020 guint
1021 gst_d3d11_memory_get_render_target_view_size (GstD3D11Memory * mem)
1022 {
1023   g_return_val_if_fail (gst_is_d3d11_memory (GST_MEMORY_CAST (mem)), 0);
1024
1025   if (!gst_d3d11_memory_ensure_render_target_view (mem))
1026     return 0;
1027
1028   return mem->priv->num_render_target_views;
1029 }
1030
1031 /**
1032  * gst_d3d11_memory_get_render_target_view:
1033  * @mem: a #GstD3D11Memory
1034  * @index: the index of the ID3D11RenderTargetView
1035  *
1036  * Returns: (transfer none) (nullable): a pointer to the
1037  * ID3D11RenderTargetView or %NULL if ID3D11RenderTargetView is unavailable
1038  * for @index
1039  *
1040  * Since: 1.22
1041  */
1042 ID3D11RenderTargetView *
1043 gst_d3d11_memory_get_render_target_view (GstD3D11Memory * mem, guint index)
1044 {
1045   GstD3D11MemoryPrivate *priv;
1046
1047   g_return_val_if_fail (gst_is_d3d11_memory (GST_MEMORY_CAST (mem)), NULL);
1048
1049   if (!gst_d3d11_memory_ensure_render_target_view (mem))
1050     return NULL;
1051
1052   priv = mem->priv;
1053
1054   if (index >= priv->num_render_target_views) {
1055     GST_ERROR ("Invalid RTV index %d", index);
1056     return NULL;
1057   }
1058
1059   return priv->render_target_view[index];
1060 }
1061
1062 static gboolean
1063 gst_d3d11_memory_ensure_decoder_output_view (GstD3D11Memory * mem,
1064     ID3D11VideoDevice * video_device, ID3D11VideoDecoder * decoder,
1065     const GUID * decoder_profile)
1066 {
1067   GstD3D11MemoryPrivate *dmem_priv = mem->priv;
1068   GstD3D11Allocator *allocator;
1069   D3D11_VIDEO_DECODER_OUTPUT_VIEW_DESC desc;
1070   HRESULT hr;
1071   gboolean ret = FALSE;
1072
1073   if (mem->priv->native_type != GST_D3D11_MEMORY_NATIVE_TYPE_TEXTURE_2D)
1074     return FALSE;
1075
1076   allocator = GST_D3D11_ALLOCATOR (GST_MEMORY_CAST (mem)->allocator);
1077
1078   if (!(dmem_priv->desc.BindFlags & D3D11_BIND_DECODER)) {
1079     GST_LOG_OBJECT (allocator,
1080         "Need BindFlags, current flag 0x%x", dmem_priv->desc.BindFlags);
1081     return FALSE;
1082   }
1083
1084   GST_D3D11_MEMORY_LOCK (mem);
1085   if (dmem_priv->decoder_output_view) {
1086     dmem_priv->decoder_output_view->GetDesc (&desc);
1087     if (IsEqualGUID (desc.DecodeProfile, *decoder_profile) &&
1088         dmem_priv->decoder_handle == decoder) {
1089       goto succeeded;
1090     } else {
1091       /* Shouldn't happen, but try again anyway */
1092       GST_WARNING_OBJECT (allocator,
1093           "Existing view has different decoder profile");
1094       GST_D3D11_CLEAR_COM (dmem_priv->decoder_output_view);
1095       GST_D3D11_CLEAR_COM (dmem_priv->decoder_handle);
1096     }
1097   }
1098
1099   if (dmem_priv->decoder_output_view)
1100     goto succeeded;
1101
1102   desc.DecodeProfile = *decoder_profile;
1103   desc.ViewDimension = D3D11_VDOV_DIMENSION_TEXTURE2D;
1104   desc.Texture2D.ArraySlice = dmem_priv->subresource_index;
1105
1106   hr = video_device->CreateVideoDecoderOutputView (dmem_priv->texture, &desc,
1107       &dmem_priv->decoder_output_view);
1108   if (!gst_d3d11_result (hr, mem->device)) {
1109     GST_ERROR_OBJECT (allocator,
1110         "Could not create decoder output view, hr: 0x%x", (guint) hr);
1111     goto done;
1112   }
1113
1114   /* XXX: decoder output view is bound to video device, not decoder handle
1115    * from API point of view. But some driver seems to be unhappy
1116    * when decoder handle is released while there are outstanding view objects */
1117   dmem_priv->decoder_handle = decoder;
1118   decoder->AddRef ();
1119
1120 succeeded:
1121   ret = TRUE;
1122
1123 done:
1124   GST_D3D11_MEMORY_UNLOCK (mem);
1125
1126   return ret;
1127 }
1128
1129 /**
1130  * gst_d3d11_memory_get_decoder_output_view:
1131  * @mem: a #GstD3D11Memory
1132  * @video_device: (transfer none): a ID3D11VideoDevice handle
1133  * @decoder: (transfer none): a ID3D11VideoDecoder handle
1134  * @decoder_profile: a DXVA decoder profile GUID
1135  *
1136  * Returns: (transfer none) (nullable): a pointer to the
1137  * ID3D11VideoDecoderOutputView or %NULL if ID3D11VideoDecoderOutputView is
1138  * unavailable
1139  *
1140  * Since: 1.22
1141  */
1142 ID3D11VideoDecoderOutputView *
1143 gst_d3d11_memory_get_decoder_output_view (GstD3D11Memory * mem,
1144     ID3D11VideoDevice * video_device, ID3D11VideoDecoder * decoder,
1145     const GUID * decoder_profile)
1146 {
1147   g_return_val_if_fail (gst_is_d3d11_memory (GST_MEMORY_CAST (mem)), NULL);
1148   g_return_val_if_fail (video_device != NULL, NULL);
1149   g_return_val_if_fail (decoder != NULL, NULL);
1150   g_return_val_if_fail (decoder_profile != NULL, NULL);
1151
1152   if (!gst_d3d11_memory_ensure_decoder_output_view (mem,
1153           video_device, decoder, decoder_profile))
1154     return NULL;
1155
1156   return mem->priv->decoder_output_view;
1157 }
1158
1159 static gboolean
1160 check_bind_flags_for_processor_input_view (guint bind_flags)
1161 {
1162   static const guint compatible_flags = (D3D11_BIND_DECODER |
1163       D3D11_BIND_VIDEO_ENCODER | D3D11_BIND_RENDER_TARGET |
1164       D3D11_BIND_UNORDERED_ACCESS);
1165
1166   if (bind_flags == 0)
1167     return TRUE;
1168
1169   if ((bind_flags & compatible_flags) != 0)
1170     return TRUE;
1171
1172   return FALSE;
1173 }
1174
1175 static gboolean
1176 gst_d3d11_memory_ensure_processor_input_view (GstD3D11Memory * mem,
1177     ID3D11VideoDevice * video_device,
1178     ID3D11VideoProcessorEnumerator * enumerator)
1179 {
1180   GstD3D11MemoryPrivate *dmem_priv = mem->priv;
1181   GstD3D11Allocator *allocator;
1182   D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC desc;
1183   HRESULT hr;
1184   gboolean ret = FALSE;
1185
1186   if (mem->priv->native_type != GST_D3D11_MEMORY_NATIVE_TYPE_TEXTURE_2D)
1187     return FALSE;
1188
1189   allocator = GST_D3D11_ALLOCATOR (GST_MEMORY_CAST (mem)->allocator);
1190
1191   if (!check_bind_flags_for_processor_input_view (dmem_priv->desc.BindFlags)) {
1192     GST_LOG_OBJECT (allocator,
1193         "Need BindFlags, current flag 0x%x", dmem_priv->desc.BindFlags);
1194     return FALSE;
1195   }
1196
1197   GST_D3D11_MEMORY_LOCK (mem);
1198   if (dmem_priv->processor_input_view)
1199     goto succeeded;
1200
1201   desc.FourCC = 0;
1202   desc.ViewDimension = D3D11_VPIV_DIMENSION_TEXTURE2D;
1203   desc.Texture2D.MipSlice = 0;
1204   desc.Texture2D.ArraySlice = dmem_priv->subresource_index;
1205
1206   hr = video_device->CreateVideoProcessorInputView (dmem_priv->texture,
1207       enumerator, &desc, &dmem_priv->processor_input_view);
1208   if (!gst_d3d11_result (hr, mem->device)) {
1209     GST_ERROR_OBJECT (allocator,
1210         "Could not create processor input view, hr: 0x%x", (guint) hr);
1211     goto done;
1212   }
1213
1214 succeeded:
1215   ret = TRUE;
1216
1217 done:
1218   GST_D3D11_MEMORY_UNLOCK (mem);
1219
1220   return ret;
1221 }
1222
1223 /**
1224  * gst_d3d11_memory_get_processor_input_view:
1225  * @mem: a #GstD3D11Memory
1226  * @video_device: a #ID3D11VideoDevice
1227  * @enumerator: a #ID3D11VideoProcessorEnumerator
1228  *
1229  * Returns: (transfer none) (nullable): a pointer to the
1230  * ID3D11VideoProcessorInputView or %NULL if ID3D11VideoProcessorInputView is
1231  * unavailable
1232  *
1233  * Since: 1.22
1234  */
1235 ID3D11VideoProcessorInputView *
1236 gst_d3d11_memory_get_processor_input_view (GstD3D11Memory * mem,
1237     ID3D11VideoDevice * video_device,
1238     ID3D11VideoProcessorEnumerator * enumerator)
1239 {
1240   g_return_val_if_fail (gst_is_d3d11_memory (GST_MEMORY_CAST (mem)), NULL);
1241   g_return_val_if_fail (video_device != NULL, NULL);
1242   g_return_val_if_fail (enumerator != NULL, NULL);
1243
1244   if (!gst_d3d11_memory_ensure_processor_input_view (mem, video_device,
1245           enumerator))
1246     return NULL;
1247
1248   return mem->priv->processor_input_view;
1249 }
1250
1251 static gboolean
1252 gst_d3d11_memory_ensure_processor_output_view (GstD3D11Memory * mem,
1253     ID3D11VideoDevice * video_device,
1254     ID3D11VideoProcessorEnumerator * enumerator)
1255 {
1256   GstD3D11MemoryPrivate *priv = mem->priv;
1257   GstD3D11Allocator *allocator;
1258   D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC desc;
1259   HRESULT hr;
1260   gboolean ret;
1261
1262   if (mem->priv->native_type != GST_D3D11_MEMORY_NATIVE_TYPE_TEXTURE_2D)
1263     return FALSE;
1264
1265   memset (&desc, 0, sizeof (D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC));
1266
1267   allocator = GST_D3D11_ALLOCATOR (GST_MEMORY_CAST (mem)->allocator);
1268
1269   if (!(priv->desc.BindFlags & D3D11_BIND_RENDER_TARGET)) {
1270     GST_LOG_OBJECT (allocator,
1271         "Need BindFlags, current flag 0x%x", priv->desc.BindFlags);
1272     return FALSE;
1273   }
1274
1275   /* FIXME: texture array should be supported at some point */
1276   if (priv->subresource_index != 0) {
1277     GST_FIXME_OBJECT (allocator,
1278         "Texture array is not suppoted for processor output view");
1279     return FALSE;
1280   }
1281
1282   GST_D3D11_MEMORY_LOCK (mem);
1283   if (priv->processor_output_view)
1284     goto succeeded;
1285
1286   desc.ViewDimension = D3D11_VPOV_DIMENSION_TEXTURE2D;
1287   desc.Texture2D.MipSlice = 0;
1288
1289   hr = video_device->CreateVideoProcessorOutputView (priv->texture,
1290       enumerator, &desc, &priv->processor_output_view);
1291   if (!gst_d3d11_result (hr, mem->device)) {
1292     GST_ERROR_OBJECT (allocator,
1293         "Could not create processor input view, hr: 0x%x", (guint) hr);
1294     goto done;
1295   }
1296
1297 succeeded:
1298   ret = TRUE;
1299
1300 done:
1301   GST_D3D11_MEMORY_UNLOCK (mem);
1302
1303   return ret;
1304 }
1305
1306 /**
1307  * gst_d3d11_memory_get_processor_output_view:
1308  * @mem: a #GstD3D11Memory
1309  * @video_device: a #ID3D11VideoDevice
1310  * @enumerator: a #ID3D11VideoProcessorEnumerator
1311  *
1312  * Returns: (transfer none) (nullable): a pointer to the
1313  * ID3D11VideoProcessorOutputView or %NULL if ID3D11VideoProcessorOutputView is
1314  * unavailable
1315  *
1316  * Since: 1.22
1317  */
1318 ID3D11VideoProcessorOutputView *
1319 gst_d3d11_memory_get_processor_output_view (GstD3D11Memory * mem,
1320     ID3D11VideoDevice * video_device,
1321     ID3D11VideoProcessorEnumerator * enumerator)
1322 {
1323   g_return_val_if_fail (gst_is_d3d11_memory (GST_MEMORY_CAST (mem)), NULL);
1324   g_return_val_if_fail (video_device != NULL, NULL);
1325   g_return_val_if_fail (enumerator != NULL, NULL);
1326
1327   if (!gst_d3d11_memory_ensure_processor_output_view (mem, video_device,
1328           enumerator))
1329     return NULL;
1330
1331   return mem->priv->processor_output_view;
1332 }
1333
1334 /* GstD3D11Allocator */
1335 struct _GstD3D11AllocatorPrivate
1336 {
1337   GstMemoryCopyFunction fallback_copy;
1338 };
1339
1340 #define gst_d3d11_allocator_parent_class alloc_parent_class
1341 G_DEFINE_TYPE_WITH_PRIVATE (GstD3D11Allocator,
1342     gst_d3d11_allocator, GST_TYPE_ALLOCATOR);
1343
1344 static GstMemory *gst_d3d11_allocator_dummy_alloc (GstAllocator * allocator,
1345     gsize size, GstAllocationParams * params);
1346 static GstMemory *gst_d3d11_allocator_alloc_internal (GstD3D11Allocator * self,
1347     GstD3D11Device * device, const D3D11_TEXTURE2D_DESC * desc,
1348     ID3D11Texture2D * texture);
1349 static void gst_d3d11_allocator_free (GstAllocator * allocator,
1350     GstMemory * mem);
1351
1352 static void
1353 gst_d3d11_allocator_class_init (GstD3D11AllocatorClass * klass)
1354 {
1355   GstAllocatorClass *allocator_class = GST_ALLOCATOR_CLASS (klass);
1356
1357   allocator_class->alloc = gst_d3d11_allocator_dummy_alloc;
1358   allocator_class->free = gst_d3d11_allocator_free;
1359 }
1360
1361 static GstMemory *
1362 gst_d3d11_memory_copy (GstMemory * mem, gssize offset, gssize size)
1363 {
1364   GstD3D11Allocator *alloc = GST_D3D11_ALLOCATOR (mem->allocator);
1365   GstD3D11AllocatorPrivate *priv = alloc->priv;
1366   GstD3D11Memory *dmem = GST_D3D11_MEMORY_CAST (mem);
1367   GstD3D11Memory *copy_dmem;
1368   GstD3D11Device *device = dmem->device;
1369   ID3D11Device *device_handle = gst_d3d11_device_get_device_handle (device);
1370   ID3D11DeviceContext *device_context =
1371       gst_d3d11_device_get_device_context_handle (device);
1372   D3D11_TEXTURE2D_DESC dst_desc = { 0, };
1373   D3D11_TEXTURE2D_DESC src_desc = { 0, };
1374   GstMemory *copy = NULL;
1375   GstMapInfo info;
1376   HRESULT hr;
1377   UINT bind_flags = 0;
1378   UINT supported_flags = 0;
1379
1380   if (dmem->priv->native_type != GST_D3D11_MEMORY_NATIVE_TYPE_TEXTURE_2D)
1381     return priv->fallback_copy (mem, offset, size);
1382
1383   /* non-zero offset or different size is not supported */
1384   if (offset != 0 || (size != -1 && (gsize) size != mem->size)) {
1385     GST_DEBUG_OBJECT (alloc, "Different size/offset, try fallback copy");
1386     return priv->fallback_copy (mem, offset, size);
1387   }
1388
1389   GstD3D11DeviceLockGuard lk (device);
1390
1391   if (!gst_memory_map (mem, &info,
1392           (GstMapFlags) (GST_MAP_READ | GST_MAP_D3D11))) {
1393
1394     GST_WARNING_OBJECT (alloc, "Failed to map memory, try fallback copy");
1395
1396     return priv->fallback_copy (mem, offset, size);
1397   }
1398
1399   dmem->priv->texture->GetDesc (&src_desc);
1400   dst_desc.Width = src_desc.Width;
1401   dst_desc.Height = src_desc.Height;
1402   dst_desc.MipLevels = 1;
1403   dst_desc.Format = src_desc.Format;
1404   dst_desc.SampleDesc.Count = 1;
1405   dst_desc.ArraySize = 1;
1406   dst_desc.Usage = D3D11_USAGE_DEFAULT;
1407
1408   /* If supported, use bind flags for SRV/RTV */
1409   hr = device_handle->CheckFormatSupport (src_desc.Format, &supported_flags);
1410   if (gst_d3d11_result (hr, device)) {
1411     if ((supported_flags & D3D11_FORMAT_SUPPORT_SHADER_SAMPLE) ==
1412         D3D11_FORMAT_SUPPORT_SHADER_SAMPLE) {
1413       bind_flags |= D3D11_BIND_SHADER_RESOURCE;
1414     }
1415
1416     if ((supported_flags & D3D11_FORMAT_SUPPORT_RENDER_TARGET) ==
1417         D3D11_FORMAT_SUPPORT_RENDER_TARGET) {
1418       bind_flags |= D3D11_BIND_RENDER_TARGET;
1419     }
1420   }
1421
1422   copy = gst_d3d11_allocator_alloc_internal (alloc, device, &dst_desc, nullptr);
1423   if (!copy) {
1424     gst_memory_unmap (mem, &info);
1425
1426     GST_WARNING_OBJECT (alloc,
1427         "Failed to allocate new d3d11 map memory, try fallback copy");
1428
1429     return priv->fallback_copy (mem, offset, size);
1430   }
1431
1432   copy_dmem = GST_D3D11_MEMORY_CAST (copy);
1433   device_context->CopySubresourceRegion (copy_dmem->priv->texture, 0, 0, 0, 0,
1434       dmem->priv->texture, dmem->priv->subresource_index, NULL);
1435   copy->maxsize = copy->size = mem->maxsize;
1436   gst_memory_unmap (mem, &info);
1437
1438   /* newly allocated memory holds valid image data. We need download this
1439    * pixel data into staging memory for CPU access */
1440   GST_MINI_OBJECT_FLAG_SET (mem, GST_D3D11_MEMORY_TRANSFER_NEED_DOWNLOAD);
1441
1442   return copy;
1443 }
1444
1445 static void
1446 gst_d3d11_allocator_init (GstD3D11Allocator * allocator)
1447 {
1448   GstAllocator *alloc = GST_ALLOCATOR_CAST (allocator);
1449   GstD3D11AllocatorPrivate *priv;
1450
1451   priv = allocator->priv = (GstD3D11AllocatorPrivate *)
1452       gst_d3d11_allocator_get_instance_private (allocator);
1453
1454   alloc->mem_type = GST_D3D11_MEMORY_NAME;
1455   alloc->mem_map_full = gst_d3d11_memory_map_full;
1456   alloc->mem_unmap_full = gst_d3d11_memory_unmap_full;
1457   alloc->mem_share = gst_d3d11_memory_share;
1458
1459   /* Store pointer to default mem_copy method for fallback copy */
1460   priv->fallback_copy = alloc->mem_copy;
1461   alloc->mem_copy = gst_d3d11_memory_copy;
1462
1463   GST_OBJECT_FLAG_SET (alloc, GST_ALLOCATOR_FLAG_CUSTOM_ALLOC);
1464 }
1465
1466 static GstMemory *
1467 gst_d3d11_allocator_dummy_alloc (GstAllocator * allocator, gsize size,
1468     GstAllocationParams * params)
1469 {
1470   g_return_val_if_reached (NULL);
1471 }
1472
1473 static void
1474 gst_d3d11_allocator_free (GstAllocator * allocator, GstMemory * mem)
1475 {
1476   GstD3D11Memory *dmem = GST_D3D11_MEMORY_CAST (mem);
1477   GstD3D11MemoryPrivate *dmem_priv = dmem->priv;
1478   gint i;
1479
1480   GST_LOG_OBJECT (allocator, "Free memory %p", mem);
1481
1482   for (i = 0; i < GST_VIDEO_MAX_PLANES; i++) {
1483     GST_D3D11_CLEAR_COM (dmem_priv->render_target_view[i]);
1484     GST_D3D11_CLEAR_COM (dmem_priv->shader_resource_view[i]);
1485   }
1486
1487   GST_D3D11_CLEAR_COM (dmem_priv->decoder_output_view);
1488   GST_D3D11_CLEAR_COM (dmem_priv->processor_input_view);
1489   GST_D3D11_CLEAR_COM (dmem_priv->processor_output_view);
1490   GST_D3D11_CLEAR_COM (dmem_priv->texture);
1491   GST_D3D11_CLEAR_COM (dmem_priv->staging);
1492   GST_D3D11_CLEAR_COM (dmem_priv->buffer);
1493
1494   GST_D3D11_CLEAR_COM (dmem_priv->decoder_handle);
1495
1496   gst_clear_object (&dmem->device);
1497   g_mutex_clear (&dmem_priv->lock);
1498
1499   if (dmem_priv->notify)
1500     dmem_priv->notify (dmem_priv->user_data);
1501
1502   g_free (dmem->priv);
1503   g_free (dmem);
1504 }
1505
1506 static GstMemory *
1507 gst_d3d11_allocator_alloc_wrapped_internal (GstD3D11Allocator * self,
1508     GstD3D11Device * device, const D3D11_TEXTURE2D_DESC * desc,
1509     ID3D11Texture2D * texture)
1510 {
1511   GstD3D11Memory *mem;
1512
1513   mem = g_new0 (GstD3D11Memory, 1);
1514   mem->priv = g_new0 (GstD3D11MemoryPrivate, 1);
1515
1516   gst_memory_init (GST_MEMORY_CAST (mem),
1517       (GstMemoryFlags) 0, GST_ALLOCATOR_CAST (self), NULL, 0, 0, 0, 0);
1518   g_mutex_init (&mem->priv->lock);
1519   mem->priv->texture = texture;
1520   mem->priv->desc = *desc;
1521   mem->priv->native_type = GST_D3D11_MEMORY_NATIVE_TYPE_TEXTURE_2D;
1522   mem->device = (GstD3D11Device *) gst_object_ref (device);
1523
1524   return GST_MEMORY_CAST (mem);
1525 }
1526
1527 typedef void (*GstD3D11ClearRTVFunc) (ID3D11DeviceContext * context_handle,
1528     ID3D11RenderTargetView * rtv);
1529
1530 static void
1531 clear_rtv_chroma (ID3D11DeviceContext * context_handle,
1532     ID3D11RenderTargetView * rtv)
1533 {
1534   const FLOAT clear_color[4] = { 0.5f, 0.5f, 0.5f, 1.0f };
1535
1536   context_handle->ClearRenderTargetView (rtv, clear_color);
1537 }
1538
1539 static void
1540 clear_rtv_vuya (ID3D11DeviceContext * context_handle,
1541     ID3D11RenderTargetView * rtv)
1542 {
1543   const FLOAT clear_color[4] = { 0.5f, 0.5f, 0.0f, 1.0f };
1544
1545   context_handle->ClearRenderTargetView (rtv, clear_color);
1546 }
1547
1548 static GstMemory *
1549 gst_d3d11_allocator_alloc_internal (GstD3D11Allocator * self,
1550     GstD3D11Device * device, const D3D11_TEXTURE2D_DESC * desc,
1551     ID3D11Texture2D * texture)
1552 {
1553   ID3D11Device *device_handle;
1554   ID3D11DeviceContext *context_handle;
1555   HRESULT hr;
1556   GstMemory *mem;
1557   GstD3D11Memory *dmem;
1558   ID3D11RenderTargetView *rtv = nullptr;
1559   GstD3D11ClearRTVFunc clear_func = nullptr;
1560
1561   device_handle = gst_d3d11_device_get_device_handle (device);
1562
1563   if (!texture) {
1564     hr = device_handle->CreateTexture2D (desc, nullptr, &texture);
1565     if (!gst_d3d11_result (hr, device)) {
1566       GST_ERROR_OBJECT (self, "Couldn't create texture");
1567       return nullptr;
1568     }
1569   }
1570
1571   mem =
1572       gst_d3d11_allocator_alloc_wrapped_internal (self, device, desc, texture);
1573   if (!mem)
1574     return nullptr;
1575
1576   /* Clear with YUV black if needed and possible
1577    * TODO: do this using UAV if RTV is not allowed (e.g., packed YUV formats) */
1578   if ((desc->BindFlags & D3D11_BIND_RENDER_TARGET) == 0)
1579     return mem;
1580
1581   dmem = GST_D3D11_MEMORY_CAST (mem);
1582   switch (desc->Format) {
1583     case DXGI_FORMAT_NV12:
1584     case DXGI_FORMAT_P010:
1585     case DXGI_FORMAT_P016:
1586       /* Y component will be zero already */
1587       rtv = gst_d3d11_memory_get_render_target_view (dmem, 1);
1588       clear_func = (GstD3D11ClearRTVFunc) clear_rtv_chroma;
1589       break;
1590     case DXGI_FORMAT_AYUV:
1591       rtv = gst_d3d11_memory_get_render_target_view (dmem, 0);
1592       clear_func = (GstD3D11ClearRTVFunc) clear_rtv_vuya;
1593       break;
1594     default:
1595       return mem;
1596   }
1597
1598   if (!rtv)
1599     return mem;
1600
1601   context_handle = gst_d3d11_device_get_device_context_handle (device);
1602   GstD3D11DeviceLockGuard lk (device);
1603   clear_func (context_handle, rtv);
1604
1605   return mem;
1606 }
1607
1608 /**
1609  * gst_d3d11_allocator_alloc:
1610  * @allocator: a #GstD3D11Allocator
1611  * @device: a #GstD3D11Device
1612  * @desc: a D3D11_TEXTURE2D_DESC struct
1613  *
1614  * Returns: a newly allocated #GstD3D11Memory with given parameters.
1615  *
1616  * Since: 1.22
1617  */
1618 GstMemory *
1619 gst_d3d11_allocator_alloc (GstD3D11Allocator * allocator,
1620     GstD3D11Device * device, const D3D11_TEXTURE2D_DESC * desc)
1621 {
1622   GstMemory *mem;
1623
1624   g_return_val_if_fail (GST_IS_D3D11_ALLOCATOR (allocator), NULL);
1625   g_return_val_if_fail (GST_IS_D3D11_DEVICE (device), NULL);
1626   g_return_val_if_fail (desc != NULL, NULL);
1627
1628   mem = gst_d3d11_allocator_alloc_internal (allocator, device, desc, nullptr);
1629   if (!mem)
1630     return NULL;
1631
1632   if (!gst_d3d11_memory_update_size (mem)) {
1633     GST_ERROR_OBJECT (allocator, "Failed to calculate size");
1634     gst_memory_unref (mem);
1635     return NULL;
1636   }
1637
1638   return mem;
1639 }
1640
1641 /**
1642  * gst_d3d11_allocator_alloc_buffer:
1643  * @allocator: a #GstD3D11Allocator
1644  * @device: a #GstD3D11Device
1645  * @desc: a D3D11_BUFFER_DESC struct
1646  *
1647  * Returns: a newly allocated #GstD3D11Memory with given parameters.
1648  *
1649  * Since: 1.22
1650  */
1651 GstMemory *
1652 gst_d3d11_allocator_alloc_buffer (GstD3D11Allocator * allocator,
1653     GstD3D11Device * device, const D3D11_BUFFER_DESC * desc)
1654 {
1655   GstD3D11Memory *mem;
1656   ID3D11Buffer *buffer;
1657   ID3D11Device *device_handle;
1658   HRESULT hr;
1659
1660   g_return_val_if_fail (GST_IS_D3D11_ALLOCATOR (allocator), nullptr);
1661   g_return_val_if_fail (GST_IS_D3D11_DEVICE (device), nullptr);
1662   g_return_val_if_fail (desc != nullptr, nullptr);
1663
1664   if (desc->Usage != D3D11_USAGE_STAGING) {
1665     GST_FIXME_OBJECT (allocator, "Non staging buffer is not supported");
1666     return nullptr;
1667   }
1668
1669   device_handle = gst_d3d11_device_get_device_handle (device);
1670
1671   hr = device_handle->CreateBuffer (desc, nullptr, &buffer);
1672   if (!gst_d3d11_result (hr, device)) {
1673     GST_ERROR_OBJECT (allocator, "Couldn't create buffer");
1674     return nullptr;
1675   }
1676
1677   mem = g_new0 (GstD3D11Memory, 1);
1678   mem->priv = g_new0 (GstD3D11MemoryPrivate, 1);
1679
1680   gst_memory_init (GST_MEMORY_CAST (mem),
1681       (GstMemoryFlags) 0, GST_ALLOCATOR_CAST (allocator), nullptr, 0, 0, 0, 0);
1682   g_mutex_init (&mem->priv->lock);
1683   mem->priv->buffer = buffer;
1684   mem->priv->buffer_desc = *desc;
1685   mem->priv->native_type = GST_D3D11_MEMORY_NATIVE_TYPE_BUFFER;
1686   mem->device = (GstD3D11Device *) gst_object_ref (device);
1687
1688   GST_MEMORY_CAST (mem)->maxsize = GST_MEMORY_CAST (mem)->size =
1689       desc->ByteWidth;
1690
1691   return GST_MEMORY_CAST (mem);
1692 }
1693
1694 /**
1695  * gst_d3d11_allocator_alloc_wrapped:
1696  * @allocator: a #GstD3D11Allocator
1697  * @device: a #GstD3D11Device
1698  * @texture: a ID3D11Texture2D
1699  * @size: CPU accessible memory size
1700  * @user_data: (allow-none): user data
1701  * @notify: (allow-none): called with @user_data when the memory is freed
1702  *
1703  * Allocates memory object with @texture. The refcount of @texture
1704  * will be increased by one.
1705  *
1706  * Caller should set valid CPU acessible memory value to @size
1707  * (which is typically calculated by using staging texture and Map/Unmap)
1708  * or zero is allowed. In that case, allocator will create a temporary staging
1709  * texture to get the size and the temporary staging texture will be released.
1710  *
1711  * Caller must not be confused that @size is CPU accessible size, not raw
1712  * texture size.
1713  *
1714  * Returns: a newly allocated #GstD3D11Memory with given @texture
1715  * if successful, or %NULL if @texture is not a valid handle or configuration
1716  * is not supported.
1717  *
1718  * Since: 1.22
1719  */
1720 GstMemory *
1721 gst_d3d11_allocator_alloc_wrapped (GstD3D11Allocator * allocator,
1722     GstD3D11Device * device, ID3D11Texture2D * texture, gsize size,
1723     gpointer user_data, GDestroyNotify notify)
1724 {
1725   GstMemory *mem;
1726   GstD3D11Memory *dmem;
1727   D3D11_TEXTURE2D_DESC desc = { 0, };
1728   ID3D11Texture2D *tex = nullptr;
1729   HRESULT hr;
1730
1731   g_return_val_if_fail (GST_IS_D3D11_ALLOCATOR (allocator), nullptr);
1732   g_return_val_if_fail (GST_IS_D3D11_DEVICE (device), nullptr);
1733   g_return_val_if_fail (texture != nullptr, nullptr);
1734
1735   hr = texture->QueryInterface (IID_PPV_ARGS (&tex));
1736   if (FAILED (hr)) {
1737     GST_WARNING_OBJECT (allocator, "Not a valid texture handle");
1738     return nullptr;
1739   }
1740
1741   tex->GetDesc (&desc);
1742   mem = gst_d3d11_allocator_alloc_internal (allocator, device, &desc, tex);
1743
1744   if (!mem)
1745     return nullptr;
1746
1747   if (size == 0) {
1748     if (!gst_d3d11_memory_update_size (mem)) {
1749       GST_ERROR_OBJECT (allocator, "Failed to calculate size");
1750       gst_memory_unref (mem);
1751       return nullptr;
1752     }
1753   } else {
1754     mem->maxsize = mem->size = size;
1755   }
1756
1757   dmem = GST_D3D11_MEMORY_CAST (mem);
1758
1759   dmem->priv->user_data = user_data;
1760   dmem->priv->notify = notify;
1761
1762   return mem;
1763 }
1764
1765 /**
1766  * gst_d3d11_allocator_set_active:
1767  * @allocator: a #GstD3D11Allocator
1768  * @active: the new active state
1769  *
1770  * Controls the active state of @allocator. Default #GstD3D11Allocator is
1771  * stateless and therefore active state is ignored, but subclass implementation
1772  * (e.g., #GstD3D11PoolAllocator) will require explicit active state control
1773  * for its internal resource management.
1774  *
1775  * This method is conceptually identical to gst_buffer_pool_set_active method.
1776  *
1777  * Returns: %TRUE if active state of @allocator was successfully updated.
1778  *
1779  * Since: 1.22
1780  */
1781 gboolean
1782 gst_d3d11_allocator_set_active (GstD3D11Allocator * allocator, gboolean active)
1783 {
1784   GstD3D11AllocatorClass *klass;
1785
1786   g_return_val_if_fail (GST_IS_D3D11_ALLOCATOR (allocator), FALSE);
1787
1788   klass = GST_D3D11_ALLOCATOR_GET_CLASS (allocator);
1789   if (klass->set_actvie)
1790     return klass->set_actvie (allocator, active);
1791
1792   return TRUE;
1793 }
1794
1795 /* GstD3D11PoolAllocator */
1796 #define GST_D3D11_POOL_ALLOCATOR_LOCK(alloc)   (g_rec_mutex_lock(&alloc->priv->lock))
1797 #define GST_D3D11_POOL_ALLOCATOR_UNLOCK(alloc) (g_rec_mutex_unlock(&alloc->priv->lock))
1798 #define GST_D3D11_POOL_ALLOCATOR_IS_FLUSHING(alloc)  (g_atomic_int_get (&alloc->priv->flushing))
1799
1800 struct _GstD3D11PoolAllocatorPrivate
1801 {
1802   /* parent texture when array typed memory is used */
1803   ID3D11Texture2D *texture;
1804   D3D11_TEXTURE2D_DESC desc;
1805
1806   /* All below member variables are analogous to that of GstBufferPool */
1807   GstAtomicQueue *queue;
1808   GstPoll *poll;
1809
1810   /* This lock will protect all below variables apart from atomic ones
1811    * (identical to GstBufferPool::priv::rec_lock) */
1812   GRecMutex lock;
1813   gboolean started;
1814   gboolean active;
1815
1816   /* atomic */
1817   gint outstanding;
1818   guint max_mems;
1819   guint cur_mems;
1820   gboolean flushing;
1821
1822   /* Calculated memory size, based on Direct3D11 staging texture map.
1823    * Note that, we cannot know the actually staging texture memory size prior
1824    * to map the staging texture because driver will likely require padding */
1825   gsize mem_size;
1826 };
1827
1828 static void gst_d3d11_pool_allocator_dispose (GObject * object);
1829 static void gst_d3d11_pool_allocator_finalize (GObject * object);
1830
1831 static gboolean
1832 gst_d3d11_pool_allocator_set_active (GstD3D11Allocator * allocator,
1833     gboolean active);
1834
1835 static gboolean gst_d3d11_pool_allocator_start (GstD3D11PoolAllocator * self);
1836 static gboolean gst_d3d11_pool_allocator_stop (GstD3D11PoolAllocator * self);
1837 static gboolean gst_d3d11_memory_release (GstMiniObject * mini_object);
1838
1839 #define gst_d3d11_pool_allocator_parent_class pool_alloc_parent_class
1840 G_DEFINE_TYPE_WITH_PRIVATE (GstD3D11PoolAllocator,
1841     gst_d3d11_pool_allocator, GST_TYPE_D3D11_ALLOCATOR);
1842
1843 static void
1844 gst_d3d11_pool_allocator_class_init (GstD3D11PoolAllocatorClass * klass)
1845 {
1846   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1847   GstD3D11AllocatorClass *d3d11alloc_class = GST_D3D11_ALLOCATOR_CLASS (klass);
1848
1849   gobject_class->dispose = gst_d3d11_pool_allocator_dispose;
1850   gobject_class->finalize = gst_d3d11_pool_allocator_finalize;
1851
1852   d3d11alloc_class->set_actvie = gst_d3d11_pool_allocator_set_active;
1853 }
1854
1855 static void
1856 gst_d3d11_pool_allocator_init (GstD3D11PoolAllocator * allocator)
1857 {
1858   GstD3D11PoolAllocatorPrivate *priv;
1859
1860   priv = allocator->priv = (GstD3D11PoolAllocatorPrivate *)
1861       gst_d3d11_pool_allocator_get_instance_private (allocator);
1862   g_rec_mutex_init (&priv->lock);
1863
1864   priv->poll = gst_poll_new_timer ();
1865   priv->queue = gst_atomic_queue_new (16);
1866   priv->flushing = 1;
1867   priv->active = FALSE;
1868   priv->started = FALSE;
1869
1870   /* 1 control write for flushing - the flush token */
1871   gst_poll_write_control (priv->poll);
1872   /* 1 control write for marking that we are not waiting for poll - the wait token */
1873   gst_poll_write_control (priv->poll);
1874 }
1875
1876 static void
1877 gst_d3d11_pool_allocator_dispose (GObject * object)
1878 {
1879   GstD3D11PoolAllocator *self = GST_D3D11_POOL_ALLOCATOR (object);
1880
1881   gst_clear_object (&self->device);
1882
1883   G_OBJECT_CLASS (pool_alloc_parent_class)->dispose (object);
1884 }
1885
1886 static void
1887 gst_d3d11_pool_allocator_finalize (GObject * object)
1888 {
1889   GstD3D11PoolAllocator *self = GST_D3D11_POOL_ALLOCATOR (object);
1890   GstD3D11PoolAllocatorPrivate *priv = self->priv;
1891
1892   GST_DEBUG_OBJECT (self, "Finalize");
1893
1894   gst_d3d11_pool_allocator_stop (self);
1895   gst_atomic_queue_unref (priv->queue);
1896   gst_poll_free (priv->poll);
1897   g_rec_mutex_clear (&priv->lock);
1898
1899   GST_D3D11_CLEAR_COM (priv->texture);
1900
1901   G_OBJECT_CLASS (pool_alloc_parent_class)->finalize (object);
1902 }
1903
1904 static gboolean
1905 gst_d3d11_pool_allocator_start (GstD3D11PoolAllocator * self)
1906 {
1907   GstD3D11PoolAllocatorPrivate *priv = self->priv;
1908   ID3D11Device *device_handle;
1909   HRESULT hr;
1910   guint i;
1911
1912   if (priv->started)
1913     return TRUE;
1914
1915   /* Nothing to do */
1916   if (priv->desc.ArraySize == 1) {
1917     priv->started = TRUE;
1918     return TRUE;
1919   }
1920
1921   device_handle = gst_d3d11_device_get_device_handle (self->device);
1922
1923   if (!priv->texture) {
1924     hr = device_handle->CreateTexture2D (&priv->desc, NULL, &priv->texture);
1925     if (!gst_d3d11_result (hr, self->device)) {
1926       GST_ERROR_OBJECT (self, "Failed to allocate texture");
1927       return FALSE;
1928     }
1929   }
1930
1931   /* Pre-allocate memory objects */
1932   for (i = 0; i < priv->desc.ArraySize; i++) {
1933     GstMemory *mem;
1934
1935     priv->texture->AddRef ();
1936     mem =
1937         gst_d3d11_allocator_alloc_wrapped_internal (GST_D3D11_ALLOCATOR_CAST
1938         (_d3d11_memory_allocator), self->device, &priv->desc, priv->texture);
1939
1940     if (i == 0) {
1941       if (!gst_d3d11_memory_update_size (mem)) {
1942         GST_ERROR_OBJECT (self, "Failed to calculate memory size");
1943         gst_memory_unref (mem);
1944         return FALSE;
1945       }
1946
1947       priv->mem_size = mem->size;
1948     } else {
1949       mem->size = mem->maxsize = priv->mem_size;
1950     }
1951
1952     GST_D3D11_MEMORY_CAST (mem)->priv->subresource_index = i;
1953
1954     g_atomic_int_add (&priv->cur_mems, 1);
1955     gst_atomic_queue_push (priv->queue, mem);
1956     gst_poll_write_control (priv->poll);
1957   }
1958
1959   priv->started = TRUE;
1960
1961   return TRUE;
1962 }
1963
1964 static void
1965 gst_d3d11_pool_allocator_do_set_flushing (GstD3D11PoolAllocator * self,
1966     gboolean flushing)
1967 {
1968   GstD3D11PoolAllocatorPrivate *priv = self->priv;
1969
1970   if (GST_D3D11_POOL_ALLOCATOR_IS_FLUSHING (self) == flushing)
1971     return;
1972
1973   if (flushing) {
1974     g_atomic_int_set (&priv->flushing, 1);
1975     /* Write the flush token to wake up any waiters */
1976     gst_poll_write_control (priv->poll);
1977   } else {
1978     while (!gst_poll_read_control (priv->poll)) {
1979       if (errno == EWOULDBLOCK) {
1980         /* This should not really happen unless flushing and unflushing
1981          * happens on different threads. Let's wait a bit to get back flush
1982          * token from the thread that was setting it to flushing */
1983         g_thread_yield ();
1984         continue;
1985       } else {
1986         /* Critical error but GstPoll already complained */
1987         break;
1988       }
1989     }
1990
1991     g_atomic_int_set (&priv->flushing, 0);
1992   }
1993 }
1994
1995 static gboolean
1996 gst_d3d11_pool_allocator_set_active (GstD3D11Allocator * allocator,
1997     gboolean active)
1998 {
1999   GstD3D11PoolAllocator *self = GST_D3D11_POOL_ALLOCATOR (allocator);
2000   GstD3D11PoolAllocatorPrivate *priv = self->priv;
2001
2002   GST_LOG_OBJECT (self, "active %d", active);
2003
2004   GST_D3D11_POOL_ALLOCATOR_LOCK (self);
2005   /* just return if we are already in the right state */
2006   if (priv->active == active)
2007     goto was_ok;
2008
2009   if (active) {
2010     if (!gst_d3d11_pool_allocator_start (self))
2011       goto start_failed;
2012
2013     /* flush_stop may release memory objects, setting to active to avoid running
2014      * do_stop while activating the pool */
2015     priv->active = TRUE;
2016
2017     gst_d3d11_pool_allocator_do_set_flushing (self, FALSE);
2018   } else {
2019     gint outstanding;
2020
2021     /* set to flushing first */
2022     gst_d3d11_pool_allocator_do_set_flushing (self, TRUE);
2023
2024     /* when all memory objects are in the pool, free them. Else they will be
2025      * freed when they are released */
2026     outstanding = g_atomic_int_get (&priv->outstanding);
2027     GST_LOG_OBJECT (self, "outstanding memories %d, (in queue %d)",
2028         outstanding, gst_atomic_queue_length (priv->queue));
2029     if (outstanding == 0) {
2030       if (!gst_d3d11_pool_allocator_stop (self))
2031         goto stop_failed;
2032     }
2033
2034     priv->active = FALSE;
2035   }
2036
2037   GST_D3D11_POOL_ALLOCATOR_UNLOCK (self);
2038
2039   return TRUE;
2040
2041 was_ok:
2042   {
2043     GST_DEBUG_OBJECT (self, "allocator was in the right state");
2044     GST_D3D11_POOL_ALLOCATOR_UNLOCK (self);
2045     return TRUE;
2046   }
2047 start_failed:
2048   {
2049     GST_ERROR_OBJECT (self, "start failed");
2050     GST_D3D11_POOL_ALLOCATOR_UNLOCK (self);
2051     return FALSE;
2052   }
2053 stop_failed:
2054   {
2055     GST_ERROR_OBJECT (self, "stop failed");
2056     GST_D3D11_POOL_ALLOCATOR_UNLOCK (self);
2057     return FALSE;
2058   }
2059 }
2060
2061 static void
2062 gst_d3d11_pool_allocator_free_memory (GstD3D11PoolAllocator * self,
2063     GstMemory * mem)
2064 {
2065   GstD3D11PoolAllocatorPrivate *priv = self->priv;
2066
2067   g_atomic_int_add (&priv->cur_mems, -1);
2068   GST_LOG_OBJECT (self, "freeing memory %p (%u left)", mem, priv->cur_mems);
2069
2070   GST_MINI_OBJECT_CAST (mem)->dispose = NULL;
2071   gst_memory_unref (mem);
2072 }
2073
2074 /* must be called with the lock */
2075 static gboolean
2076 gst_d3d11_pool_allocator_clear_queue (GstD3D11PoolAllocator * self)
2077 {
2078   GstD3D11PoolAllocatorPrivate *priv = self->priv;
2079   GstMemory *memory;
2080
2081   GST_LOG_OBJECT (self, "Clearing queue");
2082
2083   /* clear the pool */
2084   while ((memory = (GstMemory *) gst_atomic_queue_pop (priv->queue))) {
2085     while (!gst_poll_read_control (priv->poll)) {
2086       if (errno == EWOULDBLOCK) {
2087         /* We put the memory into the queue but did not finish writing control
2088          * yet, let's wait a bit and retry */
2089         g_thread_yield ();
2090         continue;
2091       } else {
2092         /* Critical error but GstPoll already complained */
2093         break;
2094       }
2095     }
2096     gst_d3d11_pool_allocator_free_memory (self, memory);
2097   }
2098
2099   GST_LOG_OBJECT (self, "Clear done");
2100
2101   return priv->cur_mems == 0;
2102 }
2103
2104 /* must be called with the lock */
2105 static gboolean
2106 gst_d3d11_pool_allocator_stop (GstD3D11PoolAllocator * self)
2107 {
2108   GstD3D11PoolAllocatorPrivate *priv = self->priv;
2109
2110   GST_DEBUG_OBJECT (self, "Stop");
2111
2112   if (priv->started) {
2113     if (!gst_d3d11_pool_allocator_clear_queue (self))
2114       return FALSE;
2115
2116     priv->started = FALSE;
2117   } else {
2118     GST_DEBUG_OBJECT (self, "Wasn't started");
2119   }
2120
2121   return TRUE;
2122 }
2123
2124 static inline void
2125 dec_outstanding (GstD3D11PoolAllocator * self)
2126 {
2127   if (g_atomic_int_dec_and_test (&self->priv->outstanding)) {
2128     /* all memory objects are returned to the pool, see if we need to free them */
2129     if (GST_D3D11_POOL_ALLOCATOR_IS_FLUSHING (self)) {
2130       /* take the lock so that set_active is not run concurrently */
2131       GST_D3D11_POOL_ALLOCATOR_LOCK (self);
2132       /* now that we have the lock, check if we have been de-activated with
2133        * outstanding buffers */
2134       if (!self->priv->active)
2135         gst_d3d11_pool_allocator_stop (self);
2136
2137       GST_D3D11_POOL_ALLOCATOR_UNLOCK (self);
2138     }
2139   }
2140 }
2141
2142 static void
2143 gst_d3d11_pool_allocator_release_memory (GstD3D11PoolAllocator * self,
2144     GstMemory * mem)
2145 {
2146   GST_LOG_OBJECT (self, "Released memory %p", mem);
2147
2148   GST_MINI_OBJECT_CAST (mem)->dispose = NULL;
2149   mem->allocator = (GstAllocator *) gst_object_ref (_d3d11_memory_allocator);
2150   gst_object_unref (self);
2151
2152   /* keep it around in our queue */
2153   gst_atomic_queue_push (self->priv->queue, mem);
2154   gst_poll_write_control (self->priv->poll);
2155   dec_outstanding (self);
2156 }
2157
2158 static gboolean
2159 gst_d3d11_memory_release (GstMiniObject * mini_object)
2160 {
2161   GstMemory *mem = GST_MEMORY_CAST (mini_object);
2162   GstD3D11PoolAllocator *alloc;
2163
2164   g_assert (mem->allocator != NULL);
2165
2166   if (!GST_IS_D3D11_POOL_ALLOCATOR (mem->allocator)) {
2167     GST_LOG_OBJECT (mem->allocator, "Not our memory, free");
2168     return TRUE;
2169   }
2170
2171   alloc = GST_D3D11_POOL_ALLOCATOR (mem->allocator);
2172   /* if flushing, free this memory */
2173   if (GST_D3D11_POOL_ALLOCATOR_IS_FLUSHING (alloc)) {
2174     GST_LOG_OBJECT (alloc, "allocator is flushing, free %p", mem);
2175     return TRUE;
2176   }
2177
2178   /* return the memory to the allocator */
2179   gst_memory_ref (mem);
2180   gst_d3d11_pool_allocator_release_memory (alloc, mem);
2181
2182   return FALSE;
2183 }
2184
2185 static GstFlowReturn
2186 gst_d3d11_pool_allocator_alloc (GstD3D11PoolAllocator * self, GstMemory ** mem)
2187 {
2188   GstD3D11PoolAllocatorPrivate *priv = self->priv;
2189   GstMemory *new_mem;
2190
2191   /* we allcates texture array during start */
2192   if (priv->desc.ArraySize > 1)
2193     return GST_FLOW_EOS;
2194
2195   /* increment the allocation counter */
2196   g_atomic_int_add (&priv->cur_mems, 1);
2197   new_mem =
2198       gst_d3d11_allocator_alloc_internal (GST_D3D11_ALLOCATOR_CAST
2199       (_d3d11_memory_allocator), self->device, &priv->desc, nullptr);
2200   if (!new_mem) {
2201     GST_ERROR_OBJECT (self, "Failed to allocate new memory");
2202     g_atomic_int_add (&priv->cur_mems, -1);
2203     return GST_FLOW_ERROR;
2204   }
2205
2206   if (!priv->mem_size) {
2207     if (!gst_d3d11_memory_update_size (new_mem)) {
2208       GST_ERROR_OBJECT (self, "Failed to calculate size");
2209       gst_memory_unref (new_mem);
2210       g_atomic_int_add (&priv->cur_mems, -1);
2211
2212       return GST_FLOW_ERROR;
2213     }
2214
2215     priv->mem_size = new_mem->size;
2216   }
2217
2218   new_mem->size = new_mem->maxsize = priv->mem_size;
2219
2220   *mem = new_mem;
2221
2222   return GST_FLOW_OK;
2223 }
2224
2225 static GstFlowReturn
2226 gst_d3d11_pool_allocator_acquire_memory_internal (GstD3D11PoolAllocator * self,
2227     GstMemory ** memory)
2228 {
2229   GstFlowReturn result;
2230   GstD3D11PoolAllocatorPrivate *priv = self->priv;
2231
2232   while (TRUE) {
2233     if (G_UNLIKELY (GST_D3D11_POOL_ALLOCATOR_IS_FLUSHING (self)))
2234       goto flushing;
2235
2236     /* try to get a memory from the queue */
2237     *memory = (GstMemory *) gst_atomic_queue_pop (priv->queue);
2238     if (G_LIKELY (*memory)) {
2239       while (!gst_poll_read_control (priv->poll)) {
2240         if (errno == EWOULDBLOCK) {
2241           /* We put the memory into the queue but did not finish writing control
2242            * yet, let's wait a bit and retry */
2243           g_thread_yield ();
2244           continue;
2245         } else {
2246           /* Critical error but GstPoll already complained */
2247           break;
2248         }
2249       }
2250       result = GST_FLOW_OK;
2251       GST_LOG_OBJECT (self, "acquired memory %p", *memory);
2252       break;
2253     }
2254
2255     /* no memory, try to allocate some more */
2256     GST_LOG_OBJECT (self, "no memory, trying to allocate");
2257     result = gst_d3d11_pool_allocator_alloc (self, memory);
2258     if (G_LIKELY (result == GST_FLOW_OK))
2259       /* we have a memory, return it */
2260       break;
2261
2262     if (G_UNLIKELY (result != GST_FLOW_EOS))
2263       /* something went wrong, return error */
2264       break;
2265
2266     /* now we release the control socket, we wait for a memory release or
2267      * flushing */
2268     if (!gst_poll_read_control (priv->poll)) {
2269       if (errno == EWOULDBLOCK) {
2270         /* This means that we have two threads trying to allocate memory
2271          * already, and the other one already got the wait token. This
2272          * means that we only have to wait for the poll now and not write the
2273          * token afterwards: we will be woken up once the other thread is
2274          * woken up and that one will write the wait token it removed */
2275         GST_LOG_OBJECT (self, "waiting for free memory or flushing");
2276         gst_poll_wait (priv->poll, GST_CLOCK_TIME_NONE);
2277       } else {
2278         /* This is a critical error, GstPoll already gave a warning */
2279         result = GST_FLOW_ERROR;
2280         break;
2281       }
2282     } else {
2283       /* We're the first thread waiting, we got the wait token and have to
2284        * write it again later
2285        * OR
2286        * We're a second thread and just consumed the flush token and block all
2287        * other threads, in which case we must not wait and give it back
2288        * immediately */
2289       if (!GST_D3D11_POOL_ALLOCATOR_IS_FLUSHING (self)) {
2290         GST_LOG_OBJECT (self, "waiting for free memory or flushing");
2291         gst_poll_wait (priv->poll, GST_CLOCK_TIME_NONE);
2292       }
2293       gst_poll_write_control (priv->poll);
2294     }
2295   }
2296
2297   return result;
2298
2299   /* ERRORS */
2300 flushing:
2301   {
2302     GST_DEBUG_OBJECT (self, "we are flushing");
2303     return GST_FLOW_FLUSHING;
2304   }
2305 }
2306
2307 /**
2308  * gst_d3d11_pool_allocator_new:
2309  * @device: a #GstD3D11Device
2310  * @desc: a D3D11_TEXTURE2D_DESC for texture allocation
2311  *
2312  * Creates a new #GstD3D11PoolAllocator instance.
2313  *
2314  * Returns: (transfer full): a new #GstD3D11PoolAllocator instance
2315  *
2316  * Since: 1.22
2317  */
2318 GstD3D11PoolAllocator *
2319 gst_d3d11_pool_allocator_new (GstD3D11Device * device,
2320     const D3D11_TEXTURE2D_DESC * desc)
2321 {
2322   GstD3D11PoolAllocator *self;
2323
2324   g_return_val_if_fail (GST_IS_D3D11_DEVICE (device), NULL);
2325   g_return_val_if_fail (desc != NULL, NULL);
2326
2327   gst_d3d11_memory_init_once ();
2328
2329   self = (GstD3D11PoolAllocator *)
2330       g_object_new (GST_TYPE_D3D11_POOL_ALLOCATOR, NULL);
2331   gst_object_ref_sink (self);
2332
2333   self->device = (GstD3D11Device *) gst_object_ref (device);
2334   self->priv->desc = *desc;
2335
2336   return self;
2337 }
2338
2339 /**
2340  * gst_d3d11_pool_allocator_acquire_memory:
2341  * @allocator: a #GstD3D11PoolAllocator
2342  * @memory: (out): a #GstMemory
2343  *
2344  * Acquires a #GstMemory from @allocator. @memory should point to a memory
2345  * location that can hold a pointer to the new #GstMemory.
2346  *
2347  * Returns: a #GstFlowReturn such as %GST_FLOW_FLUSHING when the allocator is
2348  * inactive.
2349  */
2350 GstFlowReturn
2351 gst_d3d11_pool_allocator_acquire_memory (GstD3D11PoolAllocator * allocator,
2352     GstMemory ** memory)
2353 {
2354   GstD3D11PoolAllocatorPrivate *priv;
2355   GstFlowReturn result;
2356
2357   g_return_val_if_fail (GST_IS_D3D11_POOL_ALLOCATOR (allocator),
2358       GST_FLOW_ERROR);
2359   g_return_val_if_fail (memory != NULL, GST_FLOW_ERROR);
2360
2361   priv = allocator->priv;
2362
2363   /* assume we'll have one more outstanding buffer we need to do that so
2364    * that concurrent set_active doesn't clear the buffers */
2365   g_atomic_int_inc (&priv->outstanding);
2366   result = gst_d3d11_pool_allocator_acquire_memory_internal (allocator, memory);
2367
2368   if (result == GST_FLOW_OK) {
2369     GstMemory *mem = *memory;
2370     /* Replace default allocator with ours */
2371     gst_object_unref (mem->allocator);
2372     mem->allocator = (GstAllocator *) gst_object_ref (allocator);
2373     GST_MINI_OBJECT_CAST (mem)->dispose = gst_d3d11_memory_release;
2374   } else {
2375     dec_outstanding (allocator);
2376   }
2377
2378   return result;
2379 }
2380
2381 /**
2382  * gst_d3d11_pool_allocator_get_pool_size:
2383  * @allocator: a #GstD3D11PoolAllocator
2384  * @max_size: (out) (optional): the max size of pool
2385  * @outstanding_size: (out) (optional): the number of outstanding memory
2386  *
2387  * Returns: %TRUE if the size of memory pool is known
2388  *
2389  * Since: 1.22
2390  */
2391 gboolean
2392 gst_d3d11_pool_allocator_get_pool_size (GstD3D11PoolAllocator * allocator,
2393     guint * max_size, guint * outstanding_size)
2394 {
2395   GstD3D11PoolAllocatorPrivate *priv;
2396
2397   g_return_val_if_fail (GST_IS_D3D11_POOL_ALLOCATOR (allocator), FALSE);
2398
2399   priv = allocator->priv;
2400
2401   if (max_size) {
2402     if (priv->desc.ArraySize > 1) {
2403       *max_size = priv->desc.ArraySize;
2404     } else {
2405       /* For non-texture-array memory, we don't have any limit yet */
2406       *max_size = 0;
2407     }
2408   }
2409
2410   if (outstanding_size)
2411     *outstanding_size = g_atomic_int_get (&priv->outstanding);
2412
2413   return TRUE;
2414 }