this file is part of audioread 2011 adrian sampson permission is hereby granted free of charge to any person obtaining a copy of this software and associated documentation files the software to deal in the software without restriction including without limitation the rights to use copy modify merge publish distribute sublicense andor sell copies of the software and to permit persons to whom the software is furnished to do so subject to the following conditions the above notice and this permission notice shall be included in all copies or substantial portions of the software use gstreamer to decode audio files to read an audio file pass it to the constructor for gstaudiofile and then iterate over the contents f gstaudiofile something mp3 try for block in f finally f close note that there are a few complications caused by gstreamer s asynchronous architecture this module spawns its own gobject main loop thread i m not sure how that will interact with other main loops if your program has them also in order to stop the thread and terminate your program normally you need to call the close method on every gstaudiofile you create conveniently the file can be used as a context manager to make this simpler with gstaudiofile something mp3 as f for block in f iterating a gstaudiofile yields strings containing short integer pcm data you can also read the sample rate and channel count from the file with gstaudiofile something mp3 as f print f samplerate print f channels print f duration exceptions raised when gstreamer can t decode the given file type def initself streaminfo super init can t decode stream streaminfo self streaminfo streaminfo class filereaderrorgstreamererror raised when the file was read successfully but no audio streams were found raised when gstreamer fails to report stream metadata duration channels or sample rate raised when necessary components of gstreamer namely the principal plugin packages are missing managing the gobject main loop thread get the shared mainloop thread start a new thread a daemon thread encapsulating a gobject main loop the decoder reads raw audio data from any audio file that gstreamer knows how to decode with gstaudiofile something mp3 as f print f samplerate print f channels print f duration for block in f dosomethingblock iterating the object yields blocks of 16bit pcm data three pieces of stream information are also available samplerate in hz number of channels and duration in seconds it s very important that the client call close when it s done with the object otherwise the program is likely to hang on exit alternatively of course one can just use the file as a context manager as shown above set up the gstreamer pipeline uridecodebin audioconvert or appsink is missing we need gstpluginsbase register for bus signals configure the input the callback to connect the input and a callback if decoding fails configure the output we want short integer data todo set endianness set up the characteristics of the output we don t want to drop any data nothing is realtime here we should bound the memory usage of the internal queue and most importantly setting sync to false disables the default behavior in which you consume buffers in real time this way we get data as soon as it s decoded the callback to receive decoded data we ll need to know when the stream becomes ready and we get its attributes this semaphore will become available when the caps are received that way when init returns the file and its attributes will be ready for reading link up everything but the decoder which must be linked only when it becomes ready set up the queue for data and run the main thread this wil get filled with an exception if opening fails return as soon as the stream is ready an error occurred before the stream became ready gstreamer callbacks the callback for the sinkpad s notify caps signal the sink has started to receive data so the stream is ready this also is our opportunity to read information about the stream stream attributes query duration allow constructor to complete the callback for gstelement s padadded signal decoded data is ready connect up the decoder finally the callback for gstelement s nomorepads signal sent when the pads are done adding i e there are no more streams in the file if we haven t gotten at least one decodable stream raise an exception the callback for appsink s newsample signal new data is available from the pipeline dump it into our queue or possibly block if we re full we can t use gst buffer extract to read the data as it crashes when called through pygobject we also can t use gst buffer extractdup because we have no way in python to free the memory that it returns instead we get access to the actual data via gst memory map we need to copy the data as the memoryview is released when we call mem unmap gstreamer python bindings 1 16 return a copy of the data as bytes the callback for decodebin s unknowntype signal this is called before the stream becomes ready when the file can t be read ignore nonaudio e g video decode errors the callback for gstbus s message signal for two kinds of messages the file is done tell the consumer thread if the stream ends before notifycaps was called this is an invalid file iteration wait for data from the gstreamer callbacks end of stream cleanup close the file and clean up associated resources calling close a second time has no effect unregister for signals which we registered for above with addsignalwatch without this gstreamer leaks file descriptors stop reading the file block spurious signals make space in the output queue to let the decoder thread finish otherwise the thread blocks on its enqueue and the interpreter hangs halt the pipeline closing file context manager smoke test this file is part of audioread 2011 adrian sampson permission is hereby granted free of charge to any person obtaining a copy of this software and associated documentation files the software to deal in the software without restriction including without limitation the rights to use copy modify merge publish distribute sublicense and or sell copies of the software and to permit persons to whom the software is furnished to do so subject to the following conditions the above notice and this permission notice shall be included in all copies or substantial portions of the software use gstreamer to decode audio files to read an audio file pass it to the constructor for gstaudiofile and then iterate over the contents f gstaudiofile something mp3 try for block in f finally f close note that there are a few complications caused by gstreamer s asynchronous architecture this module spawns its own gobject main loop thread i m not sure how that will interact with other main loops if your program has them also in order to stop the thread and terminate your program normally you need to call the close method on every gstaudiofile you create conveniently the file can be used as a context manager to make this simpler with gstaudiofile something mp3 as f for block in f iterating a gstaudiofile yields strings containing short integer pcm data you can also read the sample rate and channel count from the file with gstaudiofile something mp3 as f print f samplerate print f channels print f duration exceptions raised when gstreamer can t decode the given file type raised when the file can t be read at all raised when the file was read successfully but no audio streams were found raised when gstreamer fails to report stream metadata duration channels or sample rate raised when necessary components of gstreamer namely the principal plugin packages are missing managing the gobject main loop thread get the shared main loop thread start a new thread a daemon thread encapsulating a gobject main loop the decoder reads raw audio data from any audio file that gstreamer knows how to decode with gstaudiofile something mp3 as f print f samplerate print f channels print f duration for block in f do_something block iterating the object yields blocks of 16 bit pcm data three pieces of stream information are also available samplerate in hz number of channels and duration in seconds it s very important that the client call close when it s done with the object otherwise the program is likely to hang on exit alternatively of course one can just use the file as a context manager as shown above set up the gstreamer pipeline uridecodebin audioconvert or appsink is missing we need gst plugins base register for bus signals configure the input the callback to connect the input and a callback if decoding fails configure the output we want short integer data todo set endianness set up the characteristics of the output we don t want to drop any data nothing is real time here we should bound the memory usage of the internal queue and most importantly setting sync to false disables the default behavior in which you consume buffers in real time this way we get data as soon as it s decoded the callback to receive decoded data we ll need to know when the stream becomes ready and we get its attributes this semaphore will become available when the caps are received that way when __init__ returns the file and its attributes will be ready for reading link up everything but the decoder which must be linked only when it becomes ready set up the queue for data and run the main thread this wil get filled with an exception if opening fails return as soon as the stream is ready an error occurred before the stream became ready gstreamer callbacks the callback for the sinkpad s notify caps signal the sink has started to receive data so the stream is ready this also is our opportunity to read information about the stream stream attributes query duration allow constructor to complete the callback for gstelement s pad added signal decoded data is ready connect up the decoder finally the callback for gstelement s no more pads signal sent when the pads are done adding i e there are no more streams in the file if we haven t gotten at least one decodable stream raise an exception no effect if we ve already started the callback for appsink s new sample signal new data is available from the pipeline dump it into our queue or possibly block if we re full we can t use gst buffer extract to read the data as it crashes when called through pygobject we also can t use gst buffer extract_dup because we have no way in python to free the memory that it returns instead we get access to the actual data via gst memory map we need to copy the data as the memoryview is released when we call mem unmap gstreamer python bindings 1 16 return a copy of the data as bytes the callback for decodebin s unknown type signal this is called before the stream becomes ready when the file can t be read ignore non audio e g video decode errors the callback for gstbus s message signal for two kinds of messages the file is done tell the consumer thread if the stream ends before _notify_caps was called this is an invalid file iteration wait for data from the gstreamer callbacks end of stream cleanup close the file and clean up associated resources calling close a second time has no effect unregister for signals which we registered for above with add_signal_watch without this gstreamer leaks file descriptors stop reading the file block spurious signals make space in the output queue to let the decoder thread finish otherwise the thread blocks on its enqueue and the interpreter hangs halt the pipeline closing file context manager smoke test
import gi
gi.require_version('Gst', '1.0')
from gi.repository import GLib, Gst

import sys
import threading
import os
import queue
from urllib.parse import quote

from .exceptions import DecodeError
from .base import AudioFile

QUEUE_SIZE = 10
BUFFER_SIZE = 10
SENTINEL = '__GSTDEC_SENTINEL__'




class GStreamerError(DecodeError):
    pass


class UnknownTypeError(GStreamerError):
    
    def __init__(self, streaminfo):
        super().__init__(
            "can't decode stream: " + streaminfo
        )
        self.streaminfo = streaminfo


class FileReadError(GStreamerError):
    
    pass


class NoStreamError(GStreamerError):
    
    def __init__(self):
        super().__init__('no audio streams found')


class MetadataMissingError(GStreamerError):
    
    pass


class IncompleteGStreamerError(GStreamerError):
    
    def __init__(self):
        super().__init__(
            'missing GStreamer base plugins'
        )




_shared_loop_thread = None
_loop_thread_lock = threading.RLock()

Gst.init(None)

def get_loop_thread():
    
    global _shared_loop_thread
    with _loop_thread_lock:
        if not _shared_loop_thread:
            
            _shared_loop_thread = MainLoopThread()
            _shared_loop_thread.start()
        return _shared_loop_thread


class MainLoopThread(threading.Thread):
    
    def __init__(self):
        super().__init__()
        self.loop = GLib.MainLoop.new(None, False)
        self.daemon = True

    def run(self):
        self.loop.run()




class GstAudioFile(AudioFile):
    
    def __init__(self, path):
        self.running = False
        self.finished = False

        
        self.pipeline = Gst.Pipeline()

        self.dec = Gst.ElementFactory.make("uridecodebin", None)
        self.conv = Gst.ElementFactory.make("audioconvert", None)
        self.sink = Gst.ElementFactory.make("appsink", None)

        if self.dec is None or self.conv is None or self.sink is None:
            
            
            raise IncompleteGStreamerError()

        
        bus = self.pipeline.get_bus()
        bus.add_signal_watch()
        bus.connect("message::eos", self._message)
        bus.connect("message::error", self._message)

        
        uri = 'file://' + quote(os.path.abspath(path))
        self.dec.set_property("uri", uri)
        
        self.dec.connect("pad-added", self._pad_added)
        self.dec.connect("no-more-pads", self._no_more_pads)
        
        self.dec.connect("unknown-type", self._unkown_type)

        
        
        self.sink.set_property(
            'caps',
            Gst.Caps.from_string('audio/x-raw, format=(string)S16LE'),
        )
        
        
        
        
        
        
        
        self.sink.set_property('drop', False)
        self.sink.set_property('max-buffers', BUFFER_SIZE)
        self.sink.set_property('sync', False)
        
        self.sink.set_property('emit-signals', True)
        self.sink.connect("new-sample", self._new_sample)

        
        
        
        
        self.ready_sem = threading.Semaphore(0)
        self.caps_handler = self.sink.get_static_pad("sink").connect(
            "notify::caps", self._notify_caps
        )

        
        
        self.pipeline.add(self.dec)
        self.pipeline.add(self.conv)
        self.pipeline.add(self.sink)

        self.conv.link(self.sink)

        
        self.queue = queue.Queue(QUEUE_SIZE)
        self.thread = get_loop_thread()

        
        self.read_exc = None

        
        self.running = True
        self.got_caps = False
        self.pipeline.set_state(Gst.State.PLAYING)
        self.ready_sem.acquire()
        if self.read_exc:
            
            self.close(True)
            raise self.read_exc

    

    def _notify_caps(self, pad, args):
        
        
        
        
        self.got_caps = True
        info = pad.get_current_caps().get_structure(0)

        
        self.channels = info.get_int('channels')[1]
        self.samplerate = info.get_int('rate')[1]

        
        success, length = pad.get_peer().query_duration(Gst.Format.TIME)
        if success:
            self.duration = length / 1000000000
        else:
            self.read_exc = MetadataMissingError('duration not available')

        
        self.ready_sem.release()

    _got_a_pad = False

    def _pad_added(self, element, pad):
        
        
        name = pad.query_caps(None).to_string()
        if name.startswith('audio/x-raw'):
            nextpad = self.conv.get_static_pad('sink')
            if not nextpad.is_linked():
                self._got_a_pad = True
                pad.link(nextpad)

    def _no_more_pads(self, element):
        
        
        
        
        if not self._got_a_pad:
            self.read_exc = NoStreamError()
            self.ready_sem.release()  

    def _new_sample(self, sink):
        
        if self.running:
            
            
            buf = sink.emit('pull-sample').get_buffer()

            
            
            
            
            
            mem = buf.get_all_memory()
            success, info = mem.map(Gst.MapFlags.READ)
            if success:
                if isinstance(info.data, memoryview):
                    
                    
                    data = bytes(info.data)
                else:
                    
                    
                    data = info.data
                mem.unmap(info)
                self.queue.put(data)
            else:
                raise GStreamerError("Unable to map buffer memory while reading the file.")
        return Gst.FlowReturn.OK

    def _unkown_type(self, uridecodebin, decodebin, caps):
        
        
        
        streaminfo = caps.to_string()
        if not streaminfo.startswith('audio/'):
            
            return
        self.read_exc = UnknownTypeError(streaminfo)
        self.ready_sem.release()

    def _message(self, bus, message):
        
        if not self.finished:
            if message.type == Gst.MessageType.EOS:
                
                self.queue.put(SENTINEL)
                if not self.got_caps:
                    
                    
                    self.read_exc = NoStreamError()
                    self.ready_sem.release()

            elif message.type == Gst.MessageType.ERROR:
                gerror, debug = message.parse_error()
                if 'not-linked' in debug:
                    self.read_exc = NoStreamError()
                elif 'No such file' in debug:
                    self.read_exc = IOError('resource not found')
                else:
                    self.read_exc = FileReadError(debug)
                self.ready_sem.release()

    

    def __next__(self):
        
        val = self.queue.get()
        if val == SENTINEL:
            
            raise StopIteration
        return val

    def __iter__(self):
        return self

    
    def close(self, force=False):
        
        if self.running or force:
            self.running = False
            self.finished = True

            
            
            
            self.pipeline.get_bus().remove_signal_watch()

            
            self.dec.set_property("uri", None)
            
            self.sink.get_static_pad("sink").disconnect(self.caps_handler)

            
            
            
            try:
                self.queue.get_nowait()
            except queue.Empty:
                pass

            
            self.pipeline.set_state(Gst.State.NULL)

    def __del__(self):
        self.close()

    
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()
        return False



if __name__ == '__main__':
    for path in sys.argv[1:]:
        path = os.path.abspath(os.path.expanduser(path))
        with GstAudioFile(path) as f:
            print(f.channels)
            print(f.samplerate)
            print(f.duration)
            for s in f:
                print(len(s), ord(s[0]))