]> git.sesse.net Git - ffmpeg/blob - ffprobe.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / ffprobe.c
1 /*
2  * Copyright (c) 2007-2010 Stefano Sabatini
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 /**
22  * @file
23  * simple media prober based on the FFmpeg libraries
24  */
25
26 #include "config.h"
27 #include "version.h"
28
29 #include "libavformat/avformat.h"
30 #include "libavcodec/avcodec.h"
31 #include "libavutil/avstring.h"
32 #include "libavutil/opt.h"
33 #include "libavutil/pixdesc.h"
34 #include "libavutil/dict.h"
35 #include "libavdevice/avdevice.h"
36 #include "libswscale/swscale.h"
37 #include "libswresample/swresample.h"
38 #include "libpostproc/postprocess.h"
39 #include "cmdutils.h"
40
41 const char program_name[] = "ffprobe";
42 const int program_birth_year = 2007;
43
44 static int do_show_error   = 0;
45 static int do_show_format  = 0;
46 static int do_show_frames  = 0;
47 static int do_show_packets = 0;
48 static int do_show_streams = 0;
49 static int do_show_program_version  = 0;
50 static int do_show_library_versions = 0;
51
52 static int show_value_unit              = 0;
53 static int use_value_prefix             = 0;
54 static int use_byte_value_binary_prefix = 0;
55 static int use_value_sexagesimal_format = 0;
56 static int show_private_data            = 1;
57
58 static char *print_format;
59
60 static const OptionDef options[];
61
62 /* FFprobe context */
63 static const char *input_filename;
64 static AVInputFormat *iformat = NULL;
65
66 static const char *binary_unit_prefixes [] = { "", "Ki", "Mi", "Gi", "Ti", "Pi" };
67 static const char *decimal_unit_prefixes[] = { "", "K" , "M" , "G" , "T" , "P"  };
68
69 static const char *unit_second_str          = "s"    ;
70 static const char *unit_hertz_str           = "Hz"   ;
71 static const char *unit_byte_str            = "byte" ;
72 static const char *unit_bit_per_second_str  = "bit/s";
73
74 void av_noreturn exit_program(int ret)
75 {
76     exit(ret);
77 }
78
79 struct unit_value {
80     union { double d; int i; } val;
81     const char *unit;
82 };
83
84 static char *value_string(char *buf, int buf_size, struct unit_value uv)
85 {
86     double vald;
87     int show_float = 0;
88
89     if (uv.unit == unit_second_str) {
90         vald = uv.val.d;
91         show_float = 1;
92     } else {
93         vald = uv.val.i;
94     }
95
96     if (uv.unit == unit_second_str && use_value_sexagesimal_format) {
97         double secs;
98         int hours, mins;
99         secs  = vald;
100         mins  = (int)secs / 60;
101         secs  = secs - mins * 60;
102         hours = mins / 60;
103         mins %= 60;
104         snprintf(buf, buf_size, "%d:%02d:%09.6f", hours, mins, secs);
105     } else if (use_value_prefix) {
106         const char *prefix_string;
107         int index, l;
108
109         if (uv.unit == unit_byte_str && use_byte_value_binary_prefix) {
110             index = (int) (log(vald)/log(2)) / 10;
111             index = av_clip(index, 0, FF_ARRAY_ELEMS(binary_unit_prefixes) -1);
112             vald /= pow(2, index*10);
113             prefix_string = binary_unit_prefixes[index];
114         } else {
115             index = (int) (log10(vald)) / 3;
116             index = av_clip(index, 0, FF_ARRAY_ELEMS(decimal_unit_prefixes) -1);
117             vald /= pow(10, index*3);
118             prefix_string = decimal_unit_prefixes[index];
119         }
120
121         if (show_float || vald != (int)vald) l = snprintf(buf, buf_size, "%.3f", vald);
122         else                                 l = snprintf(buf, buf_size, "%d",   (int)vald);
123         snprintf(buf+l, buf_size-l, "%s%s%s", prefix_string || show_value_unit ? " " : "",
124                  prefix_string, show_value_unit ? uv.unit : "");
125     } else {
126         int l;
127
128         if (show_float) l = snprintf(buf, buf_size, "%.3f", vald);
129         else            l = snprintf(buf, buf_size, "%d",   (int)vald);
130         snprintf(buf+l, buf_size-l, "%s%s", show_value_unit ? " " : "",
131                  show_value_unit ? uv.unit : "");
132     }
133
134     return buf;
135 }
136
137 /* WRITERS API */
138
139 typedef struct WriterContext WriterContext;
140
141 #define WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS 1
142 #define WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER 2
143
144 typedef struct Writer {
145     int priv_size;                  ///< private size for the writer context
146     const char *name;
147
148     int  (*init)  (WriterContext *wctx, const char *args, void *opaque);
149     void (*uninit)(WriterContext *wctx);
150
151     void (*print_header)(WriterContext *ctx);
152     void (*print_footer)(WriterContext *ctx);
153
154     void (*print_chapter_header)(WriterContext *wctx, const char *);
155     void (*print_chapter_footer)(WriterContext *wctx, const char *);
156     void (*print_section_header)(WriterContext *wctx, const char *);
157     void (*print_section_footer)(WriterContext *wctx, const char *);
158     void (*print_integer)       (WriterContext *wctx, const char *, long long int);
159     void (*print_string)        (WriterContext *wctx, const char *, const char *);
160     void (*show_tags)           (WriterContext *wctx, AVDictionary *dict);
161     int flags;                  ///< a combination or WRITER_FLAG_*
162 } Writer;
163
164 struct WriterContext {
165     const AVClass *class;           ///< class of the writer
166     const Writer *writer;           ///< the Writer of which this is an instance
167     char *name;                     ///< name of this writer instance
168     void *priv;                     ///< private data for use by the filter
169     unsigned int nb_item;           ///< number of the item printed in the given section, starting at 0
170     unsigned int nb_section;        ///< number of the section printed in the given section sequence, starting at 0
171     unsigned int nb_chapter;        ///< number of the chapter, starting at 0
172 };
173
174 static const char *writer_get_name(void *p)
175 {
176     WriterContext *wctx = p;
177     return wctx->writer->name;
178 }
179
180 static const AVClass writer_class = {
181     "Writer",
182     writer_get_name,
183     NULL,
184     LIBAVUTIL_VERSION_INT,
185 };
186
187 static void writer_close(WriterContext **wctx)
188 {
189     if (!*wctx)
190         return;
191
192     if ((*wctx)->writer->uninit)
193         (*wctx)->writer->uninit(*wctx);
194     av_freep(&((*wctx)->priv));
195     av_freep(wctx);
196 }
197
198 static int writer_open(WriterContext **wctx, const Writer *writer,
199                        const char *args, void *opaque)
200 {
201     int ret = 0;
202
203     if (!(*wctx = av_malloc(sizeof(WriterContext)))) {
204         ret = AVERROR(ENOMEM);
205         goto fail;
206     }
207
208     if (!((*wctx)->priv = av_mallocz(writer->priv_size))) {
209         ret = AVERROR(ENOMEM);
210         goto fail;
211     }
212
213     (*wctx)->class = &writer_class;
214     (*wctx)->writer = writer;
215     if ((*wctx)->writer->init)
216         ret = (*wctx)->writer->init(*wctx, args, opaque);
217     if (ret < 0)
218         goto fail;
219
220     return 0;
221
222 fail:
223     writer_close(wctx);
224     return ret;
225 }
226
227 static inline void writer_print_header(WriterContext *wctx)
228 {
229     if (wctx->writer->print_header)
230         wctx->writer->print_header(wctx);
231     wctx->nb_chapter = 0;
232 }
233
234 static inline void writer_print_footer(WriterContext *wctx)
235 {
236     if (wctx->writer->print_footer)
237         wctx->writer->print_footer(wctx);
238 }
239
240 static inline void writer_print_chapter_header(WriterContext *wctx,
241                                                const char *chapter)
242 {
243     if (wctx->writer->print_chapter_header)
244         wctx->writer->print_chapter_header(wctx, chapter);
245     wctx->nb_section = 0;
246 }
247
248 static inline void writer_print_chapter_footer(WriterContext *wctx,
249                                                const char *chapter)
250 {
251     if (wctx->writer->print_chapter_footer)
252         wctx->writer->print_chapter_footer(wctx, chapter);
253     wctx->nb_chapter++;
254 }
255
256 static inline void writer_print_section_header(WriterContext *wctx,
257                                                const char *section)
258 {
259     if (wctx->writer->print_section_header)
260         wctx->writer->print_section_header(wctx, section);
261     wctx->nb_item = 0;
262 }
263
264 static inline void writer_print_section_footer(WriterContext *wctx,
265                                                const char *section)
266 {
267     if (wctx->writer->print_section_footer)
268         wctx->writer->print_section_footer(wctx, section);
269     wctx->nb_section++;
270 }
271
272 static inline void writer_print_integer(WriterContext *wctx,
273                                         const char *key, long long int val)
274 {
275     wctx->writer->print_integer(wctx, key, val);
276     wctx->nb_item++;
277 }
278
279 static inline void writer_print_string(WriterContext *wctx,
280                                        const char *key, const char *val, int opt)
281 {
282     if (opt && !(wctx->writer->flags & WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS))
283         return;
284     wctx->writer->print_string(wctx, key, val);
285     wctx->nb_item++;
286 }
287
288 static void writer_print_time(WriterContext *wctx, const char *key,
289                               int64_t ts, const AVRational *time_base)
290 {
291     char buf[128];
292
293     if (ts == AV_NOPTS_VALUE) {
294         writer_print_string(wctx, key, "N/A", 1);
295     } else {
296         double d = ts * av_q2d(*time_base);
297         value_string(buf, sizeof(buf), (struct unit_value){.val.d=d, .unit=unit_second_str});
298         writer_print_string(wctx, key, buf, 0);
299     }
300 }
301
302 static void writer_print_ts(WriterContext *wctx, const char *key, int64_t ts)
303 {
304     if (ts == AV_NOPTS_VALUE) {
305         writer_print_string(wctx, key, "N/A", 1);
306     } else {
307         writer_print_integer(wctx, key, ts);
308     }
309 }
310
311 static inline void writer_show_tags(WriterContext *wctx, AVDictionary *dict)
312 {
313     wctx->writer->show_tags(wctx, dict);
314 }
315
316 #define MAX_REGISTERED_WRITERS_NB 64
317
318 static const Writer *registered_writers[MAX_REGISTERED_WRITERS_NB + 1];
319
320 static int writer_register(const Writer *writer)
321 {
322     static int next_registered_writer_idx = 0;
323
324     if (next_registered_writer_idx == MAX_REGISTERED_WRITERS_NB)
325         return AVERROR(ENOMEM);
326
327     registered_writers[next_registered_writer_idx++] = writer;
328     return 0;
329 }
330
331 static const Writer *writer_get_by_name(const char *name)
332 {
333     int i;
334
335     for (i = 0; registered_writers[i]; i++)
336         if (!strcmp(registered_writers[i]->name, name))
337             return registered_writers[i];
338
339     return NULL;
340 }
341
342 /* Print helpers */
343
344 struct print_buf {
345     char *s;
346     int len;
347 };
348
349 static char *fast_asprintf(struct print_buf *pbuf, const char *fmt, ...)
350 {
351     va_list va;
352     int len;
353
354     va_start(va, fmt);
355     len = vsnprintf(NULL, 0, fmt, va);
356     va_end(va);
357     if (len < 0)
358         goto fail;
359
360     if (pbuf->len < len) {
361         char *p = av_realloc(pbuf->s, len + 1);
362         if (!p)
363             goto fail;
364         pbuf->s   = p;
365         pbuf->len = len;
366     }
367
368     va_start(va, fmt);
369     len = vsnprintf(pbuf->s, len + 1, fmt, va);
370     va_end(va);
371     if (len < 0)
372         goto fail;
373     return pbuf->s;
374
375 fail:
376     av_freep(&pbuf->s);
377     pbuf->len = 0;
378     return NULL;
379 }
380
381 #define ESCAPE_INIT_BUF_SIZE 256
382
383 #define ESCAPE_CHECK_SIZE(src, size, max_size)                          \
384     if (size > max_size) {                                              \
385         char buf[64];                                                   \
386         snprintf(buf, sizeof(buf), "%s", src);                          \
387         av_log(log_ctx, AV_LOG_WARNING,                                 \
388                "String '%s...' with is too big\n", buf);                \
389         return "FFPROBE_TOO_BIG_STRING";                                \
390     }
391
392 #define ESCAPE_REALLOC_BUF(dst_size_p, dst_p, src, size)                \
393     if (*dst_size_p < size) {                                           \
394         char *q = av_realloc(*dst_p, size);                             \
395         if (!q) {                                                       \
396             char buf[64];                                               \
397             snprintf(buf, sizeof(buf), "%s", src);                      \
398             av_log(log_ctx, AV_LOG_WARNING,                             \
399                    "String '%s...' could not be escaped\n", buf);       \
400             return "FFPROBE_THIS_STRING_COULD_NOT_BE_ESCAPED";          \
401         }                                                               \
402         *dst_size_p = size;                                             \
403         *dst = q;                                                       \
404     }
405
406 /* WRITERS */
407
408 /* Default output */
409
410 static void default_print_footer(WriterContext *wctx)
411 {
412     printf("\n");
413 }
414
415 static void default_print_chapter_header(WriterContext *wctx, const char *chapter)
416 {
417     if (wctx->nb_chapter)
418         printf("\n");
419 }
420
421 /* lame uppercasing routine, assumes the string is lower case ASCII */
422 static inline char *upcase_string(char *dst, size_t dst_size, const char *src)
423 {
424     int i;
425     for (i = 0; src[i] && i < dst_size-1; i++)
426         dst[i] = av_toupper(src[i]);
427     dst[i] = 0;
428     return dst;
429 }
430
431 static void default_print_section_header(WriterContext *wctx, const char *section)
432 {
433     char buf[32];
434
435     if (wctx->nb_section)
436         printf("\n");
437     printf("[%s]\n", upcase_string(buf, sizeof(buf), section));
438 }
439
440 static void default_print_section_footer(WriterContext *wctx, const char *section)
441 {
442     char buf[32];
443
444     printf("[/%s]", upcase_string(buf, sizeof(buf), section));
445 }
446
447 static void default_print_str(WriterContext *wctx, const char *key, const char *value)
448 {
449     printf("%s=%s\n", key, value);
450 }
451
452 static void default_print_int(WriterContext *wctx, const char *key, long long int value)
453 {
454     printf("%s=%lld\n", key, value);
455 }
456
457 static void default_show_tags(WriterContext *wctx, AVDictionary *dict)
458 {
459     AVDictionaryEntry *tag = NULL;
460     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
461         printf("TAG:");
462         writer_print_string(wctx, tag->key, tag->value, 0);
463     }
464 }
465
466 static const Writer default_writer = {
467     .name                  = "default",
468     .print_footer          = default_print_footer,
469     .print_chapter_header  = default_print_chapter_header,
470     .print_section_header  = default_print_section_header,
471     .print_section_footer  = default_print_section_footer,
472     .print_integer         = default_print_int,
473     .print_string          = default_print_str,
474     .show_tags             = default_show_tags,
475     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
476 };
477
478 /* Compact output */
479
480 /**
481  * Escape \n, \r, \\ and sep characters contained in s, and print the
482  * resulting string.
483  */
484 static const char *c_escape_str(char **dst, size_t *dst_size,
485                                 const char *src, const char sep, void *log_ctx)
486 {
487     const char *p;
488     char *q;
489     size_t size = 1;
490
491     /* precompute size */
492     for (p = src; *p; p++, size++) {
493         ESCAPE_CHECK_SIZE(src, size, SIZE_MAX-2);
494         if (*p == '\n' || *p == '\r' || *p == '\\')
495             size++;
496     }
497
498     ESCAPE_REALLOC_BUF(dst_size, dst, src, size);
499
500     q = *dst;
501     for (p = src; *p; p++) {
502         switch (*src) {
503         case '\n': *q++ = '\\'; *q++ = 'n';  break;
504         case '\r': *q++ = '\\'; *q++ = 'r';  break;
505         case '\\': *q++ = '\\'; *q++ = '\\'; break;
506         default:
507             if (*p == sep)
508                 *q++ = '\\';
509             *q++ = *p;
510         }
511     }
512     *q = 0;
513     return *dst;
514 }
515
516 /**
517  * Quote fields containing special characters, check RFC4180.
518  */
519 static const char *csv_escape_str(char **dst, size_t *dst_size,
520                                   const char *src, const char sep, void *log_ctx)
521 {
522     const char *p;
523     char *q;
524     size_t size = 1;
525     int quote = 0;
526
527     /* precompute size */
528     for (p = src; *p; p++, size++) {
529         ESCAPE_CHECK_SIZE(src, size, SIZE_MAX-4);
530         if (*p == '"' || *p == sep || *p == '\n' || *p == '\r')
531             if (!quote) {
532                 quote = 1;
533                 size += 2;
534             }
535         if (*p == '"')
536             size++;
537     }
538
539     ESCAPE_REALLOC_BUF(dst_size, dst, src, size);
540
541     q = *dst;
542     p = src;
543     if (quote)
544         *q++ = '\"';
545     while (*p) {
546         if (*p == '"')
547             *q++ = '\"';
548         *q++ = *p++;
549     }
550     if (quote)
551         *q++ = '\"';
552     *q = 0;
553
554     return *dst;
555 }
556
557 static const char *none_escape_str(char **dst, size_t *dst_size,
558                                    const char *src, const char sep, void *log_ctx)
559 {
560     return src;
561 }
562
563 typedef struct CompactContext {
564     const AVClass *class;
565     char *item_sep_str;
566     char item_sep;
567     int nokey;
568     char  *buf;
569     size_t buf_size;
570     char *escape_mode_str;
571     const char * (*escape_str)(char **dst, size_t *dst_size,
572                                const char *src, const char sep, void *log_ctx);
573 } CompactContext;
574
575 #define OFFSET(x) offsetof(CompactContext, x)
576
577 static const AVOption compact_options[]= {
578     {"item_sep", "set item separator",    OFFSET(item_sep_str),    AV_OPT_TYPE_STRING, {.str="|"},  CHAR_MIN, CHAR_MAX },
579     {"s",        "set item separator",    OFFSET(item_sep_str),    AV_OPT_TYPE_STRING, {.str="|"},  CHAR_MIN, CHAR_MAX },
580     {"nokey",    "force no key printing", OFFSET(nokey),           AV_OPT_TYPE_INT,    {.dbl=0},    0,        1        },
581     {"nk",       "force no key printing", OFFSET(nokey),           AV_OPT_TYPE_INT,    {.dbl=0},    0,        1        },
582     {"escape",   "set escape mode",       OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"},  CHAR_MIN, CHAR_MAX },
583     {"e",        "set escape mode",       OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"},  CHAR_MIN, CHAR_MAX },
584     {NULL},
585 };
586
587 static const char *compact_get_name(void *ctx)
588 {
589     return "compact";
590 }
591
592 static const AVClass compact_class = {
593     "CompactContext",
594     compact_get_name,
595     compact_options
596 };
597
598 static av_cold int compact_init(WriterContext *wctx, const char *args, void *opaque)
599 {
600     CompactContext *compact = wctx->priv;
601     int err;
602
603     compact->class = &compact_class;
604     av_opt_set_defaults(compact);
605
606     if (args &&
607         (err = (av_set_options_string(compact, args, "=", ":"))) < 0) {
608         av_log(wctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
609         return err;
610     }
611     if (strlen(compact->item_sep_str) != 1) {
612         av_log(wctx, AV_LOG_ERROR, "Item separator '%s' specified, but must contain a single character\n",
613                compact->item_sep_str);
614         return AVERROR(EINVAL);
615     }
616     compact->item_sep = compact->item_sep_str[0];
617
618     compact->buf_size = ESCAPE_INIT_BUF_SIZE;
619     if (!(compact->buf = av_malloc(compact->buf_size)))
620         return AVERROR(ENOMEM);
621
622     if      (!strcmp(compact->escape_mode_str, "none")) compact->escape_str = none_escape_str;
623     else if (!strcmp(compact->escape_mode_str, "c"   )) compact->escape_str = c_escape_str;
624     else if (!strcmp(compact->escape_mode_str, "csv" )) compact->escape_str = csv_escape_str;
625     else {
626         av_log(wctx, AV_LOG_ERROR, "Unknown escape mode '%s'\n", compact->escape_mode_str);
627         return AVERROR(EINVAL);
628     }
629
630     return 0;
631 }
632
633 static av_cold void compact_uninit(WriterContext *wctx)
634 {
635     CompactContext *compact = wctx->priv;
636
637     av_freep(&compact->item_sep_str);
638     av_freep(&compact->buf);
639     av_freep(&compact->escape_mode_str);
640 }
641
642 static void compact_print_section_header(WriterContext *wctx, const char *section)
643 {
644     CompactContext *compact = wctx->priv;
645
646     printf("%s%c", section, compact->item_sep);
647 }
648
649 static void compact_print_section_footer(WriterContext *wctx, const char *section)
650 {
651     printf("\n");
652 }
653
654 static void compact_print_str(WriterContext *wctx, const char *key, const char *value)
655 {
656     CompactContext *compact = wctx->priv;
657
658     if (wctx->nb_item) printf("%c", compact->item_sep);
659     if (!compact->nokey)
660         printf("%s=", key);
661     printf("%s", compact->escape_str(&compact->buf, &compact->buf_size,
662                                      value, compact->item_sep, wctx));
663 }
664
665 static void compact_print_int(WriterContext *wctx, const char *key, long long int value)
666 {
667     CompactContext *compact = wctx->priv;
668
669     if (wctx->nb_item) printf("%c", compact->item_sep);
670     if (!compact->nokey)
671         printf("%s=", key);
672     printf("%lld", value);
673 }
674
675 static void compact_show_tags(WriterContext *wctx, AVDictionary *dict)
676 {
677     CompactContext *compact = wctx->priv;
678     AVDictionaryEntry *tag = NULL;
679
680     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
681         if (wctx->nb_item) printf("%c", compact->item_sep);
682         if (!compact->nokey)
683             printf("tag:%s=", compact->escape_str(&compact->buf, &compact->buf_size,
684                                                   tag->key, compact->item_sep, wctx));
685         printf("%s", compact->escape_str(&compact->buf, &compact->buf_size,
686                                          tag->value, compact->item_sep, wctx));
687     }
688 }
689
690 static const Writer compact_writer = {
691     .name                 = "compact",
692     .priv_size            = sizeof(CompactContext),
693     .init                 = compact_init,
694     .uninit               = compact_uninit,
695     .print_section_header = compact_print_section_header,
696     .print_section_footer = compact_print_section_footer,
697     .print_integer        = compact_print_int,
698     .print_string         = compact_print_str,
699     .show_tags            = compact_show_tags,
700     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
701 };
702
703 /* CSV output */
704
705 static av_cold int csv_init(WriterContext *wctx, const char *args, void *opaque)
706 {
707     return compact_init(wctx, "item_sep=,:nokey=1:escape=csv", opaque);
708 }
709
710 static const Writer csv_writer = {
711     .name                 = "csv",
712     .priv_size            = sizeof(CompactContext),
713     .init                 = csv_init,
714     .uninit               = compact_uninit,
715     .print_section_header = compact_print_section_header,
716     .print_section_footer = compact_print_section_footer,
717     .print_integer        = compact_print_int,
718     .print_string         = compact_print_str,
719     .show_tags            = compact_show_tags,
720     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
721 };
722
723 /* JSON output */
724
725 typedef struct {
726     const AVClass *class;
727     int multiple_entries; ///< tells if the given chapter requires multiple entries
728     char *buf;
729     size_t buf_size;
730     int print_packets_and_frames;
731     int indent_level;
732     int compact;
733     const char *item_sep, *item_start_end;
734 } JSONContext;
735
736 #undef OFFSET
737 #define OFFSET(x) offsetof(JSONContext, x)
738
739 static const AVOption json_options[]= {
740     { "compact", "enable compact output", OFFSET(compact), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
741     { "c",       "enable compact output", OFFSET(compact), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
742     { NULL }
743 };
744
745 static const char *json_get_name(void *ctx)
746 {
747     return "json";
748 }
749
750 static const AVClass json_class = {
751     "JSONContext",
752     json_get_name,
753     json_options
754 };
755
756 static av_cold int json_init(WriterContext *wctx, const char *args, void *opaque)
757 {
758     JSONContext *json = wctx->priv;
759     int err;
760
761     json->class = &json_class;
762     av_opt_set_defaults(json);
763
764     if (args &&
765         (err = (av_set_options_string(json, args, "=", ":"))) < 0) {
766         av_log(wctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
767         return err;
768     }
769
770     json->item_sep       = json->compact ? ", " : ",\n";
771     json->item_start_end = json->compact ? " "  : "\n";
772
773     json->buf_size = ESCAPE_INIT_BUF_SIZE;
774     if (!(json->buf = av_malloc(json->buf_size)))
775         return AVERROR(ENOMEM);
776
777     return 0;
778 }
779
780 static av_cold void json_uninit(WriterContext *wctx)
781 {
782     JSONContext *json = wctx->priv;
783     av_freep(&json->buf);
784 }
785
786 static const char *json_escape_str(char **dst, size_t *dst_size, const char *src,
787                                    void *log_ctx)
788 {
789     static const char json_escape[] = {'"', '\\', '\b', '\f', '\n', '\r', '\t', 0};
790     static const char json_subst[]  = {'"', '\\',  'b',  'f',  'n',  'r',  't', 0};
791     const char *p;
792     char *q;
793     size_t size = 1;
794
795     // compute the length of the escaped string
796     for (p = src; *p; p++) {
797         ESCAPE_CHECK_SIZE(src, size, SIZE_MAX-6);
798         if (strchr(json_escape, *p))     size += 2; // simple escape
799         else if ((unsigned char)*p < 32) size += 6; // handle non-printable chars
800         else                             size += 1; // char copy
801     }
802     ESCAPE_REALLOC_BUF(dst_size, dst, src, size);
803
804     q = *dst;
805     for (p = src; *p; p++) {
806         char *s = strchr(json_escape, *p);
807         if (s) {
808             *q++ = '\\';
809             *q++ = json_subst[s - json_escape];
810         } else if ((unsigned char)*p < 32) {
811             snprintf(q, 7, "\\u00%02x", *p & 0xff);
812             q += 6;
813         } else {
814             *q++ = *p;
815         }
816     }
817     *q = 0;
818     return *dst;
819 }
820
821 static void json_print_header(WriterContext *wctx)
822 {
823     JSONContext *json = wctx->priv;
824     printf("{");
825     json->indent_level++;
826 }
827
828 static void json_print_footer(WriterContext *wctx)
829 {
830     JSONContext *json = wctx->priv;
831     json->indent_level--;
832     printf("\n}\n");
833 }
834
835 #define JSON_INDENT() printf("%*c", json->indent_level * 4, ' ')
836
837 static void json_print_chapter_header(WriterContext *wctx, const char *chapter)
838 {
839     JSONContext *json = wctx->priv;
840
841     if (wctx->nb_chapter)
842         printf(",");
843     printf("\n");
844     json->multiple_entries = !strcmp(chapter, "packets") || !strcmp(chapter, "frames" ) ||
845                              !strcmp(chapter, "packets_and_frames") ||
846                              !strcmp(chapter, "streams") || !strcmp(chapter, "library_versions");
847     if (json->multiple_entries) {
848         JSON_INDENT();
849         printf("\"%s\": [\n", json_escape_str(&json->buf, &json->buf_size, chapter, wctx));
850         json->print_packets_and_frames = !strcmp(chapter, "packets_and_frames");
851         json->indent_level++;
852     }
853 }
854
855 static void json_print_chapter_footer(WriterContext *wctx, const char *chapter)
856 {
857     JSONContext *json = wctx->priv;
858
859     if (json->multiple_entries) {
860         printf("\n");
861         json->indent_level--;
862         JSON_INDENT();
863         printf("]");
864     }
865 }
866
867 static void json_print_section_header(WriterContext *wctx, const char *section)
868 {
869     JSONContext *json = wctx->priv;
870
871     if (wctx->nb_section)
872         printf(",\n");
873     JSON_INDENT();
874     if (!json->multiple_entries)
875         printf("\"%s\": ", section);
876     printf("{%s", json->item_start_end);
877     json->indent_level++;
878     /* this is required so the parser can distinguish between packets and frames */
879     if (json->print_packets_and_frames) {
880         if (!json->compact)
881             JSON_INDENT();
882         printf("\"type\": \"%s\"%s", section, json->item_sep);
883     }
884 }
885
886 static void json_print_section_footer(WriterContext *wctx, const char *section)
887 {
888     JSONContext *json = wctx->priv;
889
890     printf("%s", json->item_start_end);
891     json->indent_level--;
892     if (!json->compact)
893         JSON_INDENT();
894     printf("}");
895 }
896
897 static inline void json_print_item_str(WriterContext *wctx,
898                                        const char *key, const char *value)
899 {
900     JSONContext *json = wctx->priv;
901
902     printf("\"%s\":", json_escape_str(&json->buf, &json->buf_size, key,   wctx));
903     printf(" \"%s\"", json_escape_str(&json->buf, &json->buf_size, value, wctx));
904 }
905
906 static void json_print_str(WriterContext *wctx, const char *key, const char *value)
907 {
908     JSONContext *json = wctx->priv;
909
910     if (wctx->nb_item) printf("%s", json->item_sep);
911     if (!json->compact)
912         JSON_INDENT();
913     json_print_item_str(wctx, key, value);
914 }
915
916 static void json_print_int(WriterContext *wctx, const char *key, long long int value)
917 {
918     JSONContext *json = wctx->priv;
919
920     if (wctx->nb_item) printf("%s", json->item_sep);
921     if (!json->compact)
922         JSON_INDENT();
923     printf("\"%s\": %lld",
924            json_escape_str(&json->buf, &json->buf_size, key, wctx), value);
925 }
926
927 static void json_show_tags(WriterContext *wctx, AVDictionary *dict)
928 {
929     JSONContext *json = wctx->priv;
930     AVDictionaryEntry *tag = NULL;
931     int is_first = 1;
932     if (!dict)
933         return;
934     printf("%s", json->item_sep);
935     if (!json->compact)
936         JSON_INDENT();
937     printf("\"tags\": {%s", json->item_start_end);
938     json->indent_level++;
939     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
940         if (is_first) is_first = 0;
941         else          printf("%s", json->item_sep);
942         if (!json->compact)
943             JSON_INDENT();
944         json_print_item_str(wctx, tag->key, tag->value);
945     }
946     json->indent_level--;
947     printf("%s", json->item_start_end);
948     if (!json->compact)
949         JSON_INDENT();
950     printf("}");
951 }
952
953 static const Writer json_writer = {
954     .name                 = "json",
955     .priv_size            = sizeof(JSONContext),
956     .init                 = json_init,
957     .uninit               = json_uninit,
958     .print_header         = json_print_header,
959     .print_footer         = json_print_footer,
960     .print_chapter_header = json_print_chapter_header,
961     .print_chapter_footer = json_print_chapter_footer,
962     .print_section_header = json_print_section_header,
963     .print_section_footer = json_print_section_footer,
964     .print_integer        = json_print_int,
965     .print_string         = json_print_str,
966     .show_tags            = json_show_tags,
967     .flags = WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
968 };
969
970 /* XML output */
971
972 typedef struct {
973     const AVClass *class;
974     int within_tag;
975     int multiple_entries; ///< tells if the given chapter requires multiple entries
976     int indent_level;
977     int fully_qualified;
978     int xsd_strict;
979     char *buf;
980     size_t buf_size;
981 } XMLContext;
982
983 #undef OFFSET
984 #define OFFSET(x) offsetof(XMLContext, x)
985
986 static const AVOption xml_options[] = {
987     {"fully_qualified", "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_INT, {.dbl=0},  0, 1 },
988     {"q",               "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_INT, {.dbl=0},  0, 1 },
989     {"xsd_strict",      "ensure that the output is XSD compliant",         OFFSET(xsd_strict),      AV_OPT_TYPE_INT, {.dbl=0},  0, 1 },
990     {"x",               "ensure that the output is XSD compliant",         OFFSET(xsd_strict),      AV_OPT_TYPE_INT, {.dbl=0},  0, 1 },
991     {NULL},
992 };
993
994 static const char *xml_get_name(void *ctx)
995 {
996     return "xml";
997 }
998
999 static const AVClass xml_class = {
1000     "XMLContext",
1001     xml_get_name,
1002     xml_options
1003 };
1004
1005 static av_cold int xml_init(WriterContext *wctx, const char *args, void *opaque)
1006 {
1007     XMLContext *xml = wctx->priv;
1008     int err;
1009
1010     xml->class = &xml_class;
1011     av_opt_set_defaults(xml);
1012
1013     if (args &&
1014         (err = (av_set_options_string(xml, args, "=", ":"))) < 0) {
1015         av_log(wctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
1016         return err;
1017     }
1018
1019     if (xml->xsd_strict) {
1020         xml->fully_qualified = 1;
1021 #define CHECK_COMPLIANCE(opt, opt_name)                                 \
1022         if (opt) {                                                      \
1023             av_log(wctx, AV_LOG_ERROR,                                  \
1024                    "XSD-compliant output selected but option '%s' was selected, XML output may be non-compliant.\n" \
1025                    "You need to disable such option with '-no%s'\n", opt_name, opt_name); \
1026             return AVERROR(EINVAL);                                     \
1027         }
1028         CHECK_COMPLIANCE(show_private_data, "private");
1029         CHECK_COMPLIANCE(show_value_unit,   "unit");
1030         CHECK_COMPLIANCE(use_value_prefix,  "prefix");
1031
1032         if (do_show_frames && do_show_packets) {
1033             av_log(wctx, AV_LOG_ERROR,
1034                    "Interleaved frames and packets are not allowed in XSD. "
1035                    "Select only one between the -show_frames and the -show_packets options.\n");
1036             return AVERROR(EINVAL);
1037         }
1038     }
1039
1040     xml->buf_size = ESCAPE_INIT_BUF_SIZE;
1041     if (!(xml->buf = av_malloc(xml->buf_size)))
1042         return AVERROR(ENOMEM);
1043     return 0;
1044 }
1045
1046 static av_cold void xml_uninit(WriterContext *wctx)
1047 {
1048     XMLContext *xml = wctx->priv;
1049     av_freep(&xml->buf);
1050 }
1051
1052 static const char *xml_escape_str(char **dst, size_t *dst_size, const char *src,
1053                                   void *log_ctx)
1054 {
1055     const char *p;
1056     char *q;
1057     size_t size = 1;
1058
1059     /* precompute size */
1060     for (p = src; *p; p++, size++) {
1061         ESCAPE_CHECK_SIZE(src, size, SIZE_MAX-10);
1062         switch (*p) {
1063         case '&' : size += strlen("&amp;");  break;
1064         case '<' : size += strlen("&lt;");   break;
1065         case '>' : size += strlen("&gt;");   break;
1066         case '\"': size += strlen("&quot;"); break;
1067         case '\'': size += strlen("&apos;"); break;
1068         default: size++;
1069         }
1070     }
1071     ESCAPE_REALLOC_BUF(dst_size, dst, src, size);
1072
1073 #define COPY_STR(str) {      \
1074         const char *s = str; \
1075         while (*s)           \
1076             *q++ = *s++;     \
1077     }
1078
1079     p = src;
1080     q = *dst;
1081     while (*p) {
1082         switch (*p) {
1083         case '&' : COPY_STR("&amp;");  break;
1084         case '<' : COPY_STR("&lt;");   break;
1085         case '>' : COPY_STR("&gt;");   break;
1086         case '\"': COPY_STR("&quot;"); break;
1087         case '\'': COPY_STR("&apos;"); break;
1088         default: *q++ = *p;
1089         }
1090         p++;
1091     }
1092     *q = 0;
1093
1094     return *dst;
1095 }
1096
1097 static void xml_print_header(WriterContext *wctx)
1098 {
1099     XMLContext *xml = wctx->priv;
1100     const char *qual = " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' "
1101         "xmlns:ffprobe='http://www.ffmpeg.org/schema/ffprobe' "
1102         "xsi:schemaLocation='http://www.ffmpeg.org/schema/ffprobe ffprobe.xsd'";
1103
1104     printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1105     printf("<%sffprobe%s>\n",
1106            xml->fully_qualified ? "ffprobe:" : "",
1107            xml->fully_qualified ? qual : "");
1108
1109     xml->indent_level++;
1110 }
1111
1112 static void xml_print_footer(WriterContext *wctx)
1113 {
1114     XMLContext *xml = wctx->priv;
1115
1116     xml->indent_level--;
1117     printf("</%sffprobe>\n", xml->fully_qualified ? "ffprobe:" : "");
1118 }
1119
1120 #define XML_INDENT() printf("%*c", xml->indent_level * 4, ' ')
1121
1122 static void xml_print_chapter_header(WriterContext *wctx, const char *chapter)
1123 {
1124     XMLContext *xml = wctx->priv;
1125
1126     if (wctx->nb_chapter)
1127         printf("\n");
1128     xml->multiple_entries = !strcmp(chapter, "packets") || !strcmp(chapter, "frames") ||
1129                             !strcmp(chapter, "packets_and_frames") ||
1130                             !strcmp(chapter, "streams") || !strcmp(chapter, "library_versions");
1131
1132     if (xml->multiple_entries) {
1133         XML_INDENT(); printf("<%s>\n", chapter);
1134         xml->indent_level++;
1135     }
1136 }
1137
1138 static void xml_print_chapter_footer(WriterContext *wctx, const char *chapter)
1139 {
1140     XMLContext *xml = wctx->priv;
1141
1142     if (xml->multiple_entries) {
1143         xml->indent_level--;
1144         XML_INDENT(); printf("</%s>\n", chapter);
1145     }
1146 }
1147
1148 static void xml_print_section_header(WriterContext *wctx, const char *section)
1149 {
1150     XMLContext *xml = wctx->priv;
1151
1152     XML_INDENT(); printf("<%s ", section);
1153     xml->within_tag = 1;
1154 }
1155
1156 static void xml_print_section_footer(WriterContext *wctx, const char *section)
1157 {
1158     XMLContext *xml = wctx->priv;
1159
1160     if (xml->within_tag)
1161         printf("/>\n");
1162     else {
1163         XML_INDENT(); printf("</%s>\n", section);
1164     }
1165 }
1166
1167 static void xml_print_str(WriterContext *wctx, const char *key, const char *value)
1168 {
1169     XMLContext *xml = wctx->priv;
1170
1171     if (wctx->nb_item)
1172         printf(" ");
1173     printf("%s=\"%s\"", key, xml_escape_str(&xml->buf, &xml->buf_size, value, wctx));
1174 }
1175
1176 static void xml_print_int(WriterContext *wctx, const char *key, long long int value)
1177 {
1178     if (wctx->nb_item)
1179         printf(" ");
1180     printf("%s=\"%lld\"", key, value);
1181 }
1182
1183 static void xml_show_tags(WriterContext *wctx, AVDictionary *dict)
1184 {
1185     XMLContext *xml = wctx->priv;
1186     AVDictionaryEntry *tag = NULL;
1187     int is_first = 1;
1188
1189     xml->indent_level++;
1190     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
1191         if (is_first) {
1192             /* close section tag */
1193             printf(">\n");
1194             xml->within_tag = 0;
1195             is_first = 0;
1196         }
1197         XML_INDENT();
1198         printf("<tag key=\"%s\"",
1199                xml_escape_str(&xml->buf, &xml->buf_size, tag->key,   wctx));
1200         printf(" value=\"%s\"/>\n",
1201                xml_escape_str(&xml->buf, &xml->buf_size, tag->value, wctx));
1202     }
1203     xml->indent_level--;
1204 }
1205
1206 static Writer xml_writer = {
1207     .name                 = "xml",
1208     .priv_size            = sizeof(XMLContext),
1209     .init                 = xml_init,
1210     .uninit               = xml_uninit,
1211     .print_header         = xml_print_header,
1212     .print_footer         = xml_print_footer,
1213     .print_chapter_header = xml_print_chapter_header,
1214     .print_chapter_footer = xml_print_chapter_footer,
1215     .print_section_header = xml_print_section_header,
1216     .print_section_footer = xml_print_section_footer,
1217     .print_integer        = xml_print_int,
1218     .print_string         = xml_print_str,
1219     .show_tags            = xml_show_tags,
1220     .flags = WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
1221 };
1222
1223 static void writer_register_all(void)
1224 {
1225     static int initialized;
1226
1227     if (initialized)
1228         return;
1229     initialized = 1;
1230
1231     writer_register(&default_writer);
1232     writer_register(&compact_writer);
1233     writer_register(&csv_writer);
1234     writer_register(&json_writer);
1235     writer_register(&xml_writer);
1236 }
1237
1238 #define print_fmt(k, f, ...) do {              \
1239     if (fast_asprintf(&pbuf, f, __VA_ARGS__))  \
1240         writer_print_string(w, k, pbuf.s, 0);  \
1241 } while (0)
1242
1243 #define print_fmt_opt(k, f, ...) do {          \
1244     if (fast_asprintf(&pbuf, f, __VA_ARGS__))  \
1245         writer_print_string(w, k, pbuf.s, 1);  \
1246 } while (0)
1247
1248 #define print_int(k, v)         writer_print_integer(w, k, v)
1249 #define print_str(k, v)         writer_print_string(w, k, v, 0)
1250 #define print_str_opt(k, v)     writer_print_string(w, k, v, 1)
1251 #define print_time(k, v, tb)    writer_print_time(w, k, v, tb)
1252 #define print_ts(k, v)          writer_print_ts(w, k, v)
1253 #define print_val(k, v, u)      writer_print_string(w, k, \
1254     value_string(val_str, sizeof(val_str), (struct unit_value){.val.i = v, .unit=u}), 0)
1255 #define print_section_header(s) writer_print_section_header(w, s)
1256 #define print_section_footer(s) writer_print_section_footer(w, s)
1257 #define show_tags(metadata)     writer_show_tags(w, metadata)
1258
1259 static void show_packet(WriterContext *w, AVFormatContext *fmt_ctx, AVPacket *pkt, int packet_idx)
1260 {
1261     char val_str[128];
1262     AVStream *st = fmt_ctx->streams[pkt->stream_index];
1263     struct print_buf pbuf = {.s = NULL};
1264     const char *s;
1265
1266     print_section_header("packet");
1267     s = av_get_media_type_string(st->codec->codec_type);
1268     if (s) print_str    ("codec_type", s);
1269     else   print_str_opt("codec_type", "unknown");
1270     print_int("stream_index",     pkt->stream_index);
1271     print_ts  ("pts",             pkt->pts);
1272     print_time("pts_time",        pkt->pts, &st->time_base);
1273     print_ts  ("dts",             pkt->dts);
1274     print_time("dts_time",        pkt->dts, &st->time_base);
1275     print_ts  ("duration",        pkt->duration);
1276     print_time("duration_time",   pkt->duration, &st->time_base);
1277     print_val("size",             pkt->size, unit_byte_str);
1278     if (pkt->pos != -1) print_fmt    ("pos", "%"PRId64, pkt->pos);
1279     else                print_str_opt("pos", "N/A");
1280     print_fmt("flags", "%c",      pkt->flags & AV_PKT_FLAG_KEY ? 'K' : '_');
1281     print_section_footer("packet");
1282
1283     av_free(pbuf.s);
1284     fflush(stdout);
1285 }
1286
1287 static void show_frame(WriterContext *w, AVFrame *frame, AVStream *stream)
1288 {
1289     struct print_buf pbuf = {.s = NULL};
1290     const char *s;
1291
1292     print_section_header("frame");
1293
1294     s = av_get_media_type_string(stream->codec->codec_type);
1295     if (s) print_str    ("media_type", s);
1296     else   print_str_opt("media_type", "unknown");
1297     print_int("key_frame",              frame->key_frame);
1298     print_ts  ("pkt_pts",               frame->pkt_pts);
1299     print_time("pkt_pts_time",          frame->pkt_pts, &stream->time_base);
1300     print_ts  ("pkt_dts",               frame->pkt_dts);
1301     print_time("pkt_dts_time",          frame->pkt_dts, &stream->time_base);
1302     if (frame->pkt_pos != -1) print_fmt    ("pkt_pos", "%"PRId64, frame->pkt_pos);
1303     else                      print_str_opt("pkt_pos", "N/A");
1304
1305     switch (stream->codec->codec_type) {
1306     case AVMEDIA_TYPE_VIDEO:
1307         print_int("width",                  frame->width);
1308         print_int("height",                 frame->height);
1309         s = av_get_pix_fmt_name(frame->format);
1310         if (s) print_str    ("pix_fmt", s);
1311         else   print_str_opt("pix_fmt", "unknown");
1312         if (frame->sample_aspect_ratio.num) {
1313             print_fmt("sample_aspect_ratio", "%d:%d",
1314                       frame->sample_aspect_ratio.num,
1315                       frame->sample_aspect_ratio.den);
1316         } else {
1317             print_str_opt("sample_aspect_ratio", "N/A");
1318         }
1319         print_fmt("pict_type",              "%c", av_get_picture_type_char(frame->pict_type));
1320         print_int("coded_picture_number",   frame->coded_picture_number);
1321         print_int("display_picture_number", frame->display_picture_number);
1322         print_int("interlaced_frame",       frame->interlaced_frame);
1323         print_int("top_field_first",        frame->top_field_first);
1324         print_int("repeat_pict",            frame->repeat_pict);
1325         print_int("reference",              frame->reference);
1326         break;
1327
1328     case AVMEDIA_TYPE_AUDIO:
1329         s = av_get_sample_fmt_name(frame->format);
1330         if (s) print_str    ("sample_fmt", s);
1331         else   print_str_opt("sample_fmt", "unknown");
1332         print_int("nb_samples",         frame->nb_samples);
1333         break;
1334     }
1335
1336     print_section_footer("frame");
1337
1338     av_free(pbuf.s);
1339     fflush(stdout);
1340 }
1341
1342 static av_always_inline int get_decoded_frame(AVFormatContext *fmt_ctx,
1343                                               AVFrame *frame, int *got_frame,
1344                                               AVPacket *pkt)
1345 {
1346     AVCodecContext *dec_ctx = fmt_ctx->streams[pkt->stream_index]->codec;
1347     int ret = 0;
1348
1349     *got_frame = 0;
1350     switch (dec_ctx->codec_type) {
1351     case AVMEDIA_TYPE_VIDEO:
1352         ret = avcodec_decode_video2(dec_ctx, frame, got_frame, pkt);
1353         break;
1354
1355     case AVMEDIA_TYPE_AUDIO:
1356         ret = avcodec_decode_audio4(dec_ctx, frame, got_frame, pkt);
1357         break;
1358     }
1359
1360     return ret;
1361 }
1362
1363 static void show_packets(WriterContext *w, AVFormatContext *fmt_ctx)
1364 {
1365     AVPacket pkt, pkt1;
1366     AVFrame frame;
1367     int i = 0, ret, got_frame;
1368
1369     av_init_packet(&pkt);
1370
1371     while (!av_read_frame(fmt_ctx, &pkt)) {
1372         if (do_show_packets)
1373             show_packet(w, fmt_ctx, &pkt, i++);
1374         if (do_show_frames) {
1375             pkt1 = pkt;
1376             while (1) {
1377                 avcodec_get_frame_defaults(&frame);
1378                 ret = get_decoded_frame(fmt_ctx, &frame, &got_frame, &pkt1);
1379                 if (ret < 0 || !got_frame)
1380                     break;
1381                 show_frame(w, &frame, fmt_ctx->streams[pkt.stream_index]);
1382                 pkt1.data += ret;
1383                 pkt1.size -= ret;
1384             }
1385         }
1386         av_free_packet(&pkt);
1387     }
1388     av_init_packet(&pkt);
1389     pkt.data = NULL;
1390     pkt.size = 0;
1391     //Flush remaining frames that are cached in the decoder
1392     for (i = 0; i < fmt_ctx->nb_streams; i++) {
1393         pkt.stream_index = i;
1394         while (get_decoded_frame(fmt_ctx, &frame, &got_frame, &pkt) >= 0 && got_frame)
1395             show_frame(w, &frame, fmt_ctx->streams[pkt.stream_index]);
1396     }
1397 }
1398
1399 static void show_stream(WriterContext *w, AVFormatContext *fmt_ctx, int stream_idx)
1400 {
1401     AVStream *stream = fmt_ctx->streams[stream_idx];
1402     AVCodecContext *dec_ctx;
1403     AVCodec *dec;
1404     char val_str[128];
1405     const char *s;
1406     AVRational display_aspect_ratio;
1407     struct print_buf pbuf = {.s = NULL};
1408
1409     print_section_header("stream");
1410
1411     print_int("index", stream->index);
1412
1413     if ((dec_ctx = stream->codec)) {
1414         if ((dec = dec_ctx->codec)) {
1415             print_str("codec_name",      dec->name);
1416             print_str("codec_long_name", dec->long_name);
1417         } else {
1418             print_str_opt("codec_name",      "unknown");
1419             print_str_opt("codec_long_name", "unknown");
1420         }
1421
1422         s = av_get_media_type_string(dec_ctx->codec_type);
1423         if (s) print_str    ("codec_type", s);
1424         else   print_str_opt("codec_type", "unknown");
1425         print_fmt("codec_time_base", "%d/%d", dec_ctx->time_base.num, dec_ctx->time_base.den);
1426
1427         /* print AVI/FourCC tag */
1428         av_get_codec_tag_string(val_str, sizeof(val_str), dec_ctx->codec_tag);
1429         print_str("codec_tag_string",    val_str);
1430         print_fmt("codec_tag", "0x%04x", dec_ctx->codec_tag);
1431
1432         switch (dec_ctx->codec_type) {
1433         case AVMEDIA_TYPE_VIDEO:
1434             print_int("width",        dec_ctx->width);
1435             print_int("height",       dec_ctx->height);
1436             print_int("has_b_frames", dec_ctx->has_b_frames);
1437             if (dec_ctx->sample_aspect_ratio.num) {
1438                 print_fmt("sample_aspect_ratio", "%d:%d",
1439                           dec_ctx->sample_aspect_ratio.num,
1440                           dec_ctx->sample_aspect_ratio.den);
1441                 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
1442                           dec_ctx->width  * dec_ctx->sample_aspect_ratio.num,
1443                           dec_ctx->height * dec_ctx->sample_aspect_ratio.den,
1444                           1024*1024);
1445                 print_fmt("display_aspect_ratio", "%d:%d",
1446                           display_aspect_ratio.num,
1447                           display_aspect_ratio.den);
1448             } else {
1449                 print_str_opt("sample_aspect_ratio", "N/A");
1450                 print_str_opt("display_aspect_ratio", "N/A");
1451             }
1452             s = av_get_pix_fmt_name(dec_ctx->pix_fmt);
1453             if (s) print_str    ("pix_fmt", s);
1454             else   print_str_opt("pix_fmt", "unknown");
1455             print_int("level",   dec_ctx->level);
1456             if (dec_ctx->timecode_frame_start >= 0) {
1457                 uint32_t tc = dec_ctx->timecode_frame_start;
1458                 print_fmt("timecode", "%02d:%02d:%02d%c%02d",
1459                           tc>>19 & 0x1f,              // hours
1460                           tc>>13 & 0x3f,              // minutes
1461                           tc>>6  & 0x3f,              // seconds
1462                           tc     & 1<<24 ? ';' : ':', // drop
1463                           tc     & 0x3f);             // frames
1464             } else {
1465                 print_str_opt("timecode", "N/A");
1466             }
1467             break;
1468
1469         case AVMEDIA_TYPE_AUDIO:
1470             s = av_get_sample_fmt_name(dec_ctx->sample_fmt);
1471             if (s) print_str    ("sample_fmt", s);
1472             else   print_str_opt("sample_fmt", "unknown");
1473             print_val("sample_rate",     dec_ctx->sample_rate, unit_hertz_str);
1474             print_int("channels",        dec_ctx->channels);
1475             print_int("bits_per_sample", av_get_bits_per_sample(dec_ctx->codec_id));
1476             break;
1477         }
1478     } else {
1479         print_str_opt("codec_type", "unknown");
1480     }
1481     if (dec_ctx->codec && dec_ctx->codec->priv_class && show_private_data) {
1482         const AVOption *opt = NULL;
1483         while (opt = av_opt_next(dec_ctx->priv_data,opt)) {
1484             uint8_t *str;
1485             if (opt->flags) continue;
1486             if (av_opt_get(dec_ctx->priv_data, opt->name, 0, &str) >= 0) {
1487                 print_str(opt->name, str);
1488                 av_free(str);
1489             }
1490         }
1491     }
1492
1493     if (fmt_ctx->iformat->flags & AVFMT_SHOW_IDS) print_fmt    ("id", "0x%x", stream->id);
1494     else                                          print_str_opt("id", "N/A");
1495     print_fmt("r_frame_rate",   "%d/%d", stream->r_frame_rate.num,   stream->r_frame_rate.den);
1496     print_fmt("avg_frame_rate", "%d/%d", stream->avg_frame_rate.num, stream->avg_frame_rate.den);
1497     print_fmt("time_base",      "%d/%d", stream->time_base.num,      stream->time_base.den);
1498     print_time("start_time",    stream->start_time, &stream->time_base);
1499     print_time("duration",      stream->duration,   &stream->time_base);
1500     if (stream->nb_frames) print_fmt    ("nb_frames", "%"PRId64, stream->nb_frames);
1501     else                   print_str_opt("nb_frames", "N/A");
1502     show_tags(stream->metadata);
1503
1504     print_section_footer("stream");
1505     av_free(pbuf.s);
1506     fflush(stdout);
1507 }
1508
1509 static void show_streams(WriterContext *w, AVFormatContext *fmt_ctx)
1510 {
1511     int i;
1512     for (i = 0; i < fmt_ctx->nb_streams; i++)
1513         show_stream(w, fmt_ctx, i);
1514 }
1515
1516 static void show_format(WriterContext *w, AVFormatContext *fmt_ctx)
1517 {
1518     char val_str[128];
1519     int64_t size = fmt_ctx->pb ? avio_size(fmt_ctx->pb) : -1;
1520
1521     print_section_header("format");
1522     print_str("filename",         fmt_ctx->filename);
1523     print_int("nb_streams",       fmt_ctx->nb_streams);
1524     print_str("format_name",      fmt_ctx->iformat->name);
1525     print_str("format_long_name", fmt_ctx->iformat->long_name);
1526     print_time("start_time",      fmt_ctx->start_time, &AV_TIME_BASE_Q);
1527     print_time("duration",        fmt_ctx->duration,   &AV_TIME_BASE_Q);
1528     if (size >= 0) print_val    ("size", size, unit_byte_str);
1529     else           print_str_opt("size", "N/A");
1530     if (fmt_ctx->bit_rate > 0) print_val    ("bit_rate", fmt_ctx->bit_rate, unit_bit_per_second_str);
1531     else                       print_str_opt("bit_rate", "N/A");
1532     show_tags(fmt_ctx->metadata);
1533     print_section_footer("format");
1534     fflush(stdout);
1535 }
1536
1537 static void show_error(WriterContext *w, int err)
1538 {
1539     char errbuf[128];
1540     const char *errbuf_ptr = errbuf;
1541
1542     if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
1543         errbuf_ptr = strerror(AVUNERROR(err));
1544
1545     writer_print_chapter_header(w, "error");
1546     print_section_header("error");
1547     print_int("code", err);
1548     print_str("string", errbuf_ptr);
1549     print_section_footer("error");
1550     writer_print_chapter_footer(w, "error");
1551 }
1552
1553 static int open_input_file(AVFormatContext **fmt_ctx_ptr, const char *filename)
1554 {
1555     int err, i;
1556     AVFormatContext *fmt_ctx = NULL;
1557     AVDictionaryEntry *t;
1558
1559     if ((err = avformat_open_input(&fmt_ctx, filename, iformat, &format_opts)) < 0) {
1560         print_error(filename, err);
1561         return err;
1562     }
1563     if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
1564         av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
1565         return AVERROR_OPTION_NOT_FOUND;
1566     }
1567
1568
1569     /* fill the streams in the format context */
1570     if ((err = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
1571         print_error(filename, err);
1572         return err;
1573     }
1574
1575     av_dump_format(fmt_ctx, 0, filename, 0);
1576
1577     /* bind a decoder to each input stream */
1578     for (i = 0; i < fmt_ctx->nb_streams; i++) {
1579         AVStream *stream = fmt_ctx->streams[i];
1580         AVCodec *codec;
1581
1582         if (!(codec = avcodec_find_decoder(stream->codec->codec_id))) {
1583             av_log(NULL, AV_LOG_ERROR, "Unsupported codec with id %d for input stream %d\n",
1584                    stream->codec->codec_id, stream->index);
1585         } else if (avcodec_open2(stream->codec, codec, NULL) < 0) {
1586             av_log(NULL, AV_LOG_ERROR, "Error while opening codec for input stream %d\n",
1587                    stream->index);
1588         }
1589     }
1590
1591     *fmt_ctx_ptr = fmt_ctx;
1592     return 0;
1593 }
1594
1595 #define PRINT_CHAPTER(name) do {                                        \
1596     if (do_show_ ## name) {                                             \
1597         writer_print_chapter_header(wctx, #name);                       \
1598         show_ ## name (wctx, fmt_ctx);                                  \
1599         writer_print_chapter_footer(wctx, #name);                       \
1600     }                                                                   \
1601 } while (0)
1602
1603 static int probe_file(WriterContext *wctx, const char *filename)
1604 {
1605     AVFormatContext *fmt_ctx;
1606     int ret, i;
1607
1608     ret = open_input_file(&fmt_ctx, filename);
1609     if (ret >= 0) {
1610         if (do_show_packets || do_show_frames) {
1611             const char *chapter;
1612             if (do_show_frames && do_show_packets &&
1613                 wctx->writer->flags & WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER)
1614                 chapter = "packets_and_frames";
1615             else if (do_show_packets && !do_show_frames)
1616                 chapter = "packets";
1617             else // (!do_show_packets && do_show_frames)
1618                 chapter = "frames";
1619             writer_print_chapter_header(wctx, chapter);
1620             show_packets(wctx, fmt_ctx);
1621             writer_print_chapter_footer(wctx, chapter);
1622         }
1623         PRINT_CHAPTER(streams);
1624         PRINT_CHAPTER(format);
1625         for (i = 0; i < fmt_ctx->nb_streams; i++)
1626             if (fmt_ctx->streams[i]->codec->codec_id != CODEC_ID_NONE)
1627                 avcodec_close(fmt_ctx->streams[i]->codec);
1628         avformat_close_input(&fmt_ctx);
1629     }
1630
1631     return ret;
1632 }
1633
1634 static void show_usage(void)
1635 {
1636     av_log(NULL, AV_LOG_INFO, "Simple multimedia streams analyzer\n");
1637     av_log(NULL, AV_LOG_INFO, "usage: %s [OPTIONS] [INPUT_FILE]\n", program_name);
1638     av_log(NULL, AV_LOG_INFO, "\n");
1639 }
1640
1641 static void ffprobe_show_program_version(WriterContext *w)
1642 {
1643     struct print_buf pbuf = {.s = NULL};
1644
1645     writer_print_chapter_header(w, "program_version");
1646     print_section_header("program_version");
1647     print_str("version", FFMPEG_VERSION);
1648     print_fmt("copyright", "Copyright (c) %d-%d the FFmpeg developers",
1649               program_birth_year, this_year);
1650     print_str("build_date", __DATE__);
1651     print_str("build_time", __TIME__);
1652     print_str("compiler_type", CC_TYPE);
1653     print_str("compiler_version", CC_VERSION);
1654     print_str("configuration", FFMPEG_CONFIGURATION);
1655     print_section_footer("program_version");
1656     writer_print_chapter_footer(w, "program_version");
1657
1658     av_free(pbuf.s);
1659 }
1660
1661 #define SHOW_LIB_VERSION(libname, LIBNAME)                              \
1662     do {                                                                \
1663         if (CONFIG_##LIBNAME) {                                         \
1664             unsigned int version = libname##_version();                 \
1665             print_section_header("library_version");                    \
1666             print_str("name",    "lib" #libname);                       \
1667             print_int("major",   LIB##LIBNAME##_VERSION_MAJOR);         \
1668             print_int("minor",   LIB##LIBNAME##_VERSION_MINOR);         \
1669             print_int("micro",   LIB##LIBNAME##_VERSION_MICRO);         \
1670             print_int("version", version);                              \
1671             print_section_footer("library_version");                    \
1672         }                                                               \
1673     } while (0)
1674
1675 static void ffprobe_show_library_versions(WriterContext *w)
1676 {
1677     writer_print_chapter_header(w, "library_versions");
1678     SHOW_LIB_VERSION(avutil,     AVUTIL);
1679     SHOW_LIB_VERSION(avcodec,    AVCODEC);
1680     SHOW_LIB_VERSION(avformat,   AVFORMAT);
1681     SHOW_LIB_VERSION(avdevice,   AVDEVICE);
1682     SHOW_LIB_VERSION(avfilter,   AVFILTER);
1683     SHOW_LIB_VERSION(swscale,    SWSCALE);
1684     SHOW_LIB_VERSION(swresample, SWRESAMPLE);
1685     SHOW_LIB_VERSION(postproc,   POSTPROC);
1686     writer_print_chapter_footer(w, "library_versions");
1687 }
1688
1689 static int opt_format(const char *opt, const char *arg)
1690 {
1691     iformat = av_find_input_format(arg);
1692     if (!iformat) {
1693         av_log(NULL, AV_LOG_ERROR, "Unknown input format: %s\n", arg);
1694         return AVERROR(EINVAL);
1695     }
1696     return 0;
1697 }
1698
1699 static void opt_input_file(void *optctx, const char *arg)
1700 {
1701     if (input_filename) {
1702         av_log(NULL, AV_LOG_ERROR, "Argument '%s' provided as input filename, but '%s' was already specified.\n",
1703                arg, input_filename);
1704         exit(1);
1705     }
1706     if (!strcmp(arg, "-"))
1707         arg = "pipe:";
1708     input_filename = arg;
1709 }
1710
1711 static int opt_help(const char *opt, const char *arg)
1712 {
1713     av_log_set_callback(log_callback_help);
1714     show_usage();
1715     show_help_options(options, "Main options:\n", 0, 0);
1716     printf("\n");
1717
1718     show_help_children(avformat_get_class(), AV_OPT_FLAG_DECODING_PARAM);
1719
1720     return 0;
1721 }
1722
1723 static int opt_pretty(const char *opt, const char *arg)
1724 {
1725     show_value_unit              = 1;
1726     use_value_prefix             = 1;
1727     use_byte_value_binary_prefix = 1;
1728     use_value_sexagesimal_format = 1;
1729     return 0;
1730 }
1731
1732 static int opt_show_versions(const char *opt, const char *arg)
1733 {
1734     do_show_program_version  = 1;
1735     do_show_library_versions = 1;
1736     return 0;
1737 }
1738
1739 static const OptionDef options[] = {
1740 #include "cmdutils_common_opts.h"
1741     { "f", HAS_ARG, {(void*)opt_format}, "force format", "format" },
1742     { "unit", OPT_BOOL, {(void*)&show_value_unit}, "show unit of the displayed values" },
1743     { "prefix", OPT_BOOL, {(void*)&use_value_prefix}, "use SI prefixes for the displayed values" },
1744     { "byte_binary_prefix", OPT_BOOL, {(void*)&use_byte_value_binary_prefix},
1745       "use binary prefixes for byte units" },
1746     { "sexagesimal", OPT_BOOL,  {(void*)&use_value_sexagesimal_format},
1747       "use sexagesimal format HOURS:MM:SS.MICROSECONDS for time units" },
1748     { "pretty", 0, {(void*)&opt_pretty},
1749       "prettify the format of displayed values, make it more human readable" },
1750     { "print_format", OPT_STRING | HAS_ARG, {(void*)&print_format},
1751       "set the output printing format (available formats are: default, compact, csv, json, xml)", "format" },
1752     { "show_error",   OPT_BOOL, {(void*)&do_show_error} ,  "show probing error" },
1753     { "show_format",  OPT_BOOL, {(void*)&do_show_format} , "show format/container info" },
1754     { "show_frames",  OPT_BOOL, {(void*)&do_show_frames} , "show frames info" },
1755     { "show_packets", OPT_BOOL, {(void*)&do_show_packets}, "show packets info" },
1756     { "show_streams", OPT_BOOL, {(void*)&do_show_streams}, "show streams info" },
1757     { "show_program_version",  OPT_BOOL, {(void*)&do_show_program_version},  "show ffprobe version" },
1758     { "show_library_versions", OPT_BOOL, {(void*)&do_show_library_versions}, "show library versions" },
1759     { "show_versions",         0, {(void*)&opt_show_versions}, "show program and library versions" },
1760     { "show_private_data", OPT_BOOL, {(void*)&show_private_data}, "show private data" },
1761     { "private",           OPT_BOOL, {(void*)&show_private_data}, "same as show_private_data" },
1762     { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
1763     { "i", HAS_ARG, {(void *)opt_input_file}, "read specified file", "input_file"},
1764     { NULL, },
1765 };
1766
1767 int main(int argc, char **argv)
1768 {
1769     const Writer *w;
1770     WriterContext *wctx;
1771     char *buf;
1772     char *w_name = NULL, *w_args = NULL;
1773     int ret;
1774
1775     av_log_set_flags(AV_LOG_SKIP_REPEATED);
1776     parse_loglevel(argc, argv, options);
1777     av_register_all();
1778     avformat_network_init();
1779     init_opts();
1780 #if CONFIG_AVDEVICE
1781     avdevice_register_all();
1782 #endif
1783
1784     show_banner(argc, argv, options);
1785     parse_options(NULL, argc, argv, options, opt_input_file);
1786
1787     writer_register_all();
1788
1789     if (!print_format)
1790         print_format = av_strdup("default");
1791     w_name = av_strtok(print_format, "=", &buf);
1792     w_args = buf;
1793
1794     w = writer_get_by_name(w_name);
1795     if (!w) {
1796         av_log(NULL, AV_LOG_ERROR, "Unknown output format with name '%s'\n", w_name);
1797         ret = AVERROR(EINVAL);
1798         goto end;
1799     }
1800
1801     if ((ret = writer_open(&wctx, w, w_args, NULL)) >= 0) {
1802         writer_print_header(wctx);
1803
1804         if (do_show_program_version)
1805             ffprobe_show_program_version(wctx);
1806         if (do_show_library_versions)
1807             ffprobe_show_library_versions(wctx);
1808
1809         if (!input_filename &&
1810             ((do_show_format || do_show_streams || do_show_packets || do_show_error) ||
1811              (!do_show_program_version && !do_show_library_versions))) {
1812             show_usage();
1813             av_log(NULL, AV_LOG_ERROR, "You have to specify one input file.\n");
1814             av_log(NULL, AV_LOG_ERROR, "Use -h to get full help or, even better, run 'man %s'.\n", program_name);
1815             ret = AVERROR(EINVAL);
1816         } else if (input_filename) {
1817             ret = probe_file(wctx, input_filename);
1818             if (ret < 0 && do_show_error)
1819                 show_error(wctx, ret);
1820         }
1821
1822         writer_print_footer(wctx);
1823         writer_close(&wctx);
1824     }
1825
1826 end:
1827     av_freep(&print_format);
1828     avformat_network_deinit();
1829
1830     return ret;
1831 }