diff mbox series

[FFmpeg-devel,09/42] avcodec/refstruct: Allow checking for exclusive ownership

Message ID AS8P250MB0744ECF7F9135CE0D308AD288FFAA@AS8P250MB0744.EURP250.PROD.OUTLOOK.COM
State New
Headers show
Series New API for reference counting and ThreadFrames | expand

Checks

Context Check Description
andriy/make_x86 success Make finished
andriy/make_fate_x86 success Make fate finished

Commit Message

Andreas Rheinhardt Sept. 19, 2023, 7:57 p.m. UTC
This is the analog of av_buffer_is_writable();
it will be used in the next commit.

Signed-off-by: Andreas Rheinhardt <andreas.rheinhardt@outlook.com>
---
 libavcodec/refstruct.c | 14 ++++++++++++++
 libavcodec/refstruct.h |  9 +++++++++
 2 files changed, 23 insertions(+)
diff mbox series

Patch

diff --git a/libavcodec/refstruct.c b/libavcodec/refstruct.c
index 917cf6b7ac..604938922a 100644
--- a/libavcodec/refstruct.c
+++ b/libavcodec/refstruct.c
@@ -48,6 +48,11 @@  static RefCount *get_refcount(void *obj)
     return (RefCount*)((char*)obj - REFCOUNT_OFFSET);
 }
 
+static const RefCount *cget_refcount(const void *data)
+{
+    return (const RefCount*)((const char*)data - REFCOUNT_OFFSET);
+}
+
 static void *get_userdata(void *buf)
 {
     return (char*)buf + REFCOUNT_OFFSET;
@@ -137,3 +142,12 @@  void ff_refstruct_replace(void *dstp, const void *src)
         memcpy(dstp, &dst, sizeof(dst));
     }
 }
+
+int ff_refstruct_exclusive(const void *data)
+{
+    const RefCount *ref = cget_refcount(data);
+    /* Casting const away here is safe, because it is a load.
+     * It is necessary because atomic_load_explicit() does not
+     * accept const atomics in C11 (see also N1807). */
+    return atomic_load_explicit((atomic_uintptr_t*)&ref->refcount, memory_order_acquire) == 1;
+}
diff --git a/libavcodec/refstruct.h b/libavcodec/refstruct.h
index 0086717c17..ee6936d77a 100644
--- a/libavcodec/refstruct.h
+++ b/libavcodec/refstruct.h
@@ -142,4 +142,13 @@  const void *ff_refstruct_ref_c(const void *obj);
  */
 void ff_refstruct_replace(void *dstp, const void *src);
 
+/**
+ * Check whether the reference count of an object managed
+ * via this API is 1.
+ *
+ * @param obj A pointer to an object managed via this API.
+ * @return 1 if the reference count of obj is 1; 0 otherwise.
+ */
+int ff_refstruct_exclusive(const void *obj);
+
 #endif /* AVCODEC_REFSTRUCT_H */