OSDN Git Service

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