+++ /dev/null
-:mod:`ossaudiodev` --- Access to OSS-compatible audio devices
-=============================================================
-
-.. module:: ossaudiodev
- :platform: Linux, FreeBSD
- :synopsis: Access to OSS-compatible audio devices.
- :deprecated:
-
-.. deprecated-removed:: 3.11 3.13
- The :mod:`ossaudiodev` module is deprecated
- (see :pep:`PEP 594 <594#ossaudiodev>` for details).
-
---------------
-
-This module allows you to access the OSS (Open Sound System) audio interface.
-OSS is available for a wide range of open-source and commercial Unices, and is
-the standard audio interface for Linux and recent versions of FreeBSD.
-
-.. Things will get more complicated for future Linux versions, since
- ALSA is in the standard kernel as of 2.5.x. Presumably if you
- use ALSA, you'll have to make sure its OSS compatibility layer
- is active to use ossaudiodev, but you're going to need it for the vast
- majority of Linux audio apps anyway.
-
- Sounds like things are also complicated for other BSDs. In response
- to my python-dev query, Thomas Wouters said:
-
- > Likewise, googling shows OpenBSD also uses OSS/Free -- the commercial
- > OSS installation manual tells you to remove references to OSS/Free from the
- > kernel :)
-
- but Aleksander Piotrowsk actually has an OpenBSD box, and he quotes
- from its <soundcard.h>:
- > * WARNING! WARNING!
- > * This is an OSS (Linux) audio emulator.
- > * Use the Native NetBSD API for developing new code, and this
- > * only for compiling Linux programs.
-
- There's also an ossaudio manpage on OpenBSD that explains things
- further. Presumably NetBSD and OpenBSD have a different standard
- audio interface. That's the great thing about standards, there are so
- many to choose from ... ;-)
-
- This probably all warrants a footnote or two, but I don't understand
- things well enough right now to write it! --GPW
-
-.. versionchanged:: 3.3
- Operations in this module now raise :exc:`OSError` where :exc:`IOError`
- was raised.
-
-
-.. seealso::
-
- `Open Sound System Programmer's Guide <http://www.opensound.com/pguide/oss.pdf>`_
- the official documentation for the OSS C API
-
- The module defines a large number of constants supplied by the OSS device
- driver; see ``<sys/soundcard.h>`` on either Linux or FreeBSD for a listing.
-
-:mod:`ossaudiodev` defines the following variables and functions:
-
-
-.. exception:: OSSAudioError
-
- This exception is raised on certain errors. The argument is a string describing
- what went wrong.
-
- (If :mod:`ossaudiodev` receives an error from a system call such as
- :c:func:`open`, :c:func:`write`, or :c:func:`ioctl`, it raises :exc:`OSError`.
- Errors detected directly by :mod:`ossaudiodev` result in :exc:`OSSAudioError`.)
-
- (For backwards compatibility, the exception class is also available as
- ``ossaudiodev.error``.)
-
-
-.. function:: open(mode)
- open(device, mode)
-
- Open an audio device and return an OSS audio device object. This object
- supports many file-like methods, such as :meth:`read`, :meth:`write`, and
- :meth:`fileno` (although there are subtle differences between conventional Unix
- read/write semantics and those of OSS audio devices). It also supports a number
- of audio-specific methods; see below for the complete list of methods.
-
- *device* is the audio device filename to use. If it is not specified, this
- module first looks in the environment variable :envvar:`AUDIODEV` for a device
- to use. If not found, it falls back to :file:`/dev/dsp`.
-
- *mode* is one of ``'r'`` for read-only (record) access, ``'w'`` for
- write-only (playback) access and ``'rw'`` for both. Since many sound cards
- only allow one process to have the recorder or player open at a time, it is a
- good idea to open the device only for the activity needed. Further, some
- sound cards are half-duplex: they can be opened for reading or writing, but
- not both at once.
-
- Note the unusual calling syntax: the *first* argument is optional, and the
- second is required. This is a historical artifact for compatibility with the
- older :mod:`linuxaudiodev` module which :mod:`ossaudiodev` supersedes.
-
- .. XXX it might also be motivated
- by my unfounded-but-still-possibly-true belief that the default
- audio device varies unpredictably across operating systems. -GW
-
-
-.. function:: openmixer([device])
-
- Open a mixer device and return an OSS mixer device object. *device* is the
- mixer device filename to use. If it is not specified, this module first looks
- in the environment variable :envvar:`MIXERDEV` for a device to use. If not
- found, it falls back to :file:`/dev/mixer`.
-
-
-.. _ossaudio-device-objects:
-
-Audio Device Objects
---------------------
-
-Before you can write to or read from an audio device, you must call three
-methods in the correct order:
-
-#. :meth:`setfmt` to set the output format
-
-#. :meth:`channels` to set the number of channels
-
-#. :meth:`speed` to set the sample rate
-
-Alternately, you can use the :meth:`setparameters` method to set all three audio
-parameters at once. This is more convenient, but may not be as flexible in all
-cases.
-
-The audio device objects returned by :func:`.open` define the following methods
-and (read-only) attributes:
-
-
-.. method:: oss_audio_device.close()
-
- Explicitly close the audio device. When you are done writing to or reading from
- an audio device, you should explicitly close it. A closed device cannot be used
- again.
-
-
-.. method:: oss_audio_device.fileno()
-
- Return the file descriptor associated with the device.
-
-
-.. method:: oss_audio_device.read(size)
-
- Read *size* bytes from the audio input and return them as a Python string.
- Unlike most Unix device drivers, OSS audio devices in blocking mode (the
- default) will block :func:`read` until the entire requested amount of data is
- available.
-
-
-.. method:: oss_audio_device.write(data)
-
- Write a :term:`bytes-like object` *data* to the audio device and return the
- number of bytes written. If the audio device is in blocking mode (the
- default), the entire data is always written (again, this is different from
- usual Unix device semantics). If the device is in non-blocking mode, some
- data may not be written---see :meth:`writeall`.
-
- .. versionchanged:: 3.5
- Writable :term:`bytes-like object` is now accepted.
-
-
-.. method:: oss_audio_device.writeall(data)
-
- Write a :term:`bytes-like object` *data* to the audio device: waits until
- the audio device is able to accept data, writes as much data as it will
- accept, and repeats until *data* has been completely written. If the device
- is in blocking mode (the default), this has the same effect as
- :meth:`write`; :meth:`writeall` is only useful in non-blocking mode. Has
- no return value, since the amount of data written is always equal to the
- amount of data supplied.
-
- .. versionchanged:: 3.5
- Writable :term:`bytes-like object` is now accepted.
-
-
-.. versionchanged:: 3.2
- Audio device objects also support the context management protocol, i.e. they can
- be used in a :keyword:`with` statement.
-
-
-The following methods each map to exactly one :c:func:`ioctl` system call. The
-correspondence is obvious: for example, :meth:`setfmt` corresponds to the
-``SNDCTL_DSP_SETFMT`` ioctl, and :meth:`sync` to ``SNDCTL_DSP_SYNC`` (this can
-be useful when consulting the OSS documentation). If the underlying
-:c:func:`ioctl` fails, they all raise :exc:`OSError`.
-
-
-.. method:: oss_audio_device.nonblock()
-
- Put the device into non-blocking mode. Once in non-blocking mode, there is no
- way to return it to blocking mode.
-
-
-.. method:: oss_audio_device.getfmts()
-
- Return a bitmask of the audio output formats supported by the soundcard. Some
- of the formats supported by OSS are:
-
- +-------------------------+---------------------------------------------+
- | Format | Description |
- +=========================+=============================================+
- | :const:`AFMT_MU_LAW` | a logarithmic encoding (used by Sun ``.au`` |
- | | files and :file:`/dev/audio`) |
- +-------------------------+---------------------------------------------+
- | :const:`AFMT_A_LAW` | a logarithmic encoding |
- +-------------------------+---------------------------------------------+
- | :const:`AFMT_IMA_ADPCM` | a 4:1 compressed format defined by the |
- | | Interactive Multimedia Association |
- +-------------------------+---------------------------------------------+
- | :const:`AFMT_U8` | Unsigned, 8-bit audio |
- +-------------------------+---------------------------------------------+
- | :const:`AFMT_S16_LE` | Signed, 16-bit audio, little-endian byte |
- | | order (as used by Intel processors) |
- +-------------------------+---------------------------------------------+
- | :const:`AFMT_S16_BE` | Signed, 16-bit audio, big-endian byte order |
- | | (as used by 68k, PowerPC, Sparc) |
- +-------------------------+---------------------------------------------+
- | :const:`AFMT_S8` | Signed, 8 bit audio |
- +-------------------------+---------------------------------------------+
- | :const:`AFMT_U16_LE` | Unsigned, 16-bit little-endian audio |
- +-------------------------+---------------------------------------------+
- | :const:`AFMT_U16_BE` | Unsigned, 16-bit big-endian audio |
- +-------------------------+---------------------------------------------+
-
- Consult the OSS documentation for a full list of audio formats, and note that
- most devices support only a subset of these formats. Some older devices only
- support :const:`AFMT_U8`; the most common format used today is
- :const:`AFMT_S16_LE`.
-
-
-.. method:: oss_audio_device.setfmt(format)
-
- Try to set the current audio format to *format*---see :meth:`getfmts` for a
- list. Returns the audio format that the device was set to, which may not be the
- requested format. May also be used to return the current audio format---do this
- by passing an "audio format" of :const:`AFMT_QUERY`.
-
-
-.. method:: oss_audio_device.channels(nchannels)
-
- Set the number of output channels to *nchannels*. A value of 1 indicates
- monophonic sound, 2 stereophonic. Some devices may have more than 2 channels,
- and some high-end devices may not support mono. Returns the number of channels
- the device was set to.
-
-
-.. method:: oss_audio_device.speed(samplerate)
-
- Try to set the audio sampling rate to *samplerate* samples per second. Returns
- the rate actually set. Most sound devices don't support arbitrary sampling
- rates. Common rates are:
-
- +-------+-------------------------------------------+
- | Rate | Description |
- +=======+===========================================+
- | 8000 | default rate for :file:`/dev/audio` |
- +-------+-------------------------------------------+
- | 11025 | speech recording |
- +-------+-------------------------------------------+
- | 22050 | |
- +-------+-------------------------------------------+
- | 44100 | CD quality audio (at 16 bits/sample and 2 |
- | | channels) |
- +-------+-------------------------------------------+
- | 96000 | DVD quality audio (at 24 bits/sample) |
- +-------+-------------------------------------------+
-
-
-.. method:: oss_audio_device.sync()
-
- Wait until the sound device has played every byte in its buffer. (This happens
- implicitly when the device is closed.) The OSS documentation recommends closing
- and re-opening the device rather than using :meth:`sync`.
-
-
-.. method:: oss_audio_device.reset()
-
- Immediately stop playing or recording and return the device to a state where it
- can accept commands. The OSS documentation recommends closing and re-opening
- the device after calling :meth:`reset`.
-
-
-.. method:: oss_audio_device.post()
-
- Tell the driver that there is likely to be a pause in the output, making it
- possible for the device to handle the pause more intelligently. You might use
- this after playing a spot sound effect, before waiting for user input, or before
- doing disk I/O.
-
-The following convenience methods combine several ioctls, or one ioctl and some
-simple calculations.
-
-
-.. method:: oss_audio_device.setparameters(format, nchannels, samplerate[, strict=False])
-
- Set the key audio sampling parameters---sample format, number of channels, and
- sampling rate---in one method call. *format*, *nchannels*, and *samplerate*
- should be as specified in the :meth:`setfmt`, :meth:`channels`, and
- :meth:`speed` methods. If *strict* is true, :meth:`setparameters` checks to
- see if each parameter was actually set to the requested value, and raises
- :exc:`OSSAudioError` if not. Returns a tuple (*format*, *nchannels*,
- *samplerate*) indicating the parameter values that were actually set by the
- device driver (i.e., the same as the return values of :meth:`setfmt`,
- :meth:`channels`, and :meth:`speed`).
-
- For example, ::
-
- (fmt, channels, rate) = dsp.setparameters(fmt, channels, rate)
-
- is equivalent to ::
-
- fmt = dsp.setfmt(fmt)
- channels = dsp.channels(channels)
- rate = dsp.rate(rate)
-
-
-.. method:: oss_audio_device.bufsize()
-
- Returns the size of the hardware buffer, in samples.
-
-
-.. method:: oss_audio_device.obufcount()
-
- Returns the number of samples that are in the hardware buffer yet to be played.
-
-
-.. method:: oss_audio_device.obuffree()
-
- Returns the number of samples that could be queued into the hardware buffer to
- be played without blocking.
-
-Audio device objects also support several read-only attributes:
-
-
-.. attribute:: oss_audio_device.closed
-
- Boolean indicating whether the device has been closed.
-
-
-.. attribute:: oss_audio_device.name
-
- String containing the name of the device file.
-
-
-.. attribute:: oss_audio_device.mode
-
- The I/O mode for the file, either ``"r"``, ``"rw"``, or ``"w"``.
-
-
-.. _mixer-device-objects:
-
-Mixer Device Objects
---------------------
-
-The mixer object provides two file-like methods:
-
-
-.. method:: oss_mixer_device.close()
-
- This method closes the open mixer device file. Any further attempts to use the
- mixer after this file is closed will raise an :exc:`OSError`.
-
-
-.. method:: oss_mixer_device.fileno()
-
- Returns the file handle number of the open mixer device file.
-
-.. versionchanged:: 3.2
- Mixer objects also support the context management protocol.
-
-
-The remaining methods are specific to audio mixing:
-
-
-.. method:: oss_mixer_device.controls()
-
- This method returns a bitmask specifying the available mixer controls ("Control"
- being a specific mixable "channel", such as :const:`SOUND_MIXER_PCM` or
- :const:`SOUND_MIXER_SYNTH`). This bitmask indicates a subset of all available
- mixer controls---the :const:`SOUND_MIXER_\*` constants defined at module level.
- To determine if, for example, the current mixer object supports a PCM mixer, use
- the following Python code::
-
- mixer=ossaudiodev.openmixer()
- if mixer.controls() & (1 << ossaudiodev.SOUND_MIXER_PCM):
- # PCM is supported
- ... code ...
-
- For most purposes, the :const:`SOUND_MIXER_VOLUME` (master volume) and
- :const:`SOUND_MIXER_PCM` controls should suffice---but code that uses the mixer
- should be flexible when it comes to choosing mixer controls. On the Gravis
- Ultrasound, for example, :const:`SOUND_MIXER_VOLUME` does not exist.
-
-
-.. method:: oss_mixer_device.stereocontrols()
-
- Returns a bitmask indicating stereo mixer controls. If a bit is set, the
- corresponding control is stereo; if it is unset, the control is either
- monophonic or not supported by the mixer (use in combination with
- :meth:`controls` to determine which).
-
- See the code example for the :meth:`controls` function for an example of getting
- data from a bitmask.
-
-
-.. method:: oss_mixer_device.reccontrols()
-
- Returns a bitmask specifying the mixer controls that may be used to record. See
- the code example for :meth:`controls` for an example of reading from a bitmask.
-
-
-.. method:: oss_mixer_device.get(control)
-
- Returns the volume of a given mixer control. The returned volume is a 2-tuple
- ``(left_volume,right_volume)``. Volumes are specified as numbers from 0
- (silent) to 100 (full volume). If the control is monophonic, a 2-tuple is still
- returned, but both volumes are the same.
-
- Raises :exc:`OSSAudioError` if an invalid control is specified, or
- :exc:`OSError` if an unsupported control is specified.
-
-
-.. method:: oss_mixer_device.set(control, (left, right))
-
- Sets the volume for a given mixer control to ``(left,right)``. ``left`` and
- ``right`` must be ints and between 0 (silent) and 100 (full volume). On
- success, the new volume is returned as a 2-tuple. Note that this may not be
- exactly the same as the volume specified, because of the limited resolution of
- some soundcard's mixers.
-
- Raises :exc:`OSSAudioError` if an invalid mixer control was specified, or if the
- specified volumes were out-of-range.
-
-
-.. method:: oss_mixer_device.get_recsrc()
-
- This method returns a bitmask indicating which control(s) are currently being
- used as a recording source.
-
-
-.. method:: oss_mixer_device.set_recsrc(bitmask)
-
- Call this function to specify a recording source. Returns a bitmask indicating
- the new recording source (or sources) if successful; raises :exc:`OSError` if an
- invalid source was specified. To set the current recording source to the
- microphone input::
-
- mixer.setrecsrc (1 << ossaudiodev.SOUND_MIXER_MIC)
+++ /dev/null
-from test import support
-from test.support import import_helper, warnings_helper
-import warnings
-support.requires('audio')
-
-from test.support import findfile
-
-with warnings.catch_warnings():
- warnings.simplefilter("ignore", DeprecationWarning)
- ossaudiodev = import_helper.import_module('ossaudiodev')
-audioop = warnings_helper.import_deprecated('audioop')
-sunau = warnings_helper.import_deprecated('sunau')
-
-import errno
-import sys
-import time
-import unittest
-
-# Arggh, AFMT_S16_NE not defined on all platforms -- seems to be a
-# fairly recent addition to OSS.
-try:
- from ossaudiodev import AFMT_S16_NE
-except ImportError:
- if sys.byteorder == "little":
- AFMT_S16_NE = ossaudiodev.AFMT_S16_LE
- else:
- AFMT_S16_NE = ossaudiodev.AFMT_S16_BE
-
-
-def read_sound_file(path):
- with open(path, 'rb') as fp:
- au = sunau.open(fp)
- rate = au.getframerate()
- nchannels = au.getnchannels()
- encoding = au._encoding
- fp.seek(0)
- data = fp.read()
-
- if encoding != sunau.AUDIO_FILE_ENCODING_MULAW_8:
- raise RuntimeError("Expect .au file with 8-bit mu-law samples")
-
- # Convert the data to 16-bit signed.
- data = audioop.ulaw2lin(data, 2)
- return (data, rate, 16, nchannels)
-
-class OSSAudioDevTests(unittest.TestCase):
-
- def play_sound_file(self, data, rate, ssize, nchannels):
- try:
- dsp = ossaudiodev.open('w')
- except OSError as msg:
- if msg.args[0] in (errno.EACCES, errno.ENOENT,
- errno.ENODEV, errno.EBUSY):
- raise unittest.SkipTest(msg)
- raise
-
- # at least check that these methods can be invoked
- dsp.bufsize()
- dsp.obufcount()
- dsp.obuffree()
- dsp.getptr()
- dsp.fileno()
-
- # Make sure the read-only attributes work.
- self.assertFalse(dsp.closed)
- self.assertEqual(dsp.name, "/dev/dsp")
- self.assertEqual(dsp.mode, "w", "bad dsp.mode: %r" % dsp.mode)
-
- # And make sure they're really read-only.
- for attr in ('closed', 'name', 'mode'):
- try:
- setattr(dsp, attr, 42)
- except (TypeError, AttributeError):
- pass
- else:
- self.fail("dsp.%s not read-only" % attr)
-
- # Compute expected running time of sound sample (in seconds).
- expected_time = float(len(data)) / (ssize/8) / nchannels / rate
-
- # set parameters based on .au file headers
- dsp.setparameters(AFMT_S16_NE, nchannels, rate)
- self.assertTrue(abs(expected_time - 3.51) < 1e-2, expected_time)
- t1 = time.monotonic()
- dsp.write(data)
- dsp.close()
- t2 = time.monotonic()
- elapsed_time = t2 - t1
-
- percent_diff = (abs(elapsed_time - expected_time) / expected_time) * 100
- self.assertTrue(percent_diff <= 10.0,
- "elapsed time (%s) > 10%% off of expected time (%s)" %
- (elapsed_time, expected_time))
-
- def set_parameters(self, dsp):
- # Two configurations for testing:
- # config1 (8-bit, mono, 8 kHz) should work on even the most
- # ancient and crufty sound card, but maybe not on special-
- # purpose high-end hardware
- # config2 (16-bit, stereo, 44.1kHz) should work on all but the
- # most ancient and crufty hardware
- config1 = (ossaudiodev.AFMT_U8, 1, 8000)
- config2 = (AFMT_S16_NE, 2, 44100)
-
- for config in [config1, config2]:
- (fmt, channels, rate) = config
- if (dsp.setfmt(fmt) == fmt and
- dsp.channels(channels) == channels and
- dsp.speed(rate) == rate):
- break
- else:
- raise RuntimeError("unable to set audio sampling parameters: "
- "you must have really weird audio hardware")
-
- # setparameters() should be able to set this configuration in
- # either strict or non-strict mode.
- result = dsp.setparameters(fmt, channels, rate, False)
- self.assertEqual(result, (fmt, channels, rate),
- "setparameters%r: returned %r" % (config, result))
-
- result = dsp.setparameters(fmt, channels, rate, True)
- self.assertEqual(result, (fmt, channels, rate),
- "setparameters%r: returned %r" % (config, result))
-
- def set_bad_parameters(self, dsp):
- # Now try some configurations that are presumably bogus: eg. 300
- # channels currently exceeds even Hollywood's ambitions, and
- # negative sampling rate is utter nonsense. setparameters() should
- # accept these in non-strict mode, returning something other than
- # was requested, but should barf in strict mode.
- fmt = AFMT_S16_NE
- rate = 44100
- channels = 2
- for config in [(fmt, 300, rate), # ridiculous nchannels
- (fmt, -5, rate), # impossible nchannels
- (fmt, channels, -50), # impossible rate
- ]:
- (fmt, channels, rate) = config
- result = dsp.setparameters(fmt, channels, rate, False)
- self.assertNotEqual(result, config,
- "unexpectedly got requested configuration")
-
- try:
- result = dsp.setparameters(fmt, channels, rate, True)
- except ossaudiodev.OSSAudioError as err:
- pass
- else:
- self.fail("expected OSSAudioError")
-
- def test_playback(self):
- sound_info = read_sound_file(findfile('audiotest.au'))
- self.play_sound_file(*sound_info)
-
- def test_set_parameters(self):
- dsp = ossaudiodev.open("w")
- try:
- self.set_parameters(dsp)
-
- # Disabled because it fails under Linux 2.6 with ALSA's OSS
- # emulation layer.
- #self.set_bad_parameters(dsp)
- finally:
- dsp.close()
- self.assertTrue(dsp.closed)
-
- def test_mixer_methods(self):
- # Issue #8139: ossaudiodev didn't initialize its types properly,
- # therefore some methods were unavailable.
- with ossaudiodev.openmixer() as mixer:
- self.assertGreaterEqual(mixer.fileno(), 0)
-
- def test_with(self):
- with ossaudiodev.open('w') as dsp:
- pass
- self.assertTrue(dsp.closed)
-
- def test_on_closed(self):
- dsp = ossaudiodev.open('w')
- dsp.close()
- self.assertRaises(ValueError, dsp.fileno)
- self.assertRaises(ValueError, dsp.read, 1)
- self.assertRaises(ValueError, dsp.write, b'x')
- self.assertRaises(ValueError, dsp.writeall, b'x')
- self.assertRaises(ValueError, dsp.bufsize)
- self.assertRaises(ValueError, dsp.obufcount)
- self.assertRaises(ValueError, dsp.obufcount)
- self.assertRaises(ValueError, dsp.obuffree)
- self.assertRaises(ValueError, dsp.getptr)
-
- mixer = ossaudiodev.openmixer()
- mixer.close()
- self.assertRaises(ValueError, mixer.fileno)
-
-def setUpModule():
- try:
- dsp = ossaudiodev.open('w')
- except (ossaudiodev.error, OSError) as msg:
- if msg.args[0] in (errno.EACCES, errno.ENOENT,
- errno.ENODEV, errno.EBUSY):
- raise unittest.SkipTest(msg)
- raise
- dsp.close()
-
-if __name__ == "__main__":
- unittest.main()
+++ /dev/null
-/*
- * ossaudiodev -- Python interface to the OSS (Open Sound System) API.
- * This is the standard audio API for Linux and some
- * flavours of BSD [XXX which ones?]; it is also available
- * for a wide range of commercial Unices.
- *
- * Originally written by Peter Bosch, March 2000, as linuxaudiodev.
- *
- * Renamed to ossaudiodev and rearranged/revised/hacked up
- * by Greg Ward <gward@python.net>, November 2002.
- * Mixer interface by Nicholas FitzRoy-Dale <wzdd@lardcave.net>, Dec 2002.
- *
- * (c) 2000 Peter Bosch. All Rights Reserved.
- * (c) 2002 Gregory P. Ward. All Rights Reserved.
- * (c) 2002 Python Software Foundation. All Rights Reserved.
- *
- * $Id$
- */
-
-#ifndef Py_BUILD_CORE_BUILTIN
-# define Py_BUILD_CORE_MODULE 1
-#endif
-
-#define PY_SSIZE_T_CLEAN
-#include "Python.h"
-#include "pycore_fileutils.h" // _Py_write()
-#include "structmember.h" // PyMemberDef
-
-#include <stdlib.h> // getenv()
-#ifdef HAVE_FCNTL_H
-#include <fcntl.h>
-#else
-#define O_RDONLY 00
-#define O_WRONLY 01
-#endif
-
-#include <sys/ioctl.h>
-#ifdef __ANDROID__
-#include <linux/soundcard.h>
-#else
-#include <sys/soundcard.h>
-#endif
-
-#ifdef __linux__
-
-#ifndef HAVE_STDINT_H
-typedef unsigned long uint32_t;
-#endif
-
-#elif defined(__FreeBSD__)
-
-# ifndef SNDCTL_DSP_CHANNELS
-# define SNDCTL_DSP_CHANNELS SOUND_PCM_WRITE_CHANNELS
-# endif
-
-#endif
-
-typedef struct {
- PyObject_HEAD
- const char *devicename; /* name of the device file */
- int fd; /* file descriptor */
- int mode; /* file mode (O_RDONLY, etc.) */
- Py_ssize_t icount; /* input count */
- Py_ssize_t ocount; /* output count */
- uint32_t afmts; /* audio formats supported by hardware */
-} oss_audio_t;
-
-typedef struct {
- PyObject_HEAD
- int fd; /* The open mixer device */
-} oss_mixer_t;
-
-
-static PyTypeObject OSSAudioType;
-static PyTypeObject OSSMixerType;
-
-static PyObject *OSSAudioError;
-
-
-/* ----------------------------------------------------------------------
- * DSP object initialization/deallocation
- */
-
-static oss_audio_t *
-newossobject(PyObject *arg)
-{
- oss_audio_t *self;
- int fd, afmts, imode;
- const char *devicename = NULL;
- const char *mode = NULL;
-
- /* Two ways to call open():
- open(device, mode) (for consistency with builtin open())
- open(mode) (for backwards compatibility)
- because the *first* argument is optional, parsing args is
- a wee bit tricky. */
- if (!PyArg_ParseTuple(arg, "s|s:open", &devicename, &mode))
- return NULL;
- if (mode == NULL) { /* only one arg supplied */
- mode = devicename;
- devicename = NULL;
- }
-
- if (strcmp(mode, "r") == 0)
- imode = O_RDONLY;
- else if (strcmp(mode, "w") == 0)
- imode = O_WRONLY;
- else if (strcmp(mode, "rw") == 0)
- imode = O_RDWR;
- else {
- PyErr_SetString(OSSAudioError, "mode must be 'r', 'w', or 'rw'");
- return NULL;
- }
-
- /* Open the correct device: either the 'device' argument,
- or the AUDIODEV environment variable, or "/dev/dsp". */
- if (devicename == NULL) { /* called with one arg */
- devicename = getenv("AUDIODEV");
- if (devicename == NULL) /* $AUDIODEV not set */
- devicename = "/dev/dsp";
- }
-
- /* Open with O_NONBLOCK to avoid hanging on devices that only allow
- one open at a time. This does *not* affect later I/O; OSS
- provides a special ioctl() for non-blocking read/write, which is
- exposed via oss_nonblock() below. */
- fd = _Py_open(devicename, imode|O_NONBLOCK);
- if (fd == -1)
- return NULL;
-
- /* And (try to) put it back in blocking mode so we get the
- expected write() semantics. */
- if (fcntl(fd, F_SETFL, 0) == -1) {
- close(fd);
- PyErr_SetFromErrnoWithFilename(PyExc_OSError, devicename);
- return NULL;
- }
-
- if (ioctl(fd, SNDCTL_DSP_GETFMTS, &afmts) == -1) {
- close(fd);
- PyErr_SetFromErrnoWithFilename(PyExc_OSError, devicename);
- return NULL;
- }
- /* Create and initialize the object */
- if ((self = PyObject_New(oss_audio_t, &OSSAudioType)) == NULL) {
- close(fd);
- return NULL;
- }
- self->devicename = devicename;
- self->fd = fd;
- self->mode = imode;
- self->icount = self->ocount = 0;
- self->afmts = afmts;
- return self;
-}
-
-static void
-oss_dealloc(oss_audio_t *self)
-{
- /* if already closed, don't reclose it */
- if (self->fd != -1)
- close(self->fd);
- PyObject_Free(self);
-}
-
-
-/* ----------------------------------------------------------------------
- * Mixer object initialization/deallocation
- */
-
-static oss_mixer_t *
-newossmixerobject(PyObject *arg)
-{
- const char *devicename = NULL;
- int fd;
- oss_mixer_t *self;
-
- if (!PyArg_ParseTuple(arg, "|s", &devicename)) {
- return NULL;
- }
-
- if (devicename == NULL) {
- devicename = getenv("MIXERDEV");
- if (devicename == NULL) /* MIXERDEV not set */
- devicename = "/dev/mixer";
- }
-
- fd = _Py_open(devicename, O_RDWR);
- if (fd == -1)
- return NULL;
-
- if ((self = PyObject_New(oss_mixer_t, &OSSMixerType)) == NULL) {
- close(fd);
- return NULL;
- }
-
- self->fd = fd;
-
- return self;
-}
-
-static void
-oss_mixer_dealloc(oss_mixer_t *self)
-{
- /* if already closed, don't reclose it */
- if (self->fd != -1)
- close(self->fd);
- PyObject_Free(self);
-}
-
-
-/* Methods to wrap the OSS ioctls. The calling convention is pretty
- simple:
- nonblock() -> ioctl(fd, SNDCTL_DSP_NONBLOCK)
- fmt = setfmt(fmt) -> ioctl(fd, SNDCTL_DSP_SETFMT, &fmt)
- etc.
-*/
-
-
-/* ----------------------------------------------------------------------
- * Helper functions
- */
-
-/* Check if a given file descriptor is valid (i.e. hasn't been closed).
- * If true, return 1. Otherwise, raise ValueError and return 0.
- */
-static int _is_fd_valid(int fd)
-{
- /* the FD is set to -1 in oss_close()/oss_mixer_close() */
- if (fd >= 0) {
- return 1;
- } else {
- PyErr_SetString(PyExc_ValueError,
- "Operation on closed OSS device.");
- return 0;
- }
-}
-
-/* _do_ioctl_1() is a private helper function used for the OSS ioctls --
- SNDCTL_DSP_{SETFMT,CHANNELS,SPEED} -- that are called from C
- like this:
- ioctl(fd, SNDCTL_DSP_cmd, &arg)
-
- where arg is the value to set, and on return the driver sets arg to
- the value that was actually set. Mapping this to Python is obvious:
- arg = dsp.xxx(arg)
-*/
-static PyObject *
-_do_ioctl_1(int fd, PyObject *args, char *fname, unsigned long cmd)
-{
- char argfmt[33] = "i:";
- int arg;
-
- assert(strlen(fname) <= 30);
- strncat(argfmt, fname, 30);
- if (!PyArg_ParseTuple(args, argfmt, &arg))
- return NULL;
-
- if (ioctl(fd, cmd, &arg) == -1)
- return PyErr_SetFromErrno(PyExc_OSError);
- return PyLong_FromLong(arg);
-}
-
-
-/* _do_ioctl_1_internal() is a wrapper for ioctls that take no inputs
- but return an output -- ie. we need to pass a pointer to a local C
- variable so the driver can write its output there, but from Python
- all we see is the return value. For example,
- SOUND_MIXER_READ_DEVMASK returns a bitmask of available mixer
- devices, but does not use the value of the parameter passed-in in any
- way.
-*/
-static PyObject *
-_do_ioctl_1_internal(int fd, PyObject *args, char *fname, unsigned long cmd)
-{
- char argfmt[32] = ":";
- int arg = 0;
-
- assert(strlen(fname) <= 30);
- strncat(argfmt, fname, 30);
- if (!PyArg_ParseTuple(args, argfmt, &arg))
- return NULL;
-
- if (ioctl(fd, cmd, &arg) == -1)
- return PyErr_SetFromErrno(PyExc_OSError);
- return PyLong_FromLong(arg);
-}
-
-
-
-/* _do_ioctl_0() is a private helper for the no-argument ioctls:
- SNDCTL_DSP_{SYNC,RESET,POST}. */
-static PyObject *
-_do_ioctl_0(int fd, PyObject *args, char *fname, unsigned long cmd)
-{
- char argfmt[32] = ":";
- int rv;
-
- assert(strlen(fname) <= 30);
- strncat(argfmt, fname, 30);
- if (!PyArg_ParseTuple(args, argfmt))
- return NULL;
-
- /* According to hannu@opensound.com, all three of the ioctls that
- use this function can block, so release the GIL. This is
- especially important for SYNC, which can block for several
- seconds. */
- Py_BEGIN_ALLOW_THREADS
- rv = ioctl(fd, cmd, 0);
- Py_END_ALLOW_THREADS
-
- if (rv == -1)
- return PyErr_SetFromErrno(PyExc_OSError);
- Py_RETURN_NONE;
-}
-
-
-/* ----------------------------------------------------------------------
- * Methods of DSP objects (OSSAudioType)
- */
-
-static PyObject *
-oss_nonblock(oss_audio_t *self, PyObject *unused)
-{
- if (!_is_fd_valid(self->fd))
- return NULL;
-
- /* Hmmm: it doesn't appear to be possible to return to blocking
- mode once we're in non-blocking mode! */
- if (ioctl(self->fd, SNDCTL_DSP_NONBLOCK, NULL) == -1)
- return PyErr_SetFromErrno(PyExc_OSError);
- Py_RETURN_NONE;
-}
-
-static PyObject *
-oss_setfmt(oss_audio_t *self, PyObject *args)
-{
- if (!_is_fd_valid(self->fd))
- return NULL;
-
- return _do_ioctl_1(self->fd, args, "setfmt", SNDCTL_DSP_SETFMT);
-}
-
-static PyObject *
-oss_getfmts(oss_audio_t *self, PyObject *unused)
-{
- int mask;
-
- if (!_is_fd_valid(self->fd))
- return NULL;
-
- if (ioctl(self->fd, SNDCTL_DSP_GETFMTS, &mask) == -1)
- return PyErr_SetFromErrno(PyExc_OSError);
- return PyLong_FromLong(mask);
-}
-
-static PyObject *
-oss_channels(oss_audio_t *self, PyObject *args)
-{
- if (!_is_fd_valid(self->fd))
- return NULL;
-
- return _do_ioctl_1(self->fd, args, "channels", SNDCTL_DSP_CHANNELS);
-}
-
-static PyObject *
-oss_speed(oss_audio_t *self, PyObject *args)
-{
- if (!_is_fd_valid(self->fd))
- return NULL;
-
- return _do_ioctl_1(self->fd, args, "speed", SNDCTL_DSP_SPEED);
-}
-
-static PyObject *
-oss_sync(oss_audio_t *self, PyObject *args)
-{
- if (!_is_fd_valid(self->fd))
- return NULL;
-
- return _do_ioctl_0(self->fd, args, "sync", SNDCTL_DSP_SYNC);
-}
-
-static PyObject *
-oss_reset(oss_audio_t *self, PyObject *args)
-{
- if (!_is_fd_valid(self->fd))
- return NULL;
-
- return _do_ioctl_0(self->fd, args, "reset", SNDCTL_DSP_RESET);
-}
-
-static PyObject *
-oss_post(oss_audio_t *self, PyObject *args)
-{
- if (!_is_fd_valid(self->fd))
- return NULL;
-
- return _do_ioctl_0(self->fd, args, "post", SNDCTL_DSP_POST);
-}
-
-
-/* Regular file methods: read(), write(), close(), etc. as well
- as one convenience method, writeall(). */
-
-static PyObject *
-oss_read(oss_audio_t *self, PyObject *args)
-{
- Py_ssize_t size, count;
- PyObject *rv;
-
- if (!_is_fd_valid(self->fd))
- return NULL;
-
- if (!PyArg_ParseTuple(args, "n:read", &size))
- return NULL;
-
- rv = PyBytes_FromStringAndSize(NULL, size);
- if (rv == NULL)
- return NULL;
-
- count = _Py_read(self->fd, PyBytes_AS_STRING(rv), size);
- if (count == -1) {
- Py_DECREF(rv);
- return NULL;
- }
-
- self->icount += count;
- _PyBytes_Resize(&rv, count);
- return rv;
-}
-
-static PyObject *
-oss_write(oss_audio_t *self, PyObject *args)
-{
- Py_buffer data;
- Py_ssize_t rv;
-
- if (!_is_fd_valid(self->fd))
- return NULL;
-
- if (!PyArg_ParseTuple(args, "y*:write", &data)) {
- return NULL;
- }
-
- rv = _Py_write(self->fd, data.buf, data.len);
- PyBuffer_Release(&data);
- if (rv == -1)
- return NULL;
-
- self->ocount += rv;
- return PyLong_FromLong(rv);
-}
-
-static PyObject *
-oss_writeall(oss_audio_t *self, PyObject *args)
-{
- Py_buffer data;
- const char *cp;
- Py_ssize_t size;
- Py_ssize_t rv;
- fd_set write_set_fds;
- int select_rv;
-
- /* NB. writeall() is only useful in non-blocking mode: according to
- Guenter Geiger <geiger@xdv.org> on the linux-audio-dev list
- (http://eca.cx/lad/2002/11/0380.html), OSS guarantees that
- write() in blocking mode consumes the whole buffer. In blocking
- mode, the behaviour of write() and writeall() from Python is
- indistinguishable. */
-
- if (!_is_fd_valid(self->fd))
- return NULL;
-
- if (!PyArg_ParseTuple(args, "y*:writeall", &data))
- return NULL;
-
- if (!_PyIsSelectable_fd(self->fd)) {
- PyErr_SetString(PyExc_ValueError,
- "file descriptor out of range for select");
- PyBuffer_Release(&data);
- return NULL;
- }
- /* use select to wait for audio device to be available */
- FD_ZERO(&write_set_fds);
- FD_SET(self->fd, &write_set_fds);
- cp = (const char *)data.buf;
- size = data.len;
-
- while (size > 0) {
- Py_BEGIN_ALLOW_THREADS
- select_rv = select(self->fd+1, NULL, &write_set_fds, NULL, NULL);
- Py_END_ALLOW_THREADS
-
- assert(select_rv != 0); /* no timeout, can't expire */
- if (select_rv == -1) {
- PyBuffer_Release(&data);
- return PyErr_SetFromErrno(PyExc_OSError);
- }
-
- rv = _Py_write(self->fd, cp, Py_MIN(size, INT_MAX));
- if (rv == -1) {
- /* buffer is full, try again */
- if (errno == EAGAIN) {
- PyErr_Clear();
- continue;
- }
- /* it's a real error */
- PyBuffer_Release(&data);
- return NULL;
- }
-
- /* wrote rv bytes */
- self->ocount += rv;
- size -= rv;
- cp += rv;
- }
- PyBuffer_Release(&data);
- Py_RETURN_NONE;
-}
-
-static PyObject *
-oss_close(oss_audio_t *self, PyObject *unused)
-{
- if (self->fd >= 0) {
- Py_BEGIN_ALLOW_THREADS
- close(self->fd);
- Py_END_ALLOW_THREADS
- self->fd = -1;
- }
- Py_RETURN_NONE;
-}
-
-static PyObject *
-oss_self(PyObject *self, PyObject *unused)
-{
- return Py_NewRef(self);
-}
-
-static PyObject *
-oss_exit(PyObject *self, PyObject *unused)
-{
- PyObject *ret = PyObject_CallMethod(self, "close", NULL);
- if (!ret)
- return NULL;
- Py_DECREF(ret);
- Py_RETURN_NONE;
-}
-
-static PyObject *
-oss_fileno(oss_audio_t *self, PyObject *unused)
-{
- if (!_is_fd_valid(self->fd))
- return NULL;
-
- return PyLong_FromLong(self->fd);
-}
-
-
-/* Convenience methods: these generally wrap a couple of ioctls into one
- common task. */
-
-static PyObject *
-oss_setparameters(oss_audio_t *self, PyObject *args)
-{
- int wanted_fmt, wanted_channels, wanted_rate, strict=0;
- int fmt, channels, rate;
-
- if (!_is_fd_valid(self->fd))
- return NULL;
-
- if (!PyArg_ParseTuple(args, "iii|p:setparameters",
- &wanted_fmt, &wanted_channels, &wanted_rate,
- &strict))
- return NULL;
-
- fmt = wanted_fmt;
- if (ioctl(self->fd, SNDCTL_DSP_SETFMT, &fmt) == -1) {
- return PyErr_SetFromErrno(PyExc_OSError);
- }
- if (strict && fmt != wanted_fmt) {
- return PyErr_Format
- (OSSAudioError,
- "unable to set requested format (wanted %d, got %d)",
- wanted_fmt, fmt);
- }
-
- channels = wanted_channels;
- if (ioctl(self->fd, SNDCTL_DSP_CHANNELS, &channels) == -1) {
- return PyErr_SetFromErrno(PyExc_OSError);
- }
- if (strict && channels != wanted_channels) {
- return PyErr_Format
- (OSSAudioError,
- "unable to set requested channels (wanted %d, got %d)",
- wanted_channels, channels);
- }
-
- rate = wanted_rate;
- if (ioctl(self->fd, SNDCTL_DSP_SPEED, &rate) == -1) {
- return PyErr_SetFromErrno(PyExc_OSError);
- }
- if (strict && rate != wanted_rate) {
- return PyErr_Format
- (OSSAudioError,
- "unable to set requested rate (wanted %d, got %d)",
- wanted_rate, rate);
- }
-
- /* Construct the return value: a (fmt, channels, rate) tuple that
- tells what the audio hardware was actually set to. */
- return Py_BuildValue("(iii)", fmt, channels, rate);
-}
-
-static int
-_ssize(oss_audio_t *self, int *nchannels, int *ssize)
-{
- int fmt;
-
- fmt = 0;
- if (ioctl(self->fd, SNDCTL_DSP_SETFMT, &fmt) < 0)
- return -errno;
-
- switch (fmt) {
- case AFMT_MU_LAW:
- case AFMT_A_LAW:
- case AFMT_U8:
- case AFMT_S8:
- *ssize = 1; /* 8 bit formats: 1 byte */
- break;
- case AFMT_S16_LE:
- case AFMT_S16_BE:
- case AFMT_U16_LE:
- case AFMT_U16_BE:
- *ssize = 2; /* 16 bit formats: 2 byte */
- break;
- case AFMT_MPEG:
- case AFMT_IMA_ADPCM:
- default:
- return -EOPNOTSUPP;
- }
- if (ioctl(self->fd, SNDCTL_DSP_CHANNELS, nchannels) < 0)
- return -errno;
- return 0;
-}
-
-
-/* bufsize returns the size of the hardware audio buffer in number
- of samples */
-static PyObject *
-oss_bufsize(oss_audio_t *self, PyObject *unused)
-{
- audio_buf_info ai;
- int nchannels=0, ssize=0;
-
- if (!_is_fd_valid(self->fd))
- return NULL;
-
- if (_ssize(self, &nchannels, &ssize) < 0 || !nchannels || !ssize) {
- PyErr_SetFromErrno(PyExc_OSError);
- return NULL;
- }
- if (ioctl(self->fd, SNDCTL_DSP_GETOSPACE, &ai) < 0) {
- PyErr_SetFromErrno(PyExc_OSError);
- return NULL;
- }
- return PyLong_FromLong((ai.fragstotal * ai.fragsize) / (nchannels * ssize));
-}
-
-/* obufcount returns the number of samples that are available in the
- hardware for playing */
-static PyObject *
-oss_obufcount(oss_audio_t *self, PyObject *unused)
-{
- audio_buf_info ai;
- int nchannels=0, ssize=0;
-
- if (!_is_fd_valid(self->fd))
- return NULL;
-
- if (_ssize(self, &nchannels, &ssize) < 0 || !nchannels || !ssize) {
- PyErr_SetFromErrno(PyExc_OSError);
- return NULL;
- }
- if (ioctl(self->fd, SNDCTL_DSP_GETOSPACE, &ai) < 0) {
- PyErr_SetFromErrno(PyExc_OSError);
- return NULL;
- }
- return PyLong_FromLong((ai.fragstotal * ai.fragsize - ai.bytes) /
- (ssize * nchannels));
-}
-
-/* obufcount returns the number of samples that can be played without
- blocking */
-static PyObject *
-oss_obuffree(oss_audio_t *self, PyObject *unused)
-{
- audio_buf_info ai;
- int nchannels=0, ssize=0;
-
- if (!_is_fd_valid(self->fd))
- return NULL;
-
- if (_ssize(self, &nchannels, &ssize) < 0 || !nchannels || !ssize) {
- PyErr_SetFromErrno(PyExc_OSError);
- return NULL;
- }
- if (ioctl(self->fd, SNDCTL_DSP_GETOSPACE, &ai) < 0) {
- PyErr_SetFromErrno(PyExc_OSError);
- return NULL;
- }
- return PyLong_FromLong(ai.bytes / (ssize * nchannels));
-}
-
-static PyObject *
-oss_getptr(oss_audio_t *self, PyObject *unused)
-{
- count_info info;
- int req;
-
- if (!_is_fd_valid(self->fd))
- return NULL;
-
- if (self->mode == O_RDONLY)
- req = SNDCTL_DSP_GETIPTR;
- else
- req = SNDCTL_DSP_GETOPTR;
- if (ioctl(self->fd, req, &info) == -1) {
- PyErr_SetFromErrno(PyExc_OSError);
- return NULL;
- }
- return Py_BuildValue("iii", info.bytes, info.blocks, info.ptr);
-}
-
-
-/* ----------------------------------------------------------------------
- * Methods of mixer objects (OSSMixerType)
- */
-
-static PyObject *
-oss_mixer_close(oss_mixer_t *self, PyObject *unused)
-{
- if (self->fd >= 0) {
- close(self->fd);
- self->fd = -1;
- }
- Py_RETURN_NONE;
-}
-
-static PyObject *
-oss_mixer_fileno(oss_mixer_t *self, PyObject *unused)
-{
- if (!_is_fd_valid(self->fd))
- return NULL;
-
- return PyLong_FromLong(self->fd);
-}
-
-/* Simple mixer interface methods */
-
-static PyObject *
-oss_mixer_controls(oss_mixer_t *self, PyObject *args)
-{
- if (!_is_fd_valid(self->fd))
- return NULL;
-
- return _do_ioctl_1_internal(self->fd, args, "controls",
- SOUND_MIXER_READ_DEVMASK);
-}
-
-static PyObject *
-oss_mixer_stereocontrols(oss_mixer_t *self, PyObject *args)
-{
- if (!_is_fd_valid(self->fd))
- return NULL;
-
- return _do_ioctl_1_internal(self->fd, args, "stereocontrols",
- SOUND_MIXER_READ_STEREODEVS);
-}
-
-static PyObject *
-oss_mixer_reccontrols(oss_mixer_t *self, PyObject *args)
-{
- if (!_is_fd_valid(self->fd))
- return NULL;
-
- return _do_ioctl_1_internal(self->fd, args, "reccontrols",
- SOUND_MIXER_READ_RECMASK);
-}
-
-static PyObject *
-oss_mixer_get(oss_mixer_t *self, PyObject *args)
-{
- int channel, volume;
-
- if (!_is_fd_valid(self->fd))
- return NULL;
-
- /* Can't use _do_ioctl_1 because of encoded arg thingy. */
- if (!PyArg_ParseTuple(args, "i:get", &channel))
- return NULL;
-
- if (channel < 0 || channel > SOUND_MIXER_NRDEVICES) {
- PyErr_SetString(OSSAudioError, "Invalid mixer channel specified.");
- return NULL;
- }
-
- if (ioctl(self->fd, MIXER_READ(channel), &volume) == -1)
- return PyErr_SetFromErrno(PyExc_OSError);
-
- return Py_BuildValue("(ii)", volume & 0xff, (volume & 0xff00) >> 8);
-}
-
-static PyObject *
-oss_mixer_set(oss_mixer_t *self, PyObject *args)
-{
- int channel, volume, leftVol, rightVol;
-
- if (!_is_fd_valid(self->fd))
- return NULL;
-
- /* Can't use _do_ioctl_1 because of encoded arg thingy. */
- if (!PyArg_ParseTuple(args, "i(ii):set", &channel, &leftVol, &rightVol))
- return NULL;
-
- if (channel < 0 || channel > SOUND_MIXER_NRDEVICES) {
- PyErr_SetString(OSSAudioError, "Invalid mixer channel specified.");
- return NULL;
- }
-
- if (leftVol < 0 || rightVol < 0 || leftVol > 100 || rightVol > 100) {
- PyErr_SetString(OSSAudioError, "Volumes must be between 0 and 100.");
- return NULL;
- }
-
- volume = (rightVol << 8) | leftVol;
-
- if (ioctl(self->fd, MIXER_WRITE(channel), &volume) == -1)
- return PyErr_SetFromErrno(PyExc_OSError);
-
- return Py_BuildValue("(ii)", volume & 0xff, (volume & 0xff00) >> 8);
-}
-
-static PyObject *
-oss_mixer_get_recsrc(oss_mixer_t *self, PyObject *args)
-{
- if (!_is_fd_valid(self->fd))
- return NULL;
-
- return _do_ioctl_1_internal(self->fd, args, "get_recsrc",
- SOUND_MIXER_READ_RECSRC);
-}
-
-static PyObject *
-oss_mixer_set_recsrc(oss_mixer_t *self, PyObject *args)
-{
- if (!_is_fd_valid(self->fd))
- return NULL;
-
- return _do_ioctl_1(self->fd, args, "set_recsrc",
- SOUND_MIXER_WRITE_RECSRC);
-}
-
-
-/* ----------------------------------------------------------------------
- * Method tables and other bureaucracy
- */
-
-static PyMethodDef oss_methods[] = {
- /* Regular file methods */
- { "read", (PyCFunction)oss_read, METH_VARARGS },
- { "write", (PyCFunction)oss_write, METH_VARARGS },
- { "writeall", (PyCFunction)oss_writeall, METH_VARARGS },
- { "close", (PyCFunction)oss_close, METH_NOARGS },
- { "fileno", (PyCFunction)oss_fileno, METH_NOARGS },
-
- /* Simple ioctl wrappers */
- { "nonblock", (PyCFunction)oss_nonblock, METH_NOARGS },
- { "setfmt", (PyCFunction)oss_setfmt, METH_VARARGS },
- { "getfmts", (PyCFunction)oss_getfmts, METH_NOARGS },
- { "channels", (PyCFunction)oss_channels, METH_VARARGS },
- { "speed", (PyCFunction)oss_speed, METH_VARARGS },
- { "sync", (PyCFunction)oss_sync, METH_VARARGS },
- { "reset", (PyCFunction)oss_reset, METH_VARARGS },
- { "post", (PyCFunction)oss_post, METH_VARARGS },
-
- /* Convenience methods -- wrap a couple of ioctls together */
- { "setparameters", (PyCFunction)oss_setparameters, METH_VARARGS },
- { "bufsize", (PyCFunction)oss_bufsize, METH_NOARGS },
- { "obufcount", (PyCFunction)oss_obufcount, METH_NOARGS },
- { "obuffree", (PyCFunction)oss_obuffree, METH_NOARGS },
- { "getptr", (PyCFunction)oss_getptr, METH_NOARGS },
-
- /* Aliases for backwards compatibility */
- { "flush", (PyCFunction)oss_sync, METH_VARARGS },
-
- /* Support for the context management protocol */
- { "__enter__", oss_self, METH_NOARGS },
- { "__exit__", oss_exit, METH_VARARGS },
-
- { NULL, NULL} /* sentinel */
-};
-
-static PyMethodDef oss_mixer_methods[] = {
- /* Regular file method - OSS mixers are ioctl-only interface */
- { "close", (PyCFunction)oss_mixer_close, METH_NOARGS },
- { "fileno", (PyCFunction)oss_mixer_fileno, METH_NOARGS },
-
- /* Support for the context management protocol */
- { "__enter__", oss_self, METH_NOARGS },
- { "__exit__", oss_exit, METH_VARARGS },
-
- /* Simple ioctl wrappers */
- { "controls", (PyCFunction)oss_mixer_controls, METH_VARARGS },
- { "stereocontrols", (PyCFunction)oss_mixer_stereocontrols, METH_VARARGS},
- { "reccontrols", (PyCFunction)oss_mixer_reccontrols, METH_VARARGS},
- { "get", (PyCFunction)oss_mixer_get, METH_VARARGS },
- { "set", (PyCFunction)oss_mixer_set, METH_VARARGS },
- { "get_recsrc", (PyCFunction)oss_mixer_get_recsrc, METH_VARARGS },
- { "set_recsrc", (PyCFunction)oss_mixer_set_recsrc, METH_VARARGS },
-
- { NULL, NULL}
-};
-
-static PyMemberDef oss_members[] = {
- {"name", T_STRING, offsetof(oss_audio_t, devicename), READONLY, NULL},
- {NULL}
-};
-
-static PyObject *
-oss_closed_getter(oss_audio_t *self, void *closure)
-{
- return PyBool_FromLong(self->fd == -1);
-}
-
-static PyObject *
-oss_mode_getter(oss_audio_t *self, void *closure)
-{
- switch(self->mode) {
- case O_RDONLY:
- return PyUnicode_FromString("r");
- break;
- case O_RDWR:
- return PyUnicode_FromString("rw");
- break;
- case O_WRONLY:
- return PyUnicode_FromString("w");
- break;
- default:
- /* From newossobject(), self->mode can only be one
- of these three values. */
- Py_UNREACHABLE();
- }
-}
-
-static PyGetSetDef oss_getsetlist[] = {
- {"closed", (getter)oss_closed_getter, (setter)NULL, NULL},
- {"mode", (getter)oss_mode_getter, (setter)NULL, NULL},
- {NULL},
-};
-
-static PyTypeObject OSSAudioType = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "ossaudiodev.oss_audio_device", /*tp_name*/
- sizeof(oss_audio_t), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)oss_dealloc, /*tp_dealloc*/
- 0, /*tp_vectorcall_offset*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_as_async*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash*/
- 0, /*tp_call*/
- 0, /*tp_str*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT, /*tp_flags*/
- 0, /*tp_doc*/
- 0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- oss_methods, /*tp_methods*/
- oss_members, /*tp_members*/
- oss_getsetlist, /*tp_getset*/
-};
-
-static PyTypeObject OSSMixerType = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "ossaudiodev.oss_mixer_device", /*tp_name*/
- sizeof(oss_mixer_t), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)oss_mixer_dealloc, /*tp_dealloc*/
- 0, /*tp_vectorcall_offset*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_as_async*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash*/
- 0, /*tp_call*/
- 0, /*tp_str*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT, /*tp_flags*/
- 0, /*tp_doc*/
- 0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- oss_mixer_methods, /*tp_methods*/
-};
-
-
-static PyObject *
-ossopen(PyObject *self, PyObject *args)
-{
- return (PyObject *)newossobject(args);
-}
-
-static PyObject *
-ossopenmixer(PyObject *self, PyObject *args)
-{
- return (PyObject *)newossmixerobject(args);
-}
-
-static PyMethodDef ossaudiodev_methods[] = {
- { "open", ossopen, METH_VARARGS },
- { "openmixer", ossopenmixer, METH_VARARGS },
- { 0, 0 },
-};
-
-
-#define _EXPORT_INT(mod, name) \
- if (PyModule_AddIntConstant(mod, #name, (long) (name)) == -1) return NULL;
-
-
-static char *control_labels[] = SOUND_DEVICE_LABELS;
-static char *control_names[] = SOUND_DEVICE_NAMES;
-
-
-static int
-build_namelists (PyObject *module)
-{
- PyObject *labels;
- PyObject *names;
- PyObject *s;
- int num_controls;
- int i;
-
- num_controls = Py_ARRAY_LENGTH(control_labels);
- assert(num_controls == Py_ARRAY_LENGTH(control_names));
-
- labels = PyList_New(num_controls);
- names = PyList_New(num_controls);
- if (labels == NULL || names == NULL)
- goto error2;
- for (i = 0; i < num_controls; i++) {
- s = PyUnicode_FromString(control_labels[i]);
- if (s == NULL)
- goto error2;
- PyList_SET_ITEM(labels, i, s);
-
- s = PyUnicode_FromString(control_names[i]);
- if (s == NULL)
- goto error2;
- PyList_SET_ITEM(names, i, s);
- }
-
- if (PyModule_AddObject(module, "control_labels", labels) == -1)
- goto error2;
- if (PyModule_AddObject(module, "control_names", names) == -1)
- goto error1;
-
- return 0;
-
-error2:
- Py_XDECREF(labels);
-error1:
- Py_XDECREF(names);
- return -1;
-}
-
-
-static struct PyModuleDef ossaudiodevmodule = {
- PyModuleDef_HEAD_INIT,
- "ossaudiodev",
- NULL,
- -1,
- ossaudiodev_methods,
- NULL,
- NULL,
- NULL,
- NULL
-};
-
-PyMODINIT_FUNC
-PyInit_ossaudiodev(void)
-{
- PyObject *m;
-
- if (PyErr_WarnEx(PyExc_DeprecationWarning,
- "'ossaudiodev' is deprecated and slated for removal in "
- "Python 3.13",
- 7)) {
- return NULL;
- }
-
- if (PyType_Ready(&OSSAudioType) < 0)
- return NULL;
-
- if (PyType_Ready(&OSSMixerType) < 0)
- return NULL;
-
- m = PyModule_Create(&ossaudiodevmodule);
- if (m == NULL)
- return NULL;
-
- OSSAudioError = PyErr_NewException("ossaudiodev.OSSAudioError",
- NULL, NULL);
- if (OSSAudioError) {
- /* Each call to PyModule_AddObject decrefs it; compensate: */
- PyModule_AddObject(m, "error", Py_NewRef(OSSAudioError));
- PyModule_AddObject(m, "OSSAudioError", Py_NewRef(OSSAudioError));
- }
-
- /* Build 'control_labels' and 'control_names' lists and add them
- to the module. */
- if (build_namelists(m) == -1) /* XXX what to do here? */
- return NULL;
-
- /* Expose the audio format numbers -- essential! */
- _EXPORT_INT(m, AFMT_QUERY);
- _EXPORT_INT(m, AFMT_MU_LAW);
- _EXPORT_INT(m, AFMT_A_LAW);
- _EXPORT_INT(m, AFMT_IMA_ADPCM);
- _EXPORT_INT(m, AFMT_U8);
- _EXPORT_INT(m, AFMT_S16_LE);
- _EXPORT_INT(m, AFMT_S16_BE);
- _EXPORT_INT(m, AFMT_S8);
- _EXPORT_INT(m, AFMT_U16_LE);
- _EXPORT_INT(m, AFMT_U16_BE);
- _EXPORT_INT(m, AFMT_MPEG);
-#ifdef AFMT_AC3
- _EXPORT_INT(m, AFMT_AC3);
-#endif
-#ifdef AFMT_S16_NE
- _EXPORT_INT(m, AFMT_S16_NE);
-#endif
-#ifdef AFMT_U16_NE
- _EXPORT_INT(m, AFMT_U16_NE);
-#endif
-#ifdef AFMT_S32_LE
- _EXPORT_INT(m, AFMT_S32_LE);
-#endif
-#ifdef AFMT_S32_BE
- _EXPORT_INT(m, AFMT_S32_BE);
-#endif
-#ifdef AFMT_MPEG
- _EXPORT_INT(m, AFMT_MPEG);
-#endif
-
- /* Expose the sound mixer device numbers. */
- _EXPORT_INT(m, SOUND_MIXER_NRDEVICES);
- _EXPORT_INT(m, SOUND_MIXER_VOLUME);
- _EXPORT_INT(m, SOUND_MIXER_BASS);
- _EXPORT_INT(m, SOUND_MIXER_TREBLE);
- _EXPORT_INT(m, SOUND_MIXER_SYNTH);
- _EXPORT_INT(m, SOUND_MIXER_PCM);
- _EXPORT_INT(m, SOUND_MIXER_SPEAKER);
- _EXPORT_INT(m, SOUND_MIXER_LINE);
- _EXPORT_INT(m, SOUND_MIXER_MIC);
- _EXPORT_INT(m, SOUND_MIXER_CD);
- _EXPORT_INT(m, SOUND_MIXER_IMIX);
- _EXPORT_INT(m, SOUND_MIXER_ALTPCM);
- _EXPORT_INT(m, SOUND_MIXER_RECLEV);
- _EXPORT_INT(m, SOUND_MIXER_IGAIN);
- _EXPORT_INT(m, SOUND_MIXER_OGAIN);
- _EXPORT_INT(m, SOUND_MIXER_LINE1);
- _EXPORT_INT(m, SOUND_MIXER_LINE2);
- _EXPORT_INT(m, SOUND_MIXER_LINE3);
-#ifdef SOUND_MIXER_DIGITAL1
- _EXPORT_INT(m, SOUND_MIXER_DIGITAL1);
-#endif
-#ifdef SOUND_MIXER_DIGITAL2
- _EXPORT_INT(m, SOUND_MIXER_DIGITAL2);
-#endif
-#ifdef SOUND_MIXER_DIGITAL3
- _EXPORT_INT(m, SOUND_MIXER_DIGITAL3);
-#endif
-#ifdef SOUND_MIXER_PHONEIN
- _EXPORT_INT(m, SOUND_MIXER_PHONEIN);
-#endif
-#ifdef SOUND_MIXER_PHONEOUT
- _EXPORT_INT(m, SOUND_MIXER_PHONEOUT);
-#endif
-#ifdef SOUND_MIXER_VIDEO
- _EXPORT_INT(m, SOUND_MIXER_VIDEO);
-#endif
-#ifdef SOUND_MIXER_RADIO
- _EXPORT_INT(m, SOUND_MIXER_RADIO);
-#endif
-#ifdef SOUND_MIXER_MONITOR
- _EXPORT_INT(m, SOUND_MIXER_MONITOR);
-#endif
-
- /* Expose all the ioctl numbers for masochists who like to do this
- stuff directly. */
-#ifdef SNDCTL_COPR_HALT
- _EXPORT_INT(m, SNDCTL_COPR_HALT);
-#endif
-#ifdef SNDCTL_COPR_LOAD
- _EXPORT_INT(m, SNDCTL_COPR_LOAD);
-#endif
-#ifdef SNDCTL_COPR_RCODE
- _EXPORT_INT(m, SNDCTL_COPR_RCODE);
-#endif
-#ifdef SNDCTL_COPR_RCVMSG
- _EXPORT_INT(m, SNDCTL_COPR_RCVMSG);
-#endif
-#ifdef SNDCTL_COPR_RDATA
- _EXPORT_INT(m, SNDCTL_COPR_RDATA);
-#endif
-#ifdef SNDCTL_COPR_RESET
- _EXPORT_INT(m, SNDCTL_COPR_RESET);
-#endif
-#ifdef SNDCTL_COPR_RUN
- _EXPORT_INT(m, SNDCTL_COPR_RUN);
-#endif
-#ifdef SNDCTL_COPR_SENDMSG
- _EXPORT_INT(m, SNDCTL_COPR_SENDMSG);
-#endif
-#ifdef SNDCTL_COPR_WCODE
- _EXPORT_INT(m, SNDCTL_COPR_WCODE);
-#endif
-#ifdef SNDCTL_COPR_WDATA
- _EXPORT_INT(m, SNDCTL_COPR_WDATA);
-#endif
-#ifdef SNDCTL_DSP_BIND_CHANNEL
- _EXPORT_INT(m, SNDCTL_DSP_BIND_CHANNEL);
-#endif
- _EXPORT_INT(m, SNDCTL_DSP_CHANNELS);
- _EXPORT_INT(m, SNDCTL_DSP_GETBLKSIZE);
- _EXPORT_INT(m, SNDCTL_DSP_GETCAPS);
-#ifdef SNDCTL_DSP_GETCHANNELMASK
- _EXPORT_INT(m, SNDCTL_DSP_GETCHANNELMASK);
-#endif
- _EXPORT_INT(m, SNDCTL_DSP_GETFMTS);
- _EXPORT_INT(m, SNDCTL_DSP_GETIPTR);
- _EXPORT_INT(m, SNDCTL_DSP_GETISPACE);
-#ifdef SNDCTL_DSP_GETODELAY
- _EXPORT_INT(m, SNDCTL_DSP_GETODELAY);
-#endif
- _EXPORT_INT(m, SNDCTL_DSP_GETOPTR);
- _EXPORT_INT(m, SNDCTL_DSP_GETOSPACE);
-#ifdef SNDCTL_DSP_GETSPDIF
- _EXPORT_INT(m, SNDCTL_DSP_GETSPDIF);
-#endif
- _EXPORT_INT(m, SNDCTL_DSP_GETTRIGGER);
-#ifdef SNDCTL_DSP_MAPINBUF
- _EXPORT_INT(m, SNDCTL_DSP_MAPINBUF);
-#endif
-#ifdef SNDCTL_DSP_MAPOUTBUF
- _EXPORT_INT(m, SNDCTL_DSP_MAPOUTBUF);
-#endif
- _EXPORT_INT(m, SNDCTL_DSP_NONBLOCK);
- _EXPORT_INT(m, SNDCTL_DSP_POST);
-#ifdef SNDCTL_DSP_PROFILE
- _EXPORT_INT(m, SNDCTL_DSP_PROFILE);
-#endif
- _EXPORT_INT(m, SNDCTL_DSP_RESET);
- _EXPORT_INT(m, SNDCTL_DSP_SAMPLESIZE);
- _EXPORT_INT(m, SNDCTL_DSP_SETDUPLEX);
- _EXPORT_INT(m, SNDCTL_DSP_SETFMT);
- _EXPORT_INT(m, SNDCTL_DSP_SETFRAGMENT);
-#ifdef SNDCTL_DSP_SETSPDIF
- _EXPORT_INT(m, SNDCTL_DSP_SETSPDIF);
-#endif
- _EXPORT_INT(m, SNDCTL_DSP_SETSYNCRO);
- _EXPORT_INT(m, SNDCTL_DSP_SETTRIGGER);
- _EXPORT_INT(m, SNDCTL_DSP_SPEED);
- _EXPORT_INT(m, SNDCTL_DSP_STEREO);
- _EXPORT_INT(m, SNDCTL_DSP_SUBDIVIDE);
- _EXPORT_INT(m, SNDCTL_DSP_SYNC);
-#ifdef SNDCTL_FM_4OP_ENABLE
- _EXPORT_INT(m, SNDCTL_FM_4OP_ENABLE);
-#endif
-#ifdef SNDCTL_FM_LOAD_INSTR
- _EXPORT_INT(m, SNDCTL_FM_LOAD_INSTR);
-#endif
-#ifdef SNDCTL_MIDI_INFO
- _EXPORT_INT(m, SNDCTL_MIDI_INFO);
-#endif
-#ifdef SNDCTL_MIDI_MPUCMD
- _EXPORT_INT(m, SNDCTL_MIDI_MPUCMD);
-#endif
-#ifdef SNDCTL_MIDI_MPUMODE
- _EXPORT_INT(m, SNDCTL_MIDI_MPUMODE);
-#endif
-#ifdef SNDCTL_MIDI_PRETIME
- _EXPORT_INT(m, SNDCTL_MIDI_PRETIME);
-#endif
-#ifdef SNDCTL_SEQ_CTRLRATE
- _EXPORT_INT(m, SNDCTL_SEQ_CTRLRATE);
-#endif
-#ifdef SNDCTL_SEQ_GETINCOUNT
- _EXPORT_INT(m, SNDCTL_SEQ_GETINCOUNT);
-#endif
-#ifdef SNDCTL_SEQ_GETOUTCOUNT
- _EXPORT_INT(m, SNDCTL_SEQ_GETOUTCOUNT);
-#endif
-#ifdef SNDCTL_SEQ_GETTIME
- _EXPORT_INT(m, SNDCTL_SEQ_GETTIME);
-#endif
-#ifdef SNDCTL_SEQ_NRMIDIS
- _EXPORT_INT(m, SNDCTL_SEQ_NRMIDIS);
-#endif
-#ifdef SNDCTL_SEQ_NRSYNTHS
- _EXPORT_INT(m, SNDCTL_SEQ_NRSYNTHS);
-#endif
-#ifdef SNDCTL_SEQ_OUTOFBAND
- _EXPORT_INT(m, SNDCTL_SEQ_OUTOFBAND);
-#endif
-#ifdef SNDCTL_SEQ_PANIC
- _EXPORT_INT(m, SNDCTL_SEQ_PANIC);
-#endif
-#ifdef SNDCTL_SEQ_PERCMODE
- _EXPORT_INT(m, SNDCTL_SEQ_PERCMODE);
-#endif
-#ifdef SNDCTL_SEQ_RESET
- _EXPORT_INT(m, SNDCTL_SEQ_RESET);
-#endif
-#ifdef SNDCTL_SEQ_RESETSAMPLES
- _EXPORT_INT(m, SNDCTL_SEQ_RESETSAMPLES);
-#endif
-#ifdef SNDCTL_SEQ_SYNC
- _EXPORT_INT(m, SNDCTL_SEQ_SYNC);
-#endif
-#ifdef SNDCTL_SEQ_TESTMIDI
- _EXPORT_INT(m, SNDCTL_SEQ_TESTMIDI);
-#endif
-#ifdef SNDCTL_SEQ_THRESHOLD
- _EXPORT_INT(m, SNDCTL_SEQ_THRESHOLD);
-#endif
-#ifdef SNDCTL_SYNTH_CONTROL
- _EXPORT_INT(m, SNDCTL_SYNTH_CONTROL);
-#endif
-#ifdef SNDCTL_SYNTH_ID
- _EXPORT_INT(m, SNDCTL_SYNTH_ID);
-#endif
-#ifdef SNDCTL_SYNTH_INFO
- _EXPORT_INT(m, SNDCTL_SYNTH_INFO);
-#endif
-#ifdef SNDCTL_SYNTH_MEMAVL
- _EXPORT_INT(m, SNDCTL_SYNTH_MEMAVL);
-#endif
-#ifdef SNDCTL_SYNTH_REMOVESAMPLE
- _EXPORT_INT(m, SNDCTL_SYNTH_REMOVESAMPLE);
-#endif
-#ifdef SNDCTL_TMR_CONTINUE
- _EXPORT_INT(m, SNDCTL_TMR_CONTINUE);
-#endif
-#ifdef SNDCTL_TMR_METRONOME
- _EXPORT_INT(m, SNDCTL_TMR_METRONOME);
-#endif
-#ifdef SNDCTL_TMR_SELECT
- _EXPORT_INT(m, SNDCTL_TMR_SELECT);
-#endif
-#ifdef SNDCTL_TMR_SOURCE
- _EXPORT_INT(m, SNDCTL_TMR_SOURCE);
-#endif
-#ifdef SNDCTL_TMR_START
- _EXPORT_INT(m, SNDCTL_TMR_START);
-#endif
-#ifdef SNDCTL_TMR_STOP
- _EXPORT_INT(m, SNDCTL_TMR_STOP);
-#endif
-#ifdef SNDCTL_TMR_TEMPO
- _EXPORT_INT(m, SNDCTL_TMR_TEMPO);
-#endif
-#ifdef SNDCTL_TMR_TIMEBASE
- _EXPORT_INT(m, SNDCTL_TMR_TIMEBASE);
-#endif
- return m;
-}