/* JEsd
 * Copyright (C) 1999 JCraft Inc.
 *  
 * Written by: 1999 ymnk
 *   
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public License
 * as published by the Free Software Foundation; either version 2 of
 * the License, or (at your option) any later version.
   
 * This program 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 Library General Public License for more details.
 * 
 * You should have received a copy of the GNU Library General Public
 * License along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

import com.jcraft.jesd.*;

public class Play{
  Play(String[] arg) throws java.io.IOException{
    String file=null;
    String host="localhost";

    int i=0;
    for(;i<arg.length;i++){
      if(arg[i].equals("-h")){
	System.out.println("usage: Play [-s server] file");
	System.exit(0);
      }
      if(arg[i].equals("-s")){
	i++;
	host=arg[i];
	continue;
      }
      break;
    }
    file=arg[i];

    WAVEFile wave=new WAVEFile(file);
    int frame_count=wave.getFrameCount();
    int in_channels=wave.getChannels();
    int in_rate=wave.getRate();
    int in_width=wave.getSampleFormatWidth();

    int out_bits, out_channels, out_rate;
    int out_mode=JEsd.ESD_STREAM, out_func=JEsd.ESD_PLAY;

    if(in_width==8) out_bits=JEsd.ESD_BITS8; 
    else if(in_width==16) out_bits=JEsd.ESD_BITS16; 
    else{
      System.exit(-1);
    }

    int bytes_per_frame=(in_width*in_channels)/8;

    if(in_channels==1) out_channels=JEsd.ESD_MONO;
    else if(in_channels==2) out_channels=JEsd.ESD_STEREO;
    else{
      System.exit(-1);
    }

    int out_format=out_bits|out_channels|out_mode|out_func;
    out_rate=in_rate;


    JEsd jesd=null;
    try{
      jesd=JEsd.play_stream_fallback(out_format, 
				     out_rate,
				     host, 
				     file);
    }
    catch(Exception e){
      System.out.println(e);
      System.exit(-1);
    }

    //jesd.send_file(wave, bytes_per_frame);

    byte[] buf=new byte[JEsd.ESD_BUF_SIZE];
    int buf_frames=JEsd.ESD_BUF_SIZE/bytes_per_frame;
    int frames_read=0, bytes_written=0;

    while((frames_read=wave.readFrame(buf, buf_frames))>0){
      bytes_written+=frames_read*bytes_per_frame;
      if(jesd.write(buf, frames_read * bytes_per_frame)<=0) return;
    }
    System.out.println("byte_written="+bytes_written);

    jesd.close();
    wave.close();
  }
  public static void main(String[] arg){
    try{new Play(arg);}
    catch(Exception e){}
  }
}
