// AudioVolumeDlg.cpp : implementation file
//

#include "stdafx.h"
#include "AudioVolume.h"
#include "AudioVolumeDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

class CAudioDeviceStorage
{
	DISABLE_COPY(CAudioDeviceStorage);

public:
	CAudioDeviceStorage(const wclAudioDevice& _Device)
	{
		Device = _Device;
	}

	wclAudioDevice Device;
};

// CAudioVolumeDlg dialog




CAudioVolumeDlg::CAudioVolumeDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CAudioVolumeDlg::IDD, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CAudioVolumeDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_COMBO_ENDPOINTS, cbEndpoints);
	DDX_Control(pDX, IDC_LIST_LOG, lbLog);
	DDX_Control(pDX, IDC_PROGRESS_MASTER, pbMaster);
	DDX_Control(pDX, IDC_SLIDER_VOLUME, tbMaster);
	DDX_Control(pDX, IDC_CHECK_MUTE, cbMute);
}

BEGIN_MESSAGE_MAP(CAudioVolumeDlg, CDialog)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	//}}AFX_MSG_MAP
	ON_WM_TIMER()
	ON_WM_DESTROY()
	ON_BN_CLICKED(IDC_BUTTON_CLOSE, &CAudioVolumeDlg::OnBnClickedButtonClose)
	ON_BN_CLICKED(IDC_BUTTON_OPEN, &CAudioVolumeDlg::OnBnClickedButtonOpen)
	ON_BN_CLICKED(IDC_CHECK_MUTE, &CAudioVolumeDlg::OnBnClickedCheckMute)
	ON_WM_HSCROLL()
	ON_WM_VSCROLL()
END_MESSAGE_MAP()


// CAudioVolumeDlg message handlers

BOOL CAudioVolumeDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	// TODO: Add extra initialization here

	__hook(&CwclAudioSwitcher::OnClosed, &AudioSwitcher, &CAudioVolumeDlg::AudioSwitcherClosed);
	__hook(&CwclAudioSwitcher::OnOpened, &AudioSwitcher, &CAudioVolumeDlg::AudioSwitcherOpened);
	__hook(&CwclAudioSwitcher::OnDeviceRemoved, &AudioSwitcher, &CAudioVolumeDlg::AudioSwitcherDeviceRemoved);
	__hook(&CwclAudioSwitcher::OnDeviceAdded, &AudioSwitcher, &CAudioVolumeDlg::AudioSwitcherDeviceAdded);
	__hook(&CwclAudioSwitcher::OnStateChanged, &AudioSwitcher, &CAudioVolumeDlg::AudioSwitcherStateChanged);
	__hook(&CwclAudioSwitcher::OnDefaultDeviceChanged, &AudioSwitcher, &CAudioVolumeDlg::AudioSwitcherDefaultDeviceChanged);

	__hook(&CwclAudioMeter::OnOpened, &AudioMeter, &CAudioVolumeDlg::AudioMeterOpened);
	__hook(&CwclAudioMeter::OnClosed, &AudioMeter, &CAudioVolumeDlg::AudioMeterClosed);
	__hook(&CwclAudioMeter::OnDisconnected, &AudioMeter, &CAudioVolumeDlg::AudioMeterDisconnected);

	__hook(&CwclAudioVolume::OnOpened, &AudioVolume, &CAudioVolumeDlg::AudioVolumeOpened);
	__hook(&CwclAudioVolume::OnClosed, &AudioVolume, &CAudioVolumeDlg::AudioVolumeClosed);
	__hook(&CwclAudioVolume::OnDisconnected, &AudioVolume, &CAudioVolumeDlg::AudioVolumeDisconnected);
	__hook(&CwclAudioVolume::OnChanged, &AudioVolume, &CAudioVolumeDlg::AudioVolumeChanged);

	pbMaster.SetRange(0, 100);
	tbMaster.SetRange(0, 100);

	int Res = AudioSwitcher.Open();
	if (Res != WCL_E_SUCCESS)
		Trace(_T("Audio switcher open failed"), Res);

	return TRUE;  // return TRUE  unless you set the focus to a control
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CAudioVolumeDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CAudioVolumeDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

void CAudioVolumeDlg::Trace(const CString& Msg)
{
	lbLog.AddString(Msg);
}

void CAudioVolumeDlg::Trace(const CString& Msg, const int Error)
{
	CString s;
	s.Format(_T("%.8X"), Error);
	s = Msg + _T(": 0x") + s;
	Trace(s);
}

void CAudioVolumeDlg::OnDestroy()
{
	CDialog::OnDestroy();

	AudioVolume.Close();
	AudioMeter.Close();
	AudioSwitcher.Close();

	__unhook(&AudioMeter);
	__unhook(&AudioSwitcher);
}

void CAudioVolumeDlg::AudioSwitcherClosed(void* Sender)
{
	UNREFERENCED_PARAMETER(Sender);

	Trace(_T("Audio switcher closed"));
	
	if (cbEndpoints.GetCount() > 0)
	{
		for (int i = 0; i < cbEndpoints.GetCount(); i++)
			delete (CAudioDeviceStorage*)cbEndpoints.GetItemData(i);
		cbEndpoints.ResetContent();
	}
}

void CAudioVolumeDlg::AudioSwitcherOpened(void* Sender)
{
	UNREFERENCED_PARAMETER(Sender);

	Trace(_T("Audio switcher opened"));

	wclAudioDevices Devices;
	wclAudioDeviceStates States;
	States.insert(asActive);
	int Res = AudioSwitcher.Enum(States, Devices);
	if (Res != WCL_E_SUCCESS)
		Trace(_T("Enum audio endpoints failed"), Res);
	else
	{
		if (Devices.size() == 0)
			Trace(_T("No active audio endpoints found"));
		else
		{
			for (wclAudioDevices::iterator i = Devices.begin(); i != Devices.end(); i++)
				AddDevice(*i);
			
			if (cbEndpoints.GetCount() == 0)
				Trace(_T("No output audio endpoints found"));
			else
				SelectActiveDevice();
		}
	}
}

void CAudioVolumeDlg::AudioSwitcherDeviceRemoved(void* Sender, const tstring& Id)
{
	UNREFERENCED_PARAMETER(Sender);

	DeleteDevice(Id);
}

void CAudioVolumeDlg::DeleteDevice(const tstring& Id)
{
	if (cbEndpoints.GetCount() > 0)
	{
		for (int i = 0; i < cbEndpoints.GetCount(); i++)
		{
			CAudioDeviceStorage* Storage = (CAudioDeviceStorage*)cbEndpoints.GetItemData(i);
			if (Storage->Device.Id == Id)
			{
				delete Storage;
				cbEndpoints.DeleteString(i);
				if (cbEndpoints.GetCount() > 0)
					SelectActiveDevice();
				break;
			}
		}
	}
}

void CAudioVolumeDlg::SelectActiveDevice()
{
	if (cbEndpoints.GetCount() > 0)
	{
		for (int i = 0; i < cbEndpoints.GetCount(); i++)
		{
			CAudioDeviceStorage* Storage = (CAudioDeviceStorage*)cbEndpoints.GetItemData(i);
			wclAudioDevice Device;
			int Res = AudioSwitcher.GetDeviceDetails(Storage->Device.Id, Device);
			if (Res == WCL_E_SUCCESS)
				Storage->Device = Device;
			if (Storage->Device.Roles.find(drMultimedia) != Storage->Device.Roles.end())
			{
				cbEndpoints.SetCurSel(i);
				return;
			}
		}
	}
	
	cbEndpoints.SetCurSel(-1);
}

void CAudioVolumeDlg::AudioSwitcherDeviceAdded(void* Sender, const tstring& Id)
{
	UNREFERENCED_PARAMETER(Sender);

	wclAudioDevice Device;
	if (AudioSwitcher.GetDeviceDetails(Id, Device) == WCL_E_SUCCESS)
		AddDevice(Device);
}

void CAudioVolumeDlg::AddDevice(const wclAudioDevice& Device)
{
	if (Device.State == asActive && Device.Flow == dfRender)
	{
		CAudioDeviceStorage* Storage = new CAudioDeviceStorage(Device);
		int i = cbEndpoints.AddString(Device.FriendlyName.c_str());
		cbEndpoints.SetItemData(i, (DWORD_PTR)Storage);
		
		SelectActiveDevice();
	}
}

void CAudioVolumeDlg::AudioMeterOpened(void* Sender)
{
	UNREFERENCED_PARAMETER(Sender);

	Trace(_T("Audio meter opened"));
	cbEndpoints.EnableWindow(FALSE);
	pbMaster.ShowWindow(SW_SHOW);

	wclAudioHardwareFeatures Features;
	int Res = AudioMeter.GetHardwareFeatures(Features);
	if (Res != WCL_E_SUCCESS)
		Trace(_T("Get hardware features failed"), Res);
	else
	{
		Trace(_T("Hardware features"));
		if (Features.find(hfVolume) != Features.end())
			Trace(_T("  Volume"));
		if (Features.find(hfMute) != Features.end())
			Trace(_T("  Mute"));
		if (Features.find(hfMeter) != Features.end())
			Trace(_T("  Meter"));
	}

	unsigned long Channels;
	Res = AudioMeter.GetChannels(Channels);
	if (Res != WCL_E_SUCCESS)
		Trace(_T("Get channels count failed"), Res);
	else
	{
		if (Channels == 0)
		{
			Trace(_T("No mettering channels available"));
			AudioMeter.Close();
		}
		else
		{
			CString s;
			s.Format(_T("%d"), Channels);
			Trace(_T("Channels: ") + s);
			
			RECT Rect;
			pbMaster.GetWindowRect(&Rect);
			ScreenToClient(&Rect);
			LONG Width = Rect.right - Rect.left;

			Rect.left = Rect.right + 5;
			Rect.right = Rect.left + Width;
			for (unsigned long i = 0; i < Channels; i++)
			{
				CProgressCtrl* Bar = new CProgressCtrl();
				Bar->Create(WS_CHILD | WS_VISIBLE | WS_TABSTOP | PBS_SMOOTH | PBS_VERTICAL,
					Rect, this, 20000 + i);
				Bar->SetRange(0, 100);
				Rect.left = Rect.right + 5;
				Rect.right = Rect.left + Width;
				
				FBars.push_back(Bar);
			}
			
			UpdateChannelsValue();
			
			SetTimer(ID_TIMER, 100, NULL);
		}
	}
}

void CAudioVolumeDlg::AudioMeterClosed(void* Sender)
{
	UNREFERENCED_PARAMETER(Sender);

	Trace(_T("Audio meter closed"));
	KillTimer(ID_TIMER);
	cbEndpoints.EnableWindow(TRUE);
	
	if (FBars.size() > 0)
	{
		for (std::vector<CProgressCtrl*>::iterator i = FBars.begin(); i != FBars.end(); i++)
			delete (*i);
		FBars.clear();
	}
	
	pbMaster.SetPos(0);
	pbMaster.ShowWindow(SW_HIDE);
}

void CAudioVolumeDlg::AudioMeterDisconnected(void* Sender)
{
	UNREFERENCED_PARAMETER(Sender);

	Trace(_T("Audio meter device ") + CString(AudioMeter.Id.c_str()) + _T(" disconnected"));
}

void CAudioVolumeDlg::OnBnClickedButtonClose()
{
	int Res = AudioVolume.Close();
	if (Res != WCL_E_SUCCESS)
		Trace(_T("Audio volume close failed"), Res);

	Res = AudioMeter.Close();
	if (Res != WCL_E_SUCCESS)
		Trace(_T("Audio meter close failed"), Res);
}

void CAudioVolumeDlg::OnBnClickedButtonOpen()
{
	if (cbEndpoints.GetCurSel() == -1)
		Trace(_T("No audio endpoints found"));
	else
	{
		tstring Id = ((CAudioDeviceStorage*)cbEndpoints.GetItemData(cbEndpoints.GetCurSel()))->Device.Id;
		
		int Res = AudioMeter.Open(Id);
		if (Res != WCL_E_SUCCESS)
			Trace(_T("Audio meter open failed"), Res);

		Res = AudioVolume.Open(Id);
		if (Res != WCL_E_SUCCESS)
			Trace(_T("Audio volume open failed"), Res);
	}
}

void CAudioVolumeDlg::UpdateChannelsValue()
{
	float Value;
	int Res = AudioMeter.GetPeak(Value);
	if (Res == WCL_E_SUCCESS)
	{
		if (tbMaster.IsWindowVisible())
		{
			Value = (float)(Value * 100.00 * ((100 - tbMaster.GetPos()) / 100.00));
			pbMaster.SetPos((int)Value);
		}
		else
			pbMaster.SetPos((int)(Value * 100));
	}
	
	if (FBars.size() > 0)
	{
		wclAudioPeakValues Values;
		Res = AudioMeter.GetChannelsPeak(Values);
		if (Res == WCL_E_SUCCESS && Values.size() > 0)
		{
			for (unsigned int i = 0; i < Values.size(); i++)
				FBars[i]->SetPos((int)(Values[i] * 100));
		}
	}
}

void CAudioVolumeDlg::AudioSwitcherStateChanged(void* Sender, const tstring& Id,
	const wclAudioDeviceState State)
{
	UNREFERENCED_PARAMETER(Sender);

	if (State == asActive)
		AudioSwitcherDeviceAdded(&AudioSwitcher, Id);
	else
		DeleteDevice(Id);
}

void CAudioVolumeDlg::AudioSwitcherDefaultDeviceChanged(void* Sender,
	const tstring& Id, const wclAudioDeviceDataFlow Flow,
	const wclAudioDeviceRole Role)
{
	UNREFERENCED_PARAMETER(Sender);
	UNREFERENCED_PARAMETER(Id);
	UNREFERENCED_PARAMETER(Flow);
	UNREFERENCED_PARAMETER(Role);

	Trace(_T("Active device changed"));
	
	if (!AudioMeter.Active)
		SelectActiveDevice();
}

void CAudioVolumeDlg::OnTimer(UINT_PTR uTime)
{
	UNREFERENCED_PARAMETER(uTime);

	UpdateChannelsValue();
}

void CAudioVolumeDlg::AudioVolumeOpened(void* Sender)
{
	UNREFERENCED_PARAMETER(Sender);

	Trace(_T("Audio volume opened"));
	cbEndpoints.EnableWindow(FALSE);
	
	wclAudioHardwareFeatures Features;
	int Res = AudioVolume.GetHardwareFeatures(Features);
	if (Res != WCL_E_SUCCESS)
		Trace(_T("Get hardware features failed"), Res);
	else
	{
		Trace(_T("Hardware features"));
		if (Features.find(hfVolume) != Features.end())
			Trace(_T("  Volume"));
		if (Features.find(hfMute) != Features.end())
			Trace(_T("  Mute"));
		if (Features.find(hfMeter) != Features.end())
			Trace(_T("  Meter"));
	}
	
	float Volume;
	Res = AudioVolume.GetVolume(Volume);
	if (Res != WCL_E_SUCCESS)
		Trace(_T("Get volume failed"), Res);
	else
	{
		tbMaster.ShowWindow(SW_SHOW);
		tbMaster.SetPos((int)(100 - Volume * 100));
	}
	
	bool Mute;
	Res = AudioVolume.GetMute(Mute);
	if (Res != WCL_E_SUCCESS)
		Trace(_T("Get mute failed"), Res);
	else
	{
		cbMute.ShowWindow(SW_SHOW);
		cbMute.SetCheck(Mute);
	}
}

void CAudioVolumeDlg::AudioVolumeClosed(void* Sender)
{
	UNREFERENCED_PARAMETER(Sender);

	Trace(_T("Audio volume closed"));
	cbEndpoints.EnableWindow(TRUE);
	tbMaster.ShowWindow(FALSE);
	tbMaster.SetPos(100);
	cbMute.ShowWindow(FALSE);
}

void CAudioVolumeDlg::AudioVolumeDisconnected(void* Sender)
{
	UNREFERENCED_PARAMETER(Sender);

	Trace(_T("Audio volume device ") + CString(AudioVolume.Id.c_str()) + _T(" disconnected"));
}

void CAudioVolumeDlg::OnBnClickedCheckMute()
{
	if (AudioVolume.Active)
	{
		int Res = AudioVolume.SetMute(cbMute.GetCheck() != FALSE);
		if (Res != WCL_E_SUCCESS)
			Trace(_T("Set mute failed"), Res);
	}
}

void CAudioVolumeDlg::AudioVolumeChanged(void* Sender, const bool Muted,
	const float Volume, const wclAudioPeakValues& Volumes)
{
	UNREFERENCED_PARAMETER(Sender);
	UNREFERENCED_PARAMETER(Volumes);

	if (AudioVolume.Active)
	{
		Trace(_T("Volume changed"));
		
		cbMute.SetCheck(Muted);
		tbMaster.SetPos((int)(100 - Volume * 100));
	}
}

void CAudioVolumeDlg::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
{
	CSliderCtrl* pSlider = reinterpret_cast<CSliderCtrl*>(pScrollBar);
	if (pSlider == &tbMaster && AudioVolume.Active)
	{
		int Res = AudioVolume.SetVolume((float)((100 - tbMaster.GetPos()) / 100.00));
		if (Res != WCL_E_SUCCESS)
			Trace(_T("Set volume failed"), Res);
	}

	CDialog::OnHScroll(nSBCode, nPos, pScrollBar);
}

void CAudioVolumeDlg::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
{
	CSliderCtrl* pSlider = reinterpret_cast<CSliderCtrl*>(pScrollBar);
	if (pSlider == &tbMaster && AudioVolume.Active)
	{
		int Res = AudioVolume.SetVolume((float)((100 - tbMaster.GetPos()) / 100.00));
		if (Res != WCL_E_SUCCESS)
			Trace(_T("Set volume failed"), Res);
	}

	CDialog::OnVScroll(nSBCode, nPos, pScrollBar);
}
