note
	description: "Controller for the audio library."
	author: "Louis Marchand"
	date: "Tue, 07 Apr 2015 01:15:20 +0000"
	revision: "2.0"

class 
	AUDIO_LIBRARY_CONTROLLER

create 
	make

feature {NONE} -- Initialization

	default_create
			-- Process instances of classes with no creation clause.
			-- (Default: do nothing.)
			-- (from ANY)
		do
		end

	make
			-- Initialization for Current.
			-- Activates the sound context.
		do
			sound_buffer_size := 65536
			is_thread_init := False
			create launch_mutex.make
			create {LINKED_LIST [AUDIO_SOURCE]} internal_sources.make
			create internal_listener
		end

	make_thread
			-- Initialize Current.
			-- (from THREAD)
		do
			create launch_mutex.make
		end
	
feature -- Access

	capture_controller: AUDIO_CAPTURE_CONTROLLER
			-- Used to capture sound from microphone
		require
			capture_enabled: is_capture_enable
		do
			check
					attached internal_capture_controller as la_controller
			then
				Result := la_controller
			end
		end

	capture_device: AUDIO_DEVICE
			-- The capture AUDIO_DEVICE presently used by Current
		require
			sound_enabled: is_capture_enable
		do
			create Result.make ({AUDIO_EXTERNAL}.alc_get_string (internal_capture_device, {AUDIO_EXTERNAL}.alc_capture_device_specifier), False)
		end

	capture_devices: LIST [AUDIO_DEVICE]
			-- Lists all possible capture devices that Current may use
		local
			l_result: POINTER
			l_c_string: C_STRING
			l_item: AUDIO_DEVICE
		do
			if is_extension_present (null, "ALC_enumeration_EXT") then
				Result := devices_list ({AUDIO_EXTERNAL}.alc_capture_device_specifier, True)
			else
				create {ARRAYED_LIST [AUDIO_DEVICE]} Result.make (0)
			end
		ensure
			all_playback_device: across
					Result as la_result
				all
					la_result.item.is_capture
				end
		end

	current_thread_id: POINTER
			-- Thread identifier of the Current thread
			-- (from THREAD_ENVIRONMENT)
		external
			"C inline use <eif_threads.h>"
		alias
			"return eif_thr_thread_id();"
		end

	device_specifier: READABLE_STRING_GENERAL
		obsolete "Use playback_device.name"
			-- A text representation of the device used by Current
		require
			sound_enabled: is_playback_enable
		do
			Result := playback_device.name
		end

	devices: LIST [READABLE_STRING_GENERAL]
		obsolete "Use playback_devices"
			-- Lists all possible devices that Current may use
		local
			l_devices: LIST [AUDIO_DEVICE]
		do
			l_devices := playback_devices
			create {ARRAYED_LIST [READABLE_STRING_GENERAL]} Result.make (l_devices.count)
			across
				l_devices as la_devices
			loop
				Result.extend (la_devices.item.name)
			end
		end

	disable_capture
			-- Closes the capture sound context.
		local
			l_ok: BOOLEAN
		do
			if is_capture_enable then
				capture_controller.close_device
				clear_alc_error (internal_capture_device)
				l_ok := {AUDIO_EXTERNAL}.alc_capture_close_device (internal_capture_device)
				if not l_ok then
					read_alc_error (null, "Cannot close audio capture device.")
				end
			end
		end

	disable_playback
			-- Closes the playback sound context.
		local
			l_ok: BOOLEAN
		do
			if is_playback_enable then
				if is_thread_executing then
					stop_thread
				end;
				internal_sources.do_all (agent {AUDIO_SOURCE}.close);
				internal_sources.wipe_out
				{AUDIO_EXTERNAL}.alc_suspend_context (context)
				{AUDIO_EXTERNAL}.alc_destroy_context (context)
				clear_error
				l_ok := {AUDIO_EXTERNAL}.alc_close_device (internal_playback_device)
				if not l_ok then
					read_alc_error (null, "Cannot close audio context.")
				end
			end
		end

	disable_sound
		obsolete "Use disable_playback"
			-- Closes the playback sound context.
		do
			disable_playback
		end

	enable_capture (a_frequency, a_channel_count, a_bits_per_sample, a_buffer_count: INTEGER_32)
			-- Activates the capture sound context using the system default device. The capturing can be done with capture_controller.
			-- The resulting capture_controller will have use a_channel_count number of channel, a_bits_per_sample number of bits per
			-- single channel sample (8 or 16) and the internal buffer will be able to contain a_buffer_count samples (for example,
			-- a stereo 16 bits capture with a buffer count of 1024 will have the size 1024*2*2 = 5096 bytes)
		require
			is_not_already_enabled: not is_capture_enable
			channel_valid: a_channel_count >= 1 and a_channel_count <= 2
			bits_per_sample_valid: a_bits_per_sample ~ 8 or a_bits_per_sample ~ 16
			frequency_valid: a_frequency > 0
		do
			enable_capture_inmplementaton (null, a_frequency, a_channel_count, a_bits_per_sample, a_buffer_count)
		end

	enable_capture_with_device (a_device: AUDIO_DEVICE; a_frequency, a_channel_count, a_bits_per_sample, a_buffer_count: INTEGER_32)
			-- Activates the capture sound context using a_device. The capturing can be done with capture_controller.
			-- The resulting capture_controller will have use a_channel_count number of channel, a_bits_per_sample number of bits per
			-- single channel sample (8 or 16) and the internal buffer will be able to contain a_buffer_count samples (for example,
			-- a stereo 16 bits capture with a buffer count of 1024 will have the size 1024*2*2 = 5096 bytes)
		require
			is_not_already_enabled: not is_capture_enable
			device_valid: a_device.is_capture and capture_devices.has (a_device)
			channel_valid: a_channel_count >= 1 and a_channel_count <= 2
			bits_per_sample_valid: a_bits_per_sample ~ 8 or a_bits_per_sample ~ 16
			frequency_valid: a_frequency > 0
		do
			enable_capture_inmplementaton (a_device.name_pointer, a_frequency, a_channel_count, a_bits_per_sample, a_buffer_count)
		end

	enable_playback
			-- Activates the playback sound context.
		require
			is_not_already_enabled: not is_playback_enable
		do
			enable_playback_implementaton (null)
		end

	enable_playback_with_device (a_device: AUDIO_DEVICE)
			-- Activates the playback sound context using a_device.
		require
			is_not_already_enabled: not is_playback_enable
			is_device_valid: a_device.is_playback and playback_devices.has (a_device)
		do
			enable_playback_implementaton (a_device.name_pointer)
		end

	enable_sound
		obsolete "Use enable_playback"
			-- Activates the playback sound context.
		do
			enable_playback
		end

	generating_type: TYPE [detachable AUDIO_LIBRARY_CONTROLLER]
			-- Type of current object
			-- (type of which it is a direct instance)
			-- (from ANY)
		external
			"built_in"
		ensure -- from ANY
			generating_type_not_void: Result /= Void
		end

	generator: STRING_8
			-- Name of current object's generating class
			-- (base class of the type of which it is a direct instance)
			-- (from ANY)
		external
			"built_in"
		ensure -- from ANY
			generator_not_void: Result /= Void
			generator_not_empty: not Result.is_empty
		end

	get_current_id: POINTER
		obsolete "Use `current_thread_id' instead. [2017-05-31]"
			-- Returns a pointer to the thread-id of the thread.
			-- (from THREAD_ENVIRONMENT)
		do
			Result := current_thread_id
		end

	has_error: BOOLEAN
			-- Is the library has generate an error
			-- (from GAME_ERROR_MANAGER)

	is_capture_enable: BOOLEAN
			-- True when a capture sound is active.
		do
			Result := not internal_capture_device.is_default_pointer
		end

	is_playback_enable: BOOLEAN
			-- True when a playback sound context is active.
		do
			Result := not {AUDIO_EXTERNAL}.alc_get_current_context.is_default_pointer
		end

	is_sound_enable: BOOLEAN
		obsolete "Use is_playback_enable"
			-- True when a playback sound context is active.
		do
			Result := is_playback_enable
		end

	last_error: READABLE_STRING_GENERAL
			-- The last error generate by the library
			-- (from AUDIO_OPENAL_ERROR_MANAGER)
		do
			if is_manual_error then
				Result := Precursor {GAME_ERROR_MANAGER}
			elseif last_al_error_code /= {AUDIO_EXTERNAL}.al_no_error then
				if last_al_error_code = {AUDIO_EXTERNAL}.al_invalid_enum then
					Result := "An invalid enum value was passed to an OpenAL function."
				elseif last_al_error_code = {AUDIO_EXTERNAL}.al_invalid_value then
					Result := "An invalid value was passed to an OpenAL function."
				elseif last_al_error_code = {AUDIO_EXTERNAL}.al_invalid_operation then
					Result := "The requested operation is not valid."
				elseif last_al_error_code = {AUDIO_EXTERNAL}.al_invalid_name then
					Result := "A bad name (ID) was passed to an OpenAL function."
				elseif last_al_error_code = {AUDIO_EXTERNAL}.al_out_of_memory then
					Result := "The requested operation resulted in OpenAL running out of memory."
				else
					Result := "Unmanaged OpenAL error."
				end
			elseif last_alc_error_code /= {AUDIO_EXTERNAL}.alc_no_error then
				if last_alc_error_code = {AUDIO_EXTERNAL}.alc_invalid_value then
					Result := "An invalid value was passed to an OpenAL context function."
				elseif last_alc_error_code = {AUDIO_EXTERNAL}.alc_invalid_device then
					Result := "The device is not valid."
				elseif last_alc_error_code = {AUDIO_EXTERNAL}.alc_invalid_context then
					Result := "The context is not valid."
				elseif last_alc_error_code = {AUDIO_EXTERNAL}.alc_invalid_enum then
					Result := "Invalid enum parameter passed to an ALC call."
				elseif last_alc_error_code = {AUDIO_EXTERNAL}.alc_out_of_memory then
					Result := "Out of memory."
				else
					Result := "Unmanaged OpenAL context error."
				end
			else
				Result := "No error."
			end
		end

	listener: AUDIO_LISTENER
			-- Gets the sound listener.
		require
			get_listener_sound_open: is_playback_enable
		do
			Result := internal_listener
		end

	playback_device: AUDIO_DEVICE
			-- The playback AUDIO_DEVICE presently used by Current
		require
			sound_enabled: is_playback_enable
		do
			create Result.make ({AUDIO_EXTERNAL}.alc_get_string (internal_playback_device, {AUDIO_EXTERNAL}.alc_device_specifier), False)
		end

	playback_devices: LIST [AUDIO_DEVICE]
			-- Lists all possible playback devices that Current may use.
		do
			if is_extension_present (null, "ALC_enumeration_EXT") then
				if is_extension_present (null, "ALC_enumerate_all_EXT") then
					Result := devices_list ({AUDIO_EXTERNAL}.alc_all_device_specifier, False)
				else
					Result := devices_list ({AUDIO_EXTERNAL}.alc_device_specifier, False)
				end
			else
				create {ARRAYED_LIST [AUDIO_DEVICE]} Result.make (0)
			end
		ensure
			all_playback_device: across
					Result as la_result
				all
					la_result.item.is_playback
				end
		end

	quit_library
			-- Clears the library. Must be used before the end of the application
		local
			mem: MEMORY
		do
			if is_playback_enable then
				sources_wipe_out
				create mem;
				mem.full_collect
				disable_playback
				disable_capture
			end
		end

	terminated: BOOLEAN
			-- True if the thread has terminated.
			-- (from THREAD)

	thread_id: POINTER
			-- Thread-id of the current thread object.
			-- (from THREAD)
	
feature -- Comparison

	frozen deep_equal (a: detachable ANY; b: like arg #1): BOOLEAN
			-- Are a and b either both void
			-- or attached to isomorphic object structures?
			-- (from ANY)
		do
			if a = Void then
				Result := b = Void
			else
				Result := b /= Void and then a.is_deep_equal (b)
			end
		ensure -- from ANY
			instance_free: class
			shallow_implies_deep: standard_equal (a, b) implies Result
			both_or_none_void: (a = Void) implies (Result = (b = Void))
			same_type: (Result and (a /= Void)) implies (b /= Void and then a.same_type (b))
			symmetric: Result implies deep_equal (b, a)
		end

	frozen equal (a: detachable ANY; b: like arg #1): BOOLEAN
			-- Are a and b either both void or attached
			-- to objects considered equal?
			-- (from ANY)
		do
			if a = Void then
				Result := b = Void
			else
				Result := b /= Void and then a.is_equal (b)
			end
		ensure -- from ANY
			instance_free: class
			definition: Result = (a = Void and b = Void) or else ((a /= Void and b /= Void) and then a.is_equal (b))
		end

	frozen is_deep_equal alias "≡≡≡" (other: AUDIO_LIBRARY_CONTROLLER): BOOLEAN
			-- Are Current and other attached to isomorphic object structures?
			-- (from ANY)
		require -- from ANY
			other_not_void: other /= Void
		external
			"built_in"
		ensure -- from ANY
			shallow_implies_deep: standard_is_equal (other) implies Result
			same_type: Result implies same_type (other)
			symmetric: Result implies other.is_deep_equal (Current)
		end

	is_equal (other: AUDIO_LIBRARY_CONTROLLER): BOOLEAN
			-- Is other attached to an object considered
			-- equal to current object?
			-- (from ANY)
		require -- from ANY
			other_not_void: other /= Void
		external
			"built_in"
		ensure -- from ANY
			symmetric: Result implies other ~ Current
			consistent: standard_is_equal (other) implies Result
		end

	frozen standard_equal (a: detachable ANY; b: like arg #1): BOOLEAN
			-- Are a and b either both void or attached to
			-- field-by-field identical objects of the same type?
			-- Always uses default object comparison criterion.
			-- (from ANY)
		do
			if a = Void then
				Result := b = Void
			else
				Result := b /= Void and then a.standard_is_equal (b)
			end
		ensure -- from ANY
			instance_free: class
			definition: Result = (a = Void and b = Void) or else ((a /= Void and b /= Void) and then a.standard_is_equal (b))
		end

	frozen standard_is_equal alias "≜" (other: AUDIO_LIBRARY_CONTROLLER): BOOLEAN
			-- Is other attached to an object of the same type
			-- as current object, and field-by-field identical to it?
			-- (from ANY)
		require -- from ANY
			other_not_void: other /= Void
		external
			"built_in"
		ensure -- from ANY
			same_type: Result implies same_type (other)
			symmetric: Result implies other.standard_is_equal (Current)
		end
	
feature -- Status report

	conforms_to (other: ANY): BOOLEAN
			-- Does type of current object conform to type
			-- of other (as per Eiffel: The Language, chapter 13)?
			-- (from ANY)
		require -- from ANY
			other_not_void: other /= Void
		external
			"built_in"
		end

	is_exit_supported: BOOLEAN
			-- Can exit be called?
			-- (from THREAD)
		do
			Result := True
		ensure -- from THREAD
			is_class: class
		end

	is_last_launch_successful: BOOLEAN
			-- Was the last call to launch or launch_with_attributes in current thread
			-- of execution successful?
			-- (from THREAD)
		do
			Result := Is_last_launch_successful_cell.item
		end

	is_launchable: BOOLEAN
			-- Can we launch a new thread?
			-- (from THREAD)
		do
			Result := launch_mutex.is_set and thread_id = default_pointer and not terminated
		end

	same_type (other: ANY): BOOLEAN
			-- Is type of current object identical to type of other?
			-- (from ANY)
		require -- from ANY
			other_not_void: other /= Void
		external
			"built_in"
		ensure -- from ANY
			definition: Result = (conforms_to (other) and other.conforms_to (Current))
		end
	
feature -- Duplication

	frozen clone (other: detachable ANY): like other
		obsolete "Use `twin' instead. [2017-05-31]"
			-- Void if other is void; otherwise new object
			-- equal to other
			--
			-- For non-void other, clone calls copy;
			-- to change copying/cloning semantics, redefine copy.
			-- (from ANY)
		do
			if other /= Void then
				Result := other.twin
			end
		ensure -- from ANY
			instance_free: class
			equal: Result ~ other
		end

	copy (other: AUDIO_LIBRARY_CONTROLLER)
			-- Update current object using fields of object attached
			-- to other, so as to yield equal objects.
			-- (from ANY)
		require -- from ANY
			other_not_void: other /= Void
			type_identity: same_type (other)
		external
			"built_in"
		ensure -- from ANY
			is_equal: Current ~ other
		end

	frozen deep_clone (other: detachable ANY): like other
		obsolete "Use `deep_twin' instead. [2017-05-31]"
			-- Void if other is void: otherwise, new object structure
			-- recursively duplicated from the one attached to other
			-- (from ANY)
		do
			if other /= Void then
				Result := other.deep_twin
			end
		ensure -- from ANY
			instance_free: class
			deep_equal: deep_equal (other, Result)
		end

	frozen deep_copy (other: AUDIO_LIBRARY_CONTROLLER)
			-- Effect equivalent to that of:
			--		copy (other . deep_twin)
			-- (from ANY)
		require -- from ANY
			other_not_void: other /= Void
		do
			copy (other.deep_twin)
		ensure -- from ANY
			deep_equal: deep_equal (Current, other)
		end

	frozen deep_twin: AUDIO_LIBRARY_CONTROLLER
			-- New object structure recursively duplicated from Current.
			-- (from ANY)
		external
			"built_in"
		ensure -- from ANY
			deep_twin_not_void: Result /= Void
			deep_equal: deep_equal (Current, Result)
		end

	frozen standard_clone (other: detachable ANY): like other
		obsolete "Use `standard_twin' instead. [2017-05-31]"
			-- Void if other is void; otherwise new object
			-- field-by-field identical to other.
			-- Always uses default copying semantics.
			-- (from ANY)
		do
			if other /= Void then
				Result := other.standard_twin
			end
		ensure -- from ANY
			instance_free: class
			equal: standard_equal (Result, other)
		end

	frozen standard_copy (other: AUDIO_LIBRARY_CONTROLLER)
			-- Copy every field of other onto corresponding field
			-- of current object.
			-- (from ANY)
		require -- from ANY
			other_not_void: other /= Void
			type_identity: same_type (other)
		external
			"built_in"
		ensure -- from ANY
			is_standard_equal: standard_is_equal (other)
		end

	frozen standard_twin: AUDIO_LIBRARY_CONTROLLER
			-- New object field-by-field identical to other.
			-- Always uses default copying semantics.
			-- (from ANY)
		external
			"built_in"
		ensure -- from ANY
			standard_twin_not_void: Result /= Void
			equal: standard_equal (Result, Current)
		end

	frozen twin: AUDIO_LIBRARY_CONTROLLER
			-- New object equal to Current
			-- twin calls copy; to change copying/twinning semantics, redefine copy.
			-- (from ANY)
		external
			"built_in"
		ensure -- from ANY
			twin_not_void: Result /= Void
			is_equal: Result ~ Current
		end
	
feature -- Basic operations

	frozen as_attached: attached AUDIO_LIBRARY_CONTROLLER
		obsolete "Remove calls to this feature. [2017-05-31]"
			-- Attached version of Current.
			-- (Can be used during transitional period to convert
			-- non-void-safe classes to void-safe ones.)
			-- (from ANY)
		do
			Result := Current
		end

	frozen default: detachable AUDIO_LIBRARY_CONTROLLER
			-- Default value of object's type
			-- (from ANY)
		do
		end

	frozen default_pointer: POINTER
			-- Default value of type POINTER
			-- (Avoid the need to write p.default for
			-- some p of type POINTER.)
			-- (from ANY)
		do
		ensure -- from ANY
			instance_free: class
		end

	default_rescue
			-- Process exception for routines with no Rescue clause.
			-- (Default: do nothing.)
			-- (from ANY)
		do
		end

	frozen do_nothing
			-- Execute a null action.
			-- (from ANY)
		do
		ensure -- from ANY
			instance_free: class
		end

	exit
			-- Exit calling thread. Must be called from the thread itself.
			-- (from THREAD)
		require -- from THREAD
			is_exit_supported: is_exit_supported
			self: current_thread_id = thread_id
		do
			c_exit
		end

	frozen launch_thread
			-- Initialize a new thread running execute.
			-- Set is_last_launch_successful to True if successful, False otherwise.			
			-- (from THREAD)
		require -- from THREAD
			thread_capable: {PLATFORM}.is_thread_capable
			is_launchable: is_launchable
		do
			launch_with_attributes (create {THREAD_ATTRIBUTES}.make)
		end

	frozen launch_with_attributes (attr: THREAD_ATTRIBUTES)
			-- Initialize a new thread running execute, using attributes.
			-- Set is_last_launch_successful to True if successful, False otherwise.
			-- (from THREAD)
		require -- from THREAD
			thread_capable: {PLATFORM}.is_thread_capable
			is_launchable: is_launchable
		do
			launch_mutex.lock
			if not is_launchable then
				Is_last_launch_successful_cell.put (False)
			else
				create_thread_with_attr (Current, $thr_main, $thr_set_terminated, attr.item)
				thread_id := last_created_thread;
				Is_last_launch_successful_cell.put (True)
			end;
			launch_mutex.unlock
		rescue
			Is_last_launch_successful_cell.put (False);
			launch_mutex.unlock
		end

	sleep (nanoseconds: INTEGER_64)
			-- Suspend thread execution for interval specified in
			-- nanoseconds (1 nanosecond = 10^(-9) second).
			-- (from THREAD)
		require -- from THREAD
			self: current_thread_id = thread_id
			non_negative_nanoseconds: nanoseconds >= 0
		do
			(create {EXECUTION_ENVIRONMENT}).sleep (nanoseconds)
		end
	
feature {NONE} -- Basic operations

	c_exit
			-- Implementation of exit.
			-- (from THREAD)
		require -- from THREAD
			is_exit_supported: is_exit_supported
			self: 
		external
			"C use %"eif_threads.h%""
		alias
			"eif_thr_exit"
		end
	
feature {NONE} -- Implementation

	Is_last_launch_successful_cell: CELL [BOOLEAN]
			-- Internal storage for is_last_launch_successful.
			-- It is a once per thread and not an attribute because if you have multiple threads
			-- calling launch on the same object, one will set it to True, and the other will
			-- override the value with False.
			-- (from THREAD)
		once
			create Result.put (False)
		end

	launch_mutex: MUTEX
			-- Mutex used to ensure that no two threads call launch or launch_with_attributes
			-- on the same object. This ensures the validity of querying thread_id from
			-- the launch routines.
			-- (from THREAD)

	manual_error: detachable READABLE_STRING_GENERAL
			-- The specific message for the last error
			-- (from GAME_ERROR_MANAGER)

	Print_on_error_internal: CELL [BOOLEAN]
			-- True when an error occured,
			-- The library will print it right away.
			-- (from GAME_ERROR_MANAGER)
		once ("PROCESS")
			create Result.put (True)
		end

	frozen thr_get_terminated: BOOLEAN
			-- Get value of terminated.
			-- (from THREAD)
		do
			launch_mutex.lock
			Result := terminated;
			launch_mutex.unlock
		end

	frozen thr_main (a_logical_id: INTEGER_32)
			-- Call thread routine.
			-- (from THREAD)
		do
			launch_mutex.lock;
			launch_mutex.unlock
			execute;
			launch_mutex.lock
			terminated := True
			thread_id := default_pointer;
			launch_mutex.unlock
		rescue
			launch_mutex.lock
			terminated := True
			thread_id := default_pointer;
			launch_mutex.unlock
		end

	frozen thr_set_terminated (b: BOOLEAN)
			-- Set terminated to b.
			-- (from THREAD)
		do
			launch_mutex.lock
			terminated := b;
			launch_mutex.unlock
		end
	
feature -- Implementation

	disable_print_on_error
			-- Desactive the print_on_error functionnality.
			-- (from GAME_ERROR_MANAGER)
		do
			Print_on_error_internal.put (False)
		end

	enable_print_on_error
			-- Active the print_on_error functionnality.
			-- (from GAME_ERROR_MANAGER)
		do
			Print_on_error_internal.put (True)
		end

	print_on_error: BOOLEAN
			-- When an error occured, the library will print
			-- informations about the error on the error console
			-- output (default is True).
			-- (from GAME_ERROR_MANAGER)
		do
			Result := Print_on_error_internal.item
		end

	set_print_on_error (a_value: BOOLEAN)
			-- Assign to print_on_error the value of a_value
			-- (from GAME_ERROR_MANAGER)
		do
			if a_value then
				enable_print_on_error
			else
				disable_print_on_error
			end
		ensure -- from GAME_ERROR_MANAGER
			is_assign: print_on_error ~ a_value
		end
	
feature {NONE} 

	clear_alc_error (a_device: POINTER)
			-- (from AUDIO_OPENAL_ERROR_MANAGER)
		do
			clear_error
			last_alc_error_code := {AUDIO_EXTERNAL}.alc_get_error (a_device)
		end

	clear_error
			-- Remove error pending in Current
			-- (from AUDIO_OPENAL_ERROR_MANAGER)
		do
			last_alc_error_code := {AUDIO_EXTERNAL}.alc_get_error (create {POINTER})
			last_al_error_code := {AUDIO_EXTERNAL}.al_get_error
			Precursor {GAME_ERROR_MANAGER}
		ensure -- from GAME_ERROR_MANAGER
			no_error: not has_error
		end

	is_error_managable: BOOLEAN
			-- Can the present error can be manage
			-- (from AUDIO_OPENAL_ERROR_MANAGER)
		do
			Result := last_al_error_code = {AUDIO_EXTERNAL}.al_out_of_memory or last_al_error_code = {AUDIO_EXTERNAL}.al_no_error
		end

	is_manual_error: BOOLEAN
			-- Is the present error a manual error
			-- (from AUDIO_OPENAL_ERROR_MANAGER)

	last_al_error_code: INTEGER_32
			-- The last error index return by the OpenAL library.
			-- (from AUDIO_OPENAL_ERROR_MANAGER)

	last_alc_error_code: INTEGER_32
			-- The last error index return by the OpenAL context library.
			-- (from AUDIO_OPENAL_ERROR_MANAGER)

	put_manual_error (a_general_message, a_specific_error: READABLE_STRING_GENERAL)
			-- Create a manual error using a_general_error for the debug information
			-- and a_specific_error for the lasting information
			-- (from AUDIO_OPENAL_ERROR_MANAGER)
		do
			last_al_error_code := {AUDIO_EXTERNAL}.al_no_error
			is_manual_error := True
			Precursor {GAME_ERROR_MANAGER} (a_general_message, a_specific_error)
		ensure -- from GAME_ERROR_MANAGER
				has_error
		end

	read_al_error (a_message: READABLE_STRING_GENERAL)
			-- Read the next OpenAL error
			-- (from AUDIO_OPENAL_ERROR_MANAGER)
		do
			last_alc_error_code := {AUDIO_EXTERNAL}.alc_no_error
			last_al_error_code := {AUDIO_EXTERNAL}.al_get_error
			has_error := last_al_error_code /= {AUDIO_EXTERNAL}.al_no_error
			if has_error and Print_on_error_internal.item then
				Io.Error.put_string (a_message.to_string_8 + "%N");
				Io.Error.put_string (last_error.to_string_8 + "%N")
			end
		end

	read_alc_error (a_device: POINTER; a_message: READABLE_STRING_GENERAL)
			-- Read the next OpenAL error
			-- (from AUDIO_OPENAL_ERROR_MANAGER)
		do
			last_al_error_code := {AUDIO_EXTERNAL}.al_no_error
			last_alc_error_code := {AUDIO_EXTERNAL}.alc_get_error (a_device)
			has_error := last_alc_error_code /= {AUDIO_EXTERNAL}.alc_no_error
			if has_error and Print_on_error_internal.item then
				Io.Error.put_string (a_message.to_string_8 + "%N");
				Io.Error.put_string (last_error.to_string_8 + "%N")
			end
		end

	sources_extend (a_source: AUDIO_SOURCE)
			-- Adds a_source in the sources chain
		require
			sources_push_sound_open: is_playback_enable
		do
			if is_thread_executing then
				launch_mutex.lock
			end;
			internal_sources.extend (a_source)
			if is_thread_executing then
				last_source_added.set_thread_safe;
				launch_mutex.unlock
			end
		ensure
				internal_sources.count = old internal_sources.count + 1
		end
	
feature {NONE} -- Externals

	create_thread_with_attr (current_obj: THREAD; init_func, set_terminated_func, attr: POINTER)
			-- Initialize and start thread, after setting its priority
			-- and stack size.
			-- (from THREAD)
		external
			"C signature (EIF_OBJECT, EIF_PROCEDURE, EIF_PROCEDURE, EIF_POINTER) use %"eif_threads.h%""
		alias
			"eif_thr_create_with_attr"
		end

	last_created_thread: POINTER
			-- Returns a pointer to the thread-id of the last created thread.
			-- (from THREAD)
		external
			"C use %"eif_threads.h%""
		alias
			"eif_thr_last_thread"
		end

	thread_wait (current_obj: THREAD; get_terminated_func: POINTER)
			-- The calling C thread waits for the current Eiffel thread to
			-- terminate.
			-- (from THREAD)
		external
			"C signature (EIF_OBJECT, EIF_BOOLEAN_FUNCTION) use %"eif_threads.h%""
		alias
			"eif_thr_wait"
		end

	thread_wait_with_timeout (current_obj: THREAD; get_terminated_func: POINTER; a_timeout_ms: NATURAL_64): BOOLEAN
			-- The calling C thread waits for the current Eiffel thread to
			-- terminate.
			-- (from THREAD)
		external
			"C signature (EIF_OBJECT, EIF_BOOLEAN_FUNCTION, EIF_NATURAL_64): EIF_BOOLEAN use %"eif_threads.h%""
		alias
			"eif_thr_wait_with_timeout"
		end
	
feature {NONE} -- Implementation Class Variable

	context: POINTER
			-- Internal C pointer to the audio context

	internal_capture_controller: detachable AUDIO_CAPTURE_CONTROLLER
			-- The internal representation of capture_controller

	internal_capture_device: POINTER
			-- Internal C Pointer to the audio device

	internal_listener: AUDIO_LISTENER
			-- The audio listener to be returned by listener

	internal_playback_device: POINTER
			-- Internal C Pointer to the audio device

	internal_sources: LIST [AUDIO_SOURCE]
			-- Every audio sources initialized by the library

	is_thread_init: BOOLEAN
			-- Is thread initialization already done.

	must_stop_thread: BOOLEAN
			-- True when the principal thread asked the update thread to stop.

	null: POINTER
	
feature {NONE} -- Implementation Routine

	devices_list (a_specifier_type: INTEGER_32; a_is_capture: BOOLEAN): LIST [AUDIO_DEVICE]
			-- Lists all possible devices that Current may use (fetch with the internal type a_specifier_type).
			-- If a_is_capture, then the devices are capturing device. Else, they are playback device.
		local
			l_result: POINTER
			l_c_string: C_STRING
			l_item: AUDIO_DEVICE
		do
			create {LINKED_LIST [AUDIO_DEVICE]} Result.make;
			Result.compare_objects
			l_result := {AUDIO_EXTERNAL}.alc_get_string (null, a_specifier_type)
			if not l_result.is_default_pointer then
				from
					create l_item.make (l_result, a_is_capture)
				until
					l_item.name.is_empty
				loop
					Result.extend (l_item)
					l_result := l_result.plus (l_item.name.count + 1)
					create l_item.make (l_result, a_is_capture)
				end
			end
		end

	enable_capture_inmplementaton (a_pointer: POINTER; a_frequency: INTEGER_32; a_channel_count, a_bits_per_sample, a_buffer_count: INTEGER_32)
			-- Activates the capture sound context using a_pointer as internal_capture_device.
			-- The resulting capture_controller will have use a_channel_count number of channel, a_bits_per_sample number of bits per
			-- single channel sample (8 or 16) and the internal buffer will be able to contain a_buffer_count samples (for example,
			-- a stereo 16 bits capture with a buffer count of 1024 will have the size 1024*2*2 = 5096 bytes)
		require
			is_not_already_enabled: not is_capture_enable
			channel_valid: a_channel_count >= 1 and a_channel_count <= 2
			bits_per_sample_valid: a_bits_per_sample ~ 8 or a_bits_per_sample ~ 16
			frequency_valid: a_frequency > 0
		local
			l_ok: BOOLEAN
			l_format: INTEGER_32
			l_buffer_size: INTEGER_32
		do
			if a_channel_count = 1 then
				if a_bits_per_sample = 8 then
					l_format := {AUDIO_EXTERNAL}.al_format_mono8
				else
					l_format := {AUDIO_EXTERNAL}.al_format_mono16
				end
			else
				if a_bits_per_sample = 8 then
					l_format := {AUDIO_EXTERNAL}.al_format_stereo8
				else
					l_format := {AUDIO_EXTERNAL}.al_format_stereo16
				end
			end
			l_buffer_size := a_buffer_count * a_channel_count * (a_bits_per_sample // 8)
			clear_error
			internal_capture_device := {AUDIO_EXTERNAL}.alc_capture_open_device (a_pointer, a_frequency.to_natural_32, l_format, l_buffer_size)
			read_alc_error (null, "Cannot open capture device.")
			if not internal_capture_device.is_default_pointer then
				create internal_capture_controller.make (internal_capture_device, a_frequency, a_channel_count, a_bits_per_sample, a_buffer_count)
			end
		ensure
			capture_enabled: not has_error implies is_capture_enable
		end

	enable_playback_implementaton (a_pointer: POINTER)
			-- Activates the playback sound context using a_pointer as internal_playback_device.
		require
			is_not_already_enabled: not is_playback_enable
		local
			l_ok: BOOLEAN
		do
			clear_error
			internal_playback_device := {AUDIO_EXTERNAL}.alc_open_device (a_pointer)
			read_alc_error (null, "Cannot open audio device.")
			if not internal_playback_device.is_default_pointer then
				clear_alc_error (internal_playback_device)
				context := {AUDIO_EXTERNAL}.alc_create_context (internal_playback_device, null)
				read_alc_error (internal_playback_device, "Cannot open audio context.")
				if not context.is_default_pointer then
					clear_alc_error (internal_playback_device)
					l_ok := {AUDIO_EXTERNAL}.alc_make_context_current (context)
					if l_ok then
						internal_listener.initialize
					else
						read_alc_error (null, "Cannot make audio context current.")
						{AUDIO_EXTERNAL}.alc_destroy_context (context)
						l_ok := {AUDIO_EXTERNAL}.alc_close_device (internal_playback_device)
					end
				else
					l_ok := {AUDIO_EXTERNAL}.alc_close_device (internal_playback_device)
				end
			end
		end

	is_extension_present (a_device: POINTER; a_extension_text: STRING_8): BOOLEAN
			-- Check if OpenAL support the extension identified by a_extension_text
			-- is supported by a_device
		local
			l_c_string: C_STRING
		do
			create l_c_string.make (a_extension_text)
			Result := {AUDIO_EXTERNAL}.alc_is_extension_present (a_device, l_c_string.item)
		end
	
feature -- Implementation Routine

	execute
			-- The thread main loop (started with launch_in_thread)
		local
			env: EXECUTION_ENVIRONMENT
		do
			create env
			from
				must_stop_thread := False
			until
				must_stop_thread
			loop
				launch_mutex.lock
				update;
				launch_mutex.unlock;
				env.sleep (10000000)
			end
		end
	
feature -- Output

	Io: STD_FILES
			-- Handle to standard file setup
			-- (from ANY)
		once
			create Result;
			Result.set_output_default
		ensure -- from ANY
			instance_free: class
			io_not_void: Result /= Void
		end

	out: STRING_8
			-- New string containing terse printable representation
			-- of current object
			-- (from ANY)
		do
			Result := tagged_out
		ensure -- from ANY
			out_not_void: Result /= Void
		end

	print (o: detachable ANY)
			-- Write terse external representation of o
			-- on standard output.
			-- (from ANY)
		local
			s: READABLE_STRING_8
		do
			if attached o then
				s := o.out
				if attached {READABLE_STRING_32} s as s32 then
					Io.put_string_32 (s32)
				elseif attached {READABLE_STRING_8} s as s8 then
					Io.put_string (s8)
				else
					Io.put_string_32 (s.as_string_32)
				end
			end
		ensure -- from ANY
			instance_free: class
		end

	frozen tagged_out: STRING_8
			-- New string containing terse printable representation
			-- of current object
			-- (from ANY)
		external
			"built_in"
		ensure -- from ANY
			tagged_out_not_void: Result /= Void
		end
	
feature -- Platform

	Operating_environment: OPERATING_ENVIRONMENT
			-- Objects available from the operating system
			-- (from ANY)
		once
			create Result
		ensure -- from ANY
			instance_free: class
			operating_environment_not_void: Result /= Void
		end
	
feature {NONE} -- Retrieval

	frozen internal_correct_mismatch
			-- Called from runtime to perform a proper dynamic dispatch on correct_mismatch
			-- from MISMATCH_CORRECTOR.
			-- (from ANY)
		local
			l_msg: STRING_32
			l_exc: EXCEPTIONS
		do
			if attached {MISMATCH_CORRECTOR} Current as l_corrector then
				l_corrector.correct_mismatch
			else
				create l_msg.make_from_string ("Mismatch: ".as_string_32)
				create l_exc;
				l_msg.append (generating_type.name_32);
				l_exc.raise_retrieval_exception (l_msg)
			end
		end
	
feature -- Sources management

	is_thread_executing: BOOLEAN
			-- The update thread is running

	last_source_added: AUDIO_SOURCE
			-- Returns the last sound source that has been created.
		require
			sources_get_last_add_sound_open: is_playback_enable
		do
			Result := sources_at (sources_count)
		end

	launch_in_thread
			-- Makes Current automatically update using another thread.
			-- You have to manually call stop_thread before closing the application
		require
			launch_in_thread_sound_open: is_playback_enable
			not_thread_running: not is_thread_executing
		do
			if not is_thread_init then
				internal_sources.do_all (agent {AUDIO_SOURCE}.set_thread_safe)
				make_thread
				is_thread_init := True
			end
			is_thread_executing := True
			launch_thread
		ensure
			is_thread_running: is_thread_executing
		end

	set_sound_buffer_size (a_buffer_size: INTEGER_32)
			-- Set the buffer size for the sound streaming (default is 65536). Allocating too little memory to the buffer can cause sound to stop before finishing.
		do
			sound_buffer_size := a_buffer_size
		end

	sound_buffer_size: INTEGER_32 assign set_sound_buffer_size
			-- The buffer size for the sound streaming (default is 65536). Allocating too little memory to the buffer can cause sound to stop before finishing.

	sources: CHAIN_INDEXABLE_ITERATOR [AUDIO_SOURCE]
			-- All AUDIO_SOURCE of the system.
		require
			sources_sound_open: is_playback_enable
		do
			create Result.make (internal_sources)
		end

	sources_add
			-- Creates a new sound source. To receive the sound source, use the source_get_last_add method.
		require
			sources_add_sound_open: is_playback_enable
		do
			if is_thread_executing then
				launch_mutex.lock
			end;
			internal_sources.extend (create {AUDIO_SOURCE}.make (sound_buffer_size))
			if is_thread_executing then
				last_source_added.set_thread_safe;
				launch_mutex.unlock
			end
		ensure
				internal_sources.count = old internal_sources.count + 1
		end

	sources_at (a_index: INTEGER_32): AUDIO_SOURCE
			-- Returns the a_index-th sound source.
		require
			sources_get_at_sound_open: is_playback_enable
			al_controler_source_get_index_valid: a_index > 0 and then a_index < sources_count + 1
		do
			Result := internal_sources.at (a_index)
		end

	sources_count: INTEGER_32
			-- The current number of sound sources in the sound context.
		require
			sources_count_sound_open: is_playback_enable
		do
			Result := internal_sources.count
		end

	sources_has (a_source: AUDIO_SOURCE): BOOLEAN
			-- Returns true if the sound source a_source is still in the sound controller.
		require
			sources_has_sound_open: is_playback_enable
		do
			Result := internal_sources.has (a_source)
		end

	sources_prune (a_source: AUDIO_SOURCE)
			-- Removes the sound source a_source from the sound controller. A sound that has been removed from the sound
			-- Controller can continue to work on its own, but it will not be updated by the update_sound_playing routine.
		require
			sources_remove_sound_open: is_playback_enable
			al_controler_source_remove_source_valid: a_source /= Void and then sources_has (a_source)
		do
			a_source.close;
			internal_sources.prune_all (a_source)
		ensure
			al_controler_source_remove_source_removed: not internal_sources.has (a_source)
		end

	sources_remove (a_index: INTEGER_32)
			-- Removes the a_index-th sound source.
		require
			sources_remove_at_sound_open: is_playback_enable
			al_controler_source_remove_index_valid: a_index > 0 and then a_index < sources_count + 1
		do
			internal_sources.go_i_th (a_index);
			internal_sources.item.close;
			internal_sources.remove
		end

	sources_wipe_out
			-- This method removes all sound sources in the sound context.
		require
			update_sound_playing_sound_open: is_playback_enable
		do
			internal_sources.do_all (agent {AUDIO_SOURCE}.close);
			internal_sources.wipe_out
		end

	stop_thread
			-- Stops the thread previously called with launch_in_thread
		require
			is_thread_running: is_thread_executing
		do
			must_stop_thread := True
			join
			is_thread_executing := False
		ensure
			is_thread_not_running: not is_thread_executing
		end

	update
			-- This method must be executed at regular interval. If it is not executed enough in a certain time lap, the sound will stop before finishing.
			-- If this happens, you can call this method more often or use bigger sound_buffer_size. You can use the method update_playing for each individual
			-- Sound sources in the project and it will do the same effect.
		require
			update_sound_playing_sound_open: is_playback_enable
		do
			internal_sources.do_all (agent {AUDIO_SOURCE}.update_playing)
		end
	
feature -- Synchronization

	join
			-- The calling thread waits for the current child thread to terminate.
			-- (from THREAD)
		do
			if not terminated then
				thread_wait (Current, $thr_get_terminated)
			end
		end

	join_all
			-- The calling thread waits for all other threads to terminate.
			-- (from THREAD_CONTROL)
		external
			"C blocking use %"eif_threads.h%""
		alias
			"eif_thr_join_all"
		end

	join_with_timeout (a_timeout_ms: NATURAL_64): BOOLEAN
			-- The calling thread waits for the current child thread to
			-- terminate for at most a_timeout_ms milliseconds.
			-- True if wait terminates within a_timeout_ms, False otherwise.
			-- (from THREAD)
		do
			if terminated then
				Result := True
			else
				Result := thread_wait_with_timeout (Current, $thr_get_terminated, a_timeout_ms)
			end
		end

	yield
			-- The calling thread yields its execution in favor of another
			-- thread for an OS specific amount of time.
			-- (from THREAD_CONTROL)
		external
			"C use %"eif_threads.h%""
		alias
			"eif_thr_yield"
		end
	
invariant
	is_sound_open_context_valid: is_playback_enable implies (not {AUDIO_EXTERNAL}.alc_get_current_context.is_default_pointer)
	is_sound_open_sources_valid: (not is_playback_enable) implies (internal_sources.count = 0)
	capture_valid: (is_capture_enable implies attached internal_capture_controller) and (attached internal_capture_controller implies is_capture_enable)

		-- from ANY
	reflexive_equality: standard_is_equal (Current)
	reflexive_conformance: conforms_to (Current)

end -- class AUDIO_LIBRARY_CONTROLLER

Generated by ISE EiffelStudio