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