
#include "audio.h"
#include <stdio.h>


void data_callback(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount)
{
	ma_data_source_read_pcm_frames((ma_data_source*)pDevice->pUserData, pOutput, frameCount, NULL);

	(void)pInput;
}

int main(int argc, char** argv)
{
	ma_result							result;
	ma_device_config					deviceConfig;
	ma_device							device;
	ma_resource_manager_config			resourceManagerConfig;
	ma_resource_manager					resourceManager;
	ma_resource_manager_data_source		dataSource;

	if (argc < 2)
	{
		printf("No input file.");
		return (-1);
	}

	/* Device */
	deviceConfig = ma_device_config_init(ma_device_type_playback);
	deviceConfig.dataCallback = data_callback;
	deviceConfig.pUserData    = &dataSource;
	result = ma_device_init(NULL, &deviceConfig, &device);
	if (result != MA_SUCCESS)
	{
		printf("Failed to initialize device.");
		return (-1);
	}

	/* ResourceManager */
	resourceManagerConfig = ma_resource_manager_config_init();
	resourceManagerConfig.decodedFormat     = device.playback.format;
	resourceManagerConfig.decodedChannels   = device.playback.channels;
	resourceManagerConfig.decodedSampleRate = device.sampleRate;
	result = ma_resource_manager_init(&resourceManagerConfig, &resourceManager);
	if (result != MA_SUCCESS) {
		ma_device_uninit(&device);
		printf("Failed to initialize the resource manager.");
		return (-1);
	}

	/* Load the sound. */
	result = ma_resource_manager_data_source_init(
		&resourceManager,
		argv[1],
		MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE | MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC | MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM,
		NULL,   /* Async notification. */
		&dataSource);
	if (result != MA_SUCCESS) {
		printf("Failed to load sound \"%s\".", argv[1]);
		return (-1);
	}

	/* Looping. */
	ma_data_source_set_looping(&dataSource, MA_TRUE);

	/* Start the device. */
	result = ma_device_start(&device);
	if (result != MA_SUCCESS) {
		ma_device_uninit(&device);
		printf("Failed to start device.");
		return (-1);
	}

	printf("Press Enter to quit...\n");
	getchar();

	/* Teardown. */
	ma_device_uninit(&device);
	ma_resource_manager_data_source_uninit(&dataSource);
	ma_resource_manager_uninit(&resourceManager);

	return 0;
}

