/***************************************************************************
 *   Copyright (C) 2004 by Predrag Viceic                                  *
 *   viceic@net2000.ch                                             *
 *                                                                         *
 *   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; 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 General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
 /*
    JACK layer taken from AlsaModularSynth project by Matthias Nagorni
    http://alsamodular.sourceforge.net/

    /dev/dsp layer taken from libsndfile examples by Erik de Castro Lopo
    http://www.mega-nerd.com/libsndfile/
*/

#ifndef SOUNDPLAYER_H
#define SOUNDPLAYER_H

#include <qthread.h>
#include <sndfile.h>
#include <stdio.h>
#include <iostream>
#ifdef HAS_OSS
    #include 	<fcntl.h>
    #include 	<sys/ioctl.h>
    #include 	<sys/soundcard.h>
#endif
#include 	<string.h>
#include <unistd.h>
#include <qcanvas.h>
#include <qsplashscreen.h>
#include <qapplication.h>
#include "drawsoundwidget.h"
#include "spectrumview.h"
#include "soundmanager.h"
#include "playpositionchanged.h"
#ifdef HAS_JACK
    #include <jack/jack.h>
#endif
#ifdef HAS_PORTAUDIO
    #include "portaudio.h"
#endif

#ifdef HAS_ALSA
   #include <alsa/asoundlib.h>
#endif

#include "qdatetime.h"
#include <qapplication.h>

/**
@author Predrag Viceic

\class SoundPlayer

\brief class used for playing

This class can play via JACK interface (OutputDriver::OUTPUT_JACK) or to OSS
(OutputDriver::OUTPUT_DEVDSP).
Depending of your system configuration this class will choose automatically between the two output methods
*/
class SoundPlayer :public QThread
{
public:
    SoundPlayer();
    ~SoundPlayer();
    void setSoundmanager(SoundManager*);
    int linux_open_dsp_device(int, int);
    void run();
    void exit(int);
    void playDevDsp();
    void stopPlay();
    void positionChanged(unsigned long);
    QPtrList <QObject> soundMonitors;
    bool isPlaying();
    void setPlaying(bool);
    void setLoop(long,long);
    void setOneTimeLoop(long,long);
    void setPlayingOnce(bool);
    #ifdef HAS_JACK
        int connect_jack();
        static int jack_static_callback (jack_nframes_t , void *);
        int jack_callback (jack_nframes_t);
        int setJackNotPlaying(jack_default_audio_sample_t *, jack_nframes_t);
    #endif
    #ifdef HAS_OSS
        int connect_devdsp();
    #endif
    #ifdef HAS_ALSA
        snd_pcm_t *alsa_pcm_handle;                  /* Handle for the PCM device */
        snd_pcm_stream_t alsa_stream; /* Playback stream */
        snd_pcm_hw_params_t *alsa_hwparams; /* hardware information */
        snd_pcm_sw_params_t *alsa_swparams; 
        char *alsa_pcm_name; /* name of the pcm device */
        unsigned int alsa_rate; /* Sample rate */
        unsigned int alsa_exact_rate;   /* Sample rate returned by */
                        /* snd_pcm_hw_params_set_rate_near */ 
        int alsa_dir;          /* exact_rate == rate --> dir = 0 */
                        /* exact_rate < rate  --> dir = -1 */
                        /* exact_rate > rate  --> dir = 1 */
        int alsa_periods;       /* Number of periods */
        snd_pcm_uframes_t alsa_periodsize; /* Periodsize (bytes) */
        int alsa_buffer_size;
        int alsa_frames;
    #endif
    enum OutputDriver {OUTPUT_NONE,OUTPUT_DEVDSP,OUTPUT_JACK,OUTPUT_PORTAUDIO,OUTPUT_ALSA};
    static const int PLAY_PORTS=2;
    OutputDriver output;
    void init();
    void setBufferLen(int);
    void setJackBuffersLen(int);
    int getOutputType();
    void cropped(unsigned long,unsigned long);
    
    void addSoundMonitor(QObject*);
    void initLoop();
    void playFromFile(QString path);
    void playFromFileThreaded();
    void stopPlayFromFile();
    void resetLoop();
    void setPosition(long pos);
    void close();
    void removeSoundMonitor(QObject* sm);
    void pausePlayFromFile();
    #ifdef HAS_PORTAUDIO
    static int portaudio_static_callback( const void *inputBuffer,
                    void *outputBuffer,
                     unsigned long framesPerBuffer,
                     const PaStreamCallbackTimeInfo* timeInfo,
                     PaStreamCallbackFlags statusFlags, void *userData );
    int portaudio_callback( const void *inputBuffer, void *outputBuffer,
                     unsigned long framesPerBuffer,
                     const PaStreamCallbackTimeInfo* timeInfo,
                     PaStreamCallbackFlags statusFlags);
    int connect_portaudio();
    void closePortaudio();
    int startPAStream();
    int stopPAStream();
    #endif
    
    #ifdef HAS_ALSA
         int connect_alsa();
         void playALSA();
         QStringList getAlsaInterfaces();
         int setAlsaParameters(QString name, int frames, int periods, int rate);
         QString getAlsaPcmName();
    #endif
    void setLeftLoop(const unsigned long& theValue);
    unsigned long getLeftLoop() const;

	void setMainApplication(QApplication* theValue);
	int processedPositions;
	

protected:
    SoundManager* soundManager;
    unsigned long position; /**< current playing position */
    bool playing; /**  are we playing? */
    bool playingOnce; /**< should we stop at the end of the loop ? */
    bool stopped; /**< should we stop at the next return from callback? */
    short* bufferLR_S;
    float* bufferLR_F;
    float* bufferPointerL;
    float* bufferPointerR;
    float** bufferPointersLR;
    uint buffer_len;
    unsigned long leftLoop;
    unsigned long rightLoop;
    unsigned long savedLeftLoop;
    unsigned long savedRightLoop;
    #ifdef HAS_JACK
        int closeJack();
        jack_client_t *jack_handle;
        jack_port_t *jack_out [PLAY_PORTS];
    #endif
    void setRightLoop(const unsigned long& theValue);
    unsigned long getRightLoop() const;
    #ifdef HAS_OSS
        int devdsp_audio_device;
    #endif
    QString playFromFilePath;
    SNDFILE* previewFile;
    SF_INFO sfinfoForPreview;
    bool closeV;
    QApplication* mainApplication;
    #ifdef HAS_PORTAUDIO
        PaStream *portaudio_stream;
    #endif

private:
    bool playFromFileV;
};

#endif
