view src/java/org/classpath/icedtea/pulseaudio/PulseAudioDataLine.java @ 136:2d384ad19c3e

Ioana Ivan <iivan@redhat.com> * src/java/org/classpath/icedtea/pulseaudio/PulseAudioDataLine.java: -split open() into createStream(), addStreamListeners() and connect(), which can be reused when reconnecting the line for synchronization -added recconectForSynchronization() -made some changes to stop()/start() in order to send START/STOP events both when corking and in case of underflow * src/java/org/classpath/icedtea/pulseaudio/PulseAudioMixer.java: -changes to synchronize() * src/java/org/classpath/icedtea/pulseaudio/PulseAudioSourceDataLine.java: -changed connectLine to take the masterStream as a parameter in case we want to synchronize the Line * src/java/org/classpath/icedtea/pulseaudio/PulseAudioClip.java: -changed connectLine to take the masterStream as a parameter in case we want to synchronize the Line
author Ioana Ivan <iivan@redhat.com>
date Tue, 23 Sep 2008 17:01:26 -0400
parents c46f6e0e7959
children 9c11cbf114f3
line wrap: on
line source

/* PulseAudioClip.java
   Copyright (C) 2008 Red Hat, Inc.

This file is part of IcedTea.

IcedTea is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 2.

IcedTea is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with IcedTea; see the file COPYING.  If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version.
 */

package org.classpath.icedtea.pulseaudio;

import java.util.ArrayList;
import java.util.concurrent.Semaphore;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineUnavailableException;

import org.classpath.icedtea.pulseaudio.Stream.WriteListener;

public abstract class PulseAudioDataLine extends PulseAudioLine implements
		DataLine {

	protected static final int DEFAULT_BUFFER_SIZE = StreamBufferAttributes.SANE_DEFAULT;
	protected static final String PULSEAUDIO_FORMAT_KEY = "PulseAudioFormatKey";

	protected String streamName = "Java Stream";

	// true between start() and stop()
	protected boolean isStarted = false;

	protected boolean dataWritten = false;
	protected boolean corked = true;

	// true if a stream has been paused
	// protected boolean isPaused = false;

	protected AudioFormat[] supportedFormats = null;
	protected AudioFormat currentFormat = null;
	protected AudioFormat defaultFormat = null;
	protected boolean sendEvents = true;

	protected int bufferSize = 0;

	protected EventLoop eventLoop = null;
	protected Semaphore semaphore = new Semaphore(0);
	protected Stream stream;
	private ArrayList<PulseAudioDataLine> synchronizedLines;

	public void open(AudioFormat format, int bufferSize)
			throws LineUnavailableException {

		if (isOpen) {
			throw new IllegalStateException("DataLine is already open");
		}

		createStream(format);

		addStreamListeners();
		connect(null, bufferSize);

	}

	public void createStream(AudioFormat format)
			throws LineUnavailableException {

		for (AudioFormat myFormat : supportedFormats) {
			if (format.matches(myFormat)) {
				synchronized (eventLoop.threadLock) {
					stream = new Stream(eventLoop.getContextPointer(),
							streamName, Stream.Format.valueOf((String) myFormat
									.getProperty(PULSEAUDIO_FORMAT_KEY)),
							(int) format.getSampleRate(), format.getChannels());

				}
				currentFormat = format;
				super.open();
			}
		}

		if (!isOpen) {
			throw new IllegalArgumentException("Invalid format");
		}

		System.out.println("Stream " + stream + " created");

	}

	public void addStreamListeners() {
		Stream.StateListener openCloseListener = new Stream.StateListener() {

			@Override
			public void update() {
				synchronized (eventLoop.threadLock) {

					/*
					 * Not the order: first we notify all the listeners, and
					 * then return. this means no race conditions when the
					 * listeners are removed before they get called by close
					 * 
					 * eg:
					 * 
					 * line.close(); line.removeLineListener(listener)
					 * 
					 * the listener is guaranteed to have run
					 * 
					 */

					if (stream.getState() == Stream.State.READY) {
						if (sendEvents) {
							fireLineEvent(new LineEvent(
									PulseAudioDataLine.this,
									LineEvent.Type.OPEN,
									AudioSystem.NOT_SPECIFIED));
						}
						semaphore.release();

					} else if (stream.getState() == Stream.State.TERMINATED
							|| stream.getState() == Stream.State.FAILED) {
						if (sendEvents) {
							fireLineEvent((new LineEvent(
									PulseAudioDataLine.this,
									LineEvent.Type.CLOSE,
									AudioSystem.NOT_SPECIFIED)));
						}
						semaphore.release();

					}
				}
			}
		};

		stream.addStateListener(openCloseListener);

		Stream.UnderflowListener stoppedListener = new Stream.UnderflowListener() {
			@Override
			public void update() {
				dataWritten = false;
				
				if (!corked) {
					fireLineEvent(new LineEvent(PulseAudioDataLine.this,
							LineEvent.Type.STOP, AudioSystem.NOT_SPECIFIED));
				}

			}
		};
		stream.addUnderflowListener(stoppedListener);

		Stream.PlaybackStartedListener startedListener = new Stream.PlaybackStartedListener() {
			@Override
			public void update() {

				dataWritten = true;
				if (!corked) {
					fireLineEvent(new LineEvent(PulseAudioDataLine.this,
							LineEvent.Type.START, AudioSystem.NOT_SPECIFIED));
				}

			}
		};

		stream.addPlaybackStartedListener(startedListener);

		WriteListener writeNotifier = new WriteListener() {

			@Override
			public void update() {
				// System.out.println("can write");
				eventLoop.threadLock.notifyAll();
			}

		};
		stream.addWriteListener(writeNotifier);

		Stream.CorkListener corkListener = new Stream.CorkListener() {

			@Override
			public void update() {

				eventLoop.threadLock.notifyAll();
			}

		};
		stream.addCorkListener(corkListener);
	}

	public void connect(Stream masterStream, int bufferSize)
			throws LineUnavailableException {

		try {
			synchronized (eventLoop.threadLock) {
				connectLine(bufferSize, masterStream);
			}
		} catch (LineUnavailableException e) {
			// error connecting to the server!
			//stream.removePlaybackStartedListener(startedListener);
			//stream.removeUnderflowListener(stoppedListener);
			//stream.removeStateListener(openCloseListener);
			stream.free();
			stream = null;
			throw e;

		}
		this.bufferSize = bufferSize;
		try {
			semaphore.acquire();
			synchronized (eventLoop.threadLock) {
				if (stream.getState() != Stream.State.READY) {
					System.out.println(stream.getState());
					stream.disconnect();
					stream.free();
					throw new LineUnavailableException(
							"unable to obtain a line");
				}
			}
		} catch (InterruptedException e) {
			throw new LineUnavailableException("unable to prepare stream");
		}
	}

	public void open(AudioFormat format) throws LineUnavailableException {
		open(format, DEFAULT_BUFFER_SIZE);

	}

	public void open() throws LineUnavailableException {
		assert (defaultFormat != null);

		open(defaultFormat, DEFAULT_BUFFER_SIZE);
	}

	public void close() {
		if (!isOpen) {
			throw new IllegalStateException(
					"Line must be open for close() to work");
		}

		drain();

		synchronized (eventLoop.threadLock) {
			stream.disconnect();
		}

		try {
			semaphore.acquire();
		} catch (InterruptedException e) {
			throw new RuntimeException("unable to prepare stream");
		}

		synchronized (eventLoop.threadLock) {
			stream.free();
		}

		super.close();

	}

	public void reconnectforSynchronization(Stream masterStream) {
		sendEvents = false;
		drain();

		synchronized (eventLoop.threadLock) {
			stream.disconnect();
		}
		try {
			semaphore.acquire();
		} catch (InterruptedException e) {
			throw new RuntimeException("unable to prepare stream");
		}
		try {
			createStream(getFormat());
		} catch (LineUnavailableException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		addStreamListeners();
		try {
			connect(masterStream, getBufferSize());
		} catch (LineUnavailableException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		sendEvents = true;
	}

	public void start() {
		if (!isOpen) {
			throw new IllegalStateException(
					"Line must be open()ed before it can be start()ed");
		}

		if (!corked) {
			System.out.println("Already started, returning");
			return;
		}

		corked = false;
		Operation op;
		synchronized (eventLoop.threadLock) {
			op = stream.unCork();
		}

		op.waitForCompletion();
		op.releaseReference();
		isStarted = true;
		
		/*if (dataWritten) {
			fireLineEvent(new LineEvent(PulseAudioDataLine.this,
					LineEvent.Type.START, AudioSystem.NOT_SPECIFIED));
		}*/

	}

	public synchronized void stop() {
		if (!isOpen) {
			throw new IllegalStateException(
					"Line must be open()ed before it can be start()ed");

		}
		if (corked) {
			return;
		}
		corked = true;
		Operation op;
		synchronized (eventLoop.threadLock) {
			op = stream.cork();
		}

		op.waitForCompletion();
		op.releaseReference();

		isStarted = false;
		if (dataWritten) {
			fireLineEvent(new LineEvent(PulseAudioDataLine.this,
					LineEvent.Type.STOP, AudioSystem.NOT_SPECIFIED));
		}

		isStarted = false;

	}

	/*
	 * TODO
	 * 
	 * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4791152 :
	 * 
	 * a line is active in between calls to start() and stop(). In that sense,
	 * active means that the line is ready to take or give data. Running is
	 * tightly bound to data flow in the line. I.e. when you start a
	 * SourceDataLine but never write data to it, the line should not be
	 * running. This also means that a line should become not running on buffer
	 * underrun/overflow.
	 * 
	 * 
	 * HOWEVER, the javadocs say the opposite thing!
	 * 
	 */

	public boolean isActive() {
		return isStarted;
	}

	public boolean isRunning() {
		return !corked && dataWritten;
	}

	protected abstract void connectLine(int bufferSize, Stream masterStream)
			throws LineUnavailableException;

	public abstract void drain();

	public Stream getStream() {
		if (!isOpen) {
			throw new IllegalStateException("Line must be open");
		}

		return stream;
	}

	@Override
	public int getBufferSize() {
		if (!isOpen) {
			return DEFAULT_BUFFER_SIZE;
		}
		return bufferSize;
	}

	public javax.sound.sampled.Line.Info getLineInfo() {
		return new DataLine.Info(this.getClass(), supportedFormats,
				StreamBufferAttributes.MIN_VALUE,
				StreamBufferAttributes.MAX_VALUE);
	}

	@Override
	public AudioFormat getFormat() {
		if (!isOpen) {
			return defaultFormat;
		}
		return currentFormat;
	}

	public float getLevel() {
		return AudioSystem.NOT_SPECIFIED;
	}

	public void setName(String streamName) {
		if (isOpen) {
			/*
			 * Note: setting the name of the stream after it's created wont
			 * work. In fact, it sets the name of the application! This is a bug
			 * in PulseAudio 0.9.12 but fixed in git.
			 */

			Operation o;
			synchronized (eventLoop.threadLock) {
				o = stream.setName(streamName);
			}
			o.waitForCompletion();
			o.releaseReference();

		}

		this.streamName = streamName;

	}

	public String getName() {
		return streamName;
	}

}