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