#ifndef __CWEBCAM_HANDLER_H__
#define __CWEBCAM_HANDLER_H__

#include <rdr/mutex.h>
#include <rdr/MultiOutStream.h>
#include <rfb/Configuration.h>

#define MAX_DATAGRAM_LEN 64 * 1024

class CWebcamHandler {
	public:
		CWebcamHandler(rdr::MultiOutStream* multios);
		~CWebcamHandler();
		static void killAllFfmpegProcesses();
		static TGVNC_CONDITION_TYPE webcamEnabledCondition;
		static MUTEX_TYPE webcamEnabledConditionLock;
		static TGVNC_CONDITION_TYPE udpPortCondition;
		static MUTEX_TYPE udpPortConditionLock;

		static rfb::StringParameter webcamExtraParam;

	private:
		// MultiOutStream object used to send packages
		rdr::MultiOutStream* multios;
		// If ffmpeg is running, stores the process id. If not, a 0.
		static int ffmpegPid;
#if !defined(__APPLE__)
		char* ffmpegExe;
#endif
		bool lastWebcamEnabledValue;
#if 0
		bool lastMicEnabledValue;
#endif

		static THREAD_ID webcamEnablerThreadId;
		static THREAD_ID webcamSocketThreadId;

		// Watches the webcamEnabled vnc parameter. It simply polls periodically.
		// TODO: it would be much nicer to use a TGVNC_CONDITION_TYPE
		// (and MUTEX_TYPE) for this.

		// Responsible for:
		// - starting/stopping a ffmpeg webcam capture process
		// - starting a thread which opens a UDP socket (see CWebcamHandler::webcamEnablerThread(void* param))
		//   TODO: it would be very nice if we could close the socket once webcamEnabled
		//   is set to false, but Windows' closesocket doesn't seem to do as we'd like.

		// Directly started on object creation.
		static THREAD_FUNC webcamEnablerThread(void* param);

		// Open a UDP socket and most importantly decide what to do with the received packets.
		// Basically, check if webcam is actually enabled and send them through a multi channel.

		// TODO: for now, it opens it in a hard-coded 50000 port. It would be nice to copy pulseaudio's logic
		// to try different ports (and set them as a port range too).
		static THREAD_FUNC webcamSocketThread(void* param);

		// Starts a ffmpeg process, which starts capturing the webcam and sends the processed video packets
		// to a local UDP port.
		// It saves the process id in the CWebcamHandler::ffmpegPid field.
		void startFfmpeg();
		void stopFfmpeg();
};

#endif /* __CWEBCAM_HANDLER_H__ */
