Heavily refactor the sitemap
[platform/upstream/gstreamer.git] / markdown / additional / design / meta.md
1 # GstMeta
2
3 This document describes the design for arbitrary per-buffer metadata.
4
5 Buffer metadata typically describes the low level properties of the
6 buffer content. These properties are commonly not negotiated with caps
7 but they are negotiated in the bufferpools.
8
9 Some examples of metadata:
10
11   - interlacing information
12
13   - video alignment, cropping, panning information
14
15   - extra container information such as granulepos, …
16
17   - extra global buffer properties
18
19 ## Requirements
20
21   - It must be fast
22
23       - allocation, free, low fragmentation
24
25       - access to the metadata fields, preferably not much slower than
26         directly accessing a C structure field
27
28   - It must be extensible. Elements should be able to add new arbitrary
29     metadata without requiring much effort. Also new metadata fields
30     should not break API or ABI.
31
32   - It plays nice with subbuffers. When a subbuffer is created, the
33     various buffer metadata should be copied/updated correctly.
34
35   - We should be able to negotiate metadata between elements
36
37 ## Use cases
38
39 - **Video planes**: Video data is sometimes allocated in non-contiguous planes
40 for the Y and the UV data. We need to be able to specify the data on a buffer
41 using multiple pointers in memory. We also need to be able to specify the
42 stride for these planes.
43
44 - **Extra buffer data**: Some elements might need to store extra data for
45 a buffer. This is typically done when the resources are allocated from another
46 subsystem such as OMX or X11.
47
48 - **Processing information**: Pan and crop information can be added to the
49 buffer data when the downstream element can understand and use this metadata.
50 An imagesink can, for example, use the pan and cropping information when
51 blitting the image on the screen with little overhead.
52
53 ## GstMeta
54
55 A `GstMeta` is a structure as follows:
56
57 ``` c
58 struct _GstMeta {
59   GstMetaFlags       flags;
60   const GstMetaInfo *info;    /* tag and info for the meta item */
61 };
62 ```
63
64 The purpose of this structure is to serve as a common header for all
65 metadata information that we can attach to a buffer. Specific metadata,
66 such as timing metadata, will have this structure as the first field.
67 For example:
68
69 ``` c
70 struct _GstMetaTiming {
71   GstMeta        meta;        /* common meta header */
72
73   GstClockTime   dts;         /* decoding timestamp */
74   GstClockTime   pts;         /* presentation timestamp */
75   GstClockTime   duration;    /* duration of the data */
76   GstClockTime   clock_rate;  /* clock rate for the above values */
77 };
78 ```
79
80 Or another example for the video memory regions that consists of both
81 fields and methods.
82
83 ``` c
84 #define GST_VIDEO_MAX_PLANES 4
85
86 struct GstVideoMeta {
87   GstMeta       meta;
88
89   GstBuffer         *buffer;
90
91   GstVideoFlags      flags;
92   GstVideoFormat     format;
93   guint              id
94   guint              width;
95   guint              height;
96
97   guint              n_planes;
98   gsize              offset[GST_VIDEO_MAX_PLANES];   /* offset in the buffer memory region of the
99                                                     * first pixel. */
100   gint               stride[GST_VIDEO_MAX_PLANES];   /* stride of the image lines. Can be negative when
101                                                     * the image is upside-down */
102
103   gpointer (*map)    (GstVideoMeta *meta, guint plane, gpointer * data, gint *stride,
104                       GstMapFlags flags);
105   gboolean (*unmap)  (GstVideoMeta *meta, guint plane, gpointer data);
106 };
107
108 gpointer gst_meta_video_map   (GstVideoMeta *meta, guint plane, gpointer * data,
109                                gint *stride, GstMapflags flags);
110 gboolean gst_meta_video_unmap (GstVideoMeta *meta, guint plane, gpointer data);
111 ```
112
113 `GstMeta` derived structures define the API of the metadata. The API can
114 consist of fields and/or methods. It is possible to have different
115 implementations for the same `GstMeta` structure.
116
117 The implementation of the `GstMeta` API would typically add more fields to
118 the public structure that allow it to implement the API.
119
120 `GstMetaInfo` will point to more information about the metadata and looks
121 like this:
122
123 ``` c
124 struct _GstMetaInfo {
125   GType                      api;       /* api type */
126   GType                      type;      /* implementation type */
127   gsize                      size;      /* size of the structure */
128
129   GstMetaInitFunction        init_func;
130   GstMetaFreeFunction        free_func;
131   GstMetaTransformFunction   transform_func;
132 };
133 ```
134
135 The `api` member will contain a `GType` of the metadata API. A repository of
136 registered `MetaInfo` will be maintained by the core. We will register some
137 common metadata structures in core and some media specific info for
138 audio/video/text in -base. Plugins can register additional custom metadata.
139
140 For each implementation of api, there will thus be a unique `GstMetaInfo`.
141 In the case of metadata with a well defined API, the implementation
142 specific init function will setup the methods in the metadata structure.
143 A unique `GType` will be made for each implementation and stored in the
144 type field.
145
146 Along with the metadata description we will have functions to
147 initialize/free (and/or refcount) a specific `GstMeta` instance. We also
148 have the possibility to add a custom transform function that can be used
149 to modify the metadata when a transformation happens.
150
151 There are no explicit methods to serialize and deserialize the metadata.
152 Since each type has a `GType`, we can reuse the `GValue` transform functions
153 for this.
154
155 The purpose of the separate `MetaInfo` is to not have to carry the
156 free/init functions in each buffer instance but to define them globally.
157 We still want quick access to the info so we need to make the buffer
158 metadata point to the info.
159
160 Technically we could also specify the field and types in the `MetaInfo`
161 and provide a generic API to retrieve the metadata fields without the
162 need for a header file. We will not do this yet.
163
164 Allocation of the `GstBuffer` structure will result in the allocation of a
165 memory region of a customizable size (512 bytes). Only the first `sizeof
166 (GstBuffer)` bytes of this region will initially be used. The remaining
167 bytes will be part of the free metadata region of the buffer. Different
168 implementations are possible and are invisible in the API or ABI.
169
170 The complete buffer with metadata could, for example, look as follows:
171
172 ```
173                          +----------------------------------+
174 GstMiniObject            |  GType (GstBuffer)               |
175                          |  refcount, flags, copy/disp/free |
176                          +----------------------------------+
177 GstBuffer                |  pool,pts,dts,duration,offsets   |
178                          |  <private data>                  |
179                          +..................................+
180                          |  next                           ---+
181                       +- |  info                           ------> GstMetaInfo
182 GstMetaTiming         |  |                                  | |
183                       |  |  dts                             | |
184                       |  |  pts                             | |
185                       |  |  duration                        | |
186                       +- |  clock_rate                      | |
187                          +  . . . . . . . . . . . . . . . . + |
188                          |  next                           <--+
189 GstVideoMeta       +- +- |  info                           ------> GstMetaInfo
190                    |  |  |                                  | |
191                    |  |  |  flags                           | |
192                    |  |  |  n_planes                        | |
193                    |  |  |  planes[]                        | |
194                    |  |  |  map                             | |
195                    |  |  |  unmap                           | |
196                    +- |  |                                  | |
197                       |  |  private fields                  | |
198 GstVideoMetaImpl      |  |  ...                             | |
199                       |  |  ...                             | |
200                       +- |                                  | |
201                          +  . . . . . . . . . . . . . . . . + .
202                          .                                    .
203 ```
204
205 ## API examples
206
207 Buffers are created using the normal `gst_buffer_new()` functions. The
208 standard fields are initialized as usual. A memory area that is bigger
209 than the structure size is allocated for the buffer metadata.
210
211 ``` c
212 gst_buffer_new ();
213 ```
214
215 After creating a buffer, the application can set caps and add metadata
216 information.
217
218 To add or retrieve metadata, a handle to a `GstMetaInfo` structure needs
219 to be obtained. This defines the implementation and API of the metadata.
220 Usually, a handle to this info structure can be obtained by calling a
221 public `_get_info()` method from a shared library (for shared metadata).
222
223 The following defines can usually be found in the shared .h file.
224
225 ``` c
226 GstMetaInfo * gst_meta_timing_get_info();
227 #define GST_META_TIMING_INFO  (gst_meta_timing_get_info())
228 ```
229
230 Adding metadata to a buffer can be done with the
231 `gst_buffer_add_meta()` call. This function will create new metadata
232 based on the implementation specified by the `GstMetaInfo`. It is also
233 possible to pass a generic pointer to the `add_meta()` function that can
234 contain parameters to initialize the new metadata fields.
235
236 Retrieving the metadata on a buffer can be done with the
237 `gst_buffer_meta_get()` method. This function retrieves an existing
238 metadata conforming to the API specified in the given info. When no such
239 metadata exists, the function will return NULL.
240
241 ``` c
242 GstMetaTiming *timing;
243
244 timing = gst_buffer_get_meta (buffer, GST_META_TIMING_INFO);
245 ```
246
247 Once a reference to the info has been obtained, the associated metadata
248 can be added or modified on a buffer.
249
250 ``` c
251 timing->timestamp = 0;
252 timing->duration = 20 * GST_MSECOND;
253 ```
254
255 Other convenience macros can be made to simplify the above code:
256
257 ``` c
258 #define gst_buffer_get_meta_timing(b) \
259    ((GstMetaTiming *) gst_buffer_get_meta ((b), GST_META_TIMING_INFO)
260 ```
261
262 This makes the code look like this:
263
264 ``` c
265 GstMetaTiming *timing;
266
267 timing = gst_buffer_get_meta_timing (buffer);
268 timing->timestamp = 0;
269 timing->duration = 20 * GST_MSECOND;
270 ```
271
272 To iterate the different metainfo structures, one can use the
273 `gst_buffer_meta_get_next()` methods.
274
275 ``` c
276 GstMeta *current = NULL;
277
278 /* passing NULL gives the first entry */
279 current = gst_buffer_meta_get_next (buffer, current);
280
281 /* passing a GstMeta returns the next */
282 current = gst_buffer_meta_get_next (buffer, current);
283 ```
284
285 ## Memory management
286
287 ### allocation
288
289 We initially allocate a reasonable sized `GstBuffer` structure (say 512 bytes).
290
291 Since the complete buffer structure, including a large area for metadata, is
292 allocated in one go, we can reduce the number of memory allocations while still
293 providing dynamic metadata.
294
295 When adding metadata, we need to call the init function of the associated
296 metadata info structure. Since adding the metadata requires the caller to pass
297 a handle to the info, this operation does not require table lookups.
298
299 Per-metadata memory initialisation is needed because not all metadata is
300 initialized in the same way. We need to, for example, set the timestamps to
301 NONE in the MetaTiming structures.
302
303 The init/free functions can also be used to implement refcounting for a metadata
304 structure. This can be useful when a structure is shared between buffers.
305
306 When the `free_size` of the `GstBuffer` is exhausted, we will allocate new
307 memory for each newly added Meta and use the next pointers to point to this. It
308 is expected that this does not occur often and we might be able to optimize
309 this transparently in the future.
310
311 ### free
312
313 When a `GstBuffer` is freed, we potentially might have to call a custom `free()`
314 function on the metadata info. In the case of the Memory metadata, we need to
315 call the associated `free()` function to free the memory.
316
317 When freeing a `GstBuffer`, the custom buffer free function will iterate all of
318 the metadata in the buffer and call the associated free functions in the
319 `MetaInfo` associated with the entries. Usually, this function will be NULL.
320
321 ## Serialization
322
323 When a buffer should be sent over the wire or be serialized in GDP, we
324 need a way to perform custom serialization and deserialization on the
325 metadata. For this we can use the `GValue` transform functions.
326
327 ## Transformations
328
329 After certain transformations, the metadata on a buffer might not be
330 relevant anymore.
331
332 Consider, for example, metadata that lists certain regions of interest
333 on the video data. If the video is scaled or rotated, the coordinates
334 might not make sense anymore. A transform element should be able to
335 adjust or remove the associated metadata when it becomes invalid.
336
337 We can make the transform element aware of the metadata so that it can
338 adjust or remove in an intelligent way. Since we allow arbitrary
339 metadata, we can’t do this for all metadata and thus we need some other
340 way.
341
342 One proposition is to tag the metadata type with keywords that specify
343 what it functionally refers too. We could, for example, tag the metadata
344 for the regions of interest with a tag that notes that the metadata
345 refers to absolute pixel positions. A transform could then know that the
346 metadata is not valid anymore when the position of the pixels changed
347 (due to rotation, flipping, scaling and so on).
348
349 ## Subbuffers
350
351 Subbuffers are implemented with a generic copy. Parameters to the copy
352 are the offset and size. This allows each metadata structure to
353 implement the actions needed to update the metadata of the subbuffer.
354
355 It might not make sense for some metadata to work with subbuffers. For
356 example when we take a subbuffer of a buffer with a video frame, the
357 `GstVideoMeta` simply becomes invalid and is removed from the new
358 subbuffer.
359
360 ## Relationship with GstCaps
361
362 The difference between `GstCaps`, used in negotiation, and the metadata is
363 not clearly defined.
364
365 We would like to think of the `GstCaps` containing the information needed
366 to functionally negotiate the format between two elements. The Metadata
367 should then only contain variables that can change between each buffer.
368
369 For example, for video we would have width/height/framerate in the caps
370 but then have the more technical details, such as stride, data pointers,
371 pan/crop/zoom etc in the metadata.
372
373 A scheme like this would still allow us to functionally specify the
374 desired video resolution while the implementation details would be
375 inside the metadata.
376
377 ## Relationship with GstMiniObject qdata
378
379 qdata on a miniobject is element private and is not visible to other
380 element. Therefore qdata never contains essential information that
381 describes the buffer content.
382
383 ## Compatibility
384
385 We need to make sure that elements exchange metadata that they both
386 understand, This is particularly important when the metadata describes
387 the data layout in memory (such as strides).
388
389 The `ALLOCATION` query is used to let upstream know what metadata we can
390 support.
391
392 It is also possible to have a bufferpool add certain metadata to the
393 buffers from the pool. This feature is activated by enabling a buffer
394 option when configuring the pool.
395
396 ## Notes
397
398 Some structures that we need to be able to add to buffers.
399
400 - Clean Aperture
401 - Arbitrary Matrix Transform
402 - Aspect ratio
403 - Pan/crop/zoom
404 - Video strides
405
406 Some of these overlap, we need to find a minimal set of metadata
407 structures that allows us to define all use cases.