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