% linein - Live input signal
%
% linein ::
%    C:natural ~'desired no. of channels',
%    R:nonneg  ~'desired sample rate',
%    options {
%       bufsize :: natural/0 ~'desired buffer size, 0 is auto'
%    }
% -> signal(C,R).
classdef linein < sigbase
	properties (GetAccess=private, SetAccess=immutable)
		opts
	end
	methods
		function s=linein(channels,rate,varargin)
			s=s@sigbase(channels,rate);
			s.opts = options('bufsize',0,'bits',16,'quiet',0,varargin{:});
		end
		function c=tostring(sig), c='linein'; end

		function s=construct(sig)
			import javax.sound.sampled.*;
			import ishara.audio.*;

			src=LineSource(audio_format(sig.channels,sig.rate,sig.opts.bits),sig.opts.bufsize);
			ref=disposables('reg',src);
			if ~sig.opts.quiet
				fprintf('\nOpened audio input device:\n  %s\n',char(src.toString));
				fprintf('  Actual buffer size is %d.\n',src.getLine.getBufferSize);
			end

			s.stop    = @stop;
			s.start   = @start;
			s.dispose = @dispose;
			s.reader = @reader;

			s.getLine = @()src.getLine();

			function start, src.start(); src.check(); end
			function stop, src.check(); src.stop(); end
			function r=reader(n)
				ch=sig.channels;
				rdr=src.reader(ch*n);
				r=@next;
				function [x,rem]=next
					x=reshape(rdr.next(),ch,n); rem=0;
				end
			end

			function dispose
				disposables('dereg',ref);
				src.dispose();
			end
		end
	end
end
