#include <stdio.h>
#include <libavformat/avformat.h>
#include <libavutil/opt.h>

int main(int argc, char **argv) {
  const char *filename;
  AVFormatContext *format_context = NULL;
  AVFrame *frame = NULL;
  AVStream *stream;
  AVPacket *packet = NULL;
  AVDictionaryEntry *tag = NULL;
  int ret;

  if (argc <= 1) {
    fprintf(stderr, "Usage: %s <input url>\n", argv[0]);
    exit(0);
  }

  filename = argv[1];
  const AVInputFormat *format = av_find_input_format("ogg");
  AVDictionary *options = NULL;
  ret = avformat_open_input(&format_context, filename, format, &options);
  if (ret < 0) {
    fprintf(stderr, "Could not open %s: %s\n", filename, av_err2str(ret));
    exit(1);
  }

  ret = avformat_find_stream_info(format_context, 0);
  if (ret < 0) {
    fprintf(stderr, "Failed to retrieve input stream information: %s\n", av_err2str(ret));
    exit(1);
  }

  av_dump_format(format_context, 0, argv[0], 0);

  stream = format_context->streams[0];

  packet = av_packet_alloc();
  if (!packet) {
    fprintf(stderr, "Could not allocate packet\n");
    exit(1);
  }

  printf("Reading from: %s\n", filename);
  while (av_read_frame(format_context, packet) >= 0) {
    av_packet_unref(packet);

    while ((tag = av_dict_get(stream->metadata, "", tag, AV_DICT_IGNORE_SUFFIX))) {
      printf("%s=%s\n", tag->key, tag->value);
    }
  }
end:
  avformat_close_input(&format_context);
  av_packet_free(&packet);

  return 0;
}
