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