
/*
 * --- 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/ALSAStreamPlayback.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 "ALSAIOStream.hh"
#include "Timer.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;
  }
  
  alsa_stream.SetPlayback (true);
  alsa_stream.SetCapture (false);
  alsa_stream.SetRate (48000);
  
  if (!alsa_stream.StartIO () ) {
    std::cout << "ALSA start io failed!" << std::endl;
    return -1;
  }
  
  local_index period_size = alsa_stream.PlaybackPeriodSize ();
  std::cout << "Period size in use: " << period_size << std::endl;

  BasicStream stream (2, period_size);
  stream.SetUsedSize (period_size);
  
  for (local_index i = 0; i < period_size; ++i) {
    stream[0]->data [i] = GSMP::PcmTraits<int32_t>::Zero();
    stream[1]->data [i] = GSMP::PcmTraits<int32_t>::Zero();
  }
  
  Utility::Timer timer;
  global_index samples = 0;
  while (true)
    {
      local_index written = 0;
      while (written < period_size)
	{
	  written += alsa_stream.Write (&stream, written);
	  if (written != period_size)
	    usleep (1000000 / 44100 * (period_size - written));
	}
      samples += written;
      
      std::cout << written << " samples written"
		<< ", playback xruns: " << alsa_stream.PlaybackXRuns ()
		<< std::endl;
      
      std::cout << (double) timer.PerSecond () * samples / timer.Delta() << std::endl;
    }
  
  if (!alsa_stream.StopIO () ) {
    std::cout << "ALSA stop io failed!" << std::endl;
    return -1;    
  }
  
  return 0;
}
