/* Copyright 2022-2026 Kurt Nienhaus
 *
 * This file is part of VgaGames.
 * VgaGames is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 * VgaGames is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with VgaGames.  If not, see <http://www.gnu.org/licenses/>.
 */

/* testen: aplay -t raw -c 2 -f S16_LE -r 44100 <RAW-Datei> */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
#include <vorbis/vorbisfile.h>

static int decode_file(FILE *);


static int decode_file(FILE *ffp)
{
  OggVorbis_File vf;
  int bits = 16;
  int bs = 0;
  char buf[8192];
  long ovret;
  int channels, samplerate;

  (void)OV_CALLBACKS_STREAMONLY_NOCLOSE;
  (void)OV_CALLBACKS_STREAMONLY;
  (void)OV_CALLBACKS_NOCLOSE;

  if (ov_open_callbacks(ffp, &vf, NULL, 0, OV_CALLBACKS_DEFAULT) < 0) {
    fprintf(stderr, "OGG: Failed to open input as Vorbis\n");
    fclose(ffp);
    return 0;
  }

  channels = ov_info(&vf, 0)->channels;
  samplerate = ov_info(&vf, 0)->rate;

  while ((ovret = ov_read(&vf, buf, (int)sizeof(buf), 0, bits / 8, 1, &bs)) != 0) {
    if (bs != 0) {
      vorbis_info *vi = ov_info(&vf, -1);
      if (channels != vi->channels || samplerate != vi->rate) {
        fprintf(stderr, "OGG: Logical bitstreams with changing parameters are not supported\n");
        break;
      }
    }

    if (ovret == OV_HOLE) {
      continue;
    } else if (ovret < 0L) {
      ov_clear(&vf);
      return 0;
    }

    if (fwrite(buf, 1, (size_t)ovret, stdout) != (size_t)ovret) {
      fprintf(stderr, "OGG: Error writing to stdout: %s\n", strerror(errno));
      ov_clear(&vf);
      return 0;
    }
  }

  ov_clear(&vf);

  return 1;
}


int
main(int argc, char **argv)
{
  FILE * ffp;
  if (argc < 2 || strcmp(argv[1], "-h") == 0) { fprintf(stderr, "Usage: %s <WAVE-file>\n", argv[0]); exit(1); }
  if ((ffp = fopen(argv[1], "r")) == NULL) { fprintf(stderr, "OGG: fopen %s: %s\n", argv[1], strerror(errno)); exit(1); }
  if (!decode_file(ffp)) { exit(1); }
  exit(0);
}
