OSDN Git Service

avfilter/palette{gen,use}: add Copyright
[android-x86/external-ffmpeg.git] / ffprobe.c
1 /*
2  * Copyright (c) 2007-2010 Stefano Sabatini
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 /**
22  * @file
23  * simple media prober based on the FFmpeg libraries
24  */
25
26 #include "config.h"
27 #include "libavutil/ffversion.h"
28
29 #include <string.h>
30
31 #include "libavformat/avformat.h"
32 #include "libavcodec/avcodec.h"
33 #include "libavutil/avassert.h"
34 #include "libavutil/avstring.h"
35 #include "libavutil/bprint.h"
36 #include "libavutil/hash.h"
37 #include "libavutil/opt.h"
38 #include "libavutil/pixdesc.h"
39 #include "libavutil/dict.h"
40 #include "libavutil/libm.h"
41 #include "libavutil/parseutils.h"
42 #include "libavutil/timecode.h"
43 #include "libavutil/timestamp.h"
44 #include "libavdevice/avdevice.h"
45 #include "libswscale/swscale.h"
46 #include "libswresample/swresample.h"
47 #include "libpostproc/postprocess.h"
48 #include "cmdutils.h"
49
50 const char program_name[] = "ffprobe";
51 const int program_birth_year = 2007;
52
53 static int do_bitexact = 0;
54 static int do_count_frames = 0;
55 static int do_count_packets = 0;
56 static int do_read_frames  = 0;
57 static int do_read_packets = 0;
58 static int do_show_chapters = 0;
59 static int do_show_error   = 0;
60 static int do_show_format  = 0;
61 static int do_show_frames  = 0;
62 static int do_show_packets = 0;
63 static int do_show_programs = 0;
64 static int do_show_streams = 0;
65 static int do_show_stream_disposition = 0;
66 static int do_show_data    = 0;
67 static int do_show_program_version  = 0;
68 static int do_show_library_versions = 0;
69 static int do_show_pixel_formats = 0;
70 static int do_show_pixel_format_flags = 0;
71 static int do_show_pixel_format_components = 0;
72
73 static int do_show_chapter_tags = 0;
74 static int do_show_format_tags = 0;
75 static int do_show_frame_tags = 0;
76 static int do_show_program_tags = 0;
77 static int do_show_stream_tags = 0;
78
79 static int show_value_unit              = 0;
80 static int use_value_prefix             = 0;
81 static int use_byte_value_binary_prefix = 0;
82 static int use_value_sexagesimal_format = 0;
83 static int show_private_data            = 1;
84
85 static char *print_format;
86 static char *stream_specifier;
87 static char *show_data_hash;
88
89 typedef struct ReadInterval {
90     int id;             ///< identifier
91     int64_t start, end; ///< start, end in second/AV_TIME_BASE units
92     int has_start, has_end;
93     int start_is_offset, end_is_offset;
94     int duration_frames;
95 } ReadInterval;
96
97 static ReadInterval *read_intervals;
98 static int read_intervals_nb = 0;
99
100 /* section structure definition */
101
102 #define SECTION_MAX_NB_CHILDREN 10
103
104 struct section {
105     int id;             ///< unique id identifying a section
106     const char *name;
107
108 #define SECTION_FLAG_IS_WRAPPER      1 ///< the section only contains other sections, but has no data at its own level
109 #define SECTION_FLAG_IS_ARRAY        2 ///< the section contains an array of elements of the same type
110 #define SECTION_FLAG_HAS_VARIABLE_FIELDS 4 ///< the section may contain a variable number of fields with variable keys.
111                                            ///  For these sections the element_name field is mandatory.
112     int flags;
113     int children_ids[SECTION_MAX_NB_CHILDREN+1]; ///< list of children section IDS, terminated by -1
114     const char *element_name; ///< name of the contained element, if provided
115     const char *unique_name;  ///< unique section name, in case the name is ambiguous
116     AVDictionary *entries_to_show;
117     int show_all_entries;
118 };
119
120 typedef enum {
121     SECTION_ID_NONE = -1,
122     SECTION_ID_CHAPTER,
123     SECTION_ID_CHAPTER_TAGS,
124     SECTION_ID_CHAPTERS,
125     SECTION_ID_ERROR,
126     SECTION_ID_FORMAT,
127     SECTION_ID_FORMAT_TAGS,
128     SECTION_ID_FRAME,
129     SECTION_ID_FRAMES,
130     SECTION_ID_FRAME_TAGS,
131     SECTION_ID_FRAME_SIDE_DATA_LIST,
132     SECTION_ID_FRAME_SIDE_DATA,
133     SECTION_ID_LIBRARY_VERSION,
134     SECTION_ID_LIBRARY_VERSIONS,
135     SECTION_ID_PACKET,
136     SECTION_ID_PACKETS,
137     SECTION_ID_PACKETS_AND_FRAMES,
138     SECTION_ID_PIXEL_FORMAT,
139     SECTION_ID_PIXEL_FORMAT_FLAGS,
140     SECTION_ID_PIXEL_FORMAT_COMPONENT,
141     SECTION_ID_PIXEL_FORMAT_COMPONENTS,
142     SECTION_ID_PIXEL_FORMATS,
143     SECTION_ID_PROGRAM_STREAM_DISPOSITION,
144     SECTION_ID_PROGRAM_STREAM_TAGS,
145     SECTION_ID_PROGRAM,
146     SECTION_ID_PROGRAM_STREAMS,
147     SECTION_ID_PROGRAM_STREAM,
148     SECTION_ID_PROGRAM_TAGS,
149     SECTION_ID_PROGRAM_VERSION,
150     SECTION_ID_PROGRAMS,
151     SECTION_ID_ROOT,
152     SECTION_ID_STREAM,
153     SECTION_ID_STREAM_DISPOSITION,
154     SECTION_ID_STREAMS,
155     SECTION_ID_STREAM_TAGS,
156     SECTION_ID_SUBTITLE,
157 } SectionID;
158
159 static struct section sections[] = {
160     [SECTION_ID_CHAPTERS] =           { SECTION_ID_CHAPTERS, "chapters", SECTION_FLAG_IS_ARRAY, { SECTION_ID_CHAPTER, -1 } },
161     [SECTION_ID_CHAPTER] =            { SECTION_ID_CHAPTER, "chapter", 0, { SECTION_ID_CHAPTER_TAGS, -1 } },
162     [SECTION_ID_CHAPTER_TAGS] =       { SECTION_ID_CHAPTER_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "chapter_tags" },
163     [SECTION_ID_ERROR] =              { SECTION_ID_ERROR, "error", 0, { -1 } },
164     [SECTION_ID_FORMAT] =             { SECTION_ID_FORMAT, "format", 0, { SECTION_ID_FORMAT_TAGS, -1 } },
165     [SECTION_ID_FORMAT_TAGS] =        { SECTION_ID_FORMAT_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "format_tags" },
166     [SECTION_ID_FRAMES] =             { SECTION_ID_FRAMES, "frames", SECTION_FLAG_IS_ARRAY, { SECTION_ID_FRAME, SECTION_ID_SUBTITLE, -1 } },
167     [SECTION_ID_FRAME] =              { SECTION_ID_FRAME, "frame", 0, { SECTION_ID_FRAME_TAGS, SECTION_ID_FRAME_SIDE_DATA_LIST, -1 } },
168     [SECTION_ID_FRAME_TAGS] =         { SECTION_ID_FRAME_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "frame_tags" },
169     [SECTION_ID_FRAME_SIDE_DATA_LIST] ={ SECTION_ID_FRAME_SIDE_DATA_LIST, "side_data_list", SECTION_FLAG_IS_ARRAY, { SECTION_ID_FRAME_SIDE_DATA, -1 } },
170     [SECTION_ID_FRAME_SIDE_DATA] =     { SECTION_ID_FRAME_SIDE_DATA, "side_data", 0, { -1 } },
171     [SECTION_ID_LIBRARY_VERSIONS] =   { SECTION_ID_LIBRARY_VERSIONS, "library_versions", SECTION_FLAG_IS_ARRAY, { SECTION_ID_LIBRARY_VERSION, -1 } },
172     [SECTION_ID_LIBRARY_VERSION] =    { SECTION_ID_LIBRARY_VERSION, "library_version", 0, { -1 } },
173     [SECTION_ID_PACKETS] =            { SECTION_ID_PACKETS, "packets", SECTION_FLAG_IS_ARRAY, { SECTION_ID_PACKET, -1} },
174     [SECTION_ID_PACKETS_AND_FRAMES] = { SECTION_ID_PACKETS_AND_FRAMES, "packets_and_frames", SECTION_FLAG_IS_ARRAY, { SECTION_ID_PACKET, -1} },
175     [SECTION_ID_PACKET] =             { SECTION_ID_PACKET, "packet", 0, { -1 } },
176     [SECTION_ID_PIXEL_FORMATS] =      { SECTION_ID_PIXEL_FORMATS, "pixel_formats", SECTION_FLAG_IS_ARRAY, { SECTION_ID_PIXEL_FORMAT, -1 } },
177     [SECTION_ID_PIXEL_FORMAT] =       { SECTION_ID_PIXEL_FORMAT, "pixel_format", 0, { SECTION_ID_PIXEL_FORMAT_FLAGS, SECTION_ID_PIXEL_FORMAT_COMPONENTS, -1 } },
178     [SECTION_ID_PIXEL_FORMAT_FLAGS] = { SECTION_ID_PIXEL_FORMAT_FLAGS, "flags", 0, { -1 }, .unique_name = "pixel_format_flags" },
179     [SECTION_ID_PIXEL_FORMAT_COMPONENTS] = { SECTION_ID_PIXEL_FORMAT_COMPONENTS, "components", SECTION_FLAG_IS_ARRAY, {SECTION_ID_PIXEL_FORMAT_COMPONENT, -1 }, .unique_name = "pixel_format_components" },
180     [SECTION_ID_PIXEL_FORMAT_COMPONENT]  = { SECTION_ID_PIXEL_FORMAT_COMPONENT, "component", 0, { -1 } },
181     [SECTION_ID_PROGRAM_STREAM_DISPOSITION] = { SECTION_ID_PROGRAM_STREAM_DISPOSITION, "disposition", 0, { -1 }, .unique_name = "program_stream_disposition" },
182     [SECTION_ID_PROGRAM_STREAM_TAGS] =        { SECTION_ID_PROGRAM_STREAM_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "program_stream_tags" },
183     [SECTION_ID_PROGRAM] =                    { SECTION_ID_PROGRAM, "program", 0, { SECTION_ID_PROGRAM_TAGS, SECTION_ID_PROGRAM_STREAMS, -1 } },
184     [SECTION_ID_PROGRAM_STREAMS] =            { SECTION_ID_PROGRAM_STREAMS, "streams", SECTION_FLAG_IS_ARRAY, { SECTION_ID_PROGRAM_STREAM, -1 }, .unique_name = "program_streams" },
185     [SECTION_ID_PROGRAM_STREAM] =             { SECTION_ID_PROGRAM_STREAM, "stream", 0, { SECTION_ID_PROGRAM_STREAM_DISPOSITION, SECTION_ID_PROGRAM_STREAM_TAGS, -1 }, .unique_name = "program_stream" },
186     [SECTION_ID_PROGRAM_TAGS] =               { SECTION_ID_PROGRAM_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "program_tags" },
187     [SECTION_ID_PROGRAM_VERSION] =    { SECTION_ID_PROGRAM_VERSION, "program_version", 0, { -1 } },
188     [SECTION_ID_PROGRAMS] =                   { SECTION_ID_PROGRAMS, "programs", SECTION_FLAG_IS_ARRAY, { SECTION_ID_PROGRAM, -1 } },
189     [SECTION_ID_ROOT] =               { SECTION_ID_ROOT, "root", SECTION_FLAG_IS_WRAPPER,
190                                         { SECTION_ID_CHAPTERS, SECTION_ID_FORMAT, SECTION_ID_FRAMES, SECTION_ID_PROGRAMS, SECTION_ID_STREAMS,
191                                           SECTION_ID_PACKETS, SECTION_ID_ERROR, SECTION_ID_PROGRAM_VERSION, SECTION_ID_LIBRARY_VERSIONS,
192                                           SECTION_ID_PIXEL_FORMATS, -1} },
193     [SECTION_ID_STREAMS] =            { SECTION_ID_STREAMS, "streams", SECTION_FLAG_IS_ARRAY, { SECTION_ID_STREAM, -1 } },
194     [SECTION_ID_STREAM] =             { SECTION_ID_STREAM, "stream", 0, { SECTION_ID_STREAM_DISPOSITION, SECTION_ID_STREAM_TAGS, -1 } },
195     [SECTION_ID_STREAM_DISPOSITION] = { SECTION_ID_STREAM_DISPOSITION, "disposition", 0, { -1 }, .unique_name = "stream_disposition" },
196     [SECTION_ID_STREAM_TAGS] =        { SECTION_ID_STREAM_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "stream_tags" },
197     [SECTION_ID_SUBTITLE] =           { SECTION_ID_SUBTITLE, "subtitle", 0, { -1 } },
198 };
199
200 static const OptionDef *options;
201
202 /* FFprobe context */
203 static const char *input_filename;
204 static AVInputFormat *iformat = NULL;
205
206 static struct AVHashContext *hash;
207
208 static const char *const binary_unit_prefixes [] = { "", "Ki", "Mi", "Gi", "Ti", "Pi" };
209 static const char *const decimal_unit_prefixes[] = { "", "K" , "M" , "G" , "T" , "P"  };
210
211 static const char unit_second_str[]         = "s"    ;
212 static const char unit_hertz_str[]          = "Hz"   ;
213 static const char unit_byte_str[]           = "byte" ;
214 static const char unit_bit_per_second_str[] = "bit/s";
215
216 static int nb_streams;
217 static uint64_t *nb_streams_packets;
218 static uint64_t *nb_streams_frames;
219 static int *selected_streams;
220
221 static void ffprobe_cleanup(int ret)
222 {
223     int i;
224     for (i = 0; i < FF_ARRAY_ELEMS(sections); i++)
225         av_dict_free(&(sections[i].entries_to_show));
226 }
227
228 struct unit_value {
229     union { double d; long long int i; } val;
230     const char *unit;
231 };
232
233 static char *value_string(char *buf, int buf_size, struct unit_value uv)
234 {
235     double vald;
236     long long int vali;
237     int show_float = 0;
238
239     if (uv.unit == unit_second_str) {
240         vald = uv.val.d;
241         show_float = 1;
242     } else {
243         vald = vali = uv.val.i;
244     }
245
246     if (uv.unit == unit_second_str && use_value_sexagesimal_format) {
247         double secs;
248         int hours, mins;
249         secs  = vald;
250         mins  = (int)secs / 60;
251         secs  = secs - mins * 60;
252         hours = mins / 60;
253         mins %= 60;
254         snprintf(buf, buf_size, "%d:%02d:%09.6f", hours, mins, secs);
255     } else {
256         const char *prefix_string = "";
257
258         if (use_value_prefix && vald > 1) {
259             long long int index;
260
261             if (uv.unit == unit_byte_str && use_byte_value_binary_prefix) {
262                 index = (long long int) (log2(vald)) / 10;
263                 index = av_clip(index, 0, FF_ARRAY_ELEMS(binary_unit_prefixes) - 1);
264                 vald /= exp2(index * 10);
265                 prefix_string = binary_unit_prefixes[index];
266             } else {
267                 index = (long long int) (log10(vald)) / 3;
268                 index = av_clip(index, 0, FF_ARRAY_ELEMS(decimal_unit_prefixes) - 1);
269                 vald /= pow(10, index * 3);
270                 prefix_string = decimal_unit_prefixes[index];
271             }
272             vali = vald;
273         }
274
275         if (show_float || (use_value_prefix && vald != (long long int)vald))
276             snprintf(buf, buf_size, "%f", vald);
277         else
278             snprintf(buf, buf_size, "%lld", vali);
279         av_strlcatf(buf, buf_size, "%s%s%s", *prefix_string || show_value_unit ? " " : "",
280                  prefix_string, show_value_unit ? uv.unit : "");
281     }
282
283     return buf;
284 }
285
286 /* WRITERS API */
287
288 typedef struct WriterContext WriterContext;
289
290 #define WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS 1
291 #define WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER 2
292
293 typedef enum {
294     WRITER_STRING_VALIDATION_FAIL,
295     WRITER_STRING_VALIDATION_REPLACE,
296     WRITER_STRING_VALIDATION_IGNORE,
297     WRITER_STRING_VALIDATION_NB
298 } StringValidation;
299
300 typedef struct Writer {
301     const AVClass *priv_class;      ///< private class of the writer, if any
302     int priv_size;                  ///< private size for the writer context
303     const char *name;
304
305     int  (*init)  (WriterContext *wctx);
306     void (*uninit)(WriterContext *wctx);
307
308     void (*print_section_header)(WriterContext *wctx);
309     void (*print_section_footer)(WriterContext *wctx);
310     void (*print_integer)       (WriterContext *wctx, const char *, long long int);
311     void (*print_rational)      (WriterContext *wctx, AVRational *q, char *sep);
312     void (*print_string)        (WriterContext *wctx, const char *, const char *);
313     int flags;                  ///< a combination or WRITER_FLAG_*
314 } Writer;
315
316 #define SECTION_MAX_NB_LEVELS 10
317
318 struct WriterContext {
319     const AVClass *class;           ///< class of the writer
320     const Writer *writer;           ///< the Writer of which this is an instance
321     char *name;                     ///< name of this writer instance
322     void *priv;                     ///< private data for use by the filter
323
324     const struct section *sections; ///< array containing all sections
325     int nb_sections;                ///< number of sections
326
327     int level;                      ///< current level, starting from 0
328
329     /** number of the item printed in the given section, starting from 0 */
330     unsigned int nb_item[SECTION_MAX_NB_LEVELS];
331
332     /** section per each level */
333     const struct section *section[SECTION_MAX_NB_LEVELS];
334     AVBPrint section_pbuf[SECTION_MAX_NB_LEVELS]; ///< generic print buffer dedicated to each section,
335                                                   ///  used by various writers
336
337     unsigned int nb_section_packet; ///< number of the packet section in case we are in "packets_and_frames" section
338     unsigned int nb_section_frame;  ///< number of the frame  section in case we are in "packets_and_frames" section
339     unsigned int nb_section_packet_frame; ///< nb_section_packet or nb_section_frame according if is_packets_and_frames
340
341     StringValidation string_validation;
342     char *string_validation_replacement;
343     unsigned int string_validation_utf8_flags;
344 };
345
346 static const char *writer_get_name(void *p)
347 {
348     WriterContext *wctx = p;
349     return wctx->writer->name;
350 }
351
352 #define OFFSET(x) offsetof(WriterContext, x)
353
354 static const AVOption writer_options[] = {
355     { "string_validation", "set string validation mode",
356       OFFSET(string_validation), AV_OPT_TYPE_INT, {.i64=WRITER_STRING_VALIDATION_REPLACE}, 0, WRITER_STRING_VALIDATION_NB-1, .unit = "sv" },
357     { "sv", "set string validation mode",
358       OFFSET(string_validation), AV_OPT_TYPE_INT, {.i64=WRITER_STRING_VALIDATION_REPLACE}, 0, WRITER_STRING_VALIDATION_NB-1, .unit = "sv" },
359     { "ignore",  NULL, 0, AV_OPT_TYPE_CONST, {.i64 = WRITER_STRING_VALIDATION_IGNORE},  .unit = "sv" },
360     { "replace", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = WRITER_STRING_VALIDATION_REPLACE}, .unit = "sv" },
361     { "fail",    NULL, 0, AV_OPT_TYPE_CONST, {.i64 = WRITER_STRING_VALIDATION_FAIL},    .unit = "sv" },
362     { "string_validation_replacement", "set string validation replacement string", OFFSET(string_validation_replacement), AV_OPT_TYPE_STRING, {.str=""}},
363     { "svr", "set string validation replacement string", OFFSET(string_validation_replacement), AV_OPT_TYPE_STRING, {.str="\xEF\xBF\xBD"}},
364     { NULL }
365 };
366
367 static void *writer_child_next(void *obj, void *prev)
368 {
369     WriterContext *ctx = obj;
370     if (!prev && ctx->writer && ctx->writer->priv_class && ctx->priv)
371         return ctx->priv;
372     return NULL;
373 }
374
375 static const AVClass writer_class = {
376     .class_name = "Writer",
377     .item_name  = writer_get_name,
378     .option     = writer_options,
379     .version    = LIBAVUTIL_VERSION_INT,
380     .child_next = writer_child_next,
381 };
382
383 static void writer_close(WriterContext **wctx)
384 {
385     int i;
386
387     if (!*wctx)
388         return;
389
390     if ((*wctx)->writer->uninit)
391         (*wctx)->writer->uninit(*wctx);
392     for (i = 0; i < SECTION_MAX_NB_LEVELS; i++)
393         av_bprint_finalize(&(*wctx)->section_pbuf[i], NULL);
394     if ((*wctx)->writer->priv_class)
395         av_opt_free((*wctx)->priv);
396     av_freep(&((*wctx)->priv));
397     av_opt_free(*wctx);
398     av_freep(wctx);
399 }
400
401 static void bprint_bytes(AVBPrint *bp, const uint8_t *ubuf, size_t ubuf_size)
402 {
403     int i;
404     av_bprintf(bp, "0X");
405     for (i = 0; i < ubuf_size; i++)
406         av_bprintf(bp, "%02X", ubuf[i]);
407 }
408
409
410 static int writer_open(WriterContext **wctx, const Writer *writer, const char *args,
411                        const struct section *sections, int nb_sections)
412 {
413     int i, ret = 0;
414
415     if (!(*wctx = av_mallocz(sizeof(WriterContext)))) {
416         ret = AVERROR(ENOMEM);
417         goto fail;
418     }
419
420     if (!((*wctx)->priv = av_mallocz(writer->priv_size))) {
421         ret = AVERROR(ENOMEM);
422         goto fail;
423     }
424
425     (*wctx)->class = &writer_class;
426     (*wctx)->writer = writer;
427     (*wctx)->level = -1;
428     (*wctx)->sections = sections;
429     (*wctx)->nb_sections = nb_sections;
430
431     av_opt_set_defaults(*wctx);
432
433     if (writer->priv_class) {
434         void *priv_ctx = (*wctx)->priv;
435         *((const AVClass **)priv_ctx) = writer->priv_class;
436         av_opt_set_defaults(priv_ctx);
437     }
438
439     /* convert options to dictionary */
440     if (args) {
441         AVDictionary *opts = NULL;
442         AVDictionaryEntry *opt = NULL;
443
444         if ((ret = av_dict_parse_string(&opts, args, "=", ":", 0)) < 0) {
445             av_log(*wctx, AV_LOG_ERROR, "Failed to parse option string '%s' provided to writer context\n", args);
446             av_dict_free(&opts);
447             goto fail;
448         }
449
450         while ((opt = av_dict_get(opts, "", opt, AV_DICT_IGNORE_SUFFIX))) {
451             if ((ret = av_opt_set(*wctx, opt->key, opt->value, AV_OPT_SEARCH_CHILDREN)) < 0) {
452                 av_log(*wctx, AV_LOG_ERROR, "Failed to set option '%s' with value '%s' provided to writer context\n",
453                        opt->key, opt->value);
454                 av_dict_free(&opts);
455                 goto fail;
456             }
457         }
458
459         av_dict_free(&opts);
460     }
461
462     /* validate replace string */
463     {
464         const uint8_t *p = (*wctx)->string_validation_replacement;
465         const uint8_t *endp = p + strlen(p);
466         while (*p) {
467             const uint8_t *p0 = p;
468             int32_t code;
469             ret = av_utf8_decode(&code, &p, endp, (*wctx)->string_validation_utf8_flags);
470             if (ret < 0) {
471                 AVBPrint bp;
472                 av_bprint_init(&bp, 0, AV_BPRINT_SIZE_AUTOMATIC);
473                 bprint_bytes(&bp, p0, p-p0),
474                     av_log(wctx, AV_LOG_ERROR,
475                            "Invalid UTF8 sequence %s found in string validation replace '%s'\n",
476                            bp.str, (*wctx)->string_validation_replacement);
477                 return ret;
478             }
479         }
480     }
481
482     for (i = 0; i < SECTION_MAX_NB_LEVELS; i++)
483         av_bprint_init(&(*wctx)->section_pbuf[i], 1, AV_BPRINT_SIZE_UNLIMITED);
484
485     if ((*wctx)->writer->init)
486         ret = (*wctx)->writer->init(*wctx);
487     if (ret < 0)
488         goto fail;
489
490     return 0;
491
492 fail:
493     writer_close(wctx);
494     return ret;
495 }
496
497 static inline void writer_print_section_header(WriterContext *wctx,
498                                                int section_id)
499 {
500     int parent_section_id;
501     wctx->level++;
502     av_assert0(wctx->level < SECTION_MAX_NB_LEVELS);
503     parent_section_id = wctx->level ?
504         (wctx->section[wctx->level-1])->id : SECTION_ID_NONE;
505
506     wctx->nb_item[wctx->level] = 0;
507     wctx->section[wctx->level] = &wctx->sections[section_id];
508
509     if (section_id == SECTION_ID_PACKETS_AND_FRAMES) {
510         wctx->nb_section_packet = wctx->nb_section_frame =
511         wctx->nb_section_packet_frame = 0;
512     } else if (parent_section_id == SECTION_ID_PACKETS_AND_FRAMES) {
513         wctx->nb_section_packet_frame = section_id == SECTION_ID_PACKET ?
514             wctx->nb_section_packet : wctx->nb_section_frame;
515     }
516
517     if (wctx->writer->print_section_header)
518         wctx->writer->print_section_header(wctx);
519 }
520
521 static inline void writer_print_section_footer(WriterContext *wctx)
522 {
523     int section_id = wctx->section[wctx->level]->id;
524     int parent_section_id = wctx->level ?
525         wctx->section[wctx->level-1]->id : SECTION_ID_NONE;
526
527     if (parent_section_id != SECTION_ID_NONE)
528         wctx->nb_item[wctx->level-1]++;
529     if (parent_section_id == SECTION_ID_PACKETS_AND_FRAMES) {
530         if (section_id == SECTION_ID_PACKET) wctx->nb_section_packet++;
531         else                                     wctx->nb_section_frame++;
532     }
533     if (wctx->writer->print_section_footer)
534         wctx->writer->print_section_footer(wctx);
535     wctx->level--;
536 }
537
538 static inline void writer_print_integer(WriterContext *wctx,
539                                         const char *key, long long int val)
540 {
541     const struct section *section = wctx->section[wctx->level];
542
543     if (section->show_all_entries || av_dict_get(section->entries_to_show, key, NULL, 0)) {
544         wctx->writer->print_integer(wctx, key, val);
545         wctx->nb_item[wctx->level]++;
546     }
547 }
548
549 static inline int validate_string(WriterContext *wctx, char **dstp, const char *src)
550 {
551     const uint8_t *p, *endp;
552     AVBPrint dstbuf;
553     int invalid_chars_nb = 0, ret = 0;
554
555     av_bprint_init(&dstbuf, 0, AV_BPRINT_SIZE_UNLIMITED);
556
557     endp = src + strlen(src);
558     for (p = (uint8_t *)src; *p;) {
559         uint32_t code;
560         int invalid = 0;
561         const uint8_t *p0 = p;
562
563         if (av_utf8_decode(&code, &p, endp, wctx->string_validation_utf8_flags) < 0) {
564             AVBPrint bp;
565             av_bprint_init(&bp, 0, AV_BPRINT_SIZE_AUTOMATIC);
566             bprint_bytes(&bp, p0, p-p0);
567             av_log(wctx, AV_LOG_DEBUG,
568                    "Invalid UTF-8 sequence %s found in string '%s'\n", bp.str, src);
569             invalid = 1;
570         }
571
572         if (invalid) {
573             invalid_chars_nb++;
574
575             switch (wctx->string_validation) {
576             case WRITER_STRING_VALIDATION_FAIL:
577                 av_log(wctx, AV_LOG_ERROR,
578                        "Invalid UTF-8 sequence found in string '%s'\n", src);
579                 ret = AVERROR_INVALIDDATA;
580                 goto end;
581                 break;
582
583             case WRITER_STRING_VALIDATION_REPLACE:
584                 av_bprintf(&dstbuf, "%s", wctx->string_validation_replacement);
585                 break;
586             }
587         }
588
589         if (!invalid || wctx->string_validation == WRITER_STRING_VALIDATION_IGNORE)
590             av_bprint_append_data(&dstbuf, p0, p-p0);
591     }
592
593     if (invalid_chars_nb && wctx->string_validation == WRITER_STRING_VALIDATION_REPLACE) {
594         av_log(wctx, AV_LOG_WARNING,
595                "%d invalid UTF-8 sequence(s) found in string '%s', replaced with '%s'\n",
596                invalid_chars_nb, src, wctx->string_validation_replacement);
597     }
598
599 end:
600     av_bprint_finalize(&dstbuf, dstp);
601     return ret;
602 }
603
604 #define PRINT_STRING_OPT      1
605 #define PRINT_STRING_VALIDATE 2
606
607 static inline int writer_print_string(WriterContext *wctx,
608                                       const char *key, const char *val, int flags)
609 {
610     const struct section *section = wctx->section[wctx->level];
611     int ret = 0;
612
613     if ((flags & PRINT_STRING_OPT)
614         && !(wctx->writer->flags & WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS))
615         return 0;
616
617     if (section->show_all_entries || av_dict_get(section->entries_to_show, key, NULL, 0)) {
618         if (flags & PRINT_STRING_VALIDATE) {
619             char *key1 = NULL, *val1 = NULL;
620             ret = validate_string(wctx, &key1, key);
621             if (ret < 0) goto end;
622             ret = validate_string(wctx, &val1, val);
623             if (ret < 0) goto end;
624             wctx->writer->print_string(wctx, key1, val1);
625         end:
626             if (ret < 0) {
627                 av_log(wctx, AV_LOG_ERROR,
628                        "Invalid key=value string combination %s=%s in section %s\n",
629                        key, val, section->unique_name);
630             }
631             av_free(key1);
632             av_free(val1);
633         } else {
634             wctx->writer->print_string(wctx, key, val);
635         }
636
637         wctx->nb_item[wctx->level]++;
638     }
639
640     return ret;
641 }
642
643 static inline void writer_print_rational(WriterContext *wctx,
644                                          const char *key, AVRational q, char sep)
645 {
646     AVBPrint buf;
647     av_bprint_init(&buf, 0, AV_BPRINT_SIZE_AUTOMATIC);
648     av_bprintf(&buf, "%d%c%d", q.num, sep, q.den);
649     writer_print_string(wctx, key, buf.str, 0);
650 }
651
652 static void writer_print_time(WriterContext *wctx, const char *key,
653                               int64_t ts, const AVRational *time_base, int is_duration)
654 {
655     char buf[128];
656
657     if ((!is_duration && ts == AV_NOPTS_VALUE) || (is_duration && ts == 0)) {
658         writer_print_string(wctx, key, "N/A", PRINT_STRING_OPT);
659     } else {
660         double d = ts * av_q2d(*time_base);
661         struct unit_value uv;
662         uv.val.d = d;
663         uv.unit = unit_second_str;
664         value_string(buf, sizeof(buf), uv);
665         writer_print_string(wctx, key, buf, 0);
666     }
667 }
668
669 static void writer_print_ts(WriterContext *wctx, const char *key, int64_t ts, int is_duration)
670 {
671     if ((!is_duration && ts == AV_NOPTS_VALUE) || (is_duration && ts == 0)) {
672         writer_print_string(wctx, key, "N/A", PRINT_STRING_OPT);
673     } else {
674         writer_print_integer(wctx, key, ts);
675     }
676 }
677
678 static void writer_print_data(WriterContext *wctx, const char *name,
679                               uint8_t *data, int size)
680 {
681     AVBPrint bp;
682     int offset = 0, l, i;
683
684     av_bprint_init(&bp, 0, AV_BPRINT_SIZE_UNLIMITED);
685     av_bprintf(&bp, "\n");
686     while (size) {
687         av_bprintf(&bp, "%08x: ", offset);
688         l = FFMIN(size, 16);
689         for (i = 0; i < l; i++) {
690             av_bprintf(&bp, "%02x", data[i]);
691             if (i & 1)
692                 av_bprintf(&bp, " ");
693         }
694         av_bprint_chars(&bp, ' ', 41 - 2 * i - i / 2);
695         for (i = 0; i < l; i++)
696             av_bprint_chars(&bp, data[i] - 32U < 95 ? data[i] : '.', 1);
697         av_bprintf(&bp, "\n");
698         offset += l;
699         data   += l;
700         size   -= l;
701     }
702     writer_print_string(wctx, name, bp.str, 0);
703     av_bprint_finalize(&bp, NULL);
704 }
705
706 static void writer_print_data_hash(WriterContext *wctx, const char *name,
707                                    uint8_t *data, int size)
708 {
709     char *p, buf[AV_HASH_MAX_SIZE * 2 + 64] = { 0 };
710
711     if (!hash)
712         return;
713     av_hash_init(hash);
714     av_hash_update(hash, data, size);
715     snprintf(buf, sizeof(buf), "%s:", av_hash_get_name(hash));
716     p = buf + strlen(buf);
717     av_hash_final_hex(hash, p, buf + sizeof(buf) - p);
718     writer_print_string(wctx, name, buf, 0);
719 }
720
721 #define MAX_REGISTERED_WRITERS_NB 64
722
723 static const Writer *registered_writers[MAX_REGISTERED_WRITERS_NB + 1];
724
725 static int writer_register(const Writer *writer)
726 {
727     static int next_registered_writer_idx = 0;
728
729     if (next_registered_writer_idx == MAX_REGISTERED_WRITERS_NB)
730         return AVERROR(ENOMEM);
731
732     registered_writers[next_registered_writer_idx++] = writer;
733     return 0;
734 }
735
736 static const Writer *writer_get_by_name(const char *name)
737 {
738     int i;
739
740     for (i = 0; registered_writers[i]; i++)
741         if (!strcmp(registered_writers[i]->name, name))
742             return registered_writers[i];
743
744     return NULL;
745 }
746
747
748 /* WRITERS */
749
750 #define DEFINE_WRITER_CLASS(name)                   \
751 static const char *name##_get_name(void *ctx)       \
752 {                                                   \
753     return #name ;                                  \
754 }                                                   \
755 static const AVClass name##_class = {               \
756     .class_name = #name,                            \
757     .item_name  = name##_get_name,                  \
758     .option     = name##_options                    \
759 }
760
761 /* Default output */
762
763 typedef struct DefaultContext {
764     const AVClass *class;
765     int nokey;
766     int noprint_wrappers;
767     int nested_section[SECTION_MAX_NB_LEVELS];
768 } DefaultContext;
769
770 #undef OFFSET
771 #define OFFSET(x) offsetof(DefaultContext, x)
772
773 static const AVOption default_options[] = {
774     { "noprint_wrappers", "do not print headers and footers", OFFSET(noprint_wrappers), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
775     { "nw",               "do not print headers and footers", OFFSET(noprint_wrappers), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
776     { "nokey",          "force no key printing",     OFFSET(nokey),          AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
777     { "nk",             "force no key printing",     OFFSET(nokey),          AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
778     {NULL},
779 };
780
781 DEFINE_WRITER_CLASS(default);
782
783 /* lame uppercasing routine, assumes the string is lower case ASCII */
784 static inline char *upcase_string(char *dst, size_t dst_size, const char *src)
785 {
786     int i;
787     for (i = 0; src[i] && i < dst_size-1; i++)
788         dst[i] = av_toupper(src[i]);
789     dst[i] = 0;
790     return dst;
791 }
792
793 static void default_print_section_header(WriterContext *wctx)
794 {
795     DefaultContext *def = wctx->priv;
796     char buf[32];
797     const struct section *section = wctx->section[wctx->level];
798     const struct section *parent_section = wctx->level ?
799         wctx->section[wctx->level-1] : NULL;
800
801     av_bprint_clear(&wctx->section_pbuf[wctx->level]);
802     if (parent_section &&
803         !(parent_section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY))) {
804         def->nested_section[wctx->level] = 1;
805         av_bprintf(&wctx->section_pbuf[wctx->level], "%s%s:",
806                    wctx->section_pbuf[wctx->level-1].str,
807                    upcase_string(buf, sizeof(buf),
808                                  av_x_if_null(section->element_name, section->name)));
809     }
810
811     if (def->noprint_wrappers || def->nested_section[wctx->level])
812         return;
813
814     if (!(section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY)))
815         printf("[%s]\n", upcase_string(buf, sizeof(buf), section->name));
816 }
817
818 static void default_print_section_footer(WriterContext *wctx)
819 {
820     DefaultContext *def = wctx->priv;
821     const struct section *section = wctx->section[wctx->level];
822     char buf[32];
823
824     if (def->noprint_wrappers || def->nested_section[wctx->level])
825         return;
826
827     if (!(section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY)))
828         printf("[/%s]\n", upcase_string(buf, sizeof(buf), section->name));
829 }
830
831 static void default_print_str(WriterContext *wctx, const char *key, const char *value)
832 {
833     DefaultContext *def = wctx->priv;
834
835     if (!def->nokey)
836         printf("%s%s=", wctx->section_pbuf[wctx->level].str, key);
837     printf("%s\n", value);
838 }
839
840 static void default_print_int(WriterContext *wctx, const char *key, long long int value)
841 {
842     DefaultContext *def = wctx->priv;
843
844     if (!def->nokey)
845         printf("%s%s=", wctx->section_pbuf[wctx->level].str, key);
846     printf("%lld\n", value);
847 }
848
849 static const Writer default_writer = {
850     .name                  = "default",
851     .priv_size             = sizeof(DefaultContext),
852     .print_section_header  = default_print_section_header,
853     .print_section_footer  = default_print_section_footer,
854     .print_integer         = default_print_int,
855     .print_string          = default_print_str,
856     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
857     .priv_class            = &default_class,
858 };
859
860 /* Compact output */
861
862 /**
863  * Apply C-language-like string escaping.
864  */
865 static const char *c_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
866 {
867     const char *p;
868
869     for (p = src; *p; p++) {
870         switch (*p) {
871         case '\b': av_bprintf(dst, "%s", "\\b");  break;
872         case '\f': av_bprintf(dst, "%s", "\\f");  break;
873         case '\n': av_bprintf(dst, "%s", "\\n");  break;
874         case '\r': av_bprintf(dst, "%s", "\\r");  break;
875         case '\\': av_bprintf(dst, "%s", "\\\\"); break;
876         default:
877             if (*p == sep)
878                 av_bprint_chars(dst, '\\', 1);
879             av_bprint_chars(dst, *p, 1);
880         }
881     }
882     return dst->str;
883 }
884
885 /**
886  * Quote fields containing special characters, check RFC4180.
887  */
888 static const char *csv_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
889 {
890     char meta_chars[] = { sep, '"', '\n', '\r', '\0' };
891     int needs_quoting = !!src[strcspn(src, meta_chars)];
892
893     if (needs_quoting)
894         av_bprint_chars(dst, '"', 1);
895
896     for (; *src; src++) {
897         if (*src == '"')
898             av_bprint_chars(dst, '"', 1);
899         av_bprint_chars(dst, *src, 1);
900     }
901     if (needs_quoting)
902         av_bprint_chars(dst, '"', 1);
903     return dst->str;
904 }
905
906 static const char *none_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
907 {
908     return src;
909 }
910
911 typedef struct CompactContext {
912     const AVClass *class;
913     char *item_sep_str;
914     char item_sep;
915     int nokey;
916     int print_section;
917     char *escape_mode_str;
918     const char * (*escape_str)(AVBPrint *dst, const char *src, const char sep, void *log_ctx);
919     int nested_section[SECTION_MAX_NB_LEVELS];
920     int has_nested_elems[SECTION_MAX_NB_LEVELS];
921     int terminate_line[SECTION_MAX_NB_LEVELS];
922 } CompactContext;
923
924 #undef OFFSET
925 #define OFFSET(x) offsetof(CompactContext, x)
926
927 static const AVOption compact_options[]= {
928     {"item_sep", "set item separator",    OFFSET(item_sep_str),    AV_OPT_TYPE_STRING, {.str="|"},  CHAR_MIN, CHAR_MAX },
929     {"s",        "set item separator",    OFFSET(item_sep_str),    AV_OPT_TYPE_STRING, {.str="|"},  CHAR_MIN, CHAR_MAX },
930     {"nokey",    "force no key printing", OFFSET(nokey),           AV_OPT_TYPE_INT,    {.i64=0},    0,        1        },
931     {"nk",       "force no key printing", OFFSET(nokey),           AV_OPT_TYPE_INT,    {.i64=0},    0,        1        },
932     {"escape",   "set escape mode",       OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"},  CHAR_MIN, CHAR_MAX },
933     {"e",        "set escape mode",       OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"},  CHAR_MIN, CHAR_MAX },
934     {"print_section", "print section name", OFFSET(print_section), AV_OPT_TYPE_INT,    {.i64=1},    0,        1        },
935     {"p",             "print section name", OFFSET(print_section), AV_OPT_TYPE_INT,    {.i64=1},    0,        1        },
936     {NULL},
937 };
938
939 DEFINE_WRITER_CLASS(compact);
940
941 static av_cold int compact_init(WriterContext *wctx)
942 {
943     CompactContext *compact = wctx->priv;
944
945     if (strlen(compact->item_sep_str) != 1) {
946         av_log(wctx, AV_LOG_ERROR, "Item separator '%s' specified, but must contain a single character\n",
947                compact->item_sep_str);
948         return AVERROR(EINVAL);
949     }
950     compact->item_sep = compact->item_sep_str[0];
951
952     if      (!strcmp(compact->escape_mode_str, "none")) compact->escape_str = none_escape_str;
953     else if (!strcmp(compact->escape_mode_str, "c"   )) compact->escape_str = c_escape_str;
954     else if (!strcmp(compact->escape_mode_str, "csv" )) compact->escape_str = csv_escape_str;
955     else {
956         av_log(wctx, AV_LOG_ERROR, "Unknown escape mode '%s'\n", compact->escape_mode_str);
957         return AVERROR(EINVAL);
958     }
959
960     return 0;
961 }
962
963 static void compact_print_section_header(WriterContext *wctx)
964 {
965     CompactContext *compact = wctx->priv;
966     const struct section *section = wctx->section[wctx->level];
967     const struct section *parent_section = wctx->level ?
968         wctx->section[wctx->level-1] : NULL;
969     compact->terminate_line[wctx->level] = 1;
970     compact->has_nested_elems[wctx->level] = 0;
971
972     av_bprint_clear(&wctx->section_pbuf[wctx->level]);
973     if (!(section->flags & SECTION_FLAG_IS_ARRAY) && parent_section &&
974         !(parent_section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY))) {
975         compact->nested_section[wctx->level] = 1;
976         compact->has_nested_elems[wctx->level-1] = 1;
977         av_bprintf(&wctx->section_pbuf[wctx->level], "%s%s:",
978                    wctx->section_pbuf[wctx->level-1].str,
979                    (char *)av_x_if_null(section->element_name, section->name));
980         wctx->nb_item[wctx->level] = wctx->nb_item[wctx->level-1];
981     } else {
982         if (parent_section && compact->has_nested_elems[wctx->level-1] &&
983             (section->flags & SECTION_FLAG_IS_ARRAY)) {
984             compact->terminate_line[wctx->level-1] = 0;
985             printf("\n");
986         }
987         if (compact->print_section &&
988             !(section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY)))
989             printf("%s%c", section->name, compact->item_sep);
990     }
991 }
992
993 static void compact_print_section_footer(WriterContext *wctx)
994 {
995     CompactContext *compact = wctx->priv;
996
997     if (!compact->nested_section[wctx->level] &&
998         compact->terminate_line[wctx->level] &&
999         !(wctx->section[wctx->level]->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY)))
1000         printf("\n");
1001 }
1002
1003 static void compact_print_str(WriterContext *wctx, const char *key, const char *value)
1004 {
1005     CompactContext *compact = wctx->priv;
1006     AVBPrint buf;
1007
1008     if (wctx->nb_item[wctx->level]) printf("%c", compact->item_sep);
1009     if (!compact->nokey)
1010         printf("%s%s=", wctx->section_pbuf[wctx->level].str, key);
1011     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
1012     printf("%s", compact->escape_str(&buf, value, compact->item_sep, wctx));
1013     av_bprint_finalize(&buf, NULL);
1014 }
1015
1016 static void compact_print_int(WriterContext *wctx, const char *key, long long int value)
1017 {
1018     CompactContext *compact = wctx->priv;
1019
1020     if (wctx->nb_item[wctx->level]) printf("%c", compact->item_sep);
1021     if (!compact->nokey)
1022         printf("%s%s=", wctx->section_pbuf[wctx->level].str, key);
1023     printf("%lld", value);
1024 }
1025
1026 static const Writer compact_writer = {
1027     .name                 = "compact",
1028     .priv_size            = sizeof(CompactContext),
1029     .init                 = compact_init,
1030     .print_section_header = compact_print_section_header,
1031     .print_section_footer = compact_print_section_footer,
1032     .print_integer        = compact_print_int,
1033     .print_string         = compact_print_str,
1034     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
1035     .priv_class           = &compact_class,
1036 };
1037
1038 /* CSV output */
1039
1040 #undef OFFSET
1041 #define OFFSET(x) offsetof(CompactContext, x)
1042
1043 static const AVOption csv_options[] = {
1044     {"item_sep", "set item separator",    OFFSET(item_sep_str),    AV_OPT_TYPE_STRING, {.str=","},  CHAR_MIN, CHAR_MAX },
1045     {"s",        "set item separator",    OFFSET(item_sep_str),    AV_OPT_TYPE_STRING, {.str=","},  CHAR_MIN, CHAR_MAX },
1046     {"nokey",    "force no key printing", OFFSET(nokey),           AV_OPT_TYPE_INT,    {.i64=1},    0,        1        },
1047     {"nk",       "force no key printing", OFFSET(nokey),           AV_OPT_TYPE_INT,    {.i64=1},    0,        1        },
1048     {"escape",   "set escape mode",       OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="csv"}, CHAR_MIN, CHAR_MAX },
1049     {"e",        "set escape mode",       OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="csv"}, CHAR_MIN, CHAR_MAX },
1050     {"print_section", "print section name", OFFSET(print_section), AV_OPT_TYPE_INT,    {.i64=1},    0,        1        },
1051     {"p",             "print section name", OFFSET(print_section), AV_OPT_TYPE_INT,    {.i64=1},    0,        1        },
1052     {NULL},
1053 };
1054
1055 DEFINE_WRITER_CLASS(csv);
1056
1057 static const Writer csv_writer = {
1058     .name                 = "csv",
1059     .priv_size            = sizeof(CompactContext),
1060     .init                 = compact_init,
1061     .print_section_header = compact_print_section_header,
1062     .print_section_footer = compact_print_section_footer,
1063     .print_integer        = compact_print_int,
1064     .print_string         = compact_print_str,
1065     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
1066     .priv_class           = &csv_class,
1067 };
1068
1069 /* Flat output */
1070
1071 typedef struct FlatContext {
1072     const AVClass *class;
1073     const char *sep_str;
1074     char sep;
1075     int hierarchical;
1076 } FlatContext;
1077
1078 #undef OFFSET
1079 #define OFFSET(x) offsetof(FlatContext, x)
1080
1081 static const AVOption flat_options[]= {
1082     {"sep_char", "set separator",    OFFSET(sep_str),    AV_OPT_TYPE_STRING, {.str="."},  CHAR_MIN, CHAR_MAX },
1083     {"s",        "set separator",    OFFSET(sep_str),    AV_OPT_TYPE_STRING, {.str="."},  CHAR_MIN, CHAR_MAX },
1084     {"hierarchical", "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
1085     {"h",           "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
1086     {NULL},
1087 };
1088
1089 DEFINE_WRITER_CLASS(flat);
1090
1091 static av_cold int flat_init(WriterContext *wctx)
1092 {
1093     FlatContext *flat = wctx->priv;
1094
1095     if (strlen(flat->sep_str) != 1) {
1096         av_log(wctx, AV_LOG_ERROR, "Item separator '%s' specified, but must contain a single character\n",
1097                flat->sep_str);
1098         return AVERROR(EINVAL);
1099     }
1100     flat->sep = flat->sep_str[0];
1101
1102     return 0;
1103 }
1104
1105 static const char *flat_escape_key_str(AVBPrint *dst, const char *src, const char sep)
1106 {
1107     const char *p;
1108
1109     for (p = src; *p; p++) {
1110         if (!((*p >= '0' && *p <= '9') ||
1111               (*p >= 'a' && *p <= 'z') ||
1112               (*p >= 'A' && *p <= 'Z')))
1113             av_bprint_chars(dst, '_', 1);
1114         else
1115             av_bprint_chars(dst, *p, 1);
1116     }
1117     return dst->str;
1118 }
1119
1120 static const char *flat_escape_value_str(AVBPrint *dst, const char *src)
1121 {
1122     const char *p;
1123
1124     for (p = src; *p; p++) {
1125         switch (*p) {
1126         case '\n': av_bprintf(dst, "%s", "\\n");  break;
1127         case '\r': av_bprintf(dst, "%s", "\\r");  break;
1128         case '\\': av_bprintf(dst, "%s", "\\\\"); break;
1129         case '"':  av_bprintf(dst, "%s", "\\\""); break;
1130         case '`':  av_bprintf(dst, "%s", "\\`");  break;
1131         case '$':  av_bprintf(dst, "%s", "\\$");  break;
1132         default:   av_bprint_chars(dst, *p, 1);   break;
1133         }
1134     }
1135     return dst->str;
1136 }
1137
1138 static void flat_print_section_header(WriterContext *wctx)
1139 {
1140     FlatContext *flat = wctx->priv;
1141     AVBPrint *buf = &wctx->section_pbuf[wctx->level];
1142     const struct section *section = wctx->section[wctx->level];
1143     const struct section *parent_section = wctx->level ?
1144         wctx->section[wctx->level-1] : NULL;
1145
1146     /* build section header */
1147     av_bprint_clear(buf);
1148     if (!parent_section)
1149         return;
1150     av_bprintf(buf, "%s", wctx->section_pbuf[wctx->level-1].str);
1151
1152     if (flat->hierarchical ||
1153         !(section->flags & (SECTION_FLAG_IS_ARRAY|SECTION_FLAG_IS_WRAPPER))) {
1154         av_bprintf(buf, "%s%s", wctx->section[wctx->level]->name, flat->sep_str);
1155
1156         if (parent_section->flags & SECTION_FLAG_IS_ARRAY) {
1157             int n = parent_section->id == SECTION_ID_PACKETS_AND_FRAMES ?
1158                 wctx->nb_section_packet_frame : wctx->nb_item[wctx->level-1];
1159             av_bprintf(buf, "%d%s", n, flat->sep_str);
1160         }
1161     }
1162 }
1163
1164 static void flat_print_int(WriterContext *wctx, const char *key, long long int value)
1165 {
1166     printf("%s%s=%lld\n", wctx->section_pbuf[wctx->level].str, key, value);
1167 }
1168
1169 static void flat_print_str(WriterContext *wctx, const char *key, const char *value)
1170 {
1171     FlatContext *flat = wctx->priv;
1172     AVBPrint buf;
1173
1174     printf("%s", wctx->section_pbuf[wctx->level].str);
1175     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
1176     printf("%s=", flat_escape_key_str(&buf, key, flat->sep));
1177     av_bprint_clear(&buf);
1178     printf("\"%s\"\n", flat_escape_value_str(&buf, value));
1179     av_bprint_finalize(&buf, NULL);
1180 }
1181
1182 static const Writer flat_writer = {
1183     .name                  = "flat",
1184     .priv_size             = sizeof(FlatContext),
1185     .init                  = flat_init,
1186     .print_section_header  = flat_print_section_header,
1187     .print_integer         = flat_print_int,
1188     .print_string          = flat_print_str,
1189     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS|WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
1190     .priv_class            = &flat_class,
1191 };
1192
1193 /* INI format output */
1194
1195 typedef struct INIContext {
1196     const AVClass *class;
1197     int hierarchical;
1198 } INIContext;
1199
1200 #undef OFFSET
1201 #define OFFSET(x) offsetof(INIContext, x)
1202
1203 static const AVOption ini_options[] = {
1204     {"hierarchical", "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
1205     {"h",           "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
1206     {NULL},
1207 };
1208
1209 DEFINE_WRITER_CLASS(ini);
1210
1211 static char *ini_escape_str(AVBPrint *dst, const char *src)
1212 {
1213     int i = 0;
1214     char c = 0;
1215
1216     while (c = src[i++]) {
1217         switch (c) {
1218         case '\b': av_bprintf(dst, "%s", "\\b"); break;
1219         case '\f': av_bprintf(dst, "%s", "\\f"); break;
1220         case '\n': av_bprintf(dst, "%s", "\\n"); break;
1221         case '\r': av_bprintf(dst, "%s", "\\r"); break;
1222         case '\t': av_bprintf(dst, "%s", "\\t"); break;
1223         case '\\':
1224         case '#' :
1225         case '=' :
1226         case ':' : av_bprint_chars(dst, '\\', 1);
1227         default:
1228             if ((unsigned char)c < 32)
1229                 av_bprintf(dst, "\\x00%02x", c & 0xff);
1230             else
1231                 av_bprint_chars(dst, c, 1);
1232             break;
1233         }
1234     }
1235     return dst->str;
1236 }
1237
1238 static void ini_print_section_header(WriterContext *wctx)
1239 {
1240     INIContext *ini = wctx->priv;
1241     AVBPrint *buf = &wctx->section_pbuf[wctx->level];
1242     const struct section *section = wctx->section[wctx->level];
1243     const struct section *parent_section = wctx->level ?
1244         wctx->section[wctx->level-1] : NULL;
1245
1246     av_bprint_clear(buf);
1247     if (!parent_section) {
1248         printf("# ffprobe output\n\n");
1249         return;
1250     }
1251
1252     if (wctx->nb_item[wctx->level-1])
1253         printf("\n");
1254
1255     av_bprintf(buf, "%s", wctx->section_pbuf[wctx->level-1].str);
1256     if (ini->hierarchical ||
1257         !(section->flags & (SECTION_FLAG_IS_ARRAY|SECTION_FLAG_IS_WRAPPER))) {
1258         av_bprintf(buf, "%s%s", buf->str[0] ? "." : "", wctx->section[wctx->level]->name);
1259
1260         if (parent_section->flags & SECTION_FLAG_IS_ARRAY) {
1261             int n = parent_section->id == SECTION_ID_PACKETS_AND_FRAMES ?
1262                 wctx->nb_section_packet_frame : wctx->nb_item[wctx->level-1];
1263             av_bprintf(buf, ".%d", n);
1264         }
1265     }
1266
1267     if (!(section->flags & (SECTION_FLAG_IS_ARRAY|SECTION_FLAG_IS_WRAPPER)))
1268         printf("[%s]\n", buf->str);
1269 }
1270
1271 static void ini_print_str(WriterContext *wctx, const char *key, const char *value)
1272 {
1273     AVBPrint buf;
1274
1275     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
1276     printf("%s=", ini_escape_str(&buf, key));
1277     av_bprint_clear(&buf);
1278     printf("%s\n", ini_escape_str(&buf, value));
1279     av_bprint_finalize(&buf, NULL);
1280 }
1281
1282 static void ini_print_int(WriterContext *wctx, const char *key, long long int value)
1283 {
1284     printf("%s=%lld\n", key, value);
1285 }
1286
1287 static const Writer ini_writer = {
1288     .name                  = "ini",
1289     .priv_size             = sizeof(INIContext),
1290     .print_section_header  = ini_print_section_header,
1291     .print_integer         = ini_print_int,
1292     .print_string          = ini_print_str,
1293     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS|WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
1294     .priv_class            = &ini_class,
1295 };
1296
1297 /* JSON output */
1298
1299 typedef struct JSONContext {
1300     const AVClass *class;
1301     int indent_level;
1302     int compact;
1303     const char *item_sep, *item_start_end;
1304 } JSONContext;
1305
1306 #undef OFFSET
1307 #define OFFSET(x) offsetof(JSONContext, x)
1308
1309 static const AVOption json_options[]= {
1310     { "compact", "enable compact output", OFFSET(compact), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
1311     { "c",       "enable compact output", OFFSET(compact), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
1312     { NULL }
1313 };
1314
1315 DEFINE_WRITER_CLASS(json);
1316
1317 static av_cold int json_init(WriterContext *wctx)
1318 {
1319     JSONContext *json = wctx->priv;
1320
1321     json->item_sep       = json->compact ? ", " : ",\n";
1322     json->item_start_end = json->compact ? " "  : "\n";
1323
1324     return 0;
1325 }
1326
1327 static const char *json_escape_str(AVBPrint *dst, const char *src, void *log_ctx)
1328 {
1329     static const char json_escape[] = {'"', '\\', '\b', '\f', '\n', '\r', '\t', 0};
1330     static const char json_subst[]  = {'"', '\\',  'b',  'f',  'n',  'r',  't', 0};
1331     const char *p;
1332
1333     for (p = src; *p; p++) {
1334         char *s = strchr(json_escape, *p);
1335         if (s) {
1336             av_bprint_chars(dst, '\\', 1);
1337             av_bprint_chars(dst, json_subst[s - json_escape], 1);
1338         } else if ((unsigned char)*p < 32) {
1339             av_bprintf(dst, "\\u00%02x", *p & 0xff);
1340         } else {
1341             av_bprint_chars(dst, *p, 1);
1342         }
1343     }
1344     return dst->str;
1345 }
1346
1347 #define JSON_INDENT() printf("%*c", json->indent_level * 4, ' ')
1348
1349 static void json_print_section_header(WriterContext *wctx)
1350 {
1351     JSONContext *json = wctx->priv;
1352     AVBPrint buf;
1353     const struct section *section = wctx->section[wctx->level];
1354     const struct section *parent_section = wctx->level ?
1355         wctx->section[wctx->level-1] : NULL;
1356
1357     if (wctx->level && wctx->nb_item[wctx->level-1])
1358         printf(",\n");
1359
1360     if (section->flags & SECTION_FLAG_IS_WRAPPER) {
1361         printf("{\n");
1362         json->indent_level++;
1363     } else {
1364         av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
1365         json_escape_str(&buf, section->name, wctx);
1366         JSON_INDENT();
1367
1368         json->indent_level++;
1369         if (section->flags & SECTION_FLAG_IS_ARRAY) {
1370             printf("\"%s\": [\n", buf.str);
1371         } else if (parent_section && !(parent_section->flags & SECTION_FLAG_IS_ARRAY)) {
1372             printf("\"%s\": {%s", buf.str, json->item_start_end);
1373         } else {
1374             printf("{%s", json->item_start_end);
1375
1376             /* this is required so the parser can distinguish between packets and frames */
1377             if (parent_section && parent_section->id == SECTION_ID_PACKETS_AND_FRAMES) {
1378                 if (!json->compact)
1379                     JSON_INDENT();
1380                 printf("\"type\": \"%s\"%s", section->name, json->item_sep);
1381             }
1382         }
1383         av_bprint_finalize(&buf, NULL);
1384     }
1385 }
1386
1387 static void json_print_section_footer(WriterContext *wctx)
1388 {
1389     JSONContext *json = wctx->priv;
1390     const struct section *section = wctx->section[wctx->level];
1391
1392     if (wctx->level == 0) {
1393         json->indent_level--;
1394         printf("\n}\n");
1395     } else if (section->flags & SECTION_FLAG_IS_ARRAY) {
1396         printf("\n");
1397         json->indent_level--;
1398         JSON_INDENT();
1399         printf("]");
1400     } else {
1401         printf("%s", json->item_start_end);
1402         json->indent_level--;
1403         if (!json->compact)
1404             JSON_INDENT();
1405         printf("}");
1406     }
1407 }
1408
1409 static inline void json_print_item_str(WriterContext *wctx,
1410                                        const char *key, const char *value)
1411 {
1412     AVBPrint buf;
1413
1414     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
1415     printf("\"%s\":", json_escape_str(&buf, key,   wctx));
1416     av_bprint_clear(&buf);
1417     printf(" \"%s\"", json_escape_str(&buf, value, wctx));
1418     av_bprint_finalize(&buf, NULL);
1419 }
1420
1421 static void json_print_str(WriterContext *wctx, const char *key, const char *value)
1422 {
1423     JSONContext *json = wctx->priv;
1424
1425     if (wctx->nb_item[wctx->level])
1426         printf("%s", json->item_sep);
1427     if (!json->compact)
1428         JSON_INDENT();
1429     json_print_item_str(wctx, key, value);
1430 }
1431
1432 static void json_print_int(WriterContext *wctx, const char *key, long long int value)
1433 {
1434     JSONContext *json = wctx->priv;
1435     AVBPrint buf;
1436
1437     if (wctx->nb_item[wctx->level])
1438         printf("%s", json->item_sep);
1439     if (!json->compact)
1440         JSON_INDENT();
1441
1442     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
1443     printf("\"%s\": %lld", json_escape_str(&buf, key, wctx), value);
1444     av_bprint_finalize(&buf, NULL);
1445 }
1446
1447 static const Writer json_writer = {
1448     .name                 = "json",
1449     .priv_size            = sizeof(JSONContext),
1450     .init                 = json_init,
1451     .print_section_header = json_print_section_header,
1452     .print_section_footer = json_print_section_footer,
1453     .print_integer        = json_print_int,
1454     .print_string         = json_print_str,
1455     .flags = WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
1456     .priv_class           = &json_class,
1457 };
1458
1459 /* XML output */
1460
1461 typedef struct XMLContext {
1462     const AVClass *class;
1463     int within_tag;
1464     int indent_level;
1465     int fully_qualified;
1466     int xsd_strict;
1467 } XMLContext;
1468
1469 #undef OFFSET
1470 #define OFFSET(x) offsetof(XMLContext, x)
1471
1472 static const AVOption xml_options[] = {
1473     {"fully_qualified", "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_INT, {.i64=0},  0, 1 },
1474     {"q",               "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_INT, {.i64=0},  0, 1 },
1475     {"xsd_strict",      "ensure that the output is XSD compliant",         OFFSET(xsd_strict),      AV_OPT_TYPE_INT, {.i64=0},  0, 1 },
1476     {"x",               "ensure that the output is XSD compliant",         OFFSET(xsd_strict),      AV_OPT_TYPE_INT, {.i64=0},  0, 1 },
1477     {NULL},
1478 };
1479
1480 DEFINE_WRITER_CLASS(xml);
1481
1482 static av_cold int xml_init(WriterContext *wctx)
1483 {
1484     XMLContext *xml = wctx->priv;
1485
1486     if (xml->xsd_strict) {
1487         xml->fully_qualified = 1;
1488 #define CHECK_COMPLIANCE(opt, opt_name)                                 \
1489         if (opt) {                                                      \
1490             av_log(wctx, AV_LOG_ERROR,                                  \
1491                    "XSD-compliant output selected but option '%s' was selected, XML output may be non-compliant.\n" \
1492                    "You need to disable such option with '-no%s'\n", opt_name, opt_name); \
1493             return AVERROR(EINVAL);                                     \
1494         }
1495         CHECK_COMPLIANCE(show_private_data, "private");
1496         CHECK_COMPLIANCE(show_value_unit,   "unit");
1497         CHECK_COMPLIANCE(use_value_prefix,  "prefix");
1498
1499         if (do_show_frames && do_show_packets) {
1500             av_log(wctx, AV_LOG_ERROR,
1501                    "Interleaved frames and packets are not allowed in XSD. "
1502                    "Select only one between the -show_frames and the -show_packets options.\n");
1503             return AVERROR(EINVAL);
1504         }
1505     }
1506
1507     return 0;
1508 }
1509
1510 static const char *xml_escape_str(AVBPrint *dst, const char *src, void *log_ctx)
1511 {
1512     const char *p;
1513
1514     for (p = src; *p; p++) {
1515         switch (*p) {
1516         case '&' : av_bprintf(dst, "%s", "&amp;");  break;
1517         case '<' : av_bprintf(dst, "%s", "&lt;");   break;
1518         case '>' : av_bprintf(dst, "%s", "&gt;");   break;
1519         case '"' : av_bprintf(dst, "%s", "&quot;"); break;
1520         case '\'': av_bprintf(dst, "%s", "&apos;"); break;
1521         default: av_bprint_chars(dst, *p, 1);
1522         }
1523     }
1524
1525     return dst->str;
1526 }
1527
1528 #define XML_INDENT() printf("%*c", xml->indent_level * 4, ' ')
1529
1530 static void xml_print_section_header(WriterContext *wctx)
1531 {
1532     XMLContext *xml = wctx->priv;
1533     const struct section *section = wctx->section[wctx->level];
1534     const struct section *parent_section = wctx->level ?
1535         wctx->section[wctx->level-1] : NULL;
1536
1537     if (wctx->level == 0) {
1538         const char *qual = " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' "
1539             "xmlns:ffprobe='http://www.ffmpeg.org/schema/ffprobe' "
1540             "xsi:schemaLocation='http://www.ffmpeg.org/schema/ffprobe ffprobe.xsd'";
1541
1542         printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1543         printf("<%sffprobe%s>\n",
1544                xml->fully_qualified ? "ffprobe:" : "",
1545                xml->fully_qualified ? qual : "");
1546         return;
1547     }
1548
1549     if (xml->within_tag) {
1550         xml->within_tag = 0;
1551         printf(">\n");
1552     }
1553     if (section->flags & SECTION_FLAG_HAS_VARIABLE_FIELDS) {
1554         xml->indent_level++;
1555     } else {
1556         if (parent_section && (parent_section->flags & SECTION_FLAG_IS_WRAPPER) &&
1557             wctx->level && wctx->nb_item[wctx->level-1])
1558             printf("\n");
1559         xml->indent_level++;
1560
1561         if (section->flags & SECTION_FLAG_IS_ARRAY) {
1562             XML_INDENT(); printf("<%s>\n", section->name);
1563         } else {
1564             XML_INDENT(); printf("<%s ", section->name);
1565             xml->within_tag = 1;
1566         }
1567     }
1568 }
1569
1570 static void xml_print_section_footer(WriterContext *wctx)
1571 {
1572     XMLContext *xml = wctx->priv;
1573     const struct section *section = wctx->section[wctx->level];
1574
1575     if (wctx->level == 0) {
1576         printf("</%sffprobe>\n", xml->fully_qualified ? "ffprobe:" : "");
1577     } else if (xml->within_tag) {
1578         xml->within_tag = 0;
1579         printf("/>\n");
1580         xml->indent_level--;
1581     } else if (section->flags & SECTION_FLAG_HAS_VARIABLE_FIELDS) {
1582         xml->indent_level--;
1583     } else {
1584         XML_INDENT(); printf("</%s>\n", section->name);
1585         xml->indent_level--;
1586     }
1587 }
1588
1589 static void xml_print_str(WriterContext *wctx, const char *key, const char *value)
1590 {
1591     AVBPrint buf;
1592     XMLContext *xml = wctx->priv;
1593     const struct section *section = wctx->section[wctx->level];
1594
1595     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
1596
1597     if (section->flags & SECTION_FLAG_HAS_VARIABLE_FIELDS) {
1598         XML_INDENT();
1599         printf("<%s key=\"%s\"",
1600                section->element_name, xml_escape_str(&buf, key, wctx));
1601         av_bprint_clear(&buf);
1602         printf(" value=\"%s\"/>\n", xml_escape_str(&buf, value, wctx));
1603     } else {
1604         if (wctx->nb_item[wctx->level])
1605             printf(" ");
1606         printf("%s=\"%s\"", key, xml_escape_str(&buf, value, wctx));
1607     }
1608
1609     av_bprint_finalize(&buf, NULL);
1610 }
1611
1612 static void xml_print_int(WriterContext *wctx, const char *key, long long int value)
1613 {
1614     if (wctx->nb_item[wctx->level])
1615         printf(" ");
1616     printf("%s=\"%lld\"", key, value);
1617 }
1618
1619 static Writer xml_writer = {
1620     .name                 = "xml",
1621     .priv_size            = sizeof(XMLContext),
1622     .init                 = xml_init,
1623     .print_section_header = xml_print_section_header,
1624     .print_section_footer = xml_print_section_footer,
1625     .print_integer        = xml_print_int,
1626     .print_string         = xml_print_str,
1627     .flags = WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
1628     .priv_class           = &xml_class,
1629 };
1630
1631 static void writer_register_all(void)
1632 {
1633     static int initialized;
1634
1635     if (initialized)
1636         return;
1637     initialized = 1;
1638
1639     writer_register(&default_writer);
1640     writer_register(&compact_writer);
1641     writer_register(&csv_writer);
1642     writer_register(&flat_writer);
1643     writer_register(&ini_writer);
1644     writer_register(&json_writer);
1645     writer_register(&xml_writer);
1646 }
1647
1648 #define print_fmt(k, f, ...) do {              \
1649     av_bprint_clear(&pbuf);                    \
1650     av_bprintf(&pbuf, f, __VA_ARGS__);         \
1651     writer_print_string(w, k, pbuf.str, 0);    \
1652 } while (0)
1653
1654 #define print_int(k, v)         writer_print_integer(w, k, v)
1655 #define print_q(k, v, s)        writer_print_rational(w, k, v, s)
1656 #define print_str(k, v)         writer_print_string(w, k, v, 0)
1657 #define print_str_opt(k, v)     writer_print_string(w, k, v, PRINT_STRING_OPT)
1658 #define print_str_validate(k, v) writer_print_string(w, k, v, PRINT_STRING_VALIDATE)
1659 #define print_time(k, v, tb)    writer_print_time(w, k, v, tb, 0)
1660 #define print_ts(k, v)          writer_print_ts(w, k, v, 0)
1661 #define print_duration_time(k, v, tb) writer_print_time(w, k, v, tb, 1)
1662 #define print_duration_ts(k, v)       writer_print_ts(w, k, v, 1)
1663 #define print_val(k, v, u) do {                                     \
1664     struct unit_value uv;                                           \
1665     uv.val.i = v;                                                   \
1666     uv.unit = u;                                                    \
1667     writer_print_string(w, k, value_string(val_str, sizeof(val_str), uv), 0); \
1668 } while (0)
1669
1670 #define print_section_header(s) writer_print_section_header(w, s)
1671 #define print_section_footer(s) writer_print_section_footer(w, s)
1672
1673 #define REALLOCZ_ARRAY_STREAM(ptr, cur_n, new_n)                        \
1674 {                                                                       \
1675     ret = av_reallocp_array(&(ptr), (new_n), sizeof(*(ptr)));           \
1676     if (ret < 0)                                                        \
1677         goto end;                                                       \
1678     memset( (ptr) + (cur_n), 0, ((new_n) - (cur_n)) * sizeof(*(ptr)) ); \
1679 }
1680
1681 static inline int show_tags(WriterContext *w, AVDictionary *tags, int section_id)
1682 {
1683     AVDictionaryEntry *tag = NULL;
1684     int ret = 0;
1685
1686     if (!tags)
1687         return 0;
1688     writer_print_section_header(w, section_id);
1689
1690     while ((tag = av_dict_get(tags, "", tag, AV_DICT_IGNORE_SUFFIX))) {
1691         if ((ret = print_str_validate(tag->key, tag->value)) < 0)
1692             break;
1693     }
1694     writer_print_section_footer(w);
1695
1696     return ret;
1697 }
1698
1699 static void show_packet(WriterContext *w, AVFormatContext *fmt_ctx, AVPacket *pkt, int packet_idx)
1700 {
1701     char val_str[128];
1702     AVStream *st = fmt_ctx->streams[pkt->stream_index];
1703     AVBPrint pbuf;
1704     const char *s;
1705
1706     av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
1707
1708     writer_print_section_header(w, SECTION_ID_PACKET);
1709
1710     s = av_get_media_type_string(st->codec->codec_type);
1711     if (s) print_str    ("codec_type", s);
1712     else   print_str_opt("codec_type", "unknown");
1713     print_int("stream_index",     pkt->stream_index);
1714     print_ts  ("pts",             pkt->pts);
1715     print_time("pts_time",        pkt->pts, &st->time_base);
1716     print_ts  ("dts",             pkt->dts);
1717     print_time("dts_time",        pkt->dts, &st->time_base);
1718     print_duration_ts("duration",        pkt->duration);
1719     print_duration_time("duration_time", pkt->duration, &st->time_base);
1720     print_duration_ts("convergence_duration", pkt->convergence_duration);
1721     print_duration_time("convergence_duration_time", pkt->convergence_duration, &st->time_base);
1722     print_val("size",             pkt->size, unit_byte_str);
1723     if (pkt->pos != -1) print_fmt    ("pos", "%"PRId64, pkt->pos);
1724     else                print_str_opt("pos", "N/A");
1725     print_fmt("flags", "%c",      pkt->flags & AV_PKT_FLAG_KEY ? 'K' : '_');
1726     if (do_show_data)
1727         writer_print_data(w, "data", pkt->data, pkt->size);
1728     writer_print_data_hash(w, "data_hash", pkt->data, pkt->size);
1729     writer_print_section_footer(w);
1730
1731     av_bprint_finalize(&pbuf, NULL);
1732     fflush(stdout);
1733 }
1734
1735 static void show_subtitle(WriterContext *w, AVSubtitle *sub, AVStream *stream,
1736                           AVFormatContext *fmt_ctx)
1737 {
1738     AVBPrint pbuf;
1739
1740     av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
1741
1742     writer_print_section_header(w, SECTION_ID_SUBTITLE);
1743
1744     print_str ("media_type",         "subtitle");
1745     print_ts  ("pts",                 sub->pts);
1746     print_time("pts_time",            sub->pts, &AV_TIME_BASE_Q);
1747     print_int ("format",              sub->format);
1748     print_int ("start_display_time",  sub->start_display_time);
1749     print_int ("end_display_time",    sub->end_display_time);
1750     print_int ("num_rects",           sub->num_rects);
1751
1752     writer_print_section_footer(w);
1753
1754     av_bprint_finalize(&pbuf, NULL);
1755     fflush(stdout);
1756 }
1757
1758 static void show_frame(WriterContext *w, AVFrame *frame, AVStream *stream,
1759                        AVFormatContext *fmt_ctx)
1760 {
1761     AVBPrint pbuf;
1762     const char *s;
1763     int i;
1764
1765     av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
1766
1767     writer_print_section_header(w, SECTION_ID_FRAME);
1768
1769     s = av_get_media_type_string(stream->codec->codec_type);
1770     if (s) print_str    ("media_type", s);
1771     else   print_str_opt("media_type", "unknown");
1772     print_int("key_frame",              frame->key_frame);
1773     print_ts  ("pkt_pts",               frame->pkt_pts);
1774     print_time("pkt_pts_time",          frame->pkt_pts, &stream->time_base);
1775     print_ts  ("pkt_dts",               frame->pkt_dts);
1776     print_time("pkt_dts_time",          frame->pkt_dts, &stream->time_base);
1777     print_ts  ("best_effort_timestamp", av_frame_get_best_effort_timestamp(frame));
1778     print_time("best_effort_timestamp_time", av_frame_get_best_effort_timestamp(frame), &stream->time_base);
1779     print_duration_ts  ("pkt_duration",      av_frame_get_pkt_duration(frame));
1780     print_duration_time("pkt_duration_time", av_frame_get_pkt_duration(frame), &stream->time_base);
1781     if (av_frame_get_pkt_pos (frame) != -1) print_fmt    ("pkt_pos", "%"PRId64, av_frame_get_pkt_pos(frame));
1782     else                      print_str_opt("pkt_pos", "N/A");
1783     if (av_frame_get_pkt_size(frame) != -1) print_fmt    ("pkt_size", "%d", av_frame_get_pkt_size(frame));
1784     else                       print_str_opt("pkt_size", "N/A");
1785
1786     switch (stream->codec->codec_type) {
1787         AVRational sar;
1788
1789     case AVMEDIA_TYPE_VIDEO:
1790         print_int("width",                  frame->width);
1791         print_int("height",                 frame->height);
1792         s = av_get_pix_fmt_name(frame->format);
1793         if (s) print_str    ("pix_fmt", s);
1794         else   print_str_opt("pix_fmt", "unknown");
1795         sar = av_guess_sample_aspect_ratio(fmt_ctx, stream, frame);
1796         if (sar.num) {
1797             print_q("sample_aspect_ratio", sar, ':');
1798         } else {
1799             print_str_opt("sample_aspect_ratio", "N/A");
1800         }
1801         print_fmt("pict_type",              "%c", av_get_picture_type_char(frame->pict_type));
1802         print_int("coded_picture_number",   frame->coded_picture_number);
1803         print_int("display_picture_number", frame->display_picture_number);
1804         print_int("interlaced_frame",       frame->interlaced_frame);
1805         print_int("top_field_first",        frame->top_field_first);
1806         print_int("repeat_pict",            frame->repeat_pict);
1807         break;
1808
1809     case AVMEDIA_TYPE_AUDIO:
1810         s = av_get_sample_fmt_name(frame->format);
1811         if (s) print_str    ("sample_fmt", s);
1812         else   print_str_opt("sample_fmt", "unknown");
1813         print_int("nb_samples",         frame->nb_samples);
1814         print_int("channels", av_frame_get_channels(frame));
1815         if (av_frame_get_channel_layout(frame)) {
1816             av_bprint_clear(&pbuf);
1817             av_bprint_channel_layout(&pbuf, av_frame_get_channels(frame),
1818                                      av_frame_get_channel_layout(frame));
1819             print_str    ("channel_layout", pbuf.str);
1820         } else
1821             print_str_opt("channel_layout", "unknown");
1822         break;
1823     }
1824     if (do_show_frame_tags)
1825         show_tags(w, av_frame_get_metadata(frame), SECTION_ID_FRAME_TAGS);
1826     if (frame->nb_side_data) {
1827         writer_print_section_header(w, SECTION_ID_FRAME_SIDE_DATA_LIST);
1828         for (i = 0; i < frame->nb_side_data; i++) {
1829             AVFrameSideData *sd = frame->side_data[i];
1830             const char *name;
1831
1832             writer_print_section_header(w, SECTION_ID_FRAME_SIDE_DATA);
1833             name = av_frame_side_data_name(sd->type);
1834             print_str("side_data_type", name ? name : "unknown");
1835             print_int("side_data_size", sd->size);
1836             writer_print_section_footer(w);
1837         }
1838         writer_print_section_footer(w);
1839     }
1840
1841     writer_print_section_footer(w);
1842
1843     av_bprint_finalize(&pbuf, NULL);
1844     fflush(stdout);
1845 }
1846
1847 static av_always_inline int process_frame(WriterContext *w,
1848                                           AVFormatContext *fmt_ctx,
1849                                           AVFrame *frame, AVPacket *pkt)
1850 {
1851     AVCodecContext *dec_ctx = fmt_ctx->streams[pkt->stream_index]->codec;
1852     AVSubtitle sub;
1853     int ret = 0, got_frame = 0;
1854
1855     if (dec_ctx->codec) {
1856         switch (dec_ctx->codec_type) {
1857         case AVMEDIA_TYPE_VIDEO:
1858             ret = avcodec_decode_video2(dec_ctx, frame, &got_frame, pkt);
1859             break;
1860
1861         case AVMEDIA_TYPE_AUDIO:
1862             ret = avcodec_decode_audio4(dec_ctx, frame, &got_frame, pkt);
1863             break;
1864
1865         case AVMEDIA_TYPE_SUBTITLE:
1866             ret = avcodec_decode_subtitle2(dec_ctx, &sub, &got_frame, pkt);
1867             break;
1868         }
1869     }
1870
1871     if (ret < 0)
1872         return ret;
1873     ret = FFMIN(ret, pkt->size); /* guard against bogus return values */
1874     pkt->data += ret;
1875     pkt->size -= ret;
1876     if (got_frame) {
1877         int is_sub = (dec_ctx->codec_type == AVMEDIA_TYPE_SUBTITLE);
1878         nb_streams_frames[pkt->stream_index]++;
1879         if (do_show_frames)
1880             if (is_sub)
1881                 show_subtitle(w, &sub, fmt_ctx->streams[pkt->stream_index], fmt_ctx);
1882             else
1883                 show_frame(w, frame, fmt_ctx->streams[pkt->stream_index], fmt_ctx);
1884         if (is_sub)
1885             avsubtitle_free(&sub);
1886     }
1887     return got_frame;
1888 }
1889
1890 static void log_read_interval(const ReadInterval *interval, void *log_ctx, int log_level)
1891 {
1892     av_log(log_ctx, log_level, "id:%d", interval->id);
1893
1894     if (interval->has_start) {
1895         av_log(log_ctx, log_level, " start:%s%s", interval->start_is_offset ? "+" : "",
1896                av_ts2timestr(interval->start, &AV_TIME_BASE_Q));
1897     } else {
1898         av_log(log_ctx, log_level, " start:N/A");
1899     }
1900
1901     if (interval->has_end) {
1902         av_log(log_ctx, log_level, " end:%s", interval->end_is_offset ? "+" : "");
1903         if (interval->duration_frames)
1904             av_log(log_ctx, log_level, "#%"PRId64, interval->end);
1905         else
1906             av_log(log_ctx, log_level, "%s", av_ts2timestr(interval->end, &AV_TIME_BASE_Q));
1907     } else {
1908         av_log(log_ctx, log_level, " end:N/A");
1909     }
1910
1911     av_log(log_ctx, log_level, "\n");
1912 }
1913
1914 static int read_interval_packets(WriterContext *w, AVFormatContext *fmt_ctx,
1915                                  const ReadInterval *interval, int64_t *cur_ts)
1916 {
1917     AVPacket pkt, pkt1;
1918     AVFrame *frame = NULL;
1919     int ret = 0, i = 0, frame_count = 0;
1920     int64_t start = -INT64_MAX, end = interval->end;
1921     int has_start = 0, has_end = interval->has_end && !interval->end_is_offset;
1922
1923     av_init_packet(&pkt);
1924
1925     av_log(NULL, AV_LOG_VERBOSE, "Processing read interval ");
1926     log_read_interval(interval, NULL, AV_LOG_VERBOSE);
1927
1928     if (interval->has_start) {
1929         int64_t target;
1930         if (interval->start_is_offset) {
1931             if (*cur_ts == AV_NOPTS_VALUE) {
1932                 av_log(NULL, AV_LOG_ERROR,
1933                        "Could not seek to relative position since current "
1934                        "timestamp is not defined\n");
1935                 ret = AVERROR(EINVAL);
1936                 goto end;
1937             }
1938             target = *cur_ts + interval->start;
1939         } else {
1940             target = interval->start;
1941         }
1942
1943         av_log(NULL, AV_LOG_VERBOSE, "Seeking to read interval start point %s\n",
1944                av_ts2timestr(target, &AV_TIME_BASE_Q));
1945         if ((ret = avformat_seek_file(fmt_ctx, -1, -INT64_MAX, target, INT64_MAX, 0)) < 0) {
1946             av_log(NULL, AV_LOG_ERROR, "Could not seek to position %"PRId64": %s\n",
1947                    interval->start, av_err2str(ret));
1948             goto end;
1949         }
1950     }
1951
1952     frame = av_frame_alloc();
1953     if (!frame) {
1954         ret = AVERROR(ENOMEM);
1955         goto end;
1956     }
1957     while (!av_read_frame(fmt_ctx, &pkt)) {
1958         if (fmt_ctx->nb_streams > nb_streams) {
1959             REALLOCZ_ARRAY_STREAM(nb_streams_frames,  nb_streams, fmt_ctx->nb_streams);
1960             REALLOCZ_ARRAY_STREAM(nb_streams_packets, nb_streams, fmt_ctx->nb_streams);
1961             REALLOCZ_ARRAY_STREAM(selected_streams,   nb_streams, fmt_ctx->nb_streams);
1962             nb_streams = fmt_ctx->nb_streams;
1963         }
1964         if (selected_streams[pkt.stream_index]) {
1965             AVRational tb = fmt_ctx->streams[pkt.stream_index]->time_base;
1966
1967             if (pkt.pts != AV_NOPTS_VALUE)
1968                 *cur_ts = av_rescale_q(pkt.pts, tb, AV_TIME_BASE_Q);
1969
1970             if (!has_start && *cur_ts != AV_NOPTS_VALUE) {
1971                 start = *cur_ts;
1972                 has_start = 1;
1973             }
1974
1975             if (has_start && !has_end && interval->end_is_offset) {
1976                 end = start + interval->end;
1977                 has_end = 1;
1978             }
1979
1980             if (interval->end_is_offset && interval->duration_frames) {
1981                 if (frame_count >= interval->end)
1982                     break;
1983             } else if (has_end && *cur_ts != AV_NOPTS_VALUE && *cur_ts >= end) {
1984                 break;
1985             }
1986
1987             frame_count++;
1988             if (do_read_packets) {
1989                 if (do_show_packets)
1990                     show_packet(w, fmt_ctx, &pkt, i++);
1991                 nb_streams_packets[pkt.stream_index]++;
1992             }
1993             if (do_read_frames) {
1994                 pkt1 = pkt;
1995                 while (pkt1.size && process_frame(w, fmt_ctx, frame, &pkt1) > 0);
1996             }
1997         }
1998         av_free_packet(&pkt);
1999     }
2000     av_init_packet(&pkt);
2001     pkt.data = NULL;
2002     pkt.size = 0;
2003     //Flush remaining frames that are cached in the decoder
2004     for (i = 0; i < fmt_ctx->nb_streams; i++) {
2005         pkt.stream_index = i;
2006         if (do_read_frames)
2007             while (process_frame(w, fmt_ctx, frame, &pkt) > 0);
2008     }
2009
2010 end:
2011     av_frame_free(&frame);
2012     if (ret < 0) {
2013         av_log(NULL, AV_LOG_ERROR, "Could not read packets in interval ");
2014         log_read_interval(interval, NULL, AV_LOG_ERROR);
2015     }
2016     return ret;
2017 }
2018
2019 static int read_packets(WriterContext *w, AVFormatContext *fmt_ctx)
2020 {
2021     int i, ret = 0;
2022     int64_t cur_ts = fmt_ctx->start_time;
2023
2024     if (read_intervals_nb == 0) {
2025         ReadInterval interval = (ReadInterval) { .has_start = 0, .has_end = 0 };
2026         ret = read_interval_packets(w, fmt_ctx, &interval, &cur_ts);
2027     } else {
2028         for (i = 0; i < read_intervals_nb; i++) {
2029             ret = read_interval_packets(w, fmt_ctx, &read_intervals[i], &cur_ts);
2030             if (ret < 0)
2031                 break;
2032         }
2033     }
2034
2035     return ret;
2036 }
2037
2038 static int show_stream(WriterContext *w, AVFormatContext *fmt_ctx, int stream_idx, int in_program)
2039 {
2040     AVStream *stream = fmt_ctx->streams[stream_idx];
2041     AVCodecContext *dec_ctx;
2042     const AVCodec *dec;
2043     char val_str[128];
2044     const char *s;
2045     AVRational sar, dar;
2046     AVBPrint pbuf;
2047     const AVCodecDescriptor *cd;
2048     int ret = 0;
2049
2050     av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
2051
2052     writer_print_section_header(w, in_program ? SECTION_ID_PROGRAM_STREAM : SECTION_ID_STREAM);
2053
2054     print_int("index", stream->index);
2055
2056     if ((dec_ctx = stream->codec)) {
2057         const char *profile = NULL;
2058         dec = dec_ctx->codec;
2059         if (dec) {
2060             print_str("codec_name", dec->name);
2061             if (!do_bitexact) {
2062                 if (dec->long_name) print_str    ("codec_long_name", dec->long_name);
2063                 else                print_str_opt("codec_long_name", "unknown");
2064             }
2065         } else if ((cd = avcodec_descriptor_get(stream->codec->codec_id))) {
2066             print_str_opt("codec_name", cd->name);
2067             if (!do_bitexact) {
2068                 print_str_opt("codec_long_name",
2069                               cd->long_name ? cd->long_name : "unknown");
2070             }
2071         } else {
2072             print_str_opt("codec_name", "unknown");
2073             if (!do_bitexact) {
2074                 print_str_opt("codec_long_name", "unknown");
2075             }
2076         }
2077
2078         if (dec && (profile = av_get_profile_name(dec, dec_ctx->profile)))
2079             print_str("profile", profile);
2080         else
2081             print_str_opt("profile", "unknown");
2082
2083         s = av_get_media_type_string(dec_ctx->codec_type);
2084         if (s) print_str    ("codec_type", s);
2085         else   print_str_opt("codec_type", "unknown");
2086         print_q("codec_time_base", dec_ctx->time_base, '/');
2087
2088         /* print AVI/FourCC tag */
2089         av_get_codec_tag_string(val_str, sizeof(val_str), dec_ctx->codec_tag);
2090         print_str("codec_tag_string",    val_str);
2091         print_fmt("codec_tag", "0x%04x", dec_ctx->codec_tag);
2092
2093         switch (dec_ctx->codec_type) {
2094         case AVMEDIA_TYPE_VIDEO:
2095             print_int("width",        dec_ctx->width);
2096             print_int("height",       dec_ctx->height);
2097             print_int("has_b_frames", dec_ctx->has_b_frames);
2098             sar = av_guess_sample_aspect_ratio(fmt_ctx, stream, NULL);
2099             if (sar.den) {
2100                 print_q("sample_aspect_ratio", sar, ':');
2101                 av_reduce(&dar.num, &dar.den,
2102                           dec_ctx->width  * sar.num,
2103                           dec_ctx->height * sar.den,
2104                           1024*1024);
2105                 print_q("display_aspect_ratio", dar, ':');
2106             } else {
2107                 print_str_opt("sample_aspect_ratio", "N/A");
2108                 print_str_opt("display_aspect_ratio", "N/A");
2109             }
2110             s = av_get_pix_fmt_name(dec_ctx->pix_fmt);
2111             if (s) print_str    ("pix_fmt", s);
2112             else   print_str_opt("pix_fmt", "unknown");
2113             print_int("level",   dec_ctx->level);
2114             if (dec_ctx->color_range != AVCOL_RANGE_UNSPECIFIED)
2115                 print_str    ("color_range", av_color_range_name(dec_ctx->color_range));
2116             else
2117                 print_str_opt("color_range", "N/A");
2118             s = av_get_colorspace_name(dec_ctx->colorspace);
2119             if (s) print_str    ("color_space", s);
2120             else   print_str_opt("color_space", "unknown");
2121
2122             if (dec_ctx->color_trc != AVCOL_TRC_UNSPECIFIED)
2123                 print_str("color_transfer", av_color_transfer_name(dec_ctx->color_trc));
2124             else
2125                 print_str_opt("color_transfer", av_color_transfer_name(dec_ctx->color_trc));
2126
2127             if (dec_ctx->color_primaries != AVCOL_PRI_UNSPECIFIED)
2128                 print_str("color_primaries", av_color_primaries_name(dec_ctx->color_primaries));
2129             else
2130                 print_str_opt("color_primaries", av_color_primaries_name(dec_ctx->color_primaries));
2131
2132             if (dec_ctx->chroma_sample_location != AVCHROMA_LOC_UNSPECIFIED)
2133                 print_str("chroma_location", av_chroma_location_name(dec_ctx->chroma_sample_location));
2134             else
2135                 print_str_opt("chroma_location", av_chroma_location_name(dec_ctx->chroma_sample_location));
2136
2137             if (dec_ctx->timecode_frame_start >= 0) {
2138                 char tcbuf[AV_TIMECODE_STR_SIZE];
2139                 av_timecode_make_mpeg_tc_string(tcbuf, dec_ctx->timecode_frame_start);
2140                 print_str("timecode", tcbuf);
2141             } else {
2142                 print_str_opt("timecode", "N/A");
2143             }
2144             print_int("refs", dec_ctx->refs);
2145             break;
2146
2147         case AVMEDIA_TYPE_AUDIO:
2148             s = av_get_sample_fmt_name(dec_ctx->sample_fmt);
2149             if (s) print_str    ("sample_fmt", s);
2150             else   print_str_opt("sample_fmt", "unknown");
2151             print_val("sample_rate",     dec_ctx->sample_rate, unit_hertz_str);
2152             print_int("channels",        dec_ctx->channels);
2153
2154             if (dec_ctx->channel_layout) {
2155                 av_bprint_clear(&pbuf);
2156                 av_bprint_channel_layout(&pbuf, dec_ctx->channels, dec_ctx->channel_layout);
2157                 print_str    ("channel_layout", pbuf.str);
2158             } else {
2159                 print_str_opt("channel_layout", "unknown");
2160             }
2161
2162             print_int("bits_per_sample", av_get_bits_per_sample(dec_ctx->codec_id));
2163             break;
2164
2165         case AVMEDIA_TYPE_SUBTITLE:
2166             if (dec_ctx->width)
2167                 print_int("width",       dec_ctx->width);
2168             else
2169                 print_str_opt("width",   "N/A");
2170             if (dec_ctx->height)
2171                 print_int("height",      dec_ctx->height);
2172             else
2173                 print_str_opt("height",  "N/A");
2174             break;
2175         }
2176     } else {
2177         print_str_opt("codec_type", "unknown");
2178     }
2179     if (dec_ctx->codec && dec_ctx->codec->priv_class && show_private_data) {
2180         const AVOption *opt = NULL;
2181         while (opt = av_opt_next(dec_ctx->priv_data,opt)) {
2182             uint8_t *str;
2183             if (opt->flags) continue;
2184             if (av_opt_get(dec_ctx->priv_data, opt->name, 0, &str) >= 0) {
2185                 print_str(opt->name, str);
2186                 av_free(str);
2187             }
2188         }
2189     }
2190
2191     if (fmt_ctx->iformat->flags & AVFMT_SHOW_IDS) print_fmt    ("id", "0x%x", stream->id);
2192     else                                          print_str_opt("id", "N/A");
2193     print_q("r_frame_rate",   stream->r_frame_rate,   '/');
2194     print_q("avg_frame_rate", stream->avg_frame_rate, '/');
2195     print_q("time_base",      stream->time_base,      '/');
2196     print_ts  ("start_pts",   stream->start_time);
2197     print_time("start_time",  stream->start_time, &stream->time_base);
2198     print_ts  ("duration_ts", stream->duration);
2199     print_time("duration",    stream->duration, &stream->time_base);
2200     if (dec_ctx->bit_rate > 0) print_val    ("bit_rate", dec_ctx->bit_rate, unit_bit_per_second_str);
2201     else                       print_str_opt("bit_rate", "N/A");
2202     if (dec_ctx->rc_max_rate > 0) print_val ("max_bit_rate", dec_ctx->rc_max_rate, unit_bit_per_second_str);
2203     else                       print_str_opt("max_bit_rate", "N/A");
2204     if (dec_ctx->bits_per_raw_sample > 0) print_fmt("bits_per_raw_sample", "%d", dec_ctx->bits_per_raw_sample);
2205     else                       print_str_opt("bits_per_raw_sample", "N/A");
2206     if (stream->nb_frames) print_fmt    ("nb_frames", "%"PRId64, stream->nb_frames);
2207     else                   print_str_opt("nb_frames", "N/A");
2208     if (nb_streams_frames[stream_idx])  print_fmt    ("nb_read_frames", "%"PRIu64, nb_streams_frames[stream_idx]);
2209     else                                print_str_opt("nb_read_frames", "N/A");
2210     if (nb_streams_packets[stream_idx]) print_fmt    ("nb_read_packets", "%"PRIu64, nb_streams_packets[stream_idx]);
2211     else                                print_str_opt("nb_read_packets", "N/A");
2212     if (do_show_data)
2213         writer_print_data(w, "extradata", dec_ctx->extradata,
2214                                           dec_ctx->extradata_size);
2215     writer_print_data_hash(w, "extradata_hash", dec_ctx->extradata,
2216                                                 dec_ctx->extradata_size);
2217
2218     /* Print disposition information */
2219 #define PRINT_DISPOSITION(flagname, name) do {                                \
2220         print_int(name, !!(stream->disposition & AV_DISPOSITION_##flagname)); \
2221     } while (0)
2222
2223     if (do_show_stream_disposition) {
2224     writer_print_section_header(w, in_program ? SECTION_ID_PROGRAM_STREAM_DISPOSITION : SECTION_ID_STREAM_DISPOSITION);
2225     PRINT_DISPOSITION(DEFAULT,          "default");
2226     PRINT_DISPOSITION(DUB,              "dub");
2227     PRINT_DISPOSITION(ORIGINAL,         "original");
2228     PRINT_DISPOSITION(COMMENT,          "comment");
2229     PRINT_DISPOSITION(LYRICS,           "lyrics");
2230     PRINT_DISPOSITION(KARAOKE,          "karaoke");
2231     PRINT_DISPOSITION(FORCED,           "forced");
2232     PRINT_DISPOSITION(HEARING_IMPAIRED, "hearing_impaired");
2233     PRINT_DISPOSITION(VISUAL_IMPAIRED,  "visual_impaired");
2234     PRINT_DISPOSITION(CLEAN_EFFECTS,    "clean_effects");
2235     PRINT_DISPOSITION(ATTACHED_PIC,     "attached_pic");
2236     writer_print_section_footer(w);
2237     }
2238
2239     if (do_show_stream_tags)
2240         ret = show_tags(w, stream->metadata, in_program ? SECTION_ID_PROGRAM_STREAM_TAGS : SECTION_ID_STREAM_TAGS);
2241
2242     writer_print_section_footer(w);
2243     av_bprint_finalize(&pbuf, NULL);
2244     fflush(stdout);
2245
2246     return ret;
2247 }
2248
2249 static int show_streams(WriterContext *w, AVFormatContext *fmt_ctx)
2250 {
2251     int i, ret = 0;
2252
2253     writer_print_section_header(w, SECTION_ID_STREAMS);
2254     for (i = 0; i < fmt_ctx->nb_streams; i++)
2255         if (selected_streams[i]) {
2256             ret = show_stream(w, fmt_ctx, i, 0);
2257             if (ret < 0)
2258                 break;
2259         }
2260     writer_print_section_footer(w);
2261
2262     return ret;
2263 }
2264
2265 static int show_program(WriterContext *w, AVFormatContext *fmt_ctx, AVProgram *program)
2266 {
2267     int i, ret = 0;
2268
2269     writer_print_section_header(w, SECTION_ID_PROGRAM);
2270     print_int("program_id", program->id);
2271     print_int("program_num", program->program_num);
2272     print_int("nb_streams", program->nb_stream_indexes);
2273     print_int("pmt_pid", program->pmt_pid);
2274     print_int("pcr_pid", program->pcr_pid);
2275     print_ts("start_pts", program->start_time);
2276     print_time("start_time", program->start_time, &AV_TIME_BASE_Q);
2277     print_ts("end_pts", program->end_time);
2278     print_time("end_time", program->end_time, &AV_TIME_BASE_Q);
2279     if (do_show_program_tags)
2280         ret = show_tags(w, program->metadata, SECTION_ID_PROGRAM_TAGS);
2281     if (ret < 0)
2282         goto end;
2283
2284     writer_print_section_header(w, SECTION_ID_PROGRAM_STREAMS);
2285     for (i = 0; i < program->nb_stream_indexes; i++) {
2286         if (selected_streams[program->stream_index[i]]) {
2287             ret = show_stream(w, fmt_ctx, program->stream_index[i], 1);
2288             if (ret < 0)
2289                 break;
2290         }
2291     }
2292     writer_print_section_footer(w);
2293
2294 end:
2295     writer_print_section_footer(w);
2296     return ret;
2297 }
2298
2299 static int show_programs(WriterContext *w, AVFormatContext *fmt_ctx)
2300 {
2301     int i, ret = 0;
2302
2303     writer_print_section_header(w, SECTION_ID_PROGRAMS);
2304     for (i = 0; i < fmt_ctx->nb_programs; i++) {
2305         AVProgram *program = fmt_ctx->programs[i];
2306         if (!program)
2307             continue;
2308         ret = show_program(w, fmt_ctx, program);
2309         if (ret < 0)
2310             break;
2311     }
2312     writer_print_section_footer(w);
2313     return ret;
2314 }
2315
2316 static int show_chapters(WriterContext *w, AVFormatContext *fmt_ctx)
2317 {
2318     int i, ret = 0;
2319
2320     writer_print_section_header(w, SECTION_ID_CHAPTERS);
2321     for (i = 0; i < fmt_ctx->nb_chapters; i++) {
2322         AVChapter *chapter = fmt_ctx->chapters[i];
2323
2324         writer_print_section_header(w, SECTION_ID_CHAPTER);
2325         print_int("id", chapter->id);
2326         print_q  ("time_base", chapter->time_base, '/');
2327         print_int("start", chapter->start);
2328         print_time("start_time", chapter->start, &chapter->time_base);
2329         print_int("end", chapter->end);
2330         print_time("end_time", chapter->end, &chapter->time_base);
2331         if (do_show_chapter_tags)
2332             ret = show_tags(w, chapter->metadata, SECTION_ID_CHAPTER_TAGS);
2333         writer_print_section_footer(w);
2334     }
2335     writer_print_section_footer(w);
2336
2337     return ret;
2338 }
2339
2340 static int show_format(WriterContext *w, AVFormatContext *fmt_ctx)
2341 {
2342     char val_str[128];
2343     int64_t size = fmt_ctx->pb ? avio_size(fmt_ctx->pb) : -1;
2344     int ret = 0;
2345
2346     writer_print_section_header(w, SECTION_ID_FORMAT);
2347     print_str_validate("filename", fmt_ctx->filename);
2348     print_int("nb_streams",       fmt_ctx->nb_streams);
2349     print_int("nb_programs",      fmt_ctx->nb_programs);
2350     print_str("format_name",      fmt_ctx->iformat->name);
2351     if (!do_bitexact) {
2352         if (fmt_ctx->iformat->long_name) print_str    ("format_long_name", fmt_ctx->iformat->long_name);
2353         else                             print_str_opt("format_long_name", "unknown");
2354     }
2355     print_time("start_time",      fmt_ctx->start_time, &AV_TIME_BASE_Q);
2356     print_time("duration",        fmt_ctx->duration,   &AV_TIME_BASE_Q);
2357     if (size >= 0) print_val    ("size", size, unit_byte_str);
2358     else           print_str_opt("size", "N/A");
2359     if (fmt_ctx->bit_rate > 0) print_val    ("bit_rate", fmt_ctx->bit_rate, unit_bit_per_second_str);
2360     else                       print_str_opt("bit_rate", "N/A");
2361     print_int("probe_score", av_format_get_probe_score(fmt_ctx));
2362     if (do_show_format_tags)
2363         ret = show_tags(w, fmt_ctx->metadata, SECTION_ID_FORMAT_TAGS);
2364
2365     writer_print_section_footer(w);
2366     fflush(stdout);
2367     return ret;
2368 }
2369
2370 static void show_error(WriterContext *w, int err)
2371 {
2372     char errbuf[128];
2373     const char *errbuf_ptr = errbuf;
2374
2375     if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
2376         errbuf_ptr = strerror(AVUNERROR(err));
2377
2378     writer_print_section_header(w, SECTION_ID_ERROR);
2379     print_int("code", err);
2380     print_str("string", errbuf_ptr);
2381     writer_print_section_footer(w);
2382 }
2383
2384 static int open_input_file(AVFormatContext **fmt_ctx_ptr, const char *filename)
2385 {
2386     int err, i, orig_nb_streams;
2387     AVFormatContext *fmt_ctx = NULL;
2388     AVDictionaryEntry *t;
2389     AVDictionary **opts;
2390     int scan_all_pmts_set = 0;
2391
2392     if (!av_dict_get(format_opts, "scan_all_pmts", NULL, AV_DICT_MATCH_CASE)) {
2393         av_dict_set(&format_opts, "scan_all_pmts", "1", AV_DICT_DONT_OVERWRITE);
2394         scan_all_pmts_set = 1;
2395     }
2396     if ((err = avformat_open_input(&fmt_ctx, filename,
2397                                    iformat, &format_opts)) < 0) {
2398         print_error(filename, err);
2399         return err;
2400     }
2401     *fmt_ctx_ptr = fmt_ctx;
2402     if (scan_all_pmts_set)
2403         av_dict_set(&format_opts, "scan_all_pmts", NULL, AV_DICT_MATCH_CASE);
2404     if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
2405         av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
2406         return AVERROR_OPTION_NOT_FOUND;
2407     }
2408
2409     /* fill the streams in the format context */
2410     opts = setup_find_stream_info_opts(fmt_ctx, codec_opts);
2411     orig_nb_streams = fmt_ctx->nb_streams;
2412
2413     err = avformat_find_stream_info(fmt_ctx, opts);
2414
2415     for (i = 0; i < orig_nb_streams; i++)
2416         av_dict_free(&opts[i]);
2417     av_freep(&opts);
2418
2419     if (err < 0) {
2420         print_error(filename, err);
2421         return err;
2422     }
2423
2424     av_dump_format(fmt_ctx, 0, filename, 0);
2425
2426     /* bind a decoder to each input stream */
2427     for (i = 0; i < fmt_ctx->nb_streams; i++) {
2428         AVStream *stream = fmt_ctx->streams[i];
2429         AVCodec *codec;
2430
2431         if (stream->codec->codec_id == AV_CODEC_ID_PROBE) {
2432             av_log(NULL, AV_LOG_WARNING,
2433                    "Failed to probe codec for input stream %d\n",
2434                     stream->index);
2435         } else if (!(codec = avcodec_find_decoder(stream->codec->codec_id))) {
2436             av_log(NULL, AV_LOG_WARNING,
2437                     "Unsupported codec with id %d for input stream %d\n",
2438                     stream->codec->codec_id, stream->index);
2439         } else {
2440             AVDictionary *opts = filter_codec_opts(codec_opts, stream->codec->codec_id,
2441                                                    fmt_ctx, stream, codec);
2442             if (avcodec_open2(stream->codec, codec, &opts) < 0) {
2443                 av_log(NULL, AV_LOG_WARNING, "Could not open codec for input stream %d\n",
2444                        stream->index);
2445             }
2446             if ((t = av_dict_get(opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
2447                 av_log(NULL, AV_LOG_ERROR, "Option %s for input stream %d not found\n",
2448                        t->key, stream->index);
2449                 return AVERROR_OPTION_NOT_FOUND;
2450             }
2451         }
2452     }
2453
2454     *fmt_ctx_ptr = fmt_ctx;
2455     return 0;
2456 }
2457
2458 static void close_input_file(AVFormatContext **ctx_ptr)
2459 {
2460     int i;
2461     AVFormatContext *fmt_ctx = *ctx_ptr;
2462
2463     /* close decoder for each stream */
2464     for (i = 0; i < fmt_ctx->nb_streams; i++)
2465         if (fmt_ctx->streams[i]->codec->codec_id != AV_CODEC_ID_NONE)
2466             avcodec_close(fmt_ctx->streams[i]->codec);
2467
2468     avformat_close_input(ctx_ptr);
2469 }
2470
2471 static int probe_file(WriterContext *wctx, const char *filename)
2472 {
2473     AVFormatContext *fmt_ctx = NULL;
2474     int ret, i;
2475     int section_id;
2476
2477     do_read_frames = do_show_frames || do_count_frames;
2478     do_read_packets = do_show_packets || do_count_packets;
2479
2480     ret = open_input_file(&fmt_ctx, filename);
2481     if (ret < 0)
2482         goto end;
2483
2484 #define CHECK_END if (ret < 0) goto end
2485
2486     nb_streams = fmt_ctx->nb_streams;
2487     REALLOCZ_ARRAY_STREAM(nb_streams_frames,0,fmt_ctx->nb_streams);
2488     REALLOCZ_ARRAY_STREAM(nb_streams_packets,0,fmt_ctx->nb_streams);
2489     REALLOCZ_ARRAY_STREAM(selected_streams,0,fmt_ctx->nb_streams);
2490
2491     for (i = 0; i < fmt_ctx->nb_streams; i++) {
2492         if (stream_specifier) {
2493             ret = avformat_match_stream_specifier(fmt_ctx,
2494                                                   fmt_ctx->streams[i],
2495                                                   stream_specifier);
2496             CHECK_END;
2497             else
2498                 selected_streams[i] = ret;
2499             ret = 0;
2500         } else {
2501             selected_streams[i] = 1;
2502         }
2503     }
2504
2505     if (do_read_frames || do_read_packets) {
2506         if (do_show_frames && do_show_packets &&
2507             wctx->writer->flags & WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER)
2508             section_id = SECTION_ID_PACKETS_AND_FRAMES;
2509         else if (do_show_packets && !do_show_frames)
2510             section_id = SECTION_ID_PACKETS;
2511         else // (!do_show_packets && do_show_frames)
2512             section_id = SECTION_ID_FRAMES;
2513         if (do_show_frames || do_show_packets)
2514             writer_print_section_header(wctx, section_id);
2515         ret = read_packets(wctx, fmt_ctx);
2516         if (do_show_frames || do_show_packets)
2517             writer_print_section_footer(wctx);
2518         CHECK_END;
2519     }
2520
2521     if (do_show_programs) {
2522         ret = show_programs(wctx, fmt_ctx);
2523         CHECK_END;
2524     }
2525
2526     if (do_show_streams) {
2527         ret = show_streams(wctx, fmt_ctx);
2528         CHECK_END;
2529     }
2530     if (do_show_chapters) {
2531         ret = show_chapters(wctx, fmt_ctx);
2532         CHECK_END;
2533     }
2534     if (do_show_format) {
2535         ret = show_format(wctx, fmt_ctx);
2536         CHECK_END;
2537     }
2538
2539 end:
2540     if (fmt_ctx)
2541         close_input_file(&fmt_ctx);
2542     av_freep(&nb_streams_frames);
2543     av_freep(&nb_streams_packets);
2544     av_freep(&selected_streams);
2545
2546     return ret;
2547 }
2548
2549 static void show_usage(void)
2550 {
2551     av_log(NULL, AV_LOG_INFO, "Simple multimedia streams analyzer\n");
2552     av_log(NULL, AV_LOG_INFO, "usage: %s [OPTIONS] [INPUT_FILE]\n", program_name);
2553     av_log(NULL, AV_LOG_INFO, "\n");
2554 }
2555
2556 static void ffprobe_show_program_version(WriterContext *w)
2557 {
2558     AVBPrint pbuf;
2559     av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
2560
2561     writer_print_section_header(w, SECTION_ID_PROGRAM_VERSION);
2562     print_str("version", FFMPEG_VERSION);
2563     print_fmt("copyright", "Copyright (c) %d-%d the FFmpeg developers",
2564               program_birth_year, CONFIG_THIS_YEAR);
2565     print_str("compiler_ident", CC_IDENT);
2566     print_str("configuration", FFMPEG_CONFIGURATION);
2567     writer_print_section_footer(w);
2568
2569     av_bprint_finalize(&pbuf, NULL);
2570 }
2571
2572 #define SHOW_LIB_VERSION(libname, LIBNAME)                              \
2573     do {                                                                \
2574         if (CONFIG_##LIBNAME) {                                         \
2575             unsigned int version = libname##_version();                 \
2576             writer_print_section_header(w, SECTION_ID_LIBRARY_VERSION); \
2577             print_str("name",    "lib" #libname);                       \
2578             print_int("major",   LIB##LIBNAME##_VERSION_MAJOR);         \
2579             print_int("minor",   LIB##LIBNAME##_VERSION_MINOR);         \
2580             print_int("micro",   LIB##LIBNAME##_VERSION_MICRO);         \
2581             print_int("version", version);                              \
2582             print_str("ident",   LIB##LIBNAME##_IDENT);                 \
2583             writer_print_section_footer(w);                             \
2584         }                                                               \
2585     } while (0)
2586
2587 static void ffprobe_show_library_versions(WriterContext *w)
2588 {
2589     writer_print_section_header(w, SECTION_ID_LIBRARY_VERSIONS);
2590     SHOW_LIB_VERSION(avutil,     AVUTIL);
2591     SHOW_LIB_VERSION(avcodec,    AVCODEC);
2592     SHOW_LIB_VERSION(avformat,   AVFORMAT);
2593     SHOW_LIB_VERSION(avdevice,   AVDEVICE);
2594     SHOW_LIB_VERSION(avfilter,   AVFILTER);
2595     SHOW_LIB_VERSION(swscale,    SWSCALE);
2596     SHOW_LIB_VERSION(swresample, SWRESAMPLE);
2597     SHOW_LIB_VERSION(postproc,   POSTPROC);
2598     writer_print_section_footer(w);
2599 }
2600
2601 #define PRINT_PIX_FMT_FLAG(flagname, name)                                \
2602     do {                                                                  \
2603         print_int(name, !!(pixdesc->flags & AV_PIX_FMT_FLAG_##flagname)); \
2604     } while (0)
2605
2606 static void ffprobe_show_pixel_formats(WriterContext *w)
2607 {
2608     const AVPixFmtDescriptor *pixdesc = NULL;
2609     int i, n;
2610
2611     writer_print_section_header(w, SECTION_ID_PIXEL_FORMATS);
2612     while (pixdesc = av_pix_fmt_desc_next(pixdesc)) {
2613         writer_print_section_header(w, SECTION_ID_PIXEL_FORMAT);
2614         print_str("name", pixdesc->name);
2615         print_int("nb_components", pixdesc->nb_components);
2616         if ((pixdesc->nb_components >= 3) && !(pixdesc->flags & AV_PIX_FMT_FLAG_RGB)) {
2617             print_int    ("log2_chroma_w", pixdesc->log2_chroma_w);
2618             print_int    ("log2_chroma_h", pixdesc->log2_chroma_h);
2619         } else {
2620             print_str_opt("log2_chroma_w", "N/A");
2621             print_str_opt("log2_chroma_h", "N/A");
2622         }
2623         n = av_get_bits_per_pixel(pixdesc);
2624         if (n) print_int    ("bits_per_pixel", n);
2625         else   print_str_opt("bits_per_pixel", "N/A");
2626         if (do_show_pixel_format_flags) {
2627             writer_print_section_header(w, SECTION_ID_PIXEL_FORMAT_FLAGS);
2628             PRINT_PIX_FMT_FLAG(BE,        "big_endian");
2629             PRINT_PIX_FMT_FLAG(PAL,       "palette");
2630             PRINT_PIX_FMT_FLAG(BITSTREAM, "bitstream");
2631             PRINT_PIX_FMT_FLAG(HWACCEL,   "hwaccel");
2632             PRINT_PIX_FMT_FLAG(PLANAR,    "planar");
2633             PRINT_PIX_FMT_FLAG(RGB,       "rgb");
2634             PRINT_PIX_FMT_FLAG(PSEUDOPAL, "pseudopal");
2635             PRINT_PIX_FMT_FLAG(ALPHA,     "alpha");
2636             writer_print_section_footer(w);
2637         }
2638         if (do_show_pixel_format_components && (pixdesc->nb_components > 0)) {
2639             writer_print_section_header(w, SECTION_ID_PIXEL_FORMAT_COMPONENTS);
2640             for (i = 0; i < pixdesc->nb_components; i++) {
2641                 writer_print_section_header(w, SECTION_ID_PIXEL_FORMAT_COMPONENT);
2642                 print_int("index", i + 1);
2643                 print_int("bit_depth", pixdesc->comp[i].depth_minus1 + 1);
2644                 writer_print_section_footer(w);
2645             }
2646             writer_print_section_footer(w);
2647         }
2648         writer_print_section_footer(w);
2649     }
2650     writer_print_section_footer(w);
2651 }
2652
2653 static int opt_format(void *optctx, const char *opt, const char *arg)
2654 {
2655     iformat = av_find_input_format(arg);
2656     if (!iformat) {
2657         av_log(NULL, AV_LOG_ERROR, "Unknown input format: %s\n", arg);
2658         return AVERROR(EINVAL);
2659     }
2660     return 0;
2661 }
2662
2663 static inline void mark_section_show_entries(SectionID section_id,
2664                                              int show_all_entries, AVDictionary *entries)
2665 {
2666     struct section *section = &sections[section_id];
2667
2668     section->show_all_entries = show_all_entries;
2669     if (show_all_entries) {
2670         SectionID *id;
2671         for (id = section->children_ids; *id != -1; id++)
2672             mark_section_show_entries(*id, show_all_entries, entries);
2673     } else {
2674         av_dict_copy(&section->entries_to_show, entries, 0);
2675     }
2676 }
2677
2678 static int match_section(const char *section_name,
2679                          int show_all_entries, AVDictionary *entries)
2680 {
2681     int i, ret = 0;
2682
2683     for (i = 0; i < FF_ARRAY_ELEMS(sections); i++) {
2684         const struct section *section = &sections[i];
2685         if (!strcmp(section_name, section->name) ||
2686             (section->unique_name && !strcmp(section_name, section->unique_name))) {
2687             av_log(NULL, AV_LOG_DEBUG,
2688                    "'%s' matches section with unique name '%s'\n", section_name,
2689                    (char *)av_x_if_null(section->unique_name, section->name));
2690             ret++;
2691             mark_section_show_entries(section->id, show_all_entries, entries);
2692         }
2693     }
2694     return ret;
2695 }
2696
2697 static int opt_show_entries(void *optctx, const char *opt, const char *arg)
2698 {
2699     const char *p = arg;
2700     int ret = 0;
2701
2702     while (*p) {
2703         AVDictionary *entries = NULL;
2704         char *section_name = av_get_token(&p, "=:");
2705         int show_all_entries = 0;
2706
2707         if (!section_name) {
2708             av_log(NULL, AV_LOG_ERROR,
2709                    "Missing section name for option '%s'\n", opt);
2710             return AVERROR(EINVAL);
2711         }
2712
2713         if (*p == '=') {
2714             p++;
2715             while (*p && *p != ':') {
2716                 char *entry = av_get_token(&p, ",:");
2717                 if (!entry)
2718                     break;
2719                 av_log(NULL, AV_LOG_VERBOSE,
2720                        "Adding '%s' to the entries to show in section '%s'\n",
2721                        entry, section_name);
2722                 av_dict_set(&entries, entry, "", AV_DICT_DONT_STRDUP_KEY);
2723                 if (*p == ',')
2724                     p++;
2725             }
2726         } else {
2727             show_all_entries = 1;
2728         }
2729
2730         ret = match_section(section_name, show_all_entries, entries);
2731         if (ret == 0) {
2732             av_log(NULL, AV_LOG_ERROR, "No match for section '%s'\n", section_name);
2733             ret = AVERROR(EINVAL);
2734         }
2735         av_dict_free(&entries);
2736         av_free(section_name);
2737
2738         if (ret <= 0)
2739             break;
2740         if (*p)
2741             p++;
2742     }
2743
2744     return ret;
2745 }
2746
2747 static int opt_show_format_entry(void *optctx, const char *opt, const char *arg)
2748 {
2749     char *buf = av_asprintf("format=%s", arg);
2750     int ret;
2751
2752     av_log(NULL, AV_LOG_WARNING,
2753            "Option '%s' is deprecated, use '-show_entries format=%s' instead\n",
2754            opt, arg);
2755     ret = opt_show_entries(optctx, opt, buf);
2756     av_free(buf);
2757     return ret;
2758 }
2759
2760 static void opt_input_file(void *optctx, const char *arg)
2761 {
2762     if (input_filename) {
2763         av_log(NULL, AV_LOG_ERROR,
2764                 "Argument '%s' provided as input filename, but '%s' was already specified.\n",
2765                 arg, input_filename);
2766         exit_program(1);
2767     }
2768     if (!strcmp(arg, "-"))
2769         arg = "pipe:";
2770     input_filename = arg;
2771 }
2772
2773 static int opt_input_file_i(void *optctx, const char *opt, const char *arg)
2774 {
2775     opt_input_file(optctx, arg);
2776     return 0;
2777 }
2778
2779 void show_help_default(const char *opt, const char *arg)
2780 {
2781     av_log_set_callback(log_callback_help);
2782     show_usage();
2783     show_help_options(options, "Main options:", 0, 0, 0);
2784     printf("\n");
2785
2786     show_help_children(avformat_get_class(), AV_OPT_FLAG_DECODING_PARAM);
2787 }
2788
2789 /**
2790  * Parse interval specification, according to the format:
2791  * INTERVAL ::= [START|+START_OFFSET][%[END|+END_OFFSET]]
2792  * INTERVALS ::= INTERVAL[,INTERVALS]
2793 */
2794 static int parse_read_interval(const char *interval_spec,
2795                                ReadInterval *interval)
2796 {
2797     int ret = 0;
2798     char *next, *p, *spec = av_strdup(interval_spec);
2799     if (!spec)
2800         return AVERROR(ENOMEM);
2801
2802     if (!*spec) {
2803         av_log(NULL, AV_LOG_ERROR, "Invalid empty interval specification\n");
2804         ret = AVERROR(EINVAL);
2805         goto end;
2806     }
2807
2808     p = spec;
2809     next = strchr(spec, '%');
2810     if (next)
2811         *next++ = 0;
2812
2813     /* parse first part */
2814     if (*p) {
2815         interval->has_start = 1;
2816
2817         if (*p == '+') {
2818             interval->start_is_offset = 1;
2819             p++;
2820         } else {
2821             interval->start_is_offset = 0;
2822         }
2823
2824         ret = av_parse_time(&interval->start, p, 1);
2825         if (ret < 0) {
2826             av_log(NULL, AV_LOG_ERROR, "Invalid interval start specification '%s'\n", p);
2827             goto end;
2828         }
2829     } else {
2830         interval->has_start = 0;
2831     }
2832
2833     /* parse second part */
2834     p = next;
2835     if (p && *p) {
2836         int64_t us;
2837         interval->has_end = 1;
2838
2839         if (*p == '+') {
2840             interval->end_is_offset = 1;
2841             p++;
2842         } else {
2843             interval->end_is_offset = 0;
2844         }
2845
2846         if (interval->end_is_offset && *p == '#') {
2847             long long int lli;
2848             char *tail;
2849             interval->duration_frames = 1;
2850             p++;
2851             lli = strtoll(p, &tail, 10);
2852             if (*tail || lli < 0) {
2853                 av_log(NULL, AV_LOG_ERROR,
2854                        "Invalid or negative value '%s' for duration number of frames\n", p);
2855                 goto end;
2856             }
2857             interval->end = lli;
2858         } else {
2859             ret = av_parse_time(&us, p, 1);
2860             if (ret < 0) {
2861                 av_log(NULL, AV_LOG_ERROR, "Invalid interval end/duration specification '%s'\n", p);
2862                 goto end;
2863             }
2864             interval->end = us;
2865         }
2866     } else {
2867         interval->has_end = 0;
2868     }
2869
2870 end:
2871     av_free(spec);
2872     return ret;
2873 }
2874
2875 static int parse_read_intervals(const char *intervals_spec)
2876 {
2877     int ret, n, i;
2878     char *p, *spec = av_strdup(intervals_spec);
2879     if (!spec)
2880         return AVERROR(ENOMEM);
2881
2882     /* preparse specification, get number of intervals */
2883     for (n = 0, p = spec; *p; p++)
2884         if (*p == ',')
2885             n++;
2886     n++;
2887
2888     read_intervals = av_malloc_array(n, sizeof(*read_intervals));
2889     if (!read_intervals) {
2890         ret = AVERROR(ENOMEM);
2891         goto end;
2892     }
2893     read_intervals_nb = n;
2894
2895     /* parse intervals */
2896     p = spec;
2897     for (i = 0; p; i++) {
2898         char *next;
2899
2900         av_assert0(i < read_intervals_nb);
2901         next = strchr(p, ',');
2902         if (next)
2903             *next++ = 0;
2904
2905         read_intervals[i].id = i;
2906         ret = parse_read_interval(p, &read_intervals[i]);
2907         if (ret < 0) {
2908             av_log(NULL, AV_LOG_ERROR, "Error parsing read interval #%d '%s'\n",
2909                    i, p);
2910             goto end;
2911         }
2912         av_log(NULL, AV_LOG_VERBOSE, "Parsed log interval ");
2913         log_read_interval(&read_intervals[i], NULL, AV_LOG_VERBOSE);
2914         p = next;
2915     }
2916     av_assert0(i == read_intervals_nb);
2917
2918 end:
2919     av_free(spec);
2920     return ret;
2921 }
2922
2923 static int opt_read_intervals(void *optctx, const char *opt, const char *arg)
2924 {
2925     return parse_read_intervals(arg);
2926 }
2927
2928 static int opt_pretty(void *optctx, const char *opt, const char *arg)
2929 {
2930     show_value_unit              = 1;
2931     use_value_prefix             = 1;
2932     use_byte_value_binary_prefix = 1;
2933     use_value_sexagesimal_format = 1;
2934     return 0;
2935 }
2936
2937 static void print_section(SectionID id, int level)
2938 {
2939     const SectionID *pid;
2940     const struct section *section = &sections[id];
2941     printf("%c%c%c",
2942            section->flags & SECTION_FLAG_IS_WRAPPER           ? 'W' : '.',
2943            section->flags & SECTION_FLAG_IS_ARRAY             ? 'A' : '.',
2944            section->flags & SECTION_FLAG_HAS_VARIABLE_FIELDS  ? 'V' : '.');
2945     printf("%*c  %s", level * 4, ' ', section->name);
2946     if (section->unique_name)
2947         printf("/%s", section->unique_name);
2948     printf("\n");
2949
2950     for (pid = section->children_ids; *pid != -1; pid++)
2951         print_section(*pid, level+1);
2952 }
2953
2954 static int opt_sections(void *optctx, const char *opt, const char *arg)
2955 {
2956     printf("Sections:\n"
2957            "W.. = Section is a wrapper (contains other sections, no local entries)\n"
2958            ".A. = Section contains an array of elements of the same type\n"
2959            "..V = Section may contain a variable number of fields with variable keys\n"
2960            "FLAGS NAME/UNIQUE_NAME\n"
2961            "---\n");
2962     print_section(SECTION_ID_ROOT, 0);
2963     return 0;
2964 }
2965
2966 static int opt_show_versions(const char *opt, const char *arg)
2967 {
2968     mark_section_show_entries(SECTION_ID_PROGRAM_VERSION, 1, NULL);
2969     mark_section_show_entries(SECTION_ID_LIBRARY_VERSION, 1, NULL);
2970     return 0;
2971 }
2972
2973 #define DEFINE_OPT_SHOW_SECTION(section, target_section_id)             \
2974     static int opt_show_##section(const char *opt, const char *arg)     \
2975     {                                                                   \
2976         mark_section_show_entries(SECTION_ID_##target_section_id, 1, NULL); \
2977         return 0;                                                       \
2978     }
2979
2980 DEFINE_OPT_SHOW_SECTION(chapters,         CHAPTERS);
2981 DEFINE_OPT_SHOW_SECTION(error,            ERROR);
2982 DEFINE_OPT_SHOW_SECTION(format,           FORMAT);
2983 DEFINE_OPT_SHOW_SECTION(frames,           FRAMES);
2984 DEFINE_OPT_SHOW_SECTION(library_versions, LIBRARY_VERSIONS);
2985 DEFINE_OPT_SHOW_SECTION(packets,          PACKETS);
2986 DEFINE_OPT_SHOW_SECTION(pixel_formats,    PIXEL_FORMATS);
2987 DEFINE_OPT_SHOW_SECTION(program_version,  PROGRAM_VERSION);
2988 DEFINE_OPT_SHOW_SECTION(streams,          STREAMS);
2989 DEFINE_OPT_SHOW_SECTION(programs,         PROGRAMS);
2990
2991 static const OptionDef real_options[] = {
2992 #include "cmdutils_common_opts.h"
2993     { "f", HAS_ARG, {.func_arg = opt_format}, "force format", "format" },
2994     { "unit", OPT_BOOL, {&show_value_unit}, "show unit of the displayed values" },
2995     { "prefix", OPT_BOOL, {&use_value_prefix}, "use SI prefixes for the displayed values" },
2996     { "byte_binary_prefix", OPT_BOOL, {&use_byte_value_binary_prefix},
2997       "use binary prefixes for byte units" },
2998     { "sexagesimal", OPT_BOOL,  {&use_value_sexagesimal_format},
2999       "use sexagesimal format HOURS:MM:SS.MICROSECONDS for time units" },
3000     { "pretty", 0, {.func_arg = opt_pretty},
3001       "prettify the format of displayed values, make it more human readable" },
3002     { "print_format", OPT_STRING | HAS_ARG, {(void*)&print_format},
3003       "set the output printing format (available formats are: default, compact, csv, flat, ini, json, xml)", "format" },
3004     { "of", OPT_STRING | HAS_ARG, {(void*)&print_format}, "alias for -print_format", "format" },
3005     { "select_streams", OPT_STRING | HAS_ARG, {(void*)&stream_specifier}, "select the specified streams", "stream_specifier" },
3006     { "sections", OPT_EXIT, {.func_arg = opt_sections}, "print sections structure and section information, and exit" },
3007     { "show_data",    OPT_BOOL, {(void*)&do_show_data}, "show packets data" },
3008     { "show_data_hash", OPT_STRING | HAS_ARG, {(void*)&show_data_hash}, "show packets data hash" },
3009     { "show_error",   0, {(void*)&opt_show_error},  "show probing error" },
3010     { "show_format",  0, {(void*)&opt_show_format}, "show format/container info" },
3011     { "show_frames",  0, {(void*)&opt_show_frames}, "show frames info" },
3012     { "show_format_entry", HAS_ARG, {.func_arg = opt_show_format_entry},
3013       "show a particular entry from the format/container info", "entry" },
3014     { "show_entries", HAS_ARG, {.func_arg = opt_show_entries},
3015       "show a set of specified entries", "entry_list" },
3016     { "show_packets", 0, {(void*)&opt_show_packets}, "show packets info" },
3017     { "show_programs", 0, {(void*)&opt_show_programs}, "show programs info" },
3018     { "show_streams", 0, {(void*)&opt_show_streams}, "show streams info" },
3019     { "show_chapters", 0, {(void*)&opt_show_chapters}, "show chapters info" },
3020     { "count_frames", OPT_BOOL, {(void*)&do_count_frames}, "count the number of frames per stream" },
3021     { "count_packets", OPT_BOOL, {(void*)&do_count_packets}, "count the number of packets per stream" },
3022     { "show_program_version",  0, {(void*)&opt_show_program_version},  "show ffprobe version" },
3023     { "show_library_versions", 0, {(void*)&opt_show_library_versions}, "show library versions" },
3024     { "show_versions",         0, {(void*)&opt_show_versions}, "show program and library versions" },
3025     { "show_pixel_formats", 0, {(void*)&opt_show_pixel_formats}, "show pixel format descriptions" },
3026     { "show_private_data", OPT_BOOL, {(void*)&show_private_data}, "show private data" },
3027     { "private",           OPT_BOOL, {(void*)&show_private_data}, "same as show_private_data" },
3028     { "bitexact", OPT_BOOL, {&do_bitexact}, "force bitexact output" },
3029     { "read_intervals", HAS_ARG, {.func_arg = opt_read_intervals}, "set read intervals", "read_intervals" },
3030     { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {.func_arg = opt_default}, "generic catch all option", "" },
3031     { "i", HAS_ARG, {.func_arg = opt_input_file_i}, "read specified file", "input_file"},
3032     { NULL, },
3033 };
3034
3035 static inline int check_section_show_entries(int section_id)
3036 {
3037     int *id;
3038     struct section *section = &sections[section_id];
3039     if (sections[section_id].show_all_entries || sections[section_id].entries_to_show)
3040         return 1;
3041     for (id = section->children_ids; *id != -1; id++)
3042         if (check_section_show_entries(*id))
3043             return 1;
3044     return 0;
3045 }
3046
3047 #define SET_DO_SHOW(id, varname) do {                                   \
3048         if (check_section_show_entries(SECTION_ID_##id))                \
3049             do_show_##varname = 1;                                      \
3050     } while (0)
3051
3052 int main(int argc, char **argv)
3053 {
3054     const Writer *w;
3055     WriterContext *wctx;
3056     char *buf;
3057     char *w_name = NULL, *w_args = NULL;
3058     int ret, i;
3059
3060     av_log_set_flags(AV_LOG_SKIP_REPEATED);
3061     register_exit(ffprobe_cleanup);
3062
3063     options = real_options;
3064     parse_loglevel(argc, argv, options);
3065     av_register_all();
3066     avformat_network_init();
3067     init_opts();
3068 #if CONFIG_AVDEVICE
3069     avdevice_register_all();
3070 #endif
3071
3072     show_banner(argc, argv, options);
3073     parse_options(NULL, argc, argv, options, opt_input_file);
3074
3075     /* mark things to show, based on -show_entries */
3076     SET_DO_SHOW(CHAPTERS, chapters);
3077     SET_DO_SHOW(ERROR, error);
3078     SET_DO_SHOW(FORMAT, format);
3079     SET_DO_SHOW(FRAMES, frames);
3080     SET_DO_SHOW(LIBRARY_VERSIONS, library_versions);
3081     SET_DO_SHOW(PACKETS, packets);
3082     SET_DO_SHOW(PIXEL_FORMATS, pixel_formats);
3083     SET_DO_SHOW(PIXEL_FORMAT_FLAGS, pixel_format_flags);
3084     SET_DO_SHOW(PIXEL_FORMAT_COMPONENTS, pixel_format_components);
3085     SET_DO_SHOW(PROGRAM_VERSION, program_version);
3086     SET_DO_SHOW(PROGRAMS, programs);
3087     SET_DO_SHOW(STREAMS, streams);
3088     SET_DO_SHOW(STREAM_DISPOSITION, stream_disposition);
3089     SET_DO_SHOW(PROGRAM_STREAM_DISPOSITION, stream_disposition);
3090
3091     SET_DO_SHOW(CHAPTER_TAGS, chapter_tags);
3092     SET_DO_SHOW(FORMAT_TAGS, format_tags);
3093     SET_DO_SHOW(FRAME_TAGS, frame_tags);
3094     SET_DO_SHOW(PROGRAM_TAGS, program_tags);
3095     SET_DO_SHOW(STREAM_TAGS, stream_tags);
3096
3097     if (do_bitexact && (do_show_program_version || do_show_library_versions)) {
3098         av_log(NULL, AV_LOG_ERROR,
3099                "-bitexact and -show_program_version or -show_library_versions "
3100                "options are incompatible\n");
3101         ret = AVERROR(EINVAL);
3102         goto end;
3103     }
3104
3105     writer_register_all();
3106
3107     if (!print_format)
3108         print_format = av_strdup("default");
3109     if (!print_format) {
3110         ret = AVERROR(ENOMEM);
3111         goto end;
3112     }
3113     w_name = av_strtok(print_format, "=", &buf);
3114     w_args = buf;
3115
3116     if (show_data_hash) {
3117         if ((ret = av_hash_alloc(&hash, show_data_hash)) < 0) {
3118             if (ret == AVERROR(EINVAL)) {
3119                 const char *n;
3120                 av_log(NULL, AV_LOG_ERROR,
3121                        "Unknown hash algorithm '%s'\nKnown algorithms:",
3122                        show_data_hash);
3123                 for (i = 0; (n = av_hash_names(i)); i++)
3124                     av_log(NULL, AV_LOG_ERROR, " %s", n);
3125                 av_log(NULL, AV_LOG_ERROR, "\n");
3126             }
3127             goto end;
3128         }
3129     }
3130
3131     w = writer_get_by_name(w_name);
3132     if (!w) {
3133         av_log(NULL, AV_LOG_ERROR, "Unknown output format with name '%s'\n", w_name);
3134         ret = AVERROR(EINVAL);
3135         goto end;
3136     }
3137
3138     if ((ret = writer_open(&wctx, w, w_args,
3139                            sections, FF_ARRAY_ELEMS(sections))) >= 0) {
3140         if (w == &xml_writer)
3141             wctx->string_validation_utf8_flags |= AV_UTF8_FLAG_EXCLUDE_XML_INVALID_CONTROL_CODES;
3142
3143         writer_print_section_header(wctx, SECTION_ID_ROOT);
3144
3145         if (do_show_program_version)
3146             ffprobe_show_program_version(wctx);
3147         if (do_show_library_versions)
3148             ffprobe_show_library_versions(wctx);
3149         if (do_show_pixel_formats)
3150             ffprobe_show_pixel_formats(wctx);
3151
3152         if (!input_filename &&
3153             ((do_show_format || do_show_programs || do_show_streams || do_show_chapters || do_show_packets || do_show_error) ||
3154              (!do_show_program_version && !do_show_library_versions && !do_show_pixel_formats))) {
3155             show_usage();
3156             av_log(NULL, AV_LOG_ERROR, "You have to specify one input file.\n");
3157             av_log(NULL, AV_LOG_ERROR, "Use -h to get full help or, even better, run 'man %s'.\n", program_name);
3158             ret = AVERROR(EINVAL);
3159         } else if (input_filename) {
3160             ret = probe_file(wctx, input_filename);
3161             if (ret < 0 && do_show_error)
3162                 show_error(wctx, ret);
3163         }
3164
3165         writer_print_section_footer(wctx);
3166         writer_close(&wctx);
3167     }
3168
3169 end:
3170     av_freep(&print_format);
3171     av_freep(&read_intervals);
3172     av_hash_freep(&hash);
3173
3174     uninit_opts();
3175     for (i = 0; i < FF_ARRAY_ELEMS(sections); i++)
3176         av_dict_free(&(sections[i].entries_to_show));
3177
3178     avformat_network_deinit();
3179
3180     return ret < 0;
3181 }