aboutsummaryrefslogtreecommitdiffstats
path: root/fftools/textformat/avtextformat.c
blob: 9200b9b1ad820d000af7c175b6033f72a70435ac (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
/*
 * Copyright (c) The FFmpeg developers
 *
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * FFmpeg is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with FFmpeg; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include <limits.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>

#include "libavutil/mem.h"
#include "libavutil/avassert.h"
#include "libavutil/bprint.h"
#include "libavutil/error.h"
#include "libavutil/hash.h"
#include "libavutil/intreadwrite.h"
#include "libavutil/macros.h"
#include "libavutil/opt.h"
#include "avtextformat.h"

#define SECTION_ID_NONE -1

#define SHOW_OPTIONAL_FIELDS_AUTO       -1
#define SHOW_OPTIONAL_FIELDS_NEVER       0
#define SHOW_OPTIONAL_FIELDS_ALWAYS      1

static const struct {
    double bin_val;
    double dec_val;
    const char *bin_str;
    const char *dec_str;
} si_prefixes[] = {
    { 1.0, 1.0, "", "" },
    { 1.024e3, 1e3, "Ki", "K" },
    { 1.048576e6, 1e6, "Mi", "M" },
    { 1.073741824e9, 1e9, "Gi", "G" },
    { 1.099511627776e12, 1e12, "Ti", "T" },
    { 1.125899906842624e15, 1e15, "Pi", "P" },
};

static const char *textcontext_get_formatter_name(void *p)
{
    AVTextFormatContext *tctx = p;
    return tctx->formatter->name;
}

#define OFFSET(x) offsetof(AVTextFormatContext, x)

static const AVOption textcontext_options[] = {
    { "string_validation", "set string validation mode",
      OFFSET(string_validation), AV_OPT_TYPE_INT, {.i64=AV_TEXTFORMAT_STRING_VALIDATION_REPLACE}, 0, AV_TEXTFORMAT_STRING_VALIDATION_NB-1, .unit = "sv" },
    { "sv", "set string validation mode",
      OFFSET(string_validation), AV_OPT_TYPE_INT, {.i64=AV_TEXTFORMAT_STRING_VALIDATION_REPLACE}, 0, AV_TEXTFORMAT_STRING_VALIDATION_NB-1, .unit = "sv" },
        { "ignore",  NULL, 0, AV_OPT_TYPE_CONST, {.i64 = AV_TEXTFORMAT_STRING_VALIDATION_IGNORE},  .unit = "sv" },
        { "replace", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = AV_TEXTFORMAT_STRING_VALIDATION_REPLACE}, .unit = "sv" },
        { "fail",    NULL, 0, AV_OPT_TYPE_CONST, {.i64 = AV_TEXTFORMAT_STRING_VALIDATION_FAIL},    .unit = "sv" },
    { "string_validation_replacement", "set string validation replacement string", OFFSET(string_validation_replacement), AV_OPT_TYPE_STRING, {.str=""}},
    { "svr", "set string validation replacement string", OFFSET(string_validation_replacement), AV_OPT_TYPE_STRING, {.str="\xEF\xBF\xBD"}},
    { NULL }
};

static void *textcontext_child_next(void *obj, void *prev)
{
    AVTextFormatContext *ctx = obj;
    if (!prev && ctx->formatter && ctx->formatter->priv_class && ctx->priv)
        return ctx->priv;
    return NULL;
}

static const AVClass textcontext_class = {
    .class_name = "AVTextContext",
    .item_name  = textcontext_get_formatter_name,
    .option     = textcontext_options,
    .version    = LIBAVUTIL_VERSION_INT,
    .child_next = textcontext_child_next,
};

static void bprint_bytes(AVBPrint *bp, const uint8_t *ubuf, size_t ubuf_size)
{
    int i;
    av_bprintf(bp, "0X");
    for (i = 0; i < ubuf_size; i++)
        av_bprintf(bp, "%02X", ubuf[i]);
}

void avtext_context_close(AVTextFormatContext **ptctx)
{
    AVTextFormatContext *tctx = *ptctx;
    int i;

    if (!tctx)
        return;

    av_hash_freep(&tctx->hash);

    av_hash_freep(&tctx->hash);

    if (tctx->formatter) {
        if (tctx->formatter->uninit)
            tctx->formatter->uninit(tctx);
        if (tctx->formatter->priv_class)
            av_opt_free(tctx->priv);
    }
    for (i = 0; i < SECTION_MAX_NB_LEVELS; i++)
        av_bprint_finalize(&tctx->section_pbuf[i], NULL);
    av_freep(&tctx->priv);
    av_opt_free(tctx);
    av_freep(ptctx);
}


int avtext_context_open(AVTextFormatContext **ptctx, const AVTextFormatter *formatter, AVTextWriterContext *writer_context, const char *args,
                        const struct AVTextFormatSection *sections, int nb_sections,
                        int show_value_unit,
                        int use_value_prefix,
                        int use_byte_value_binary_prefix,
                        int use_value_sexagesimal_format,
                        int show_optional_fields,
                        char *show_data_hash)
{
    AVTextFormatContext *tctx;
    int i, ret = 0;

    if (!(tctx = av_mallocz(sizeof(AVTextFormatContext)))) {
        ret = AVERROR(ENOMEM);
        goto fail;
    }

    for (int i = 0; i < SECTION_MAX_NB_LEVELS; i++)
        av_bprint_init(&tctx->section_pbuf[i], 1, AV_BPRINT_SIZE_UNLIMITED);

    tctx->class = &textcontext_class;
    av_opt_set_defaults(tctx);

    if (!(tctx->priv = av_mallocz(formatter->priv_size))) {
        ret = AVERROR(ENOMEM);
        goto fail;
    }

    tctx->show_value_unit = show_value_unit;
    tctx->use_value_prefix = use_value_prefix;
    tctx->use_byte_value_binary_prefix = use_byte_value_binary_prefix;
    tctx->use_value_sexagesimal_format = use_value_sexagesimal_format;
    tctx->show_optional_fields = show_optional_fields;

    if (nb_sections > SECTION_MAX_NB_SECTIONS) {
        av_log(tctx, AV_LOG_ERROR, "The number of section definitions (%d) is larger than the maximum allowed (%d)\n", nb_sections, SECTION_MAX_NB_SECTIONS);
        ret = AVERROR(EINVAL);
        goto fail;
    }

    tctx->formatter = formatter;
    tctx->level = -1;
    tctx->sections = sections;
    tctx->nb_sections = nb_sections;
    tctx->writer = writer_context;

    if (formatter->priv_class) {
        void *priv_ctx = tctx->priv;
        *(const AVClass **)priv_ctx = formatter->priv_class;
        av_opt_set_defaults(priv_ctx);
    }

    /* convert options to dictionary */
    if (args) {
        AVDictionary *opts = NULL;
        const AVDictionaryEntry *opt = NULL;

        if ((ret = av_dict_parse_string(&opts, args, "=", ":", 0)) < 0) {
            av_log(tctx, AV_LOG_ERROR, "Failed to parse option string '%s' provided to textformat context\n", args);
            av_dict_free(&opts);
            goto fail;
        }

        while ((opt = av_dict_iterate(opts, opt))) {
            if ((ret = av_opt_set(tctx, opt->key, opt->value, AV_OPT_SEARCH_CHILDREN)) < 0) {
                av_log(tctx, AV_LOG_ERROR, "Failed to set option '%s' with value '%s' provided to textformat context\n",
                       opt->key, opt->value);
                av_dict_free(&opts);
                goto fail;
            }
        }

        av_dict_free(&opts);
    }

    if (show_data_hash) {
        if ((ret = av_hash_alloc(&tctx->hash, show_data_hash)) < 0) {
            if (ret == AVERROR(EINVAL)) {
                const char *n;
                av_log(NULL, AV_LOG_ERROR, "Unknown hash algorithm '%s'\nKnown algorithms:", show_data_hash);
                for (i = 0; (n = av_hash_names(i)); i++)
                    av_log(NULL, AV_LOG_ERROR, " %s", n);
                av_log(NULL, AV_LOG_ERROR, "\n");
            }
            return ret;
        }
    }

    /* validate replace string */
    {
        const uint8_t *p = tctx->string_validation_replacement;
        const uint8_t *endp = p + strlen(p);
        while (*p) {
            const uint8_t *p0 = p;
            int32_t code;
            ret = av_utf8_decode(&code, &p, endp, tctx->string_validation_utf8_flags);
            if (ret < 0) {
                AVBPrint bp;
                av_bprint_init(&bp, 0, AV_BPRINT_SIZE_AUTOMATIC);
                bprint_bytes(&bp, p0, p-p0),
                    av_log(tctx, AV_LOG_ERROR,
                           "Invalid UTF8 sequence %s found in string validation replace '%s'\n",
                           bp.str, tctx->string_validation_replacement);
                return ret;
            }
        }
    }

    if (tctx->formatter->init)
        ret = tctx->formatter->init(tctx);
    if (ret < 0)
        goto fail;

    *ptctx = tctx;

    return 0;

fail:
    avtext_context_close(&tctx);
    return ret;
}

/* Temporary definitions during refactoring */
static const char unit_second_str[]         = "s"    ;
static const char unit_hertz_str[]          = "Hz"   ;
static const char unit_byte_str[]           = "byte" ;
static const char unit_bit_per_second_str[] = "bit/s";


void avtext_print_section_header(AVTextFormatContext *tctx,
                                               const void *data,
                                               int section_id)
{
    tctx->level++;
    av_assert0(tctx->level < SECTION_MAX_NB_LEVELS);

    tctx->nb_item[tctx->level] = 0;
    memset(tctx->nb_item_type[tctx->level], 0, sizeof(tctx->nb_item_type[tctx->level]));
    tctx->section[tctx->level] = &tctx->sections[section_id];

    if (tctx->formatter->print_section_header)
        tctx->formatter->print_section_header(tctx, data);
}

void avtext_print_section_footer(AVTextFormatContext *tctx)
{
    int section_id = tctx->section[tctx->level]->id;
    int parent_section_id = tctx->level ?
        tctx->section[tctx->level-1]->id : SECTION_ID_NONE;

    if (parent_section_id != SECTION_ID_NONE) {
        tctx->nb_item[tctx->level - 1]++;
        tctx->nb_item_type[tctx->level - 1][section_id]++;
    }

    if (tctx->formatter->print_section_footer)
        tctx->formatter->print_section_footer(tctx);
    tctx->level--;
}

void avtext_print_integer(AVTextFormatContext *tctx,
                                        const char *key, int64_t val)
{
    const struct AVTextFormatSection *section = tctx->section[tctx->level];

    if (section->show_all_entries || av_dict_get(section->entries_to_show, key, NULL, 0)) {
        tctx->formatter->print_integer(tctx, key, val);
        tctx->nb_item[tctx->level]++;
    }
}

static inline int validate_string(AVTextFormatContext *tctx, char **dstp, const char *src)
{
    const uint8_t *p, *endp;
    AVBPrint dstbuf;
    int invalid_chars_nb = 0, ret = 0;

    av_bprint_init(&dstbuf, 0, AV_BPRINT_SIZE_UNLIMITED);

    endp = src + strlen(src);
    for (p = src; *p;) {
        uint32_t code;
        int invalid = 0;
        const uint8_t *p0 = p;

        if (av_utf8_decode(&code, &p, endp, tctx->string_validation_utf8_flags) < 0) {
            AVBPrint bp;
            av_bprint_init(&bp, 0, AV_BPRINT_SIZE_AUTOMATIC);
            bprint_bytes(&bp, p0, p-p0);
            av_log(tctx, AV_LOG_DEBUG,
                   "Invalid UTF-8 sequence %s found in string '%s'\n", bp.str, src);
            invalid = 1;
        }

        if (invalid) {
            invalid_chars_nb++;

            switch (tctx->string_validation) {
            case AV_TEXTFORMAT_STRING_VALIDATION_FAIL:
                av_log(tctx, AV_LOG_ERROR,
                       "Invalid UTF-8 sequence found in string '%s'\n", src);
                ret = AVERROR_INVALIDDATA;
                goto end;
                break;

            case AV_TEXTFORMAT_STRING_VALIDATION_REPLACE:
                av_bprintf(&dstbuf, "%s", tctx->string_validation_replacement);
                break;
            }
        }

        if (!invalid || tctx->string_validation == AV_TEXTFORMAT_STRING_VALIDATION_IGNORE)
            av_bprint_append_data(&dstbuf, p0, p-p0);
    }

    if (invalid_chars_nb && tctx->string_validation == AV_TEXTFORMAT_STRING_VALIDATION_REPLACE) {
        av_log(tctx, AV_LOG_WARNING,
               "%d invalid UTF-8 sequence(s) found in string '%s', replaced with '%s'\n",
               invalid_chars_nb, src, tctx->string_validation_replacement);
    }

end:
    av_bprint_finalize(&dstbuf, dstp);
    return ret;
}

struct unit_value {
    union { double d; int64_t i; } val;
    const char *unit;
};

static char *value_string(AVTextFormatContext *tctx, char *buf, int buf_size, struct unit_value uv)
{
    double vald;
    int64_t vali;
    int show_float = 0;

    if (uv.unit == unit_second_str) {
        vald = uv.val.d;
        show_float = 1;
    } else {
        vald = vali = uv.val.i;
    }

    if (uv.unit == unit_second_str && tctx->use_value_sexagesimal_format) {
        double secs;
        int hours, mins;
        secs  = vald;
        mins  = (int)secs / 60;
        secs  = secs - mins * 60;
        hours = mins / 60;
        mins %= 60;
        snprintf(buf, buf_size, "%d:%02d:%09.6f", hours, mins, secs);
    } else {
        const char *prefix_string = "";

        if (tctx->use_value_prefix && vald > 1) {
            int64_t index;

            if (uv.unit == unit_byte_str && tctx->use_byte_value_binary_prefix) {
                index = (int64_t) (log2(vald)) / 10;
                index = av_clip(index, 0, FF_ARRAY_ELEMS(si_prefixes) - 1);
                vald /= si_prefixes[index].bin_val;
                prefix_string = si_prefixes[index].bin_str;
            } else {
                index = (int64_t) (log10(vald)) / 3;
                index = av_clip(index, 0, FF_ARRAY_ELEMS(si_prefixes) - 1);
                vald /= si_prefixes[index].dec_val;
                prefix_string = si_prefixes[index].dec_str;
            }
            vali = vald;
        }

        if (show_float || (tctx->use_value_prefix && vald != (int64_t)vald))
            snprintf(buf, buf_size, "%f", vald);
        else
            snprintf(buf, buf_size, "%"PRId64, vali);
        av_strlcatf(buf, buf_size, "%s%s%s", *prefix_string || tctx->show_value_unit ? " " : "",
                 prefix_string, tctx->show_value_unit ? uv.unit : "");
    }

    return buf;
}


void avtext_print_unit_int(AVTextFormatContext *tctx, const char *key, int value, const char *unit)
{
    char val_str[128];
    struct unit_value uv;
    uv.val.i = value;
    uv.unit = unit;
    avtext_print_string(tctx, key, value_string(tctx, val_str, sizeof(val_str), uv), 0);
}


int avtext_print_string(AVTextFormatContext *tctx, const char *key, const char *val, int flags)
{
    const struct AVTextFormatSection *section = tctx->section[tctx->level];
    int ret = 0;

    if (tctx->show_optional_fields == SHOW_OPTIONAL_FIELDS_NEVER ||
        (tctx->show_optional_fields == SHOW_OPTIONAL_FIELDS_AUTO
        && (flags & AV_TEXTFORMAT_PRINT_STRING_OPTIONAL)
        && !(tctx->formatter->flags & AV_TEXTFORMAT_FLAG_SUPPORTS_OPTIONAL_FIELDS)))
        return 0;

    if (section->show_all_entries || av_dict_get(section->entries_to_show, key, NULL, 0)) {
        if (flags & AV_TEXTFORMAT_PRINT_STRING_VALIDATE) {
            char *key1 = NULL, *val1 = NULL;
            ret = validate_string(tctx, &key1, key);
            if (ret < 0) goto end;
            ret = validate_string(tctx, &val1, val);
            if (ret < 0) goto end;
            tctx->formatter->print_string(tctx, key1, val1);
        end:
            if (ret < 0) {
                av_log(tctx, AV_LOG_ERROR,
                       "Invalid key=value string combination %s=%s in section %s\n",
                       key, val, section->unique_name);
            }
            av_free(key1);
            av_free(val1);
        } else {
            tctx->formatter->print_string(tctx, key, val);
        }

        tctx->nb_item[tctx->level]++;
    }

    return ret;
}

void avtext_print_rational(AVTextFormatContext *tctx,
                                         const char *key, AVRational q, char sep)
{
    char buf[44];
    snprintf(buf, sizeof(buf), "%d%c%d", q.num, sep, q.den);
    avtext_print_string(tctx, key, buf, 0);
}

void avtext_print_time(AVTextFormatContext *tctx, const char *key,
                              int64_t ts, const AVRational *time_base, int is_duration)
{
    char buf[128];

    if ((!is_duration && ts == AV_NOPTS_VALUE) || (is_duration && ts == 0)) {
        avtext_print_string(tctx, key, "N/A", AV_TEXTFORMAT_PRINT_STRING_OPTIONAL);
    } else {
        double d = ts * av_q2d(*time_base);
        struct unit_value uv;
        uv.val.d = d;
        uv.unit = unit_second_str;
        value_string(tctx, buf, sizeof(buf), uv);
        avtext_print_string(tctx, key, buf, 0);
    }
}

void avtext_print_ts(AVTextFormatContext *tctx, const char *key, int64_t ts, int is_duration)
{
    if ((!is_duration && ts == AV_NOPTS_VALUE) || (is_duration && ts == 0)) {
        avtext_print_string(tctx, key, "N/A", AV_TEXTFORMAT_PRINT_STRING_OPTIONAL);
    } else {
        avtext_print_integer(tctx, key, ts);
    }
}

void avtext_print_data(AVTextFormatContext *tctx, const char *name,
                              const uint8_t *data, int size)
{
    AVBPrint bp;
    int offset = 0, l, i;

    av_bprint_init(&bp, 0, AV_BPRINT_SIZE_UNLIMITED);
    av_bprintf(&bp, "\n");
    while (size) {
        av_bprintf(&bp, "%08x: ", offset);
        l = FFMIN(size, 16);
        for (i = 0; i < l; i++) {
            av_bprintf(&bp, "%02x", data[i]);
            if (i & 1)
                av_bprintf(&bp, " ");
        }
        av_bprint_chars(&bp, ' ', 41 - 2 * i - i / 2);
        for (i = 0; i < l; i++)
            av_bprint_chars(&bp, data[i] - 32U < 95 ? data[i] : '.', 1);
        av_bprintf(&bp, "\n");
        offset += l;
        data   += l;
        size   -= l;
    }
    avtext_print_string(tctx, name, bp.str, 0);
    av_bprint_finalize(&bp, NULL);
}

void avtext_print_data_hash(AVTextFormatContext *tctx, const char *name,
                                   const uint8_t *data, int size)
{
    char *p, buf[AV_HASH_MAX_SIZE * 2 + 64] = { 0 };

    if (!tctx->hash)
        return;
    av_hash_init(tctx->hash);
    av_hash_update(tctx->hash, data, size);
    snprintf(buf, sizeof(buf), "%s:", av_hash_get_name(tctx->hash));
    p = buf + strlen(buf);
    av_hash_final_hex(tctx->hash, p, buf + sizeof(buf) - p);
    avtext_print_string(tctx, name, buf, 0);
}

void avtext_print_integers(AVTextFormatContext *tctx, const char *name,
                                  uint8_t *data, int size, const char *format,
                                  int columns, int bytes, int offset_add)
{
    AVBPrint bp;
    int offset = 0, l, i;

    av_bprint_init(&bp, 0, AV_BPRINT_SIZE_UNLIMITED);
    av_bprintf(&bp, "\n");
    while (size) {
        av_bprintf(&bp, "%08x: ", offset);
        l = FFMIN(size, columns);
        for (i = 0; i < l; i++) {
            if      (bytes == 1) av_bprintf(&bp, format, *data);
            else if (bytes == 2) av_bprintf(&bp, format, AV_RN16(data));
            else if (bytes == 4) av_bprintf(&bp, format, AV_RN32(data));
            data += bytes;
            size --;
        }
        av_bprintf(&bp, "\n");
        offset += offset_add;
    }
    avtext_print_string(tctx, name, bp.str, 0);
    av_bprint_finalize(&bp, NULL);
}

static const char *writercontext_get_writer_name(void *p)
{
    AVTextWriterContext *wctx = p;
    return wctx->writer->name;
}

static void *writercontext_child_next(void *obj, void *prev)
{
    AVTextFormatContext *ctx = obj;
    if (!prev && ctx->formatter && ctx->formatter->priv_class && ctx->priv)
        return ctx->priv;
    return NULL;
}

static const AVClass textwriter_class = {
    .class_name = "AVTextWriterContext",
    .item_name  = writercontext_get_writer_name,
    .version    = LIBAVUTIL_VERSION_INT,
    .child_next = writercontext_child_next,
};


void avtextwriter_context_close(AVTextWriterContext **pwctx)
{
    AVTextWriterContext *wctx = *pwctx;

    if (!wctx)
        return;

    if (wctx->writer) {
        if (wctx->writer->uninit)
            wctx->writer->uninit(wctx);
        if (wctx->writer->priv_class)
            av_opt_free(wctx->priv);
    }
    av_freep(&wctx->priv);
    av_freep(pwctx);
}


int avtextwriter_context_open(AVTextWriterContext **pwctx, const AVTextWriter *writer)
{
    AVTextWriterContext *wctx;
    int ret = 0;

    if (!(wctx = av_mallocz(sizeof(AVTextWriterContext)))) {
        ret = AVERROR(ENOMEM);
        goto fail;
    }

    if (!(wctx->priv = av_mallocz(writer->priv_size))) {
        ret = AVERROR(ENOMEM);
        goto fail;
    }

    if (writer->priv_class) {
        void *priv_ctx = wctx->priv;
        *(const AVClass **)priv_ctx = writer->priv_class;
        av_opt_set_defaults(priv_ctx);
    }

    wctx->class = &textwriter_class;
    wctx->writer = writer;

    av_opt_set_defaults(wctx);


    if (wctx->writer->init)
        ret = wctx->writer->init(wctx);
    if (ret < 0)
        goto fail;

    *pwctx = wctx;

    return 0;

fail:
    avtextwriter_context_close(&wctx);
    return ret;
}

static const AVTextFormatter *registered_formatters[7+1];
static void formatters_register_all(void)
{
    static int initialized;

    if (initialized)
        return;
    initialized = 1;

    registered_formatters[0] = &avtextformatter_default;
    registered_formatters[1] = &avtextformatter_compact;
    registered_formatters[2] = &avtextformatter_csv;
    registered_formatters[3] = &avtextformatter_flat;
    registered_formatters[4] = &avtextformatter_ini;
    registered_formatters[5] = &avtextformatter_json;
    registered_formatters[6] = &avtextformatter_xml;
}

const AVTextFormatter *avtext_get_formatter_by_name(const char *name)
{
    formatters_register_all();

    for (int i = 0; registered_formatters[i]; i++)
        if (!strcmp(registered_formatters[i]->name, name))
            return registered_formatters[i];

    return NULL;
}