
/*
 * --- GSMP-COPYRIGHT-NOTE-BEGIN ---
 * 
 * This copyright note is auto-generated by ./scripts/Create-CopyPatch.
 * Please add additional copyright information _after_ the line containing
 * the GSMP-COPYRIGHT-NOTE-END tag. Otherwise it might get removed by
 * the ./scripts/Create-CopyPatch script. Do not edit this copyright text!
 * 
 * GSMP: pcm/tests/ALSAStream.cc
 * General Sound Manipulation Program is Copyright (C) 2000 - 2004
 *   Valentin Ziegler and René Rebe
 * 
 * This program 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; version 2. A copy of the GNU General
 * Public License can be found in the file LICENSE.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANT-
 * ABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
 * Public License for more details.
 * 
 * --- GSMP-COPYRIGHT-NOTE-END ---
 */

#include <iostream>

#include "OggVorbisStream.hh"
#include "MP3Stream.hh"

#include "ALSAIOStream.hh"

using namespace std;
using namespace GSMP;

int main()
{
  ALSAIOStream alsa_stream;
  
  if (!alsa_stream.Init () ) {
    std::cout << "ALSA IO Stream init failed!" << std::endl;
    return -1;
  }
  
  int period_size = alsa_stream.PlaybackPeriodSize ();
  
  std::cout << "Period size in use: " << period_size << std::endl;
  
  BasicStream stream (2, period_size);
  
  if (!alsa_stream.StartIO () ) {
    std::cout << "ALSA start io failed!" << std::endl;
    return -1;
  }
  
  OggVorbisFileStream ogg_stream;
  ogg_stream.Open ("test.ogg");
  
  MP3FileStream mp3_stream;
  mp3_stream.Open ("test.mp3");
  
  BasicFileStream& used_stream = ogg_stream;
  
  while (true)
    {
      int written = 0;
      stream.Clear ();
      used_stream.Read (period_size, &stream);
      
      // test linear interpolation (I do not hear a difference to
      // just padding ... ?)
      if (false) {
	const int downsample = 6;
	for (channel_index c = 0; c < 2; ++c) {
	  for (int i = 0; i < period_size - period_size % downsample; ++i)
	    {
	      int32_t val1 = stream[c]->data[i];
	      int32_t val2 = val1;
	      if (i + downsample < period_size)
		val2 = stream[c]->data[i];
	      
	      stream[c]->data[i++] = val1;
	      for (int j = 1; j < downsample; ++j) {
		stream[c]->data[i++] = val1 + (val2 - val1) / j;
	      }
	    }
	}
      }
      
      while (written < period_size) {
	written += alsa_stream.Write (&stream, written);
	if (written != period_size) {
	  std::cout << "not a full period was written" << std::endl;
	  usleep (5000);
	}
      }
    }
  
  mp3_stream.Close ();
  ogg_stream.Close ();
      
  if (!alsa_stream.StopIO () ) {
    std::cout << "ALSA stop io failed!" << std::endl;
    return -1;    
  }

  return 0;
}
