
/*
 * --- 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/ALSAStreamDuplex.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"

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;
  }
  
  local_index period_size = alsa_stream.CapturePeriodSize ();
  BasicStream stream (2, period_size);
  
  std::cout << "Period size in use: " << period_size << std::endl;
  
  alsa_stream.SetPlayback (true);
  alsa_stream.SetCapture (true);
  
  if (!alsa_stream.StartIO () ) {
    std::cout << "ALSA start io failed!" << std::endl;
    return -1;
  }
  
  while (true)
    {
      stream.Clear ();
      
      local_index read = 0;
      while (read < period_size) {
	read += alsa_stream.Read (&stream);
	if (read == 0)
	  usleep (1000000 / 44100 * (period_size - read));
      }
      
      std::cout << read << " samples read ..." << std::endl;
      
      local_index written = 0;
      while (written < period_size)
	{
	  written += alsa_stream.Write (&stream, written);
	  if (written != period_size)
	    usleep (1000000 / 44100 * (period_size - written));
	}
      
      std::cout << "samples written"
		<< ", capture xruns: " << alsa_stream.CaptureXRuns ()
		<< ", playback xruns: " << alsa_stream.PlaybackXRuns ()
		<< std::endl;
    }
  
  if (!alsa_stream.StopIO () ) {
    std::cout << "ALSA stop io failed!" << std::endl;
    return -1;    
  }

  return 0;
}
