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