]> git.sesse.net Git - ffmpeg/blob - libavcodec/cbs.c
Merge commit '04e8b8b0530e2aa33010faba3d0b6b6c9c5b704e'
[ffmpeg] / libavcodec / cbs.c
1 /*
2  * This file is part of FFmpeg.
3  *
4  * FFmpeg is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * FFmpeg is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with FFmpeg; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  */
18
19 #include <string.h>
20
21 #include "config.h"
22
23 #include "libavutil/avassert.h"
24 #include "libavutil/buffer.h"
25 #include "libavutil/common.h"
26
27 #include "cbs.h"
28 #include "cbs_internal.h"
29
30
31 static const CodedBitstreamType *cbs_type_table[] = {
32 #if CONFIG_CBS_AV1
33     &ff_cbs_type_av1,
34 #endif
35 #if CONFIG_CBS_H264
36     &ff_cbs_type_h264,
37 #endif
38 #if CONFIG_CBS_H265
39     &ff_cbs_type_h265,
40 #endif
41 #if CONFIG_CBS_JPEG
42     &ff_cbs_type_jpeg,
43 #endif
44 #if CONFIG_CBS_MPEG2
45     &ff_cbs_type_mpeg2,
46 #endif
47 #if CONFIG_CBS_VP9
48     &ff_cbs_type_vp9,
49 #endif
50 };
51
52 const enum AVCodecID ff_cbs_all_codec_ids[] = {
53 #if CONFIG_CBS_AV1
54     AV_CODEC_ID_AV1,
55 #endif
56 #if CONFIG_CBS_H264
57     AV_CODEC_ID_H264,
58 #endif
59 #if CONFIG_CBS_H265
60     AV_CODEC_ID_H265,
61 #endif
62 #if CONFIG_CBS_JPEG
63     AV_CODEC_ID_MJPEG,
64 #endif
65 #if CONFIG_CBS_MPEG2
66     AV_CODEC_ID_MPEG2VIDEO,
67 #endif
68 #if CONFIG_CBS_VP9
69     AV_CODEC_ID_VP9,
70 #endif
71     AV_CODEC_ID_NONE
72 };
73
74 int ff_cbs_init(CodedBitstreamContext **ctx_ptr,
75                 enum AVCodecID codec_id, void *log_ctx)
76 {
77     CodedBitstreamContext *ctx;
78     const CodedBitstreamType *type;
79     int i;
80
81     type = NULL;
82     for (i = 0; i < FF_ARRAY_ELEMS(cbs_type_table); i++) {
83         if (cbs_type_table[i]->codec_id == codec_id) {
84             type = cbs_type_table[i];
85             break;
86         }
87     }
88     if (!type)
89         return AVERROR(EINVAL);
90
91     ctx = av_mallocz(sizeof(*ctx));
92     if (!ctx)
93         return AVERROR(ENOMEM);
94
95     ctx->log_ctx = log_ctx;
96     ctx->codec   = type;
97
98     ctx->priv_data = av_mallocz(ctx->codec->priv_data_size);
99     if (!ctx->priv_data) {
100         av_freep(&ctx);
101         return AVERROR(ENOMEM);
102     }
103
104     ctx->decompose_unit_types = NULL;
105
106     ctx->trace_enable = 0;
107     ctx->trace_level  = AV_LOG_TRACE;
108
109     *ctx_ptr = ctx;
110     return 0;
111 }
112
113 void ff_cbs_close(CodedBitstreamContext **ctx_ptr)
114 {
115     CodedBitstreamContext *ctx = *ctx_ptr;
116
117     if (!ctx)
118         return;
119
120     if (ctx->codec && ctx->codec->close)
121         ctx->codec->close(ctx);
122
123     av_freep(&ctx->priv_data);
124     av_freep(ctx_ptr);
125 }
126
127 static void cbs_unit_uninit(CodedBitstreamContext *ctx,
128                             CodedBitstreamUnit *unit)
129 {
130     av_buffer_unref(&unit->content_ref);
131     unit->content = NULL;
132
133     av_buffer_unref(&unit->data_ref);
134     unit->data             = NULL;
135     unit->data_size        = 0;
136     unit->data_bit_padding = 0;
137 }
138
139 void ff_cbs_fragment_uninit(CodedBitstreamContext *ctx,
140                             CodedBitstreamFragment *frag)
141 {
142     int i;
143
144     for (i = 0; i < frag->nb_units; i++)
145         cbs_unit_uninit(ctx, &frag->units[i]);
146     av_freep(&frag->units);
147     frag->nb_units = 0;
148
149     av_buffer_unref(&frag->data_ref);
150     frag->data             = NULL;
151     frag->data_size        = 0;
152     frag->data_bit_padding = 0;
153 }
154
155 static int cbs_read_fragment_content(CodedBitstreamContext *ctx,
156                                      CodedBitstreamFragment *frag)
157 {
158     int err, i, j;
159
160     for (i = 0; i < frag->nb_units; i++) {
161         CodedBitstreamUnit *unit = &frag->units[i];
162
163         if (ctx->decompose_unit_types) {
164             for (j = 0; j < ctx->nb_decompose_unit_types; j++) {
165                 if (ctx->decompose_unit_types[j] == unit->type)
166                     break;
167             }
168             if (j >= ctx->nb_decompose_unit_types)
169                 continue;
170         }
171
172         av_buffer_unref(&unit->content_ref);
173         unit->content = NULL;
174
175         av_assert0(unit->data && unit->data_ref);
176
177         err = ctx->codec->read_unit(ctx, unit);
178         if (err == AVERROR(ENOSYS)) {
179             av_log(ctx->log_ctx, AV_LOG_VERBOSE,
180                    "Decomposition unimplemented for unit %d "
181                    "(type %"PRIu32").\n", i, unit->type);
182         } else if (err < 0) {
183             av_log(ctx->log_ctx, AV_LOG_ERROR, "Failed to read unit %d "
184                    "(type %"PRIu32").\n", i, unit->type);
185             return err;
186         }
187     }
188
189     return 0;
190 }
191
192 static int cbs_fill_fragment_data(CodedBitstreamContext *ctx,
193                                   CodedBitstreamFragment *frag,
194                                   const uint8_t *data, size_t size)
195 {
196     av_assert0(!frag->data && !frag->data_ref);
197
198     frag->data_ref =
199         av_buffer_alloc(size + AV_INPUT_BUFFER_PADDING_SIZE);
200     if (!frag->data_ref)
201         return AVERROR(ENOMEM);
202
203     frag->data      = frag->data_ref->data;
204     frag->data_size = size;
205
206     memcpy(frag->data, data, size);
207     memset(frag->data + size, 0,
208            AV_INPUT_BUFFER_PADDING_SIZE);
209
210     return 0;
211 }
212
213 int ff_cbs_read_extradata(CodedBitstreamContext *ctx,
214                           CodedBitstreamFragment *frag,
215                           const AVCodecParameters *par)
216 {
217     int err;
218
219     memset(frag, 0, sizeof(*frag));
220
221     err = cbs_fill_fragment_data(ctx, frag, par->extradata,
222                                  par->extradata_size);
223     if (err < 0)
224         return err;
225
226     err = ctx->codec->split_fragment(ctx, frag, 1);
227     if (err < 0)
228         return err;
229
230     return cbs_read_fragment_content(ctx, frag);
231 }
232
233 int ff_cbs_read_packet(CodedBitstreamContext *ctx,
234                        CodedBitstreamFragment *frag,
235                        const AVPacket *pkt)
236 {
237     int err;
238
239     memset(frag, 0, sizeof(*frag));
240
241     if (pkt->buf) {
242         frag->data_ref = av_buffer_ref(pkt->buf);
243         if (!frag->data_ref)
244             return AVERROR(ENOMEM);
245
246         frag->data      = pkt->data;
247         frag->data_size = pkt->size;
248
249     } else {
250         err = cbs_fill_fragment_data(ctx, frag, pkt->data, pkt->size);
251         if (err < 0)
252             return err;
253     }
254
255     err = ctx->codec->split_fragment(ctx, frag, 0);
256     if (err < 0)
257         return err;
258
259     return cbs_read_fragment_content(ctx, frag);
260 }
261
262 int ff_cbs_read(CodedBitstreamContext *ctx,
263                 CodedBitstreamFragment *frag,
264                 const uint8_t *data, size_t size)
265 {
266     int err;
267
268     memset(frag, 0, sizeof(*frag));
269
270     err = cbs_fill_fragment_data(ctx, frag, data, size);
271     if (err < 0)
272         return err;
273
274     err = ctx->codec->split_fragment(ctx, frag, 0);
275     if (err < 0)
276         return err;
277
278     return cbs_read_fragment_content(ctx, frag);
279 }
280
281
282 int ff_cbs_write_fragment_data(CodedBitstreamContext *ctx,
283                                CodedBitstreamFragment *frag)
284 {
285     int err, i;
286
287     for (i = 0; i < frag->nb_units; i++) {
288         CodedBitstreamUnit *unit = &frag->units[i];
289
290         if (!unit->content)
291             continue;
292
293         av_buffer_unref(&unit->data_ref);
294         unit->data = NULL;
295
296         err = ctx->codec->write_unit(ctx, unit);
297         if (err < 0) {
298             av_log(ctx->log_ctx, AV_LOG_ERROR, "Failed to write unit %d "
299                    "(type %"PRIu32").\n", i, unit->type);
300             return err;
301         }
302         av_assert0(unit->data && unit->data_ref);
303     }
304
305     av_buffer_unref(&frag->data_ref);
306     frag->data = NULL;
307
308     err = ctx->codec->assemble_fragment(ctx, frag);
309     if (err < 0) {
310         av_log(ctx->log_ctx, AV_LOG_ERROR, "Failed to assemble fragment.\n");
311         return err;
312     }
313     av_assert0(frag->data && frag->data_ref);
314
315     return 0;
316 }
317
318 int ff_cbs_write_extradata(CodedBitstreamContext *ctx,
319                            AVCodecParameters *par,
320                            CodedBitstreamFragment *frag)
321 {
322     int err;
323
324     err = ff_cbs_write_fragment_data(ctx, frag);
325     if (err < 0)
326         return err;
327
328     av_freep(&par->extradata);
329
330     par->extradata = av_malloc(frag->data_size +
331                                AV_INPUT_BUFFER_PADDING_SIZE);
332     if (!par->extradata)
333         return AVERROR(ENOMEM);
334
335     memcpy(par->extradata, frag->data, frag->data_size);
336     memset(par->extradata + frag->data_size, 0,
337            AV_INPUT_BUFFER_PADDING_SIZE);
338     par->extradata_size = frag->data_size;
339
340     return 0;
341 }
342
343 int ff_cbs_write_packet(CodedBitstreamContext *ctx,
344                         AVPacket *pkt,
345                         CodedBitstreamFragment *frag)
346 {
347     AVBufferRef *buf;
348     int err;
349
350     err = ff_cbs_write_fragment_data(ctx, frag);
351     if (err < 0)
352         return err;
353
354     buf = av_buffer_ref(frag->data_ref);
355     if (!buf)
356         return AVERROR(ENOMEM);
357
358     av_init_packet(pkt);
359     pkt->buf  = buf;
360     pkt->data = frag->data;
361     pkt->size = frag->data_size;
362
363     return 0;
364 }
365
366
367 void ff_cbs_trace_header(CodedBitstreamContext *ctx,
368                          const char *name)
369 {
370     if (!ctx->trace_enable)
371         return;
372
373     av_log(ctx->log_ctx, ctx->trace_level, "%s\n", name);
374 }
375
376 void ff_cbs_trace_syntax_element(CodedBitstreamContext *ctx, int position,
377                                  const char *str, const int *subscripts,
378                                  const char *bits, int64_t value)
379 {
380     char name[256];
381     size_t name_len, bits_len;
382     int pad, subs, i, j, k, n;
383
384     if (!ctx->trace_enable)
385         return;
386
387     av_assert0(value >= INT_MIN && value <= UINT32_MAX);
388
389     subs = subscripts ? subscripts[0] : 0;
390     n = 0;
391     for (i = j = 0; str[i];) {
392         if (str[i] == '[') {
393             if (n < subs) {
394                 ++n;
395                 k = snprintf(name + j, sizeof(name) - j, "[%d", subscripts[n]);
396                 av_assert0(k > 0 && j + k < sizeof(name));
397                 j += k;
398                 for (++i; str[i] && str[i] != ']'; i++);
399                 av_assert0(str[i] == ']');
400             } else {
401                 while (str[i] && str[i] != ']')
402                     name[j++] = str[i++];
403                 av_assert0(str[i] == ']');
404             }
405         } else {
406             av_assert0(j + 1 < sizeof(name));
407             name[j++] = str[i++];
408         }
409     }
410     av_assert0(j + 1 < sizeof(name));
411     name[j] = 0;
412     av_assert0(n == subs);
413
414     name_len = strlen(name);
415     bits_len = strlen(bits);
416
417     if (name_len + bits_len > 60)
418         pad = bits_len + 2;
419     else
420         pad = 61 - name_len;
421
422     av_log(ctx->log_ctx, ctx->trace_level, "%-10d  %s%*s = %"PRId64"\n",
423            position, name, pad, bits, value);
424 }
425
426 int ff_cbs_read_unsigned(CodedBitstreamContext *ctx, GetBitContext *gbc,
427                          int width, const char *name,
428                          const int *subscripts, uint32_t *write_to,
429                          uint32_t range_min, uint32_t range_max)
430 {
431     uint32_t value;
432     int position;
433
434     av_assert0(width > 0 && width <= 32);
435
436     if (get_bits_left(gbc) < width) {
437         av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid value at "
438                "%s: bitstream ended.\n", name);
439         return AVERROR_INVALIDDATA;
440     }
441
442     if (ctx->trace_enable)
443         position = get_bits_count(gbc);
444
445     value = get_bits_long(gbc, width);
446
447     if (ctx->trace_enable) {
448         char bits[33];
449         int i;
450         for (i = 0; i < width; i++)
451             bits[i] = value >> (width - i - 1) & 1 ? '1' : '0';
452         bits[i] = 0;
453
454         ff_cbs_trace_syntax_element(ctx, position, name, subscripts,
455                                     bits, value);
456     }
457
458     if (value < range_min || value > range_max) {
459         av_log(ctx->log_ctx, AV_LOG_ERROR, "%s out of range: "
460                "%"PRIu32", but must be in [%"PRIu32",%"PRIu32"].\n",
461                name, value, range_min, range_max);
462         return AVERROR_INVALIDDATA;
463     }
464
465     *write_to = value;
466     return 0;
467 }
468
469 int ff_cbs_write_unsigned(CodedBitstreamContext *ctx, PutBitContext *pbc,
470                           int width, const char *name,
471                           const int *subscripts, uint32_t value,
472                           uint32_t range_min, uint32_t range_max)
473 {
474     av_assert0(width > 0 && width <= 32);
475
476     if (value < range_min || value > range_max) {
477         av_log(ctx->log_ctx, AV_LOG_ERROR, "%s out of range: "
478                "%"PRIu32", but must be in [%"PRIu32",%"PRIu32"].\n",
479                name, value, range_min, range_max);
480         return AVERROR_INVALIDDATA;
481     }
482
483     if (put_bits_left(pbc) < width)
484         return AVERROR(ENOSPC);
485
486     if (ctx->trace_enable) {
487         char bits[33];
488         int i;
489         for (i = 0; i < width; i++)
490             bits[i] = value >> (width - i - 1) & 1 ? '1' : '0';
491         bits[i] = 0;
492
493         ff_cbs_trace_syntax_element(ctx, put_bits_count(pbc),
494                                     name, subscripts, bits, value);
495     }
496
497     if (width < 32)
498         put_bits(pbc, width, value);
499     else
500         put_bits32(pbc, value);
501
502     return 0;
503 }
504
505
506 int ff_cbs_alloc_unit_content(CodedBitstreamContext *ctx,
507                               CodedBitstreamUnit *unit,
508                               size_t size,
509                               void (*free)(void *opaque, uint8_t *data))
510 {
511     av_assert0(!unit->content && !unit->content_ref);
512
513     unit->content = av_mallocz(size);
514     if (!unit->content)
515         return AVERROR(ENOMEM);
516
517     unit->content_ref = av_buffer_create(unit->content, size,
518                                          free, ctx, 0);
519     if (!unit->content_ref) {
520         av_freep(&unit->content);
521         return AVERROR(ENOMEM);
522     }
523
524     return 0;
525 }
526
527 int ff_cbs_alloc_unit_data(CodedBitstreamContext *ctx,
528                            CodedBitstreamUnit *unit,
529                            size_t size)
530 {
531     av_assert0(!unit->data && !unit->data_ref);
532
533     unit->data_ref = av_buffer_alloc(size + AV_INPUT_BUFFER_PADDING_SIZE);
534     if (!unit->data_ref)
535         return AVERROR(ENOMEM);
536
537     unit->data      = unit->data_ref->data;
538     unit->data_size = size;
539
540     memset(unit->data + size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
541
542     return 0;
543 }
544
545 static int cbs_insert_unit(CodedBitstreamContext *ctx,
546                            CodedBitstreamFragment *frag,
547                            int position)
548 {
549     CodedBitstreamUnit *units;
550
551     units = av_malloc_array(frag->nb_units + 1, sizeof(*units));
552     if (!units)
553         return AVERROR(ENOMEM);
554
555     if (position > 0)
556         memcpy(units, frag->units, position * sizeof(*units));
557     if (position < frag->nb_units)
558         memcpy(units + position + 1, frag->units + position,
559                (frag->nb_units - position) * sizeof(*units));
560
561     memset(units + position, 0, sizeof(*units));
562
563     av_freep(&frag->units);
564     frag->units = units;
565     ++frag->nb_units;
566
567     return 0;
568 }
569
570 int ff_cbs_insert_unit_content(CodedBitstreamContext *ctx,
571                                CodedBitstreamFragment *frag,
572                                int position,
573                                CodedBitstreamUnitType type,
574                                void *content,
575                                AVBufferRef *content_buf)
576 {
577     CodedBitstreamUnit *unit;
578     AVBufferRef *content_ref;
579     int err;
580
581     if (position == -1)
582         position = frag->nb_units;
583     av_assert0(position >= 0 && position <= frag->nb_units);
584
585     if (content_buf) {
586         content_ref = av_buffer_ref(content_buf);
587         if (!content_ref)
588             return AVERROR(ENOMEM);
589     } else {
590         content_ref = NULL;
591     }
592
593     err = cbs_insert_unit(ctx, frag, position);
594     if (err < 0) {
595         av_buffer_unref(&content_ref);
596         return err;
597     }
598
599     unit = &frag->units[position];
600     unit->type        = type;
601     unit->content     = content;
602     unit->content_ref = content_ref;
603
604     return 0;
605 }
606
607 int ff_cbs_insert_unit_data(CodedBitstreamContext *ctx,
608                             CodedBitstreamFragment *frag,
609                             int position,
610                             CodedBitstreamUnitType type,
611                             uint8_t *data, size_t data_size,
612                             AVBufferRef *data_buf)
613 {
614     CodedBitstreamUnit *unit;
615     AVBufferRef *data_ref;
616     int err;
617
618     if (position == -1)
619         position = frag->nb_units;
620     av_assert0(position >= 0 && position <= frag->nb_units);
621
622     if (data_buf)
623         data_ref = av_buffer_ref(data_buf);
624     else
625         data_ref = av_buffer_create(data, data_size, NULL, NULL, 0);
626     if (!data_ref)
627         return AVERROR(ENOMEM);
628
629     err = cbs_insert_unit(ctx, frag, position);
630     if (err < 0) {
631         av_buffer_unref(&data_ref);
632         return err;
633     }
634
635     unit = &frag->units[position];
636     unit->type      = type;
637     unit->data      = data;
638     unit->data_size = data_size;
639     unit->data_ref  = data_ref;
640
641     return 0;
642 }
643
644 int ff_cbs_delete_unit(CodedBitstreamContext *ctx,
645                        CodedBitstreamFragment *frag,
646                        int position)
647 {
648     if (position < 0 || position >= frag->nb_units)
649         return AVERROR(EINVAL);
650
651     cbs_unit_uninit(ctx, &frag->units[position]);
652
653     --frag->nb_units;
654
655     if (frag->nb_units == 0) {
656         av_freep(&frag->units);
657
658     } else {
659         memmove(frag->units + position,
660                 frag->units + position + 1,
661                 (frag->nb_units - position) * sizeof(*frag->units));
662
663         // Don't bother reallocating the unit array.
664     }
665
666     return 0;
667 }