pymad-0.10/0000755000175000017500000000000013142523311012107 5ustar jaqjaq00000000000000pymad-0.10/src/0000755000175000017500000000000013142523311012676 5ustar jaqjaq00000000000000pymad-0.10/src/pymadfile.h0000644000175000017500000000354112640643732015040 0ustar jaqjaq00000000000000/* $Id: pymadfile.h,v 1.5 2003/01/11 13:15:39 jaq Exp $ * * python interface to libmad (the mpeg audio decoder library) * * Copyright (c) 2002 Jamie Wilkinson * * This program is free software, you may copy and/or modify as per * the GNU General Public License version 2. */ #ifndef __PY_MADFILE_H__ #define __PY_MADFILE_H__ #include #include /* The definition of the MadFile python object. */ typedef struct { PyObject_HEAD PyObject *fobject; int close_file; struct mad_stream stream; struct mad_frame frame; struct mad_synth synth; mad_timer_t timer; unsigned char *input_buffer; unsigned int bufsize; unsigned int framecount; unsigned long total_length; } py_madfile; /* MadFile */ /* Macros for accessing elements of the MadFile object, used internally. */ #define PY_MADFILE(x) ((py_madfile *)x) #define PYMAD_STREAM(x) (PY_MADFILE(x)->stream) #define PYMAD_FRAME(x) (PY_MADFILE(x)->frame) #define PYMAD_SYNTH(x) (PY_MADFILE(x)->synth) #define PYMAD_BUFFER(x) (PY_MADFILE(x)->input_buffer) #define PYMAD_BUFSIZE(x) (PY_MADFILE(x)->bufsize) #define PYMAD_TIMER(x) (PY_MADFILE(x)->timer) /* Exported methods. */ static void py_madfile_dealloc(PyObject *self, PyObject *args); static PyObject *py_madfile_read(PyObject *self, PyObject *args); static PyObject *py_madfile_layer(PyObject *self, PyObject *args); static PyObject *py_madfile_mode(PyObject *self, PyObject *args); static PyObject *py_madfile_samplerate(PyObject *self, PyObject *args); static PyObject *py_madfile_bitrate(PyObject *self, PyObject *args); static PyObject *py_madfile_emphasis(PyObject *self, PyObject *args); static PyObject *py_madfile_total_time(PyObject *self, PyObject *args); static PyObject *py_madfile_current_time(PyObject *self, PyObject *args); static PyObject *py_madfile_seek_time(PyObject *self, PyObject *args); #endif /* __PY_MADFILE_H__ */ pymad-0.10/src/xing.c0000644000175000017500000000375112475221717014032 0ustar jaqjaq00000000000000/* * mad - MPEG audio decoder * Copyright (C) 2000-2001 Robert Leslie * * This program 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; either version 2 of the License, or * (at your option) any later version. * * This program 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 this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * $Id: xing.c,v 1.1 2003/01/11 13:16:08 jaq Exp $ */ #include "xing.h" #include "mad.h" #define XING_MAGIC (('X' << 24) | ('i' << 16) | ('n' << 8) | 'g') /* * NAME: xing->init() * DESCRIPTION: initialize Xing structure */ void xing_init(struct xing *xing) { xing->flags = 0; } /* * NAME: xing->parse() * DESCRIPTION: parse a Xing VBR header */ int xing_parse(struct xing *xing, struct mad_bitptr ptr, unsigned int bitlen) { if (bitlen < 64 || mad_bit_read(&ptr, 32) != XING_MAGIC) goto fail; xing->flags = mad_bit_read(&ptr, 32); bitlen -= 64; if (xing->flags & XING_FRAMES) { if (bitlen < 32) goto fail; xing->frames = mad_bit_read(&ptr, 32); bitlen -= 32; } if (xing->flags & XING_BYTES) { if (bitlen < 32) goto fail; xing->bytes = mad_bit_read(&ptr, 32); bitlen -= 32; } if (xing->flags & XING_TOC) { int i; if (bitlen < 800) goto fail; for (i = 0; i < 100; ++i) xing->toc[i] = mad_bit_read(&ptr, 8); bitlen -= 800; } if (xing->flags & XING_SCALE) { if (bitlen < 32) goto fail; xing->scale = mad_bit_read(&ptr, 32); bitlen -= 32; } return 0; fail: xing->flags = 0; return -1; } pymad-0.10/src/madmodule.c0000644000175000017500000000411312640643732015024 0ustar jaqjaq00000000000000/* $Id: madmodule.c,v 1.4 2002/08/18 06:21:48 jaq Exp $ * * python interface to libmad (the mpeg audio decoder library) * * Copyright (c) 2002 Jamie Wilkinson * * This program is free software, you may copy and/or modify as per * the GNU General Public License version 2. */ #include #include "madmodule.h" #if PY_MAJOR_VERSION >= 3 #define MOD_DEF(ob, name, doc, methods) \ static struct PyModuleDef moduledef = { \ PyModuleDef_HEAD_INIT, name, doc, -1, methods, \ }; \ ob = PyModule_Create(&moduledef); #else #define MOD_DEF(ob, name, doc, methods) ob = Py_InitModule3(name, methods, doc); #endif static PyMethodDef mad_methods[] = { {"MadFile", py_madfile_new, METH_VARARGS, ""}, {NULL, 0, 0, NULL}}; /* this handy tool for passing C constants to Python-land from * http://starship.python.net/crew/arcege/extwriting/pyext.html */ #if PY_MAJOR_VERSION >= 3 #define PY_CONST(x) PyDict_SetItemString(dict, #x, PyLong_FromLong(MAD_##x)) #else #define PY_CONST(x) PyDict_SetItemString(dict, #x, PyInt_FromLong(MAD_##x)) #endif extern PyTypeObject py_madfile_t; static PyObject *moduleinit(void) { PyObject *module, *dict; if (PyType_Ready(&py_madfile_t) < 0) return NULL; MOD_DEF(module, "mad", "", mad_methods); dict = PyModule_GetDict(module); PyDict_SetItemString(dict, "__version__", PyUnicode_FromString(VERSION)); /* layer */ PY_CONST(LAYER_I); PY_CONST(LAYER_II); PY_CONST(LAYER_III); /* mode */ PY_CONST(MODE_SINGLE_CHANNEL); PY_CONST(MODE_DUAL_CHANNEL); PY_CONST(MODE_JOINT_STEREO); PY_CONST(MODE_STEREO); /* emphasis */ PY_CONST(EMPHASIS_NONE); PY_CONST(EMPHASIS_50_15_US); PY_CONST(EMPHASIS_CCITT_J_17); if (PyErr_Occurred()) PyErr_SetString(PyExc_ImportError, "mad: init failed"); return module; } #if PY_MAJOR_VERSION < 3 PyMODINIT_FUNC initmad(void) { moduleinit(); } #else PyMODINIT_FUNC PyInit_mad(void) { return moduleinit(); } #endif pymad-0.10/src/madmodule.h0000644000175000017500000000072412640643732015035 0ustar jaqjaq00000000000000/* $Id: madmodule.h,v 1.1 2002/06/17 01:16:56 jaq Exp $ * * python interface to libmad (the mpeg audio decoder library) * * Copyright (c) 2002 Jamie Wilkinson * * This program is free software, you may copy and/or modify as per * the GNU General Public License version 2. */ #ifndef __MADMODULE_H__ #define __MADMODULE_H__ #include /* module accessible functions */ PyObject *py_madfile_new(PyObject *, PyObject *); #endif /* __MADMODULE_H__ */ pymad-0.10/src/pymadfile.c0000644000175000017500000005235413142523216015031 0ustar jaqjaq00000000000000/* $Id: pymadfile.c,v 1.20 2003/02/05 06:29:23 jaq Exp $ * * python interface to libmad (the mpeg audio decoder library) * * Copyright (c) 2002 Jamie Wilkinson * * This program is free software, you may copy and/or modify as per * the GNU General Public License version 2. * * The code in py_madfile_read was copied from the madlld program, which * can be found at http://www.bsd-dk.dk/~elrond/audio/madlld/ and carries * the following copyright and license: * * The madlld program is © 2001 by Bertrand Petit, all rights reserved. * It is distributed under the terms of the license similar to the * Berkeley license reproduced below. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. Neither the name of the author nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #include #include #include #include #include #include #include #include #include "madmodule.h" #include "pymadfile.h" #include "xing.h" #if PY_VERSION_HEX < 0x01060000 #define PyObject_DEL(op) PyMem_DEL((op)) #endif #ifndef PyVarObject_HEAD_INIT #define PyVarObject_HEAD_INIT(type, size) PyObject_HEAD_INIT(type) size, #endif #if PY_MAJOR_VERSION >= 3 #define MADFILE_GETATTR 0 #define PyInt_FromLong PyLong_FromLong #define PyInt_AsLong PyLong_AsLong #else #define MADFILE_GETATTR (getattrfunc) py_madfile_getattr #define PyBytes_AsStringAndSize PyString_AsStringAndSize #endif #define ERROR_MSG_SIZE 512 #define MAD_BUF_SIZE \ (5 * 8192) /* should be a multiple of 4 >= 4096 and large enough to capture \ possible \ junk at beginning of MP3 file*/ /* local helpers */ static unsigned long calc_total_time(PyObject *); static int16_t madfixed_to_int16(mad_fixed_t); static PyMethodDef madfile_methods[] = { {"read", py_madfile_read, METH_VARARGS, ""}, {"layer", py_madfile_layer, METH_VARARGS, ""}, {"mode", py_madfile_mode, METH_VARARGS, ""}, {"samplerate", py_madfile_samplerate, METH_VARARGS, ""}, {"bitrate", py_madfile_bitrate, METH_VARARGS, ""}, {"emphasis", py_madfile_emphasis, METH_VARARGS, ""}, {"total_time", py_madfile_total_time, METH_VARARGS, ""}, {"current_time", py_madfile_current_time, METH_VARARGS, ""}, {"seek_time", py_madfile_seek_time, METH_VARARGS, ""}, {NULL, 0, 0, NULL}}; PyTypeObject py_madfile_t = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "MadFile", /* tp_name */ sizeof(py_madfile), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)py_madfile_dealloc, /* tp_dealloc */ 0, /* (tp_print) */ 0, /* (tp_getattr) */ 0, /* (tp_setattr) */ 0, /* (tp_reserved) [was tp_compare] */ 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 */ 0, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ madfile_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0, /* tp_free */ 0, /* tp_is_gc */ 0, /* tp_bases */ 0, /* tp_mro */ 0, /* tp_cache */ 0, /* tp_subclasses */ 0, /* tp_weaklist */ 0, /* tp_del */ 0, /* tp_version_tag */ }; /* functions */ PyObject *py_madfile_new(PyObject *self, PyObject *args) { py_madfile *mf = NULL; int close_file = 0; #if PY_MAJOR_VERSION >= 3 int fd; #endif char *fname; PyObject *fobject = NULL; char *initial; long ibytes = 0; unsigned long int bufsize = MAD_BUF_SIZE; int n; if (PyArg_ParseTuple(args, "s|l:MadFile", &fname, &bufsize)) { #if PY_MAJOR_VERSION < 3 fobject = PyFile_FromString(fname, "r"); #else if ((fd = open(fname, O_RDONLY)) < 0) { return NULL; } fobject = PyFile_FromFd(fd, fname, "r", -1, NULL, NULL, NULL, 1); #endif close_file = 1; if (fobject == NULL) { return NULL; } } else if (PyArg_ParseTuple(args, "O|sl:MadFile", &fobject, &initial, &ibytes)) { /* clear the first failure */ PyErr_Clear(); /* make sure that if nothing else we can read it */ if (!PyObject_HasAttrString(fobject, "read")) { Py_DECREF(fobject); PyErr_SetString(PyExc_IOError, "Object must have a read method"); return NULL; } } else return NULL; /* bufsize must be an integer multiple of 4 */ if ((n = bufsize % 4)) bufsize -= n; if (bufsize <= 4096) bufsize = 4096; mf = PyObject_NEW(py_madfile, &py_madfile_t); Py_INCREF(fobject); mf->fobject = fobject; mf->close_file = close_file; /* initialise the mad structs */ mad_stream_init(&PYMAD_STREAM(mf)); mad_frame_init(&PYMAD_FRAME(mf)); mad_synth_init(&PYMAD_SYNTH(mf)); mad_timer_reset(&PYMAD_TIMER(mf)); mf->framecount = 0; mf->input_buffer = malloc(bufsize * sizeof(unsigned char)); mf->bufsize = bufsize; /* explicitly call read to fill the buffer and have the frame header * data immediately available to the caller */ py_madfile_read((PyObject *)mf, NULL); mf->total_length = calc_total_time((PyObject *)mf); return (PyObject *)mf; } static void py_madfile_dealloc(PyObject *self, PyObject *args) { PyObject *o; if (PY_MADFILE(self)->fobject) { mad_synth_finish(&PYMAD_SYNTH(self)); mad_frame_finish(&PYMAD_FRAME(self)); mad_stream_finish(&PYMAD_STREAM(self)); free(PYMAD_BUFFER(self)); PYMAD_BUFFER(self) = NULL; PYMAD_BUFSIZE(self) = 0; if (PY_MADFILE(self)->close_file) { o = PyObject_CallMethod(PY_MADFILE(self)->fobject, "close", NULL); if (o != NULL) { Py_DECREF(o); } } Py_DECREF(PY_MADFILE(self)->fobject); PY_MADFILE(self)->fobject = NULL; } PyObject_DEL(self); } /* Calculates length of MP3 by stepping through the frames and summing up * the duration of each frame. */ static unsigned long calc_total_time(PyObject *self) { mad_timer_t timer; struct xing xing; struct stat buf; unsigned long r; PyObject *o; int fnum; xing_init(&xing); xing_parse(&xing, PYMAD_STREAM(self).anc_ptr, PYMAD_STREAM(self).anc_bitlen); if (xing.flags & XING_FRAMES) { timer = PYMAD_FRAME(self).header.duration; mad_timer_multiply(&timer, xing.frames); r = mad_timer_count(timer, MAD_UNITS_MILLISECONDS); } else { o = PyObject_CallMethod(PY_MADFILE(self)->fobject, "fileno", NULL); if (o == NULL) { /* no fileno method is provided, probably not a file */ PyErr_Clear(); return -1; } fnum = PyInt_AsLong(o); Py_DECREF(o); r = fstat(fnum, &buf); /* Figure out actual length of file by stepping through it. * This is a stripped down version of how madplay does it. */ void *ptr = mmap(0, buf.st_size, PROT_READ, MAP_SHARED, fnum, 0); if (!ptr) { fprintf(stderr, "mmap failed, can't calculate length"); return -1; } mad_timer_t time = mad_timer_zero; struct mad_stream stream; struct mad_header header; mad_stream_init(&stream); mad_header_init(&header); mad_stream_buffer(&stream, ptr, buf.st_size); while (1) { if (mad_header_decode(&header, &stream) == -1) { if (MAD_RECOVERABLE(stream.error)) continue; else break; } mad_timer_add(&time, header.duration); } if (munmap(ptr, buf.st_size) == -1) { return -1; } r = time.seconds * 1000; } return r; } /* convert the MAD fixed point format to a signed 16 bit int */ static int16_t madfixed_to_int16(mad_fixed_t sample) { /* A fixed point number is formed of the following bit pattern: * * SWWWFFFFFFFFFFFFFFFFFFFFFFFFFFFF * MSB LSB * S = sign * W = whole part bits * F = fractional part bits * * This pattern contains MAD_F_FRACBITS fractional bits, one should * always use this macro when working on the bits of a fixed point * number. It is not guaranteed to be constant over the different * platforms supported by libmad. * * The int16_t value is formed by the least significant * whole part bit, followed by the 15 most significant fractional * part bits. * * This algorithm was taken from input/mad/mad_engine.c in alsaplayer, * which scales and rounds samples to 16 bits, unlike the version in * madlld. */ /* round */ sample += (1L << (MAD_F_FRACBITS - 16)); /* clip */ if (sample >= MAD_F_ONE) sample = MAD_F_ONE - 1; else if (sample < -MAD_F_ONE) sample = -MAD_F_ONE; /* quantize */ return sample >> (MAD_F_FRACBITS + 1 - 16); } static PyObject *py_madfile_read(PyObject *self, PyObject *args) { PyObject *pybuf; /* return object containing output buffer*/ int16_t *output_buffer = NULL; /* output buffer */ int16_t *output = NULL; unsigned int i; Py_ssize_t size; int nextframe = 0; int result; char errmsg[ERROR_MSG_SIZE]; /* if we are at EOF, then return None */ // FIXME: move to if null read /* if (feof(PY_MADFILE(self)->f)) { Py_INCREF(Py_None); return Py_None; } */ /* nextframe might get set during this loop, in which case the * bucket needs to be refilled */ do { nextframe = 0; /* reset */ /* The input bucket must be filled if it becomes empty or if * it's the first execution on this file */ if ((PYMAD_STREAM(self).buffer == NULL) || (PYMAD_STREAM(self).error == MAD_ERROR_BUFLEN)) { Py_ssize_t readsize, remaining; unsigned char *readstart; PyObject *o_read; char *o_buffer; /* [1] libmad may not consume all bytes of the input buffer. * If the last frame in the buffer is not wholly contained * by it, then that frame's start is pointed to by the * next_frame member of the mad_stream structure. This * common situation occurs when mad_frame_decode(): * 1) fails, * 2) sets the stream error to MAD_ERROR_BUFLEN, and * 3) sets the next_frame pointer to a non NULL value. * (See also the comment marked [2] below) * * When this occurs, the remaining unused bytes must be put * back at the beginning of the buffer and taken into * account before refilling the buffer. This means that * the input buffer must be large enough to hold a whole * frame at the highest observable bitrate (currently * 448kbps). */ if (PYMAD_STREAM(self).next_frame != NULL) { remaining = PYMAD_STREAM(self).bufend - PYMAD_STREAM(self).next_frame; memmove(PYMAD_BUFFER(self), PYMAD_STREAM(self).next_frame, remaining); readstart = PYMAD_BUFFER(self) + remaining; readsize = PYMAD_BUFSIZE(self) - remaining; } else readstart = PYMAD_BUFFER(self), readsize = PYMAD_BUFSIZE(self), remaining = 0; /* Fill in the buffer. If an error occurs, make like a tree */ o_read = PyObject_CallMethod(PY_MADFILE(self)->fobject, "read", "i", readsize); if (o_read == NULL) { // FIXME: should specifically handle read errors... Py_INCREF(Py_None); return Py_None; } PyBytes_AsStringAndSize(o_read, &o_buffer, &readsize); // EOF? if (readsize == 0) { Py_DECREF(o_read); Py_INCREF(Py_None); return Py_None; } memcpy(readstart, o_buffer, readsize); Py_DECREF(o_read); /* Pipe the new buffer content to libmad's stream decode * facility */ mad_stream_buffer(&PYMAD_STREAM(self), PYMAD_BUFFER(self), readsize + remaining); PYMAD_STREAM(self).error = 0; } /* Decode the next mpeg frame. The streams are read from the * buffer, its constituents are broken down and stored in the * frame structure, ready for examination/alteration or PCM * synthesis. Decoding options are carried to the Frame from * the Stream. * * Error handling: mad_frame_decode() returns a non-zero value * when an error occurs. The error condition can be checked in * the error member of the Stream structure. A mad error is * recoverable or fatal, the error status is checked with the * MAD_RECOVERABLE macro. * * [2] When a fatal error is encountered, all decoding activities * shall be stopped, except when a MAD_ERROR_BUFLEN is * signalled. This condition means that the * mad_frame_decode() function needs more input do its work. * One should refill the buffer and repeat the * mad_frame_decode() call. Some bytes may be left unused * at the end of the buffer if those bytes form an incomplete * frame. Before refilling, the remaining bytes must be * moved to the beginning of the buffer and used for input * for the next mad_frame_decode() invocation. (See the * comment marked [1] for earlier details) * * Recoverable errors are caused by malformed bitstreams, in * this case one can call again mad_frame_decode() in order to * skip the faulty part and resync to the next frame. */ Py_BEGIN_ALLOW_THREADS; result = mad_frame_decode(&PYMAD_FRAME(self), &PYMAD_STREAM(self)); Py_END_ALLOW_THREADS; if (result) { if (MAD_RECOVERABLE(PYMAD_STREAM(self).error)) { /* FIXME: prefer to return an error string to the caller * rather than print to stderr fprintf(stderr, "mad: recoverable frame level error: %s\n", mad_stream_errorstr(&PYMAD_STREAM(self))); fflush(stderr); */ /* go onto the next frame */ nextframe = 1; } else { if (PYMAD_STREAM(self).error == MAD_ERROR_BUFLEN) { /* not enough data to decode */ nextframe = 1; } else { snprintf(errmsg, ERROR_MSG_SIZE, "unrecoverable frame level error: %s", mad_stream_errorstr(&PYMAD_STREAM(self))); PyErr_SetString(PyExc_RuntimeError, errmsg); return NULL; } } } } while (nextframe); Py_BEGIN_ALLOW_THREADS; /* Accounting. The computed frame duration is in the frame header * structure. It is expressed as a fixed point number whose data * type is mad_timer_t. It is different from the fixed point * format of the samples and unlike it, cannot be directly added * or subtracted. The timer module provides several functions to * operate on such numbers. Be careful though, as some functions * of mad's timer module receive their mad_timer_t arguments by * value! */ PY_MADFILE(self)->framecount++; mad_timer_add(&PYMAD_TIMER(self), PYMAD_FRAME(self).header.duration); /* Once decoded, the frame can be synthesised to PCM samples. * No errors are reported by mad_synth_frame() */ mad_synth_frame(&PYMAD_SYNTH(self), &PYMAD_FRAME(self)); Py_END_ALLOW_THREADS; /* Create the buffer to store the PCM samples in, so python can * use it. We do 2 pointer increments per sample in the buffer, * so make it 2 times as big as the number of samples */ size = PYMAD_SYNTH(self).pcm.length * 2 * sizeof(int16_t); output = output_buffer = malloc(size); if (!output_buffer) { PyErr_SetString(PyExc_MemoryError, "could not allocate memory for output buffer"); return NULL; } /* die if we don't have the space */ if (size < PYMAD_SYNTH(self).pcm.length * 4) { PyErr_SetString(PyExc_MemoryError, "allocated buffer too small"); return NULL; } Py_BEGIN_ALLOW_THREADS; /* Synthesised samples must be converted from mad's fixed point format to the * consumer format -- use signed 16 bit big-endian ints on two channels. * Integer samples are temporarily stored in a buffer that is flushed when * full. */ for (i = 0; i < PYMAD_SYNTH(self).pcm.length; i++) { int16_t sample; /* left channel */ *(output++) = sample = madfixed_to_int16(PYMAD_SYNTH(self).pcm.samples[0][i]); /* right channel. * if the decoded stream is monophonic then the right channel * is the same as the left one */ if (MAD_NCHANNELS(&PYMAD_FRAME(self).header) == 2) sample = madfixed_to_int16(PYMAD_SYNTH(self).pcm.samples[1][i]); *(output++) = sample; } Py_END_ALLOW_THREADS; pybuf = PyByteArray_FromStringAndSize((const char *)output_buffer, size); free(output_buffer); return pybuf; } /* return the MPEG layer */ static PyObject *py_madfile_layer(PyObject *self, PyObject *args) { return PyInt_FromLong(PYMAD_FRAME(self).header.layer); } /* return the channel mode */ static PyObject *py_madfile_mode(PyObject *self, PyObject *args) { return PyInt_FromLong(PYMAD_FRAME(self).header.mode); } /* return the stream samplerate */ static PyObject *py_madfile_samplerate(PyObject *self, PyObject *args) { return PyInt_FromLong(PYMAD_FRAME(self).header.samplerate); } /* return the stream bitrate */ static PyObject *py_madfile_bitrate(PyObject *self, PyObject *args) { return PyInt_FromLong(PYMAD_FRAME(self).header.bitrate); } /* return the emphasis value */ static PyObject *py_madfile_emphasis(PyObject *self, PyObject *args) { return PyInt_FromLong(PYMAD_FRAME(self).header.emphasis); } /* return the estimated playtime of the track, in milliseconds */ static PyObject *py_madfile_total_time(PyObject *self, PyObject *args) { return PyInt_FromLong(PY_MADFILE(self)->total_length); } /* return the current position in the track, in milliseconds */ static PyObject *py_madfile_current_time(PyObject *self, PyObject *args) { return PyInt_FromLong( mad_timer_count(PYMAD_TIMER(self), MAD_UNITS_MILLISECONDS)); } /* seek playback to the given position, in milliseconds, from the start * FIXME: this implementation is really evil -- amazing that it semi-works */ static PyObject *py_madfile_seek_time(PyObject *self, PyObject *args) { long pos, offset; struct stat buf; int r; PyObject *o; int fnum; if (!PyArg_ParseTuple(args, "l", &pos) || pos < 0) { PyErr_SetString(PyExc_TypeError, "invalid argument"); return NULL; } o = PyObject_CallMethod(PY_MADFILE(self)->fobject, "fileno", NULL); if (o == NULL) { PyErr_SetString(PyExc_IOError, "couldn't get fileno"); return NULL; } fnum = PyInt_AsLong(o); Py_DECREF(o); r = fstat(fnum, &buf); if (r != 0) { PyErr_SetString(PyExc_IOError, "couldn't stat file"); return NULL; } offset = ((double)pos / PY_MADFILE(self)->total_length) * buf.st_size; o = PyObject_CallMethod(PY_MADFILE(self)->fobject, "seek", "l", offset); if (o == NULL) { /* most likely no seek method -- FIXME get better checking */ PyErr_SetString(PyExc_IOError, "couldn't seek file"); return NULL; } Py_DECREF(o); mad_stream_init(&PYMAD_STREAM(self)); mad_frame_init(&PYMAD_FRAME(self)); mad_synth_init(&PYMAD_SYNTH(self)); mad_timer_reset(&PYMAD_TIMER(self)); mad_timer_set(&PYMAD_TIMER(self), 0, pos, 1000); return Py_None; } pymad-0.10/src/xing.h0000644000175000017500000000263212475221717014034 0ustar jaqjaq00000000000000/* * mad - MPEG audio decoder * Copyright (C) 2000-2001 Robert Leslie * * This program 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; either version 2 of the License, or * (at your option) any later version. * * This program 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 this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * $Id: xing.h,v 1.1 2003/01/11 13:16:08 jaq Exp $ */ #ifndef XING_H #define XING_H #include "mad.h" struct xing { long flags; /* valid fields (see below) */ unsigned long frames; /* total number of frames */ unsigned long bytes; /* total number of bytes */ unsigned char toc[100]; /* 100-point seek table */ long scale; /* ?? */ }; enum { XING_FRAMES = 0x00000001L, XING_BYTES = 0x00000002L, XING_TOC = 0x00000004L, XING_SCALE = 0x00000008L }; void xing_init(struct xing *); #define xing_finish(xing) /* nothing */ int xing_parse(struct xing *, struct mad_bitptr, unsigned int); #endif pymad-0.10/PKG-INFO0000644000175000017500000000036313142523311013206 0ustar jaqjaq00000000000000Metadata-Version: 1.0 Name: pymad Version: 0.10 Summary: A wrapper for the MAD libraries. Home-page: http://spacepants.org/src/pymad/ Author: Jamie Wilkinson Author-email: jaq@spacepants.org License: GPL Description: UNKNOWN Platform: UNKNOWN pymad-0.10/AUTHORS0000644000175000017500000000026512456065725013203 0ustar jaqjaq00000000000000pymad AUTHORS ============= The following people are the primary authors of pymad. See also the file THANKS for a list of all contributors. Jamie Wilkinson pymad-0.10/config_unix.py0000755000175000017500000000435413142523216015006 0ustar jaqjaq00000000000000#!/usr/bin/env python from __future__ import print_function import os import sys def msg_checking(msg): print('Checking {0}... '.format(msg), end='') def execute(cmd, display=0): if display: print(cmd) return os.system(cmd) def run_test(inp, flags=''): try: tmp = open('_temp.c', 'w') tmp.write(inp) tmp.close() compile_cmd = '%s -o _temp _temp.c %s' % (os.environ.get('CC', 'cc'), flags) if not execute(compile_cmd): execute('./_temp') finally: execute('rm -f _temp.c _temp') MAD_TEST_PROGRAM = ''' #include #include #include #include int main () { system("touch conf.madtest"); return 0; } ''' def find_mad(mad_prefix='/usr/local', enable_madtest=1): """A rough translation of mad.m4""" mad_include_dir = mad_prefix + '/include' mad_lib_dir = mad_prefix + '/lib' msg_checking('for MAD') if enable_madtest: execute('rm -f conf.madtest', 0) try: run_test(MAD_TEST_PROGRAM, flags='-I' + mad_include_dir) if not os.path.isfile('conf.madtest'): raise RuntimeError('Did not produce output') execute('rm conf.madtest', 0) except: print('test program failed') return None print('success') return {'library_dirs': mad_lib_dir, 'include_dirs': mad_include_dir} def write_data(data): setup_file = open('setup.cfg', 'w') setup_file.write('[build_ext]\n') for item in list(data.items()): setup_file.write('%s=%s\n' % item) setup_file.close() print('Wrote setup.cfg file') def print_help(): print('''%s --prefix Give the prefix in which MAD was installed.''' % sys.argv[0]) sys.exit(0) def parse_args(): data = {} argv = sys.argv for pos in range(len(argv)): if argv[pos] == '--help': print_help() if argv[pos] == '--prefix': pos = pos + 1 if len(argv) == pos: print('Prefix needs an argument') sys.exit(1) data['prefix'] = argv[pos] return data def main(): args = parse_args() prefix = args.get('prefix', '/usr/local') data = find_mad(mad_prefix=prefix) if not data: print('Config failure') sys.exit(1) write_data(data) if __name__ == '__main__': main() pymad-0.10/COPYING0000644000175000017500000006131412456065725013170 0ustar jaqjaq00000000000000 GNU LIBRARY GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the library GPL. It is numbered 2 because it goes with version 2 of the ordinary GPL.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Library General Public License, applies to some specially designated Free Software Foundation software, and to any other libraries whose authors decide to use it. You can use it for your libraries, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library, or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link a program with the library, you must provide complete object files to the recipients so that they can relink them with the library, after making changes to the library and recompiling it. And you must show them these terms so they know their rights. Our method of protecting your rights has two steps: (1) copyright the library, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the library. Also, for each distributor's protection, we want to make certain that everyone understands that there is no warranty for this free library. If the library is modified by someone else and passed on, we want its recipients to know that what they have is not the original version, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that companies distributing free software will individually obtain patent licenses, thus in effect transforming the program into proprietary software. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License, which was designed for utility programs. This license, the GNU Library General Public License, applies to certain designated libraries. This license is quite different from the ordinary one; be sure to read it in full, and don't assume that anything in it is the same as in the ordinary license. The reason we have a separate public license for some libraries is that they blur the distinction we usually make between modifying or adding to a program and simply using it. Linking a program with a library, without changing the library, is in some sense simply using the library, and is analogous to running a utility program or application program. However, in a textual and legal sense, the linked executable is a combined work, a derivative of the original library, and the ordinary General Public License treats it as such. Because of this blurred distinction, using the ordinary General Public License for libraries did not effectively promote software sharing, because most developers did not use the libraries. We concluded that weaker conditions might promote sharing better. However, unrestricted linking of non-free programs would deprive the users of those programs of all benefit from the free status of the libraries themselves. This Library General Public License is intended to permit developers of non-free programs to use free libraries, while preserving your freedom as a user of such programs to change the free libraries that are incorporated in them. (We have not seen how to achieve this as regards changes in header files, but we have achieved it as regards changes in the actual functions of the Library.) The hope is that this will lead to faster development of free libraries. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, while the latter only works together with the library. Note that it is possible for a library to be covered by the ordinary General Public License rather than by this special one. GNU LIBRARY GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Library General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also compile or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. c) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. d) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Library General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307 USA. Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! pymad-0.10/NEWS0000644000175000017500000000213212475221717012621 0ustar jaqjaq00000000000000NEWS for pymad ============== 0.8 --- 2015-03-03 * Reinitialize buffers after seeks to prevent decoding and output of partial content prior to the seek. (Markus Demleitner) 0.6 --- 2007-01-22 * Fix decoding error with files containing largish id3v2 tags (Joerg Lehmann) * Fix length calculation (Richard Adenling) 0.5.1 (07/10/03) ----- * Fix segfault when cleaning up. 0.5 (01/10/03) --- * Now can read from any file-like Python object. * Added example program for playing internet radio streams. 0.4.1 (06/02/03) ----- * Fixed FPE caused by division by zero in the track time code. 0.4 --- * Now returns current/total track time. * Can seek to a time offset in track. 0.3 --- * emphasis() function now returns correct value. * PCM conversion works on big-endian architectures. 0.2 --- * Using distutils to configure and build pymad. * py_madfile_new can now be passed a file object as well as a filename. * frame info can be retrieved from the MadFile object * Numerous bugfixes (see ChangeLog for details) 0.1 --- * Initial release. - Can open an mp3 file and decode the stream. pymad-0.10/README.md0000644000175000017500000000402713142523216013375 0ustar jaqjaq00000000000000pymad - a Python wrapper for the MPEG Audio Decoder library =========================================================== [![Build Status](https://travis-ci.org/jaqx0r/pymad.svg?branch=master)](https://travis-ci.org/jaqx0r/pymad) pymad is a Python module that allows Python programs to use the MPEG Audio Decoder library. pymad provides a high-level API, similar to the pyogg module, which makes reading PCM data from MPEG audio streams a piece of cake. MAD is available at http://www.mars.org/home/rob/proj/mpeg/ Access this module via `import mad`. To decode an mp3 stream, you'll want to create a `mad.MadFile` object and read data from that. You can then write the data to a sound device. See the example program in `test/` for a simple mp3 player that uses the `python-pyao` wrapper around libao for the sound device. pymad wrapper isn't as low level as the C MAD API is, for example, you don't have to concern yourself with fixed point conversion -- this was done to make pymad easy to use. ```python import sys import ao import mad mf = mad.MadFile(sys.argv[1]) dev = ao.AudioDevice(0, rate=mf.samplerate()) while 1: buf = mf.read() if buf is None: # eof break dev.play(buf, len(buf)) ``` To build, you need the distutils package, availible from http://www.python.org/sigs/distutils-sig/download.html (it comes with Python 2.0). Run `python setup.py build` to build and then as root run `python setup.py install`. if you've installed your mad stuff someplace weird you may need to run the config_unix.py script, passing it a `--prefix` value to create a `setup.cfg` file with the correct include and link dirs: ```shell # python config_unix.py --prefix /usr/local # python setup.py build # python setup.py install --prefix /usr/local ``` Remember to make sure `/usr/local/python/site-packages/` is in your Python search path in that example. Alternately, you can write `setup.cfg` yourself. E.g.: [build_ext] library_dirs=/opt/mad/lib include_dirs=/opt/mad/include libraries=name_of_library_mad_might_depend_on pymad-0.10/test/0000755000175000017500000000000013142523311013066 5ustar jaqjaq00000000000000pymad-0.10/test/pymad_exc_fail.py0000644000175000017500000000060112640643732016415 0ustar jaqjaq00000000000000#! /usr/bin/python import glob import os.path import sys import io import urllib.request import urllib.parse import urllib.error import ao for p in glob.glob("build/lib.*"): sys.path.insert(0, p) print((sys.path)) import mad data = io.StringIO(open("/home/jaq/foo.mp3", "r").read()) m = mad.MadFile(data) print("MadFile returned") for x in (1, 2): pass print("got here") pymad-0.10/test/madradio.py0000644000175000017500000000241612640643732015237 0ustar jaqjaq00000000000000#! /usr/bin/env python import glob import os.path import socket import sys try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse import ao for p in glob.glob('build/lib.*'): sys.path.insert(0, p) import mad def madradio(url): scheme, netloc, path, params, query, fragment = urlparse(url) try: host, port = netloc.split(':') except ValueError: host, port = netloc, 80 if not path: path = '/' sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, int(port))) sock.send('GET %s HTTP/1.0\r\n\r\n' % path) reply = sock.recv(1500) # print repr(reply) file = sock.makefile() mf = mad.MadFile(file) print(('bitrate %lu bps' % mf.bitrate())) print(('samplerate %d Hz' % mf.samplerate())) dev = ao.AudioDevice(0, rate=mf.samplerate()) while True: buffy = mf.read() if buffy is None: break dev.play(buffy, len(buffy)) if __name__ == '__main__': import sys try: url = sys.argv[1] except IndexError: # url = 'http://62.67.195.6:8000' # lounge-radio.com # url = 'http://63.241.4.18:8069' # xtcradio.com url = 'http://mp2.somafm.com:2040' # somafm madradio(url) pymad-0.10/test/test.py0000644000175000017500000000431412640643732014435 0ustar jaqjaq00000000000000#!/usr/bin/python from __future__ import print_function import glob import os.path import sys try: from urllib.request import urlopen except ImportError: from urllib import urlopen print(sys.version_info) PYTHON_VERSION = "{}.{}".format(sys.version_info.major, sys.version_info.minor) for p in glob.glob("build/lib.*-" + PYTHON_VERSION): print("Inserting build path {}".format(p)) sys.path.insert(0, p) print((sys.path)) import mad print(mad.__file__) def play(u): mf = mad.MadFile(u) if mf.layer() == mad.LAYER_I: print("MPEG Layer I") elif mf.layer() == mad.LAYER_II: print("MPEG Layer II") elif mf.layer() == mad.LAYER_III: print("MPEG Layer III") else: print("unexpected layer value") if mf.mode() == mad.MODE_SINGLE_CHANNEL: print("single channel") elif mf.mode() == mad.MODE_DUAL_CHANNEL: print("dual channel") elif mf.mode() == mad.MODE_JOINT_STEREO: print("joint (MS/intensity) stereo") elif mf.mode() == mad.MODE_STEREO: print("normal L/R stereo") else: print("unexpected mode value") if mf.emphasis() == mad.EMPHASIS_NONE: print("no emphasis") elif mf.emphasis() == mad.EMPHASIS_50_15_US: print("50/15us emphasis") elif mf.emphasis() == mad.EMPHASIS_CCITT_J_17: print("CCITT J.17 emphasis") else: print("unexpected emphasis value") print(("bitrate %lu bps" % mf.bitrate())) print(("samplerate %d Hz" % mf.samplerate())) sys.stdout.flush() #millis = mf.total_time() #secs = millis / 1000 # print "total time %d ms (%dm%2ds)" % (millis, secs / 60, secs % 60) #dev = ao.AudioDevice(0, rate=mf.samplerate()) while 1: buffy = mf.read() if buffy is None: break #dev.play(buffy, len(buffy)) # print "current time: %d ms" % mf.current_time() if __name__ == "__main__": print(("pymad version %s" % mad.__version__)) for filename in sys.argv[1:]: if os.path.exists(filename): filename = "file://" + filename u = urlopen(filename) if u: # if os.path.exists(file): print(("playing %s" % filename)) play(u) pymad-0.10/setup.py0000755000175000017500000000154613142523252013636 0ustar jaqjaq00000000000000#!/usr/bin/env python """Setup script for the MAD module distribution.""" import os import re import sys from distutils.core import setup from distutils.extension import Extension VERSION_MAJOR = 0 VERSION_MINOR = 10 PYMAD_VERSION = str(VERSION_MAJOR) + '.' + str(VERSION_MINOR) DEFINES = [('VERSION_MAJOR', VERSION_MAJOR), ('VERSION_MINOR', VERSION_MINOR), ('VERSION', '"%s"' % PYMAD_VERSION)] MADMODULE = Extension( name='mad', sources=['src/madmodule.c', 'src/pymadfile.c', 'src/xing.c'], define_macros=DEFINES, libraries=['mad']) setup( # Distribution metadata name='pymad', version=PYMAD_VERSION, description='A wrapper for the MAD libraries.', author='Jamie Wilkinson', author_email='jaq@spacepants.org', url='http://spacepants.org/src/pymad/', license='GPL', ext_modules=[MADMODULE]) pymad-0.10/THANKS0000644000175000017500000000130312475221717013034 0ustar jaqjaq00000000000000pymad THANKS ============ Many people contributed to pymad by reporting problems, suggesting various improvements, or submitting actual code. Here is a list of these people, alphabetically by surname. Help me keep it complete and exempt of errors. Richard Adenling Andrew Baumann Markus Demleitner Charles Gray Joerg Lehmann Ben Leslie Josselin Mouette Erik Osheim Jean-Claude Rimbault Daniel Torop Brian Warner