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