pyvorbis-1.5a004075500017500000012000000000001051746404600122245ustar00ericuserspyvorbis-1.5a/test004075500017500000012000000000001051746235000131775ustar00ericuserspyvorbis-1.5a/test/comment.py010064400017500000012000000004771051746235000152770ustar00ericusers#!/usr/bin/python from ogg.vorbis import VorbisComment def test(): x = VorbisComment() x['hey'] = 'you' x['me'] = 'them' x['hEy'] = 'zoo' x['whee'] = 'them' x['Hey'] = 'boo' del x['hey'] try: print x['hey'] # should fail assert(0) except KeyError: pass test() pyvorbis-1.5a/test/enc.py010075500017500000012000000101071051746235000143740ustar00ericusers#!/usr/bin/env python import ogg import ogg.vorbis import struct import array class WaveReader: def __init__(self, filename): self.filename = filename self._f = open(filename, 'rb') self._read_header() def _read_header(self): f = self._f f.seek(12) #skip RIFF chunk, go to fmt chunk if f.read(3) != 'fmt': raise RuntimeError, "Bad chunk" f.seek(20) data = f.read(16) # format, channels, sample rate, Bpsec, Bpsample, bpsample res = struct.unpack(' Select the output device for ao module. --device-option= Give options to the ao module (unimplemented) --module=[ao, lad] Select the ao or linuxaudiodev module for output --verbose Give verbose output --quiet Shut up --shuffle Randomize the listed files before playing ''' class Player: '''A simple wrapper around an Ao object which provides an interface to play a specified file.''' def play(self, name): '''Play the given file on the current device.''' if os.path.isfile(name): vf = ogg.vorbis.VorbisFile(name) else: raise ValueError, "Play takes a filename." self.start(vf) def start(self, vf): '''Actually start playing the given VorbisFile.''' if verbose: vc = vf.comment() vi = vf.info() print 'Bitstream is %s channel, %s rate' % (vi.channels, vi.rate) # If any of these comments show up, print 'key: val' where recognized_comments = ('Artist', 'Album', 'Title', 'Version', 'Organization', 'Genre', 'Description', 'Date', 'Location', 'Copyright', 'Vendor') comment_dict = {} for com in recognized_comments: comment_dict[string.upper(com)] = '%s: %%s' % com known_keys = comment_dict.keys() for key, val in vc.items(): if key in known_keys: print comment_dict[key] % val else: print "Unknown comment: %s" % val print # Here is the little bit that actually plays the file. # Read takes the number of bytes to read and returns a tuple # containing the buffer, the number of bytes read, and I have # no idea what the bit thing is for! Then write the buffer contents # to the device. while 1: (buff, bytes, bit) = vf.read(4096) if verbose == 2: print "Read %s bytes" % bytes if bytes == 0: break self.write(buff, bytes) class AOPlayer(Player): '''A player which uses the ao module.''' def __init__(self, id=None): import ao if id is None: id = ao.driver_id('esd') self.dev = ao.AudioDevice(id) def write(self, buff, bytes): self.dev.play(buff, bytes) class LADPlayer(Player): '''A player which uses the linuxaudiodev module. I have little idea how to use this thing. At least it plays.''' def __init__(self): import linuxaudiodev self.lad = linuxaudiodev self.dev = linuxaudiodev.open('w') self.dev.setparameters(44100, 16, 2, linuxaudiodev.AFMT_S16_NE) def write(self, buff, bytes): '''The write function. I'm really guessing as to whether I'm using it correctly or not, but this seems to work, so until I hear otherwise I'll go with this. Please educate me!''' while self.dev.obuffree() < bytes: time.sleep(0.2) self.dev.write(buff[:bytes]) def usage(msg=None): if msg: print msg print print version print usage_str def main(): global verbose import getopt args = sys.argv[1:] opts = 'hVd:om:vqz' long_opts = ('help', 'version', 'device=', 'device-option=', 'module=', 'verbose', 'quiet', 'shuffle') try: optlist, args = getopt.getopt(args, opts, long_opts) except getopt.error, m: print m print usage() sys.exit(2) driver_id = None device_options = None modchoice = 'ao' choices = {'ao': AOPlayer, 'lad': LADPlayer} for arg, val in optlist: if arg == '-h' or arg == '--help': usage() sys.exit(2) elif arg == '-V' or arg == '--version': print version sys.exit(0) elif arg == '-d' or arg == '--device': try: driver_id = ao_get_driver_id(val) except aoError: sys.stderr.write('No such device %s\n' % val) sys.exit(1) elif arg == '-o' or arg == '--device-option': raise NotImplementedError elif arg == '-m' or arg == '--module': if choices.has_key(val): modchoice = val else: usage("%s is not a valid module choice" % val) sys.exit(2) elif arg == '-v' or arg == '--verbose': verbose = 2 elif arg == '-q' or arg == '--quiet': verbose = 0 elif arg == '-z' or arg == '--shuffle': ri = whrandom.randrange for pos in range(len(args)): newpos = ri(pos, len(args)) tmp = args[pos] args[pos] = args[newpos] args[newpos] = tmp if not args: #no files to play usage() sys.exit(0) myplayer = choices[modchoice]() # Either AOPlayer or LADPlayer if verbose: print "Module choice: %s" % modchoice for file in args: if verbose: print "Playing %s" % file print myplayer.play(file) if __name__ == '__main__': main() pyvorbis-1.5a/test/short.py010075500017500000012000000005571051746235000147760ustar00ericusers#!/usr/bin/env python '''short.py - a really brief demonstration of using the ao and ogg modules''' import ogg.vorbis import ao filename = 'test.ogg' device = 'esd' SIZE = 4096 vf = ogg.vorbis.VorbisFile(filename) id = ao.driver_id(device) ao = ao.AudioDevice(id) while 1: (buff, bytes, bit) = vf.read(SIZE) if bytes == 0: break ao.play(buff, bytes) pyvorbis-1.5a/src004075500017500000012000000000001051746235000130075ustar00ericuserspyvorbis-1.5a/src/vorbismodule.h010064400017500000012000000013021051746235000157420ustar00ericusers#ifndef __VORBISMODULE_H__ #define __VORBISMODULE_H__ #include #include #include "general.h" ogg_module_info *modinfo; PyObject *Py_VorbisError; /* Object docstrings */ extern char py_vorbisfile_doc[]; extern char py_vinfo_doc[]; extern char py_vcomment_doc[]; extern char py_dsp_doc[]; /* Utility functions/macros */ PyObject *v_error_from_code(int, char*); #define RETURN_IF_VAL(val, msg) if (val < 0) { \ return v_error_from_code(val, msg); \ } \ Py_INCREF(Py_None); \ return Py_None; #endif /* __VORBISMODULE_H__ */ pyvorbis-1.5a/src/general.h010064400017500000012000000005601051746235000146520ustar00ericusers#ifndef __GENERAL_H__ #define __GENERAL_H__ #include #include #define MSG_SIZE 256 #define KEY_SIZE 1024 #define PY_UNICODE (PY_VERSION_HEX >= 0x01060000) ogg_int64_t arg_to_64(PyObject *longobj); #define FDEF(x) static PyObject *py_##x (PyObject *self, PyObject *args); \ static char py_##x##_doc[] = #endif /* __GENERAL_H__ */ pyvorbis-1.5a/src/pyvorbiscodec.c010064400017500000012000000303611051746235000161050ustar00ericusers#include #include #include "general.h" #include "vorbismodule.h" #include "pyvorbiscodec.h" #include "pyvorbisinfo.h" #define MIN(x,y) ((x) < (y) ? (x) : (y)) /************************************************************** VorbisDSP Object **************************************************************/ FDEF(vorbis_analysis_headerout) "Create three header packets for an ogg\n" "stream, given an optional comment object."; FDEF(vorbis_analysis_blockout) "Output a VorbisBlock. Data must be written to the object first."; FDEF(vorbis_block_init) "Create a VorbisBlock object for use in encoding {more?!}"; FDEF(dsp_write) "Write audio data to the dsp device and have it analyzed. \n" "Each argument must be a string containing the audio data for a\n" "single channel.\n" "If None is passed as the only argument, this will signal that no more\n" "data needs to be written."; FDEF(dsp_write_wav) "Write audio data to the dsp device and have it analyzed.\n" "The single argument is the output from the python wave module. Only supports\n" "16-bit wave data (8-bit waves will produce garbage)."; FDEF(dsp_close) "Signal that all audio data has been written to the object."; FDEF(vorbis_bitrate_flushpacket) ""; static void py_dsp_dealloc(PyObject *); static PyObject *py_dsp_getattr(PyObject *, char*); char py_dsp_doc[] = ""; PyTypeObject py_dsp_type = { PyObject_HEAD_INIT(NULL) 0, "VorbisDSPState", sizeof(py_dsp), 0, /* Standard Methods */ /* destructor */ py_dsp_dealloc, /* printfunc */ 0, /* getattrfunc */ py_dsp_getattr, /* setattrfunc */ 0, /* cmpfunc */ 0, /* reprfunc */ 0, /* Type Categories */ 0, /* as number */ 0, /* as sequence */ 0, /* as mapping */ 0, /* hash */ 0, /* binary */ 0, /* repr */ 0, /* getattro */ 0, /* setattro */ 0, /* as buffer */ 0, /* tp_flags */ py_dsp_doc, }; static PyMethodDef DSP_methods[] = { {"headerout", py_vorbis_analysis_headerout, METH_VARARGS, py_vorbis_analysis_headerout_doc}, {"blockout", py_vorbis_analysis_blockout, METH_VARARGS, py_vorbis_analysis_blockout_doc}, {"create_block", py_vorbis_block_init, METH_VARARGS, py_vorbis_block_init_doc}, {"write", py_dsp_write, METH_VARARGS, py_dsp_write_doc}, {"write_wav", py_dsp_write_wav, METH_VARARGS, py_dsp_write_wav_doc}, {"close", py_dsp_close, METH_VARARGS, py_dsp_close_doc}, {"bitrate_flushpacket", py_vorbis_bitrate_flushpacket, METH_VARARGS, py_vorbis_bitrate_flushpacket_doc}, {NULL, NULL} }; PyObject * py_dsp_from_dsp(vorbis_dsp_state *vd, PyObject *parent) { py_dsp *ret = (py_dsp *) PyObject_NEW(py_dsp, &py_dsp_type); if (ret == NULL) return NULL; ret->vd = *vd; ret->parent = parent; Py_XINCREF(parent); return (PyObject *) ret; } PyObject * py_dsp_new(PyObject *self, PyObject *args) { py_vinfo* py_vi; py_dsp *ret; vorbis_info *vi; vorbis_dsp_state vd; if (!PyArg_ParseTuple(args, "O!", &py_vinfo_type, &py_vi)) return NULL; ret = (py_dsp *) PyObject_NEW(py_dsp, &py_dsp_type); ret->parent = NULL; vi = &py_vi->vi; vorbis_synthesis_init(&vd, vi); return py_dsp_from_dsp(&vd, (PyObject *) py_vi); } static void py_dsp_dealloc(PyObject *self) { vorbis_dsp_clear(PY_DSP(self)); Py_XDECREF(((py_dsp *)self)->parent); PyMem_DEL(self); } static PyObject* py_dsp_getattr(PyObject *self, char *name) { return Py_FindMethod(DSP_methods, self, name); } static PyObject * py_vorbis_analysis_blockout(PyObject *self, PyObject *args) { vorbis_block vb; int ret; py_dsp *dsp_self = (py_dsp *) self; if (!PyArg_ParseTuple(args, "")) return NULL; vorbis_block_init(&dsp_self->vd, &vb); ret = vorbis_analysis_blockout(&dsp_self->vd, &vb); if (ret == 1) return py_block_from_block(&vb, self); else { Py_INCREF(Py_None); return Py_None; } } static PyObject * py_vorbis_analysis_headerout(PyObject *self, PyObject *args) { int code; py_dsp *dsp_self = (py_dsp *) self; py_vcomment *comm = NULL; vorbis_comment vc; ogg_packet header, header_comm, header_code; PyObject *pyheader = NULL; PyObject *pyheader_comm = NULL; PyObject *pyheader_code = NULL; PyObject *ret = NULL; /* Takes a comment object as the argument. I'll just give them an empty one if they don't provied one. */ if (!PyArg_ParseTuple(args, "|O!", &py_vcomment_type, &comm)) return NULL; if (comm == NULL) { vorbis_comment_init(&vc); /* Initialize an empty comment struct */ } else { vc = *comm->vc; } if ((code = vorbis_analysis_headerout(&dsp_self->vd, &vc, &header, &header_comm, &header_code))) { v_error_from_code(code, "vorbis_analysis_header_out"); goto finish; } /* Returns a tuple of oggpackets (header, header_comm, header_code) */ pyheader = modinfo->ogg_packet_from_packet(&header); pyheader_comm = modinfo->ogg_packet_from_packet(&header_comm); pyheader_code = modinfo->ogg_packet_from_packet(&header_code); if (pyheader == NULL || pyheader_comm == NULL || pyheader_code == NULL) goto error; ret = PyTuple_New(3); PyTuple_SET_ITEM(ret, 0, pyheader); PyTuple_SET_ITEM(ret, 1, pyheader_comm); PyTuple_SET_ITEM(ret, 2, pyheader_code); finish: if (comm == NULL) /* Get rid of it if we created it */ vorbis_comment_clear(&vc); return ret; error: if (comm == NULL) vorbis_comment_clear(&vc); Py_XDECREF(pyheader); Py_XDECREF(pyheader_comm); Py_XDECREF(pyheader_code); return NULL; } static PyObject * py_vorbis_block_init(PyObject *self, PyObject *args) { vorbis_block vb; py_dsp *dsp_self = (py_dsp *) self; PyObject *ret; if (!PyArg_ParseTuple(args, "")) return NULL; vorbis_block_init(&dsp_self->vd,&vb); ret = py_block_from_block(&vb, self); return ret; } /* Returns "len" if all arguments are strings of the same length, -1 if one or more are not strings -2 if they have different lengths */ #define NON_STRING -1 #define DIFF_LENGTHS -2 static int string_size(PyObject *args, int size) { PyObject *cur; int k; int len = -1; for (k = 0; k < size; k++) { cur = PyTuple_GET_ITEM(args, k); if (!PyString_Check(cur)) return NON_STRING; /* make sure the lengths are uniform */ if (len == -1) len = PyString_Size(cur); else if (PyString_Size(cur) != len) return DIFF_LENGTHS; } return len; } static PyObject * py_dsp_write(PyObject *self, PyObject *args) { int k, channels; char err_msg[256]; float **buffs; float **analysis_buffer; int len, samples; py_dsp *dsp_self = (py_dsp *) self; PyObject *cur; assert(PyTuple_Check(args)); channels = dsp_self->vd.vi->channels; if (PyTuple_Size(args) == 1 && PyTuple_GET_ITEM(args, 0) == Py_None) { vorbis_analysis_wrote(&dsp_self->vd, 0); Py_INCREF(Py_None); return Py_None; } if (PyTuple_Size(args) != channels) { snprintf(err_msg, sizeof(err_msg), "Expected %d strings as arguments; found %d arguments", channels, PyTuple_Size(args)); PyErr_SetString(Py_VorbisError, err_msg); return NULL; } len = string_size(args, channels); if (len == NON_STRING) { PyErr_SetString(Py_VorbisError, "All arguments must be strings"); return NULL; } if (len == DIFF_LENGTHS) { PyErr_SetString(Py_VorbisError, "All arguments must have the same length."); return NULL; } samples = len / sizeof(float); buffs = (float **) malloc(channels * sizeof(float *)); for (k = 0; k < channels; k++) { cur = PyTuple_GET_ITEM(args, k); buffs[k] = (float *) PyString_AsString(cur); } analysis_buffer = vorbis_analysis_buffer(&dsp_self->vd, len * sizeof(float)); for (k = 0; k < channels; k++) memcpy(analysis_buffer[k], buffs[k], len); free(buffs); vorbis_analysis_wrote(&dsp_self->vd, samples); return PyInt_FromLong(samples); /* return the number of samples written */ } static void parse_wav_data(const char *byte_data, float **buff, int channels, int samples) { const float adjust = 1/32768.0; int j, k; for (j = 0; j < samples; j++) { for (k = 0; k < channels; k++) { float val = ((byte_data[j * 2 * channels + 2 * k + 1] << 8) | (byte_data[j * 2 * channels + 2 * k] & 0xff)) * adjust; buff[k][j] = val; } } } static PyObject * py_dsp_write_wav(PyObject *self, PyObject *args) { const char *byte_data; int num_bytes, channels, k; long samples; const int samples_per_it = 1024; py_dsp *dsp = (py_dsp *) self; float **analysis_buffer; int sample_width; channels = dsp->vd.vi->channels; sample_width = channels * 2; if (!PyArg_ParseTuple(args, "s#", &byte_data, &num_bytes)) return NULL; if (num_bytes % sample_width != 0) { PyErr_SetString(Py_VorbisError, "Data is not a multiple of (2 * # of channels)"); return NULL; } samples = num_bytes / sample_width; for (k = 0; k < (samples + samples_per_it - 1) / samples_per_it; k++) { int to_write = MIN(samples - k * samples_per_it, samples_per_it); analysis_buffer = vorbis_analysis_buffer(&dsp->vd, to_write * sizeof(float)); /* Parse the wav data directly into the analysis buffer. */ parse_wav_data(byte_data, analysis_buffer, channels, to_write); /* Skip any data we've already passed by incrementing the pointer */ byte_data += to_write * sample_width; vorbis_analysis_wrote(&dsp->vd, to_write); } return PyInt_FromLong(samples); } static PyObject * py_dsp_close(PyObject *self, PyObject *args) { py_dsp *dsp_self = (py_dsp *) self; vorbis_analysis_wrote(&dsp_self->vd, 0); Py_INCREF(Py_None); return Py_None; } static PyObject * py_vorbis_bitrate_flushpacket(PyObject *self, PyObject *args) { ogg_packet op; int ret; if (!PyArg_ParseTuple(args, "")) return NULL; ret = vorbis_bitrate_flushpacket(PY_DSP(self), &op); if (ret == 1) return modinfo->ogg_packet_from_packet(&op); else if (ret == 0) { Py_INCREF(Py_None); return Py_None; } else { PyErr_SetString(Py_VorbisError, "Unknown return code from flushpacket"); return NULL; } } /********************************************************* VorbisBlock *********************************************************/ static void py_block_dealloc(PyObject *); static PyObject *py_block_getattr(PyObject *, char*); FDEF(vorbis_analysis) "Output an OggPage."; FDEF(vorbis_bitrate_addblock) "?"; char py_block_doc[] = ""; PyTypeObject py_block_type = { PyObject_HEAD_INIT(NULL) 0, "VorbisBlock", sizeof(py_block), 0, /* Standard Methods */ /* destructor */ py_block_dealloc, /* printfunc */ 0, /* getattrfunc */ py_block_getattr, /* setattrfunc */ 0, /* cmpfunc */ 0, /* reprfunc */ 0, /* Type Categories */ 0, /* as number */ 0, /* as sequence */ 0, /* as mapping */ 0, /* hash */ 0, /* binary */ 0, /* repr */ 0, /* getattro */ 0, /* setattro */ 0, /* as buffer */ 0, /* tp_flags */ py_block_doc, }; static PyMethodDef Block_methods[] = { {"analysis", py_vorbis_analysis, METH_VARARGS, py_vorbis_analysis_doc}, {"addblock", py_vorbis_bitrate_addblock, METH_VARARGS, py_vorbis_bitrate_addblock_doc}, {NULL, NULL} }; static void py_block_dealloc(PyObject *self) { vorbis_block_clear(PY_BLOCK(self)); Py_XDECREF(((py_block *)self)->parent); PyMem_DEL(self); } static PyObject* py_block_getattr(PyObject *self, char *name) { return Py_FindMethod(Block_methods, self, name); } static PyObject* py_vorbis_analysis(PyObject *self, PyObject *args) { int ret; py_block *b_self = (py_block *) self; if (!PyArg_ParseTuple(args, "")) return NULL; ret = vorbis_analysis(&b_self->vb, NULL); if (ret < 0) { PyErr_SetString(Py_VorbisError, "vorbis_analysis failure"); return NULL; } Py_INCREF(Py_None); return Py_None; } static PyObject * py_vorbis_bitrate_addblock(PyObject *self, PyObject *args) { int ret; if (!PyArg_ParseTuple(args, "")) return NULL; ret = vorbis_bitrate_addblock(PY_BLOCK(self)); if (ret < 0) { PyErr_SetString(Py_VorbisError, "addblock failed"); return NULL; } Py_INCREF(Py_None); return Py_None; } PyObject * py_block_from_block(vorbis_block *vb, PyObject *parent) { py_block *ret = (py_block *) PyObject_NEW(py_block, &py_block_type); if (ret == NULL) return NULL; ret->vb = *vb; ret->parent = parent; Py_XINCREF(parent); return (PyObject *)ret; } pyvorbis-1.5a/src/pyvorbiscodec.h010064400017500000012000000011501051746235000161040ustar00ericusers#ifndef __VORBISCODEC_H__ #define __VORBISCODEC_H__ #include #include typedef struct { PyObject_HEAD vorbis_dsp_state vd; PyObject *parent; } py_dsp; typedef struct { PyObject_HEAD vorbis_block vb; PyObject *parent; } py_block; #define PY_DSP(x) (&(((py_dsp *) (x))->vd)) #define PY_BLOCK(x) (&(((py_block *) (x))->vb)) extern PyTypeObject py_dsp_type; extern PyTypeObject py_block_type; PyObject *py_dsp_from_dsp(vorbis_dsp_state *vd, PyObject *parent); PyObject *py_block_from_block(vorbis_block *vb, PyObject *parent); #endif /* __VORBISCODEC_H__ */ pyvorbis-1.5a/src/pyvorbisfile.c010064400017500000012000000357161051746235000157600ustar00ericusers#include #ifndef _WIN32 #include #else #define LITTLE_ENDIAN 0 #define BIG_ENDIAN 1 #define BYTE_ORDER LITTLE_ENDIAN #endif #include "general.h" #include "vorbismodule.h" #include "pyvorbisfile.h" #include "pyvorbisinfo.h" /* ********************************************************* VorbisFile Object methods ********************************************************* */ char py_vorbisfile_doc[] = ""; static void py_ov_file_dealloc(PyObject *); static PyObject *py_ov_open(py_vorbisfile *, PyObject *); static char py_ov_read_doc[] = \ "read(length=4096, bigendian=?, word=2, signed=1)\n\ Returns a tuple: (x,y,y)\n\ \twhere x is a buffer object of the data read,\n\ \ty is the number of bytes read,\n\ \tand z is whatever the bitstream value means (no clue).\n\ \n\ length is the number of bytes to read\n\ \tbigendian is the endianness you want (defaults to host endianness)\n\ \tword is the word size\n\tnot sure what signed does\n"; static PyObject *py_ov_read(PyObject *, PyObject *, PyObject *); FDEF(ov_streams) "Returns the number of logical streams in this VorbisFile"; FDEF(ov_seekable) "Returns whether this VorbisFile is seekable."; FDEF(ov_bitrate) \ "x.bitrate(stream_idx=-1):\n\n\ Returns the bitrate of this VorbisFile"; FDEF(ov_serialnumber) \ "x.serialnumber(stream_idx=-1):\n\n\ Returns the serialnumber of this VorbisFile."; FDEF(ov_bitrate_instant) \ "Returns the bitrate_instant value for this VorbisFile."; FDEF(ov_raw_total) \ "x.raw_total(stream_idx=-1):\n\n\ Returns the raw_total value for this VorbisFile."; FDEF(ov_pcm_total) \ "x.pcm_total(stream_idx=-1):\n\n\ Returns the pcm_total value for this VorbisFile."; FDEF(ov_time_total) \ "x.time_total(stream_idx=-1):\n\n\ Returns the time_total value for this VorbisFile."; FDEF(ov_raw_seek) "x.raw_seek(pos):\n\nSeeks to raw position pos."; FDEF(ov_pcm_seek) "x.pcm_seek(pos):\n\nSeeks to pcm position pos."; FDEF(ov_pcm_seek_page) "x.pcm_seek_page(pos):\n\nSeeks to pcm page pos."; FDEF(ov_time_seek) "x.time_seek(t):\n\nSeeks to time t"; FDEF(ov_time_seek_page) "x.time_seek_page(pos):\n\nSeeks to time page pos."; FDEF(ov_raw_tell) "Returns the raw position."; FDEF(ov_pcm_tell) "Returns the pcm position."; FDEF(ov_time_tell) "Returns the time position."; FDEF(ov_info) "Return an info object for this file"; FDEF(ov_comment) \ "x.comment(stream_idx=-1)\n\n\ Returns a dictionary of lists for the comments in this file.\n\ All values are stored in uppercase, since values should be case-insensitive."; static PyObject *py_ov_file_getattr(PyObject *, char *name); char OggVorbis_File_Doc[] = "A VorbisFile object is used to get information about\n\ and read data from an ogg/vorbis file.\n\ \n\ VorbisFile(f) will create a VorbisFile object; f can be\n\ either an open, readable file object or a filename string.\n\ \n\ The most useful method for a VorbisFile object is \"read\"."; PyTypeObject py_vorbisfile_type = { PyObject_HEAD_INIT(NULL) 0, "VorbisFile", sizeof(py_vorbisfile), 0, /* Standard Methods */ /* destructor */ py_ov_file_dealloc, /* printfunc */ 0, /* getattrfunc */ py_ov_file_getattr, /* setattrfunc */ 0, /* cmpfunc */ 0, /* reprfunc */ 0, /* Type Categories */ 0, /* as number */ 0, /* as sequence */ 0, /* as mapping */ 0, /* hash */ 0, /* binary */ 0, /* repr */ 0, /* getattro */ 0, /* setattro */ 0, /* as buffer */ 0, /* tp_flags */ OggVorbis_File_Doc, }; static PyMethodDef OggVorbis_File_methods[] = { {"read", (PyCFunction) py_ov_read, METH_VARARGS | METH_KEYWORDS, py_ov_read_doc}, {"info", py_ov_info, METH_VARARGS, py_ov_info_doc}, {"comment", py_ov_comment, METH_VARARGS, py_ov_comment_doc}, {"streams", py_ov_streams, METH_VARARGS, py_ov_streams_doc}, {"seekable", py_ov_seekable, METH_VARARGS, py_ov_seekable_doc}, {"bitrate", py_ov_bitrate, METH_VARARGS, py_ov_bitrate_doc}, {"serialnumber", py_ov_serialnumber, METH_VARARGS, py_ov_serialnumber_doc}, {"bitrate_instant", py_ov_bitrate_instant, METH_VARARGS, py_ov_bitrate_instant_doc}, {"raw_total", py_ov_raw_total, METH_VARARGS, py_ov_raw_total_doc}, {"pcm_total", py_ov_pcm_total, METH_VARARGS, py_ov_pcm_total_doc}, {"time_total", py_ov_time_total, METH_VARARGS, py_ov_time_total_doc}, {"raw_seek", py_ov_raw_seek, METH_VARARGS, py_ov_raw_seek_doc}, {"pcm_seek_page", py_ov_pcm_seek_page, METH_VARARGS, py_ov_pcm_seek_page_doc}, {"pcm_seek", py_ov_pcm_seek, METH_VARARGS, py_ov_pcm_seek_doc}, {"time_seek", py_ov_time_seek, METH_VARARGS, py_ov_time_seek_doc}, {"time_seek_page", py_ov_time_seek_page, METH_VARARGS, py_ov_time_seek_page_doc}, {"raw_tell", py_ov_raw_tell, METH_VARARGS, py_ov_raw_tell_doc}, {"pcm_tell", py_ov_pcm_tell, METH_VARARGS, py_ov_pcm_tell_doc}, {"time_tell", py_ov_time_tell, METH_VARARGS, py_ov_time_tell_doc}, {NULL,NULL} }; PyObject * py_file_new(PyObject *self, PyObject *args) /* change to accept kwarg */ { PyObject *ret; py_vorbisfile *newobj; newobj = PyObject_NEW(py_vorbisfile, &py_vorbisfile_type); ret = py_ov_open(newobj, args); if (ret == NULL) { PyMem_DEL(newobj); return NULL; } return (PyObject *) newobj; } static void py_ov_file_dealloc(PyObject *self) { if (PY_VORBISFILE(self)) ov_clear(PY_VORBISFILE(self)); py_vorbisfile *py_self = (py_vorbisfile *) self; if (py_self->py_file) { /* If file was opened from a file object, decref it, so it can close */ Py_DECREF(py_self->py_file); } else { /* Do NOT close the file -- ov_open() takes ownership of the FILE*, and ov_close() is responsible for closing it. */ } free(py_self->ovf); PyObject_DEL(self); } static PyObject * py_ov_open(py_vorbisfile *self, PyObject *args) { char *fname; char *initial = NULL; long ibytes = 0; FILE *file; PyObject *fobject; int retval; char errmsg[MSG_SIZE]; if (PyArg_ParseTuple(args, "s|sl", &fname, &initial, &ibytes)) { file = fopen(fname, "rb"); fobject = NULL; if (file == NULL) { snprintf(errmsg, MSG_SIZE, "Could not open file: %s", fname); PyErr_SetString(PyExc_IOError, errmsg); return NULL; } } else { PyErr_Clear(); /* clear first failure */ if (PyArg_ParseTuple(args, "O!|sl", &PyFile_Type, &fobject, &initial, &ibytes)) { fname = NULL; file = PyFile_AsFile(fobject); if (!file) return NULL; /* We have to duplicate the file descriptor, since both Python and vorbisfile will want to close it. Don't use the file after you pass it in, or much evil will occur. Really, you shouldn't be passing in files anymore, but in the interest of backwards compatibility it'll stay. */ int orig_fd, new_fd; orig_fd = fileno(file); new_fd = dup(orig_fd); file = fdopen(new_fd, "r"); if (!file) { PyErr_SetString(PyExc_IOError, "Could not duplicate file."); return NULL; } } else { PyErr_Clear(); /* clear first failure */ PyErr_SetString(PyExc_TypeError, "Argument 1 is not a filename or file object"); return NULL; } } self->ovf = (OggVorbis_File*) malloc(sizeof(OggVorbis_File)); self->py_file = fobject; Py_XINCREF(fobject); /* Prevent the file from being closed */ retval = ov_open(file, self->ovf, initial, ibytes); self->c_file = file; if (retval < 0) { if (fname != NULL) fclose(file); Py_XDECREF(self->py_file); return v_error_from_code(retval, "Error opening file: "); } Py_INCREF(Py_None); return Py_None; } static char *read_kwlist[] = {"length", "bigendian", "word", "signed", NULL}; static int is_big_endian() { static int x = 0x1; char x_as_char = *(char *) &x; return x_as_char == 0x1 ? 0 : 1; } static PyObject * py_ov_read(PyObject *self, PyObject *args, PyObject *kwdict) { py_vorbisfile * ov_self = (py_vorbisfile *) self; PyObject *retobj; int retval; PyObject *buffobj; PyObject *tuple; char *buff; int length, word, sgned, bitstream; int bigendianp; // Default to host order bigendianp = is_big_endian(); length = 4096; word = 2; sgned = 1; if (!PyArg_ParseTupleAndKeywords(args, kwdict, "|llll", read_kwlist, &length, &bigendianp, &word, &sgned)) return NULL; buffobj = PyBuffer_New(length); tuple = PyTuple_New(1); Py_INCREF(buffobj); PyTuple_SET_ITEM(tuple, 0, buffobj); if (!(PyArg_ParseTuple(tuple, "t#", &buff, &length))) { return NULL; } Py_DECREF(tuple); Py_BEGIN_ALLOW_THREADS retval = ov_read(ov_self->ovf, buff, length, bigendianp, word, sgned, &bitstream); Py_END_ALLOW_THREADS if (retval < 0) { Py_DECREF(buffobj); return v_error_from_code(retval, "Error reading file: "); } retobj = Py_BuildValue("Oii", buffobj, retval, bitstream); Py_DECREF(buffobj); return retobj; } static PyObject * py_ov_streams(PyObject *self, PyObject *args) { py_vorbisfile * ov_self = (py_vorbisfile *) self; long val; if (!PyArg_ParseTuple(args, "")) return NULL; val = ov_streams(ov_self->ovf); return PyInt_FromLong(val); } static PyObject * py_ov_seekable(PyObject *self, PyObject *args) { py_vorbisfile * ov_self = (py_vorbisfile *) self; long val; if (!PyArg_ParseTuple(args, "")) return NULL; val = ov_seekable(ov_self->ovf); return PyInt_FromLong(val); } static PyObject * py_ov_bitrate(PyObject *self, PyObject *args) { py_vorbisfile * ov_self = (py_vorbisfile *) self; long val; int stream_idx = -1; if (!PyArg_ParseTuple(args, "|i", &stream_idx)) return NULL; val = ov_bitrate(ov_self->ovf, stream_idx); if (val < 0) return v_error_from_code(val, "Error getting bitrate: "); return PyInt_FromLong(val); } static PyObject * py_ov_serialnumber(PyObject *self, PyObject *args) { py_vorbisfile * ov_self = (py_vorbisfile *) self; long val; int stream_idx = -1; if (!PyArg_ParseTuple(args, "|i", &stream_idx)) return NULL; val = ov_serialnumber(ov_self->ovf, stream_idx); return PyInt_FromLong(val); } static PyObject * py_ov_bitrate_instant(PyObject *self, PyObject *args) { py_vorbisfile * ov_self = (py_vorbisfile *) self; long val; if (!PyArg_ParseTuple(args, "")) return NULL; val = ov_bitrate_instant(ov_self->ovf); if (val < 0) return v_error_from_code(val, "Error getting bitrate_instant: "); return PyInt_FromLong(val); } static PyObject * py_ov_raw_total(PyObject *self, PyObject *args) { py_vorbisfile * ov_self = (py_vorbisfile *) self; ogg_int64_t val; int stream_idx = -1; if (!PyArg_ParseTuple(args, "|i", &stream_idx)) return NULL; val = ov_raw_total(ov_self->ovf, stream_idx); if (val < 0) return v_error_from_code(val, "Error in ov_raw_total: "); return PyLong_FromLongLong(val); } static PyObject * py_ov_pcm_total(PyObject *self, PyObject *args) { py_vorbisfile * ov_self = (py_vorbisfile *) self; ogg_int64_t val; int stream_idx = -1; if (!PyArg_ParseTuple(args, "|i", &stream_idx)) return NULL; val = ov_pcm_total(ov_self->ovf, stream_idx); if (val < 0) return v_error_from_code(val, "Error in ov_pcm_total: "); return PyLong_FromLongLong(val); } static PyObject * py_ov_time_total(PyObject *self, PyObject *args) { py_vorbisfile * ov_self = (py_vorbisfile *) self; double val; int stream_idx = -1; if (!PyArg_ParseTuple(args, "|i", &stream_idx)) return NULL; val = ov_time_total(ov_self->ovf, stream_idx); if (val < 0) return v_error_from_code(val, "Error in ov_time_total: "); return PyFloat_FromDouble(val); } static PyObject * py_ov_raw_seek(PyObject *self, PyObject *args) { py_vorbisfile * ov_self = (py_vorbisfile *) self; int val; long pos; if (!PyArg_ParseTuple(args, "l", &pos)) return NULL; val = ov_raw_seek(ov_self->ovf, pos); RETURN_IF_VAL(val, "Error in ov_raw_seek"); } static PyObject * py_ov_pcm_seek(PyObject *self, PyObject *args) { py_vorbisfile * ov_self = (py_vorbisfile *) self; PyObject *longobj; int val; ogg_int64_t pos; if (!PyArg_ParseTuple(args, "O", &longobj)) return NULL; if (!modinfo->arg_to_int64(longobj, &pos)) return NULL; val = ov_pcm_seek(ov_self->ovf, pos); RETURN_IF_VAL(val, "Error is ov_pcm_seek"); } static PyObject * py_ov_pcm_seek_page(PyObject *self, PyObject *args) { py_vorbisfile * ov_self = (py_vorbisfile *) self; int val; PyObject *longobj; ogg_int64_t pos; if (!PyArg_ParseTuple(args, "O", &longobj)) return NULL; if (!modinfo->arg_to_int64(longobj, &pos)) return NULL; val = ov_pcm_seek_page(ov_self->ovf, pos); RETURN_IF_VAL(val, "Error is ov_pcm_seek_page"); } static PyObject * py_ov_time_seek(PyObject *self, PyObject *args) { py_vorbisfile * ov_self = (py_vorbisfile *) self; int val; double pos; if (!PyArg_ParseTuple(args, "d", &pos)) return NULL; val = ov_time_seek(ov_self->ovf, pos); RETURN_IF_VAL(val, "Error is ov_pcm_time_seek"); } static PyObject * py_ov_time_seek_page(PyObject *self, PyObject *args) { py_vorbisfile * ov_self = (py_vorbisfile *) self; int val; double pos; if (!PyArg_ParseTuple(args, "d", &pos)) return NULL; val = ov_time_seek_page(ov_self->ovf, pos); RETURN_IF_VAL(val, "Error is ov_pcm_time_seek_page"); } static PyObject * py_ov_raw_tell(PyObject *self, PyObject *args) { py_vorbisfile * ov_self = (py_vorbisfile *) self; ogg_int64_t val; if (!PyArg_ParseTuple(args, "")) return NULL; val = ov_raw_tell(ov_self->ovf); return PyLong_FromLongLong(val); } static PyObject * py_ov_pcm_tell(PyObject *self, PyObject *args) { py_vorbisfile * ov_self = (py_vorbisfile *) self; ogg_int64_t val; if (!PyArg_ParseTuple(args, "")) return NULL; val = ov_pcm_tell(ov_self->ovf); return PyLong_FromLongLong(val); } static PyObject * py_ov_time_tell(PyObject *self, PyObject *args) { py_vorbisfile * ov_self = (py_vorbisfile *) self; double val; if (!PyArg_ParseTuple(args, "")) return NULL; val = ov_time_tell(ov_self->ovf); return PyFloat_FromDouble(val); } static PyObject* py_ov_info(PyObject *self, PyObject *args) { py_vorbisfile *ov_self = (py_vorbisfile *) self; int stream_idx = -1; vorbis_info *vi; if (!PyArg_ParseTuple(args, "|i", &stream_idx)) return NULL; vi = ov_info(ov_self->ovf, stream_idx); if (!vi) { PyErr_SetString(PyExc_RuntimeError, "Couldn't get info for VorbisFile."); return NULL; } return py_info_new_from_vi(vi); } static PyObject * py_ov_comment(PyObject *self, PyObject *args) { py_vorbisfile *ov_self = (py_vorbisfile *) self; vorbis_comment *comments; int stream_idx = -1; if (!PyArg_ParseTuple(args, "|i", &stream_idx)) return NULL; comments = ov_comment(ov_self->ovf, stream_idx); if (!comments) { PyErr_SetString(PyExc_RuntimeError, "Couldn't get comments"); return NULL; } return py_comment_new_from_vc(comments, self); } static PyObject* py_ov_file_getattr(PyObject *self, char *name) { return Py_FindMethod(OggVorbis_File_methods, self, name); } pyvorbis-1.5a/src/pyvorbisfile.h010064400017500000012000000007161051746235000157550ustar00ericusers#ifndef __PYVORBIS_FILE_H__ #define __PYVORBIS_FILE_H__ #include #include typedef struct { PyObject_HEAD OggVorbis_File *ovf; PyObject *py_file; FILE *c_file; } py_vorbisfile; #define PY_VORBISFILE(x) (((py_vorbisfile *)x)->ovf) #define PY_VORBISFILEOBJECT(x) (((py_vorbisfile *)x)->py_file) extern PyTypeObject py_vorbisfile_type; PyObject *py_file_new(PyObject *, PyObject *); #endif /* __PYVORBIS_FILE_H__ */ pyvorbis-1.5a/src/pyvorbisinfo.c010064400017500000012000000703721051746235000157710ustar00ericusers#include #include #include "general.h" #include "vorbismodule.h" #include "pyvorbisinfo.h" #include "pyvorbiscodec.h" #include "vcedit.h" /* ********************************************************* VorbisInfo Object methods ********************************************************* */ FDEF(ov_info_clear) "Clears a VorbisInfo object"; FDEF(vorbis_analysis_init) "Create a DSP object to start audio analysis."; FDEF(vorbis_info_blocksize) "I have NO idea what this does."; static void py_ov_info_dealloc(PyObject *); static PyObject *py_ov_info_getattr(PyObject *, char *name); static PyMethodDef py_vinfo_methods[] = { {"clear", py_ov_info_clear, METH_VARARGS, py_ov_info_clear_doc}, {"analysis_init", py_vorbis_analysis_init, METH_VARARGS, py_vorbis_analysis_init_doc}, {"blocksize", py_vorbis_info_blocksize, METH_VARARGS, py_vorbis_info_blocksize_doc}, {NULL, NULL} }; char py_vinfo_doc[] = "A VorbisInfo object stores information about a Vorbis stream.\n\ Information is stored as attributes."; static PyObject *py_ov_info_str(PyObject *); PyTypeObject py_vinfo_type = { PyObject_HEAD_INIT(NULL) 0, "VorbisInfo", sizeof(py_vinfo), 0, /* Standard Methods */ /* destructor */ py_ov_info_dealloc, /* printfunc */ 0, /* getattrfunc */ py_ov_info_getattr, /* setattrfunc */ 0, /* cmpfunc */ 0, /* reprfunc */ 0, /* Type Categories */ 0, /* as number */ 0, /* as sequence */ 0, /* as mapping */ 0, /* hash */ 0, /* binary */ &py_ov_info_str, /* repr */ 0, /* getattro */ 0, /* setattro */ 0, /* as buffer */ 0, /* tp_flags */ py_vinfo_doc, }; PyObject* py_info_new_from_vi(vorbis_info *vi) { py_vinfo *newobj; newobj = (py_vinfo *) PyObject_NEW(py_vinfo, &py_vinfo_type); newobj->vi = *vi; return (PyObject *) newobj; } static char *py_info_new_kw[] = {"channels", "rate", "max_bitrate", "nominal_bitrate", "min_bitrate", "quality", NULL}; PyObject * py_info_new(PyObject *self, PyObject *args, PyObject *kwdict) { long channels, rate, max_bitrate, nominal_bitrate, min_bitrate; double quality = -1.0; vorbis_info vi; int res; channels = 2; rate = 44100; max_bitrate = -1; nominal_bitrate = 128000; min_bitrate = -1; if (!PyArg_ParseTupleAndKeywords(args, kwdict, "|llllld", py_info_new_kw, &channels, &rate, &max_bitrate, &nominal_bitrate, &min_bitrate, &quality)) return NULL; vorbis_info_init(&vi); if (quality > -1.0) { res = vorbis_encode_init_vbr(&vi, channels, rate, quality); } else { res = vorbis_encode_init(&vi, channels, rate, max_bitrate, nominal_bitrate, min_bitrate); } if (res != 0) { vorbis_info_clear(&vi); v_error_from_code(res, "vorbis_encode_init"); } return py_info_new_from_vi(&vi); } static PyObject * py_ov_info_clear(PyObject *self, PyObject *args) { py_vinfo *ovi_self = (py_vinfo *) self; vorbis_info_clear(&ovi_self->vi); if (!PyArg_ParseTuple(args, "")) return NULL; Py_INCREF(Py_None); return Py_None; } static void py_ov_info_dealloc(PyObject *self) { PyMem_DEL(self); } #define CMP_RET(x) \ if (strcmp(name, #x) == 0) \ return PyInt_FromLong(vi->x) static PyObject * py_vorbis_info_blocksize(PyObject *self, PyObject *args) { vorbis_info *vi = PY_VINFO(self); int res, zo; if (!PyArg_ParseTuple(args, "l", &zo)) return NULL; res = vorbis_info_blocksize(vi, zo); return PyInt_FromLong(res); } static PyObject * py_ov_info_getattr(PyObject *self, char *name) { PyObject *res; vorbis_info *vi = PY_VINFO(self); char err_msg[MSG_SIZE]; res = Py_FindMethod(py_vinfo_methods, (PyObject *)self, name); if (res) return res; PyErr_Clear(); switch(name[0]) { case 'b': CMP_RET(bitrate_upper); CMP_RET(bitrate_nominal); CMP_RET(bitrate_lower); CMP_RET(bitrate_window); break; case 'c': CMP_RET(channels); break; case 'r': CMP_RET(rate); break; case 'v': CMP_RET(version); break; } snprintf(err_msg, MSG_SIZE, "No attribute: %s", name); PyErr_SetString(PyExc_AttributeError, err_msg); return NULL; } #define ADD_FIELD(field) \ { \ int added = snprintf(cur, buf_left, " %s: %d\n", #field, vi->field); \ cur += added; \ buf_left -= added; \ } static PyObject * py_ov_info_str(PyObject *self) { PyObject *ret = NULL; char buf[1000]; char *cur = &buf[0]; int buf_left = sizeof(buf) - 1; vorbis_info *vi = PY_VINFO(self); int added = snprintf(cur, buf_left, "\n"); cur += added; buf_left -= added; ADD_FIELD(version); ADD_FIELD(channels); ADD_FIELD(rate); ADD_FIELD(bitrate_upper); ADD_FIELD(bitrate_nominal); ADD_FIELD(bitrate_lower); ADD_FIELD(bitrate_window); ret = PyString_FromString(buf); return ret; } static PyObject * py_vorbis_analysis_init(PyObject *self, PyObject *args) { int res; py_vinfo *ovi_self = (py_vinfo *) self; vorbis_dsp_state vd; if (!PyArg_ParseTuple(args, "")) return NULL; if ((res = vorbis_analysis_init(&vd, &ovi_self->vi))) return v_error_from_code(res, "vorbis_analysis_init"); return py_dsp_from_dsp(&vd, self); } /* ********************************************************* VorbisComment Object methods ********************************************************* */ FDEF(vorbis_comment_clear) "Clears a VorbisComment object"; FDEF(vorbis_comment_add) "Adds a comment"; FDEF(vorbis_comment_add_tag) "Adds a comment tag"; FDEF(vorbis_comment_query) "Returns a comment_query"; FDEF(vorbis_comment_query_count) "Returns a comment_query_count"; FDEF(comment_write_to) "Write comments to an existing vorbis file"; FDEF(comment_append_to) "Append comments to an existing vorbis file"; FDEF(comment_as_dict) "Returns a dictionary representation of \ this VorbisComment object"; FDEF(comment_keys) "Returns a list of keys (like a dictionary)"; FDEF(comment_items) "Returns a list of items (like a dictionary).\n\ The list is flattened, so it is a list of strings, not a list of lists."; FDEF(comment_values) "Returns a list of values (like a dictionary).\n\ The list is flattened, so it is a list of tuples of strings,\n\ not a list of (string, list) tuples."; static void py_vorbis_comment_dealloc(PyObject *); static PyObject *py_vorbis_comment_getattr(PyObject *, char *name); static PyMethodDef py_vcomment_methods[] = { {"clear", py_vorbis_comment_clear, METH_VARARGS, py_vorbis_comment_clear_doc}, {"add", py_vorbis_comment_add, METH_VARARGS, py_vorbis_comment_add_doc}, {"add_tag", py_vorbis_comment_add_tag, METH_VARARGS, py_vorbis_comment_add_tag_doc}, {"query", py_vorbis_comment_query, METH_VARARGS, py_vorbis_comment_query_doc}, {"query_count", py_vorbis_comment_query_count, METH_VARARGS, py_vorbis_comment_query_count_doc}, {"as_dict", py_comment_as_dict, METH_VARARGS, py_comment_as_dict_doc}, {"keys", py_comment_keys, METH_VARARGS, py_comment_keys_doc}, {"items", py_comment_items, METH_VARARGS, py_comment_items_doc}, {"values", py_comment_values, METH_VARARGS, py_comment_values_doc}, {"write_to", py_comment_write_to, METH_VARARGS, py_comment_write_to_doc}, {"append_to", py_comment_append_to, METH_VARARGS, py_comment_append_to_doc}, {NULL, NULL} }; static int py_comment_length(py_vcomment *); static int py_comment_assign(py_vcomment *, PyObject *, PyObject *); static PyObject *py_comment_subscript(py_vcomment *, PyObject *); static PyMappingMethods py_vcomment_Mapping_Methods = { (inquiry) py_comment_length, (binaryfunc) py_comment_subscript, (objobjargproc) py_comment_assign }; char py_vcomment_doc[] = "A VorbisComment object stores comments about a Vorbis stream.\n\ It is used much like a Python dictionary. The keys are case-insensitive,\n\ and each value will be a list of one or more values, since keys in a\n\ Vorbis stream's comments do not have to be unique.\n\ \n\ \"mycomment[key] = val\" will append val to the list of values for key\n\ A comment object also has the keys() items() and values() functions that\n\ dictionaries have, the difference being that the lists in items() and\n\ values() are flattened. So if there are two 'Artist' entries, there will\n\ be two separate tuples in items() for 'Artist' and two strings for \n\ 'Artist' in value()."; static PyObject *py_vcomment_str(PyObject *); PyTypeObject py_vcomment_type = { PyObject_HEAD_INIT(NULL) 0, "VorbisComment", sizeof(py_vcomment), 0, /* Standard Methods */ /* destructor */ py_vorbis_comment_dealloc, /* printfunc */ 0, /* getattrfunc */ py_vorbis_comment_getattr, /* setattrfunc */ 0, /* cmpfunc */ 0, /* reprfunc */ 0, /* Type Categories */ 0, /* as number */ 0, /* as sequence */ &py_vcomment_Mapping_Methods, 0, /* hash */ 0, /* binary */ &py_vcomment_str, /* repr */ 0, /* getattro */ 0, /* setattro */ 0, /* as buffer */ 0, /* tp_flags */ py_vcomment_doc, }; /* I store the parent since I don't think the vorbis_comment data will actually stick around if we let the vorbis_file object get freed. */ PyObject * py_comment_new_from_vc(vorbis_comment *vc, PyObject *parent) { py_vcomment *newobj; newobj = (py_vcomment *) PyObject_NEW(py_vcomment, &py_vcomment_type); newobj->vc = vc; newobj->parent = parent; newobj->malloced = 0; Py_XINCREF(parent); return (PyObject *) newobj; } static PyObject * py_comment_new_empty(void) { py_vcomment *newobj; newobj = (py_vcomment *) PyObject_NEW(py_vcomment, &py_vcomment_type); if (!newobj) return NULL; newobj->parent = NULL; newobj->malloced = 1; newobj->vc = (vorbis_comment *) malloc(sizeof(vorbis_comment)); if (!newobj->vc) { PyErr_SetString(PyExc_MemoryError, "Could not create vorbis_comment"); return NULL; } vorbis_comment_init(newobj->vc); return (PyObject *) newobj; } static PyObject * py_vorbis_comment_clear(PyObject *self, PyObject *args) { py_vcomment *ovc_self = (py_vcomment *) self; if (!PyArg_ParseTuple(args, "")) return NULL; vorbis_comment_clear(ovc_self->vc); vorbis_comment_init(ovc_self->vc); Py_INCREF(Py_None); return Py_None; } static void py_vorbis_comment_dealloc(PyObject *self) { py_vcomment *ovc_self = (py_vcomment *) self; if (ovc_self->parent) { Py_DECREF(ovc_self->parent); /* parent will clear for us */ } else { vorbis_comment_clear(ovc_self->vc); } if (ovc_self->malloced) { free(ovc_self->vc); } PyMem_DEL(self); } static PyObject* py_vcomment_str(PyObject *self) { #if PY_UNICODE py_vcomment *vc_self = (py_vcomment *) self; int k, buf_len = 0; char *buf, *cur; PyObject *ret = NULL; static const char *message = "\n"; int message_len = strlen(message); static const char *prefix = " "; /* goes before each line */ int prefix_len = strlen(prefix); static const char *suffix = "\n"; /* after each line */ int suffix_len = strlen(suffix); /* first figure out how much space we need */ for (k = 0; k < vc_self->vc->comments; ++k) { buf_len += vc_self->vc->comment_lengths[k]; } /* add space for prefix/suffix and a trailing \0 */ buf_len += vc_self->vc->comments * (prefix_len + suffix_len) + 1; buf_len += message_len; buf = malloc(buf_len); strcpy(buf, message); cur = buf + message_len; /* now copy the comments in */ for (k = 0; k < vc_self->vc->comments; ++k) { int comment_len = vc_self->vc->comment_lengths[k]; strncpy(cur, prefix, prefix_len); cur += prefix_len; strncpy(cur, vc_self->vc->user_comments[k], comment_len); cur += comment_len; strncpy(cur, suffix, suffix_len); cur += suffix_len; } buf[buf_len - 1] = '\0'; ret = PyUnicode_DecodeUTF8(buf, buf_len, NULL); free(buf); return ret; #else /* We can't do much without unicode */ return PyString_FromString(""); #endif } static PyObject* py_vorbis_comment_getattr(PyObject *self, char *name) { PyObject *res; res = Py_FindMethod(py_vcomment_methods, self, name); return res; } static int py_comment_length(py_vcomment *self) { int val = self->vc->comments; if (self->vc->vendor) val++; return val; } static PyObject * py_comment_subscript(py_vcomment *self, PyObject *keyobj) { char *res, *tag; int cur = 0; PyObject *retlist, *item; if (!PyString_Check(keyobj)) { PyErr_SetString(PyExc_KeyError, "Keys may only be strings"); return NULL; } tag = PyString_AsString(keyobj); retlist = PyList_New(0); res = vorbis_comment_query(self->vc, tag, cur++); while (res != NULL) { int vallen = strlen(res); #if PY_UNICODE item = PyUnicode_DecodeUTF8(res, vallen, NULL); if (!item) { /* must clear the exception raised by PyUnicode_DecodeUTF8() */ PyErr_Clear(); /* To deal with non-UTF8 comments (against the standard) */ item = PyString_FromStringAndSize(res, vallen); } #else item = PyString_FromStringAndSize(res, vallen); #endif PyList_Append(retlist, item); Py_DECREF(item); res = vorbis_comment_query(self->vc, tag, cur++); } if (cur == 1) { Py_DECREF(retlist); PyErr_SetString(PyExc_KeyError, "Key not found"); return NULL; } return retlist; } #define UPPER(x) (((x) <= 'z' && (x) >= 'a') ? (x) - 'a' + 'A' : (x)) /* Return whether tag is of the form query=... */ static int find_tag_insensitive(char *tag, char *key) { int k; for (k = 0; key[k] != 0 && tag[k] != 0; k++) { if (UPPER(key[k]) != UPPER(tag[k])) { return 0; } } if (tag[k] != '=') { return 0; } return 1; } /* Create a new vorbis_comment, copy every comment from the old vorbis_comment which does not start with the given key, and set the new comment struct into the py_vcomment Object */ static void del_comment(py_vcomment *self, char *key) { vorbis_comment *vc = malloc(sizeof(vorbis_comment)); int k; vorbis_comment_init(vc); /* TODO: Vendor tag */ for (k = 0; k < self->vc->comments; k++) { if (!find_tag_insensitive(self->vc->user_comments[k], key)) { vorbis_comment_add(vc, self->vc->user_comments[k]); } } /* Get rid of the old comment structure */ if (self->parent) { Py_DECREF(self->parent); /* parent will clear for us */ self->parent = NULL; } else { vorbis_comment_clear(self->vc); } if (self->malloced) { free(self->vc); } /* The new vorbis_comment was malloced */ self->malloced = 1; self->vc = vc; } static int py_comment_assign(py_vcomment *self, PyObject *keyobj, PyObject *valobj) { vorbis_comment *vc = PY_VCOMMENT(self); char *tag, *val; if (!PyString_Check(keyobj)) { PyErr_SetString(PyExc_KeyError, "Keys may only be ASCII strings"); return -1; } if (valobj == NULL) { del_comment(self, PyString_AsString(keyobj)); return 0; } if (PyString_Check(valobj)) { val = PyString_AsString(valobj); } #if PY_UNICODE else if (PyUnicode_Check(valobj)) { PyObject *unistring = PyUnicode_AsUTF8String(valobj); val = PyString_AsString(unistring); Py_DECREF(unistring); } #endif else { PyErr_SetString(PyExc_KeyError, "Values may only be strings"); return -1; } tag = PyString_AsString(keyobj); vorbis_comment_add_tag(vc, tag, val); return 0; } static PyObject * py_comment_keys(PyObject *self, PyObject *args) { PyObject *dict; PyObject *keys; if (!PyArg_ParseTuple(args, "")) return NULL; dict = py_comment_as_dict(self, NULL); if (!dict) return NULL; keys = PyDict_Keys(dict); Py_DECREF(dict); return keys; } static PyObject * py_comment_items(PyObject *self, PyObject *args) { int curitem, curpos, j; PyObject *key, *val, *curval, *tuple; PyObject *retlist; PyObject *dict; if (!PyArg_ParseTuple(args, "")) return NULL; dict = py_comment_as_dict(self, NULL); if (!dict) return NULL; retlist = PyList_New(0); curitem = curpos = 0; while (PyDict_Next(dict, &curitem, &key, &val) > 0) { assert(PyList_Check(val)); /* flatten out the list */ for (j = 0; j < PyList_Size(val); j++) { tuple = PyTuple_New(2); curval = PyList_GetItem(val, j); Py_INCREF(key); Py_INCREF(curval); PyTuple_SET_ITEM(tuple, 0, key); PyTuple_SET_ITEM(tuple, 1, curval); PyList_Append(retlist, tuple); Py_DECREF(tuple); } } Py_DECREF(dict); return retlist; } static PyObject * py_comment_values(PyObject *self, PyObject *args) { int curitem, curpos, j; PyObject *key, *val, *curval; PyObject *retlist; PyObject *dict; if (!PyArg_ParseTuple(args, "")) return NULL; retlist = PyList_New(0); dict = py_comment_as_dict(self, NULL); curitem = curpos = 0; while (PyDict_Next (dict, &curitem, &key, &val)) { assert(PyList_Check(val)); /* flatten out the list */ for (j = 0; j < PyList_Size(val); j++) { curval = PyList_GET_ITEM(val, j); PyList_Append(retlist, curval); } } Py_DECREF(dict); return retlist; } static PyObject * py_vorbis_comment_add(PyObject *self, PyObject *args) { py_vcomment *ovc_self = (py_vcomment *) self; char *comment; if (!PyArg_ParseTuple(args, "s", &comment)) return NULL; vorbis_comment_add(ovc_self->vc, comment); Py_INCREF(Py_None); return Py_None; } static PyObject * py_vorbis_comment_add_tag(PyObject *self, PyObject *args) { py_vcomment *ovc_self = (py_vcomment *) self; char *comment, *tag; /* TODO: What will this store if it's unicode? I think UTF-16, want UTF-8. TODO: Learn Unicode!! */ if (!PyArg_ParseTuple(args, "ss", &comment, &tag)) return NULL; vorbis_comment_add_tag(ovc_self->vc, comment, tag); Py_INCREF(Py_None); return Py_None; } static PyObject * py_vorbis_comment_query(PyObject *self, PyObject *args) { char *tag, *res; int count; vorbis_comment *vc = PY_VCOMMENT(self); if (!PyArg_ParseTuple(args, "si", &tag, &count)) return NULL; res = vorbis_comment_query(vc, tag, count); return PyString_FromString(res); } static PyObject * py_vorbis_comment_query_count(PyObject *self, PyObject *args) { char *tag; vorbis_comment *vc = PY_VCOMMENT(self); if (!PyArg_ParseTuple(args, "s", &tag)) return NULL; return PyInt_FromLong(vorbis_comment_query_count(vc, tag)); } /* We need this for Win32, so I'll implement it rather than use strcasecmp on Linux */ static int pystrcasecmp(const char *str1, const char *str2) { int k = 0; while (str1[k] != '\0' && str2[k] != '\0') { char c1 = str1[k]; char c2 = str2[k]; if (c1 >= 'A' && c1 <= 'Z') { c1 = c1 - 'A' + 'a'; } if (c2 >= 'A' && c1 <= 'Z') { c2 = c1 - 'A' + 'a'; } if (c1 < c2) { return -1; } else if (c1 > c2) { return 1; } ++k; } return 0; } static int make_caps_key(char *in, int size) { int pos; for (pos = 0; pos < size && in[pos] != '\0'; pos++) { if (in[pos] >= 'a' && in[pos] <= 'z') in[pos] = in[pos] + 'A' - 'a'; else in[pos] = in[pos]; } in[pos] = '\0'; return 0; } /* Assign a tag in a vorbis_comment, special-casing the VENDOR tag. */ static int assign_tag(vorbis_comment *vcomment, const char *key, PyObject *tag) { char *tag_str; char tag_buff[1024]; if (PyString_Check(tag)) { tag_str = PyString_AsString(tag); } #if PY_UNICODE else if (PyUnicode_Check(tag)) { tag_str = PyString_AsString(PyUnicode_AsUTF8String(tag)); } #endif else { PyErr_SetString(PyExc_ValueError, "Setting comment with non-string object"); return 0; } if (!pystrcasecmp(key, "vendor")) { vcomment->vendor = strdup(tag_str); } else { int k; int key_len = strlen(key); int value_len = strlen(tag_str); if (key_len + value_len + 1 >= sizeof(tag_buff)) { PyErr_SetString(PyExc_ValueError, "Comment too long for allocated buffer"); return 0; } // Capitalize the key. This is not strictly necessary, but it // keeps things looking consistent. for (k = 0; k < key_len; k++) tag_buff[k] = toupper(key[k]); tag_buff[key_len] = '='; strncpy(tag_buff + key_len + 1, tag_str, sizeof(tag_buff) - key_len - 1); vorbis_comment_add(vcomment, tag_buff); } return 1; } /* NOTE: Something like this should be wrong but will, I guess, 'work': { 'Vendor' : 'me', 'VENDOR': 'someone else'} */ static int create_comment_from_items(vorbis_comment *vcomment, const char *key, PyObject *item_vals) { #if PY_UNICODE if (PyUnicode_Check(item_vals)) { return assign_tag(vcomment, key, item_vals); } else #endif if (PyString_Check(item_vals)) { return assign_tag(vcomment, key, item_vals); } else if (PySequence_Check(item_vals)) { int j, val_length = PySequence_Length(item_vals); if (!pystrcasecmp(key, "vendor") && val_length > 1) { PyErr_SetString(PyExc_ValueError, "Cannot have multiple vendor tags"); } for (j = 0; j < val_length; j++) { PyObject *tag_value = PySequence_GetItem(item_vals, j); if (!tag_value) return 0; if (!assign_tag(vcomment, key, tag_value)) return 0; } } else { PyErr_SetString(PyExc_ValueError, "Value not a string or sequence."); return 0; } return 1; } static vorbis_comment * create_comment_from_dict(PyObject *dict) { vorbis_comment *vcomment = NULL; int initted = 0; PyObject *items = NULL; int k, length; vcomment = (vorbis_comment *) malloc(sizeof(vorbis_comment)); if (!vcomment) { PyErr_SetString(PyExc_MemoryError, "error allocating vcomment"); goto error; } vorbis_comment_init(vcomment); initted = 1; items = PyDict_Items(dict); if (!items) goto error; length = PyList_Size(items); for (k = 0; k < length; k++) { PyObject *pair = PyList_GetItem(items, k); PyObject *key, *val; if (!pair) goto error; assert(PyTuple_Check(pair)); key = PyTuple_GetItem(pair, 0); val = PyTuple_GetItem(pair, 1); if (!PyString_Check(key)) { PyErr_SetString(PyExc_ValueError, "Key not a string"); goto error; } if (!create_comment_from_items(vcomment, PyString_AsString(key), val)) goto error; } return vcomment; error: /* Note: I hate dealing with memory */ Py_XDECREF(items); if (vcomment) { if (initted) vorbis_comment_clear(vcomment); free(vcomment); } return NULL; } PyObject * py_comment_new(PyObject *self, PyObject *args) { py_vcomment *pvc; PyObject *dict; vorbis_comment *vcomment; if (PyArg_ParseTuple(args, "")) { return py_comment_new_empty(); } else { PyErr_Clear(); /* Clear the first error */ if (!PyArg_ParseTuple(args, "O!", &PyDict_Type, &dict)) return NULL; } vcomment = create_comment_from_dict(dict); if (!vcomment) return NULL; pvc = (py_vcomment *) PyObject_NEW(py_vcomment, &py_vcomment_type); if (!pvc) { vorbis_comment_clear(vcomment); free(vcomment); return NULL; } pvc->vc = vcomment; pvc->parent = NULL; pvc->malloced = 1; return (PyObject *) pvc; } static PyObject * py_comment_as_dict(PyObject *self, PyObject *args) { vorbis_comment *comment; py_vcomment *ovc_self = (py_vcomment *) self; int i, keylen, vallen; char *key, *val; PyObject *retdict, *curlist, *item, *vendor_obj; /* This can be called with args=NULL as a helper function */ if (args != NULL && !PyArg_ParseTuple(args, "")) return NULL; comment = ovc_self->vc; retdict = PyDict_New(); /* If the vendor is set, set the key "VENDOR" to map to a singleton list with the vendor value in it. */ if (comment->vendor != NULL) { curlist = PyList_New(1); vendor_obj = PyString_FromString(comment->vendor); PyList_SET_ITEM(curlist, 0, vendor_obj); PyDict_SetItemString(retdict, "VENDOR", curlist); Py_DECREF(curlist); } else vendor_obj = NULL; /* These first few lines taken from the Perl bindings */ for (i = 0; i < comment->comments; i++) { /* don't want to limit this, I guess */ key = strdup(comment->user_comments[i]); if ((val = strchr(key, '='))) { keylen = val - key; *(val++) = '\0'; vallen = comment->comment_lengths[i] - keylen - 1; #if PY_UNICODE item = PyUnicode_DecodeUTF8(val, vallen, NULL); if (!item) { /* To deal with non-UTF8 comments (against the standard) */ item = PyString_FromStringAndSize(val, vallen); } #else item = PyString_FromStringAndSize(val, vallen); #endif if (!item) goto error; if (make_caps_key(key, keylen)) { /* overwrites key */ Py_DECREF(item); goto error; } /* GetItem borrows a reference */ if ((curlist = PyDict_GetItemString(retdict, key))) { /* A list already exists for that key */ if (PyList_Append(curlist, item) < 0) { Py_DECREF(item); goto error; } } else { /* Add a new list in that position */ curlist = PyList_New(1); PyList_SET_ITEM(curlist, 0, item); Py_INCREF(item); /* this does not steal a reference */ PyDict_SetItemString(retdict, key, curlist); Py_DECREF(curlist); } Py_DECREF(item); } free(key); key = NULL; } return retdict; error: Py_XDECREF(retdict); if (key) free(key); return NULL; } /* Helper function which writes/appends comments to a file */ static PyObject* write_comments(vorbis_comment *vc, const char *filename, int append) { vcedit_state *state; vorbis_comment *file_comments; FILE *in_file, *out_file; int k; char *tempfile = malloc(strlen(filename) + sizeof(".pytemp")); strcpy(tempfile, filename); strcat(tempfile, ".pytemp"); /* Open the file */ in_file = fopen(filename, "rb"); if (!in_file) { PyErr_SetFromErrno(PyExc_IOError); return NULL; } out_file = fopen(tempfile, "wb"); if (!out_file) { fclose(in_file); PyErr_SetFromErrno(PyExc_IOError); return NULL; } state = vcedit_new_state(); /* Make sure it's a vorbis file */ if (vcedit_open(state, in_file) < 0) { char buff[256]; snprintf(buff, sizeof(buff), "Could not open file %s as vorbis: %s", filename, vcedit_error(state)); PyErr_SetString(Py_VorbisError, buff); vcedit_clear(state); fclose(in_file); fclose(out_file); return NULL; } /* Get the vorbis comments that are already in the file, and clear if necessary */ file_comments = vcedit_comments(state); if (!append) { vorbis_comment_clear(file_comments); vorbis_comment_init(file_comments); } /* Append all the comments we already have in vc */ for (k = 0; k < vc->comments; k++) { vorbis_comment_add(file_comments, vc->user_comments[k]); } if (vcedit_write(state, out_file) < 0) { char buff[256]; snprintf(buff, sizeof(buff), "Could not write comments to file: %s", vcedit_error(state)); PyErr_SetString(Py_VorbisError, buff); vcedit_clear(state); fclose(in_file); fclose(out_file); return NULL; } vcedit_clear(state); fclose(in_file); fclose(out_file); /* The following comment, quoted from the vorbiscomment/vcomment.c file * of the vorbis-tools package, regards to, e.g., Windows: * * Some platforms fail to rename a file if the new name already exists, so * we need to remove, then rename. How stupid. * * This is why the following block had to be inserted to make things work under * Windows also. * * */ if (remove(filename)) { PyErr_SetFromErrno(PyExc_IOError); return NULL; } if (rename(tempfile, filename)) { PyErr_SetFromErrno(PyExc_IOError); return NULL; } Py_INCREF(Py_None); return Py_None; } static PyObject * py_comment_append_to(PyObject *self, PyObject *args) { vorbis_comment *vc = PY_VCOMMENT(self); const char *filename; if (!PyArg_ParseTuple(args, "s", &filename)) return NULL; return write_comments(vc, filename, 1); } static PyObject * py_comment_write_to(PyObject *self, PyObject *args) { vorbis_comment *vc = PY_VCOMMENT(self); const char *filename; if (!PyArg_ParseTuple(args, "s", &filename)) return NULL; return write_comments(vc, filename, 0); } pyvorbis-1.5a/src/pyvorbisinfo.h010064400017500000012000000012741051746235000157710ustar00ericusers#ifndef __PYVORBIS_INFO_H__ #define __PYVORBIS_INFO_H__ #include typedef struct { PyObject_HEAD vorbis_info vi; } py_vinfo; typedef struct { PyObject_HEAD int malloced; vorbis_comment *vc; PyObject *parent; } py_vcomment; #define PY_VINFO(x) (&(((py_vinfo *) (x))->vi)) #define PY_VCOMMENT(x) ((((py_vcomment *) (x))->vc)) extern PyTypeObject py_vinfo_type; extern PyTypeObject py_vcomment_type; PyObject *py_info_new_from_vi(vorbis_info *vi); PyObject *py_info_new(PyObject *, PyObject *, PyObject *); PyObject *py_comment_new_from_vc(vorbis_comment *vc, PyObject *parent); PyObject *py_comment_new(PyObject *, PyObject *); #endif /* __PYVORBIS_INFO_H__ */ pyvorbis-1.5a/src/vcedit.c010064400017500000012000000245611051746235000145150ustar00ericusers/* This program is licensed under the GNU Library General Public License, version 2, * a copy of which is included with this program (LICENCE.LGPL). * * (c) 2000-2001 Michael Smith * * * Comment editing backend, suitable for use by nice frontend interfaces. * * last modified: $Id: vcedit.c,v 1.1 2002/01/22 01:57:56 andrew Exp $ */ #include #include #include #include #include #include "vcedit.h" #define CHUNKSIZE 4096 vcedit_state *vcedit_new_state(void) { vcedit_state *state = malloc(sizeof(vcedit_state)); memset(state, 0, sizeof(vcedit_state)); return state; } char *vcedit_error(vcedit_state *state) { return state->lasterror; } vorbis_comment *vcedit_comments(vcedit_state *state) { return state->vc; } static void vcedit_clear_internals(vcedit_state *state) { if(state->vc) { vorbis_comment_clear(state->vc); free(state->vc); state->vc=NULL; } if(state->os) { ogg_stream_clear(state->os); free(state->os); state->os=NULL; } if(state->oy) { ogg_sync_clear(state->oy); free(state->oy); state->oy=NULL; } if(state->vendor) { free(state->vendor); state->vendor=NULL; } } void vcedit_clear(vcedit_state *state) { if(state) { vcedit_clear_internals(state); free(state); } } /* Next two functions pulled straight from libvorbis, apart from one change * - we don't want to overwrite the vendor string. */ static void _v_writestring(oggpack_buffer *o,char *s, int len) { while(len--) { oggpack_write(o,*s++,8); } } static int _commentheader_out(vorbis_comment *vc, char *vendor, ogg_packet *op) { oggpack_buffer opb; oggpack_writeinit(&opb); /* preamble */ oggpack_write(&opb,0x03,8); _v_writestring(&opb,"vorbis", 6); /* vendor */ oggpack_write(&opb,strlen(vendor),32); _v_writestring(&opb,vendor, strlen(vendor)); /* comments */ oggpack_write(&opb,vc->comments,32); if(vc->comments){ int i; for(i=0;icomments;i++){ if(vc->user_comments[i]){ oggpack_write(&opb,vc->comment_lengths[i],32); _v_writestring(&opb,vc->user_comments[i], vc->comment_lengths[i]); }else{ oggpack_write(&opb,0,32); } } } oggpack_write(&opb,1,1); op->packet = _ogg_malloc(oggpack_bytes(&opb)); memcpy(op->packet, opb.buffer, oggpack_bytes(&opb)); op->bytes=oggpack_bytes(&opb); op->b_o_s=0; op->e_o_s=0; op->granulepos=0; return 0; } static int _blocksize(vcedit_state *s, ogg_packet *p) { int this = vorbis_packet_blocksize(&s->vi, p); int ret = (this + s->prevW)/4; if(!s->prevW) { s->prevW = this; return 0; } s->prevW = this; return ret; } static int _fetch_next_packet(vcedit_state *s, ogg_packet *p, ogg_page *page) { int result; char *buffer; int bytes; result = ogg_stream_packetout(s->os, p); if(result > 0) return 1; else { if(s->eosin) return 0; while(ogg_sync_pageout(s->oy, page) <= 0) { buffer = ogg_sync_buffer(s->oy, CHUNKSIZE); bytes = s->read(buffer,1, CHUNKSIZE, s->in); ogg_sync_wrote(s->oy, bytes); if(bytes == 0) return 0; } if(ogg_page_eos(page)) s->eosin = 1; else if(ogg_page_serialno(page) != s->serial) { s->eosin = 1; s->extrapage = 1; return 0; } ogg_stream_pagein(s->os, page); return _fetch_next_packet(s, p, page); } } int vcedit_open(vcedit_state *state, FILE *in) { return vcedit_open_callbacks(state, (void *)in, (vcedit_read_func)fread, (vcedit_write_func)fwrite); } int vcedit_open_callbacks(vcedit_state *state, void *in, vcedit_read_func read_func, vcedit_write_func write_func) { char *buffer; int bytes,i; ogg_packet *header; ogg_packet header_main; ogg_packet header_comments; ogg_packet header_codebooks; ogg_page og; state->in = in; state->read = read_func; state->write = write_func; state->oy = malloc(sizeof(ogg_sync_state)); ogg_sync_init(state->oy); buffer = ogg_sync_buffer(state->oy, CHUNKSIZE); bytes = state->read(buffer, 1, CHUNKSIZE, state->in); ogg_sync_wrote(state->oy, bytes); if(ogg_sync_pageout(state->oy, &og) != 1) { if(byteslasterror = "Input truncated or empty."; else state->lasterror = "Input is not an Ogg bitstream."; goto err; } state->serial = ogg_page_serialno(&og); state->os = malloc(sizeof(ogg_stream_state)); ogg_stream_init(state->os, state->serial); vorbis_info_init(&state->vi); state->vc = malloc(sizeof(vorbis_comment)); vorbis_comment_init(state->vc); if(ogg_stream_pagein(state->os, &og) < 0) { state->lasterror = "Error reading first page of Ogg bitstream."; goto err; } if(ogg_stream_packetout(state->os, &header_main) != 1) { state->lasterror = "Error reading initial header packet."; goto err; } if(vorbis_synthesis_headerin(&state->vi, state->vc, &header_main) < 0) { state->lasterror = "Ogg bitstream does not contain vorbis data."; goto err; } state->mainlen = header_main.bytes; state->mainbuf = malloc(state->mainlen); memcpy(state->mainbuf, header_main.packet, header_main.bytes); i = 0; header = &header_comments; while(i<2) { while(i<2) { int result = ogg_sync_pageout(state->oy, &og); if(result == 0) break; /* Too little data so far */ else if(result == 1) { ogg_stream_pagein(state->os, &og); while(i<2) { result = ogg_stream_packetout(state->os, header); if(result == 0) break; if(result == -1) { state->lasterror = "Corrupt secondary header."; goto err; } vorbis_synthesis_headerin(&state->vi, state->vc, header); if(i==1) { state->booklen = header->bytes; state->bookbuf = malloc(state->booklen); memcpy(state->bookbuf, header->packet, header->bytes); } i++; header = &header_codebooks; } } } buffer = ogg_sync_buffer(state->oy, CHUNKSIZE); bytes = state->read(buffer, 1, CHUNKSIZE, state->in); if(bytes == 0 && i < 2) { state->lasterror = "EOF before end of vorbis headers."; goto err; } ogg_sync_wrote(state->oy, bytes); } /* Copy the vendor tag */ state->vendor = malloc(strlen(state->vc->vendor) +1); strcpy(state->vendor, state->vc->vendor); /* Headers are done! */ return 0; err: vcedit_clear_internals(state); return -1; } int vcedit_write(vcedit_state *state, void *out) { ogg_stream_state streamout; ogg_packet header_main; ogg_packet header_comments; ogg_packet header_codebooks; ogg_page ogout, ogin; ogg_packet op; ogg_int64_t granpos = 0; int result; char *buffer; int bytes; int needflush=0, needout=0; state->eosin = 0; state->extrapage = 0; header_main.bytes = state->mainlen; header_main.packet = state->mainbuf; header_main.b_o_s = 1; header_main.e_o_s = 0; header_main.granulepos = 0; header_codebooks.bytes = state->booklen; header_codebooks.packet = state->bookbuf; header_codebooks.b_o_s = 0; header_codebooks.e_o_s = 0; header_codebooks.granulepos = 0; ogg_stream_init(&streamout, state->serial); _commentheader_out(state->vc, state->vendor, &header_comments); ogg_stream_packetin(&streamout, &header_main); ogg_stream_packetin(&streamout, &header_comments); ogg_stream_packetin(&streamout, &header_codebooks); while((result = ogg_stream_flush(&streamout, &ogout))) { if(state->write(ogout.header,1,ogout.header_len, out) != (size_t) ogout.header_len) goto cleanup; if(state->write(ogout.body,1,ogout.body_len, out) != (size_t) ogout.body_len) goto cleanup; } while(_fetch_next_packet(state, &op, &ogin)) { int size; size = _blocksize(state, &op); granpos += size; if(needflush) { if(ogg_stream_flush(&streamout, &ogout)) { if(state->write(ogout.header,1,ogout.header_len, out) != (size_t) ogout.header_len) goto cleanup; if(state->write(ogout.body,1,ogout.body_len, out) != (size_t) ogout.body_len) goto cleanup; } } else if(needout) { if(ogg_stream_pageout(&streamout, &ogout)) { if(state->write(ogout.header,1,ogout.header_len, out) != (size_t) ogout.header_len) goto cleanup; if(state->write(ogout.body,1,ogout.body_len, out) != (size_t) ogout.body_len) goto cleanup; } } needflush=needout=0; if(op.granulepos == -1) { op.granulepos = granpos; ogg_stream_packetin(&streamout, &op); } else /* granulepos is set, validly. Use it, and force a flush to account for shortened blocks (vcut) when appropriate */ { if(granpos > op.granulepos) { granpos = op.granulepos; ogg_stream_packetin(&streamout, &op); needflush=1; } else { ogg_stream_packetin(&streamout, &op); needout=1; } } } streamout.e_o_s = 1; while(ogg_stream_flush(&streamout, &ogout)) { if(state->write(ogout.header,1,ogout.header_len, out) != (size_t) ogout.header_len) goto cleanup; if(state->write(ogout.body,1,ogout.body_len, out) != (size_t) ogout.body_len) goto cleanup; } /* FIXME: freeing this here probably leaks memory */ /* Done with this, now */ vorbis_info_clear(&state->vi); if (state->extrapage) { if(state->write(ogin.header,1,ogin.header_len, out) != (size_t) ogin.header_len) goto cleanup; if (state->write(ogin.body,1,ogin.body_len, out) != (size_t) ogin.body_len) goto cleanup; } state->eosin=0; /* clear it, because not all paths to here do */ while(!state->eosin) /* We reached eos, not eof */ { /* We copy the rest of the stream (other logical streams) * through, a page at a time. */ while(1) { result = ogg_sync_pageout(state->oy, &ogout); if(result==0) break; if(result<0) state->lasterror = "Corrupt or missing data, continuing..."; else { /* Don't bother going through the rest, we can just * write the page out now */ if(state->write(ogout.header,1,ogout.header_len, out) != (size_t) ogout.header_len) goto cleanup; if(state->write(ogout.body,1,ogout.body_len, out) != (size_t) ogout.body_len) goto cleanup; } } buffer = ogg_sync_buffer(state->oy, CHUNKSIZE); bytes = state->read(buffer,1, CHUNKSIZE, state->in); ogg_sync_wrote(state->oy, bytes); if(bytes == 0) { state->eosin = 1; break; } } cleanup: ogg_stream_clear(&streamout); ogg_packet_clear(&header_comments); free(state->mainbuf); free(state->bookbuf); vcedit_clear_internals(state); if(!state->eosin) { state->lasterror = "Error writing stream to output. " "Output stream may be corrupted or truncated."; return -1; } return 0; } pyvorbis-1.5a/src/vcedit.h010064400017500000012000000026361051746235000145210ustar00ericusers/* This program is licensed under the GNU Library General Public License, version 2, * a copy of which is included with this program (with filename LICENSE.LGPL). * * (c) 2000-2001 Michael Smith * * VCEdit header. * * last modified: $ID:$ */ #ifndef __VCEDIT_H #define __VCEDIT_H #ifdef __cplusplus extern "C" { #endif #include #include #include typedef size_t (*vcedit_read_func)(void *, size_t, size_t, void *); typedef size_t (*vcedit_write_func)(const void *, size_t, size_t, void *); typedef struct { ogg_sync_state *oy; ogg_stream_state *os; vorbis_comment *vc; vorbis_info vi; vcedit_read_func read; vcedit_write_func write; void *in; long serial; unsigned char *mainbuf; unsigned char *bookbuf; int mainlen; int booklen; char *lasterror; char *vendor; int prevW; int extrapage; int eosin; } vcedit_state; extern vcedit_state * vcedit_new_state(void); extern void vcedit_clear(vcedit_state *state); extern vorbis_comment * vcedit_comments(vcedit_state *state); extern int vcedit_open(vcedit_state *state, FILE *in); extern int vcedit_open_callbacks(vcedit_state *state, void *in, vcedit_read_func read_func, vcedit_write_func write_func); extern int vcedit_write(vcedit_state *state, void *out); extern char * vcedit_error(vcedit_state *state); #ifdef __cplusplus } #endif #endif /* __VCEDIT_H */ pyvorbis-1.5a/src/vorbismodule.c010064400017500000012000000053501051746235000157440ustar00ericusers#include #include #include "vorbismodule.h" #include "pyvorbiscodec.h" #include "pyvorbisfile.h" #include "pyvorbisinfo.h" #include "general.h" static PyMethodDef Vorbis_methods[] = { {"VorbisFile", py_file_new, METH_VARARGS, py_vorbisfile_doc}, {"VorbisInfo", (PyCFunction) py_info_new, METH_VARARGS | METH_KEYWORDS, py_vinfo_doc}, {"VorbisComment", py_comment_new, METH_VARARGS, py_vcomment_doc}, {NULL, NULL} }; static char docstring[] = ""; PyObject * v_error_from_code(int code, char *msg) { char errmsg[MSG_SIZE]; char *reason; switch (code) { case OV_FALSE: reason = "Function returned FALSE."; break; case OV_HOLE: reason = "Interruption in data."; break; case OV_EREAD: reason = "Read error."; break; case OV_EFAULT: reason = "Internal logic fault. Bug or heap/stack corruption."; break; case OV_EIMPL: reason = "Bitstream uses unimplemented feature."; break; case OV_EINVAL: reason = "Invalid argument."; break; case OV_ENOTVORBIS: reason = "Data is not Vorbis data."; break; case OV_EBADHEADER: reason = "Invalid Vorbis bitstream header."; break; case OV_EVERSION: reason = "Vorbis version mismatch."; break; case OV_ENOTAUDIO: reason = "Packet data is not audio."; break; case OV_EBADPACKET: reason = "Invalid packet."; break; case OV_EBADLINK: reason = "Invalid stream section, or the requested link is corrupt."; break; case OV_ENOSEEK: reason = "Bitstream is not seekable."; break; default: reason = "Unknown error."; } strncpy(errmsg, msg, MSG_SIZE); strncat(errmsg, reason, MSG_SIZE - strlen(errmsg)); PyErr_SetString(Py_VorbisError, errmsg); return NULL; } ogg_module_info *modinfo; void initvorbis(void) { PyObject *module, *dict; py_dsp_type.ob_type = &PyType_Type; py_block_type.ob_type = &PyType_Type; py_vorbisfile_type.ob_type = &PyType_Type; py_vinfo_type.ob_type = &PyType_Type; py_vcomment_type.ob_type = &PyType_Type; module = Py_InitModule("ogg.vorbis", Vorbis_methods); dict = PyModule_GetDict(module); modinfo = PyCObject_Import("ogg._ogg", "_moduleinfo"); if (modinfo == NULL) { PyErr_SetString(PyExc_ImportError, "Could not load ogg._ogg"); return; } Py_VorbisError = PyErr_NewException("ogg.vorbis.VorbisError", modinfo->Py_OggError, NULL); PyDict_SetItemString(dict, "VorbisError", Py_VorbisError); PyDict_SetItemString(dict, "__doc__", PyString_FromString(docstring)); PyDict_SetItemString(dict, "__version__", PyString_FromString("1.2")); if (PyErr_Occurred()) PyErr_SetString(PyExc_ImportError, "ogg.vorbis: init failed"); } pyvorbis-1.5a/src/general.c010064400017500000012000000001401051746235000146370ustar00ericusers#include "general.h" #include /* for now, just take arg_to_int64 from pyogg */ pyvorbis-1.5a/COPYING010064400017500000012000000613141051746235000133340ustar00ericusers 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! pyvorbis-1.5a/ChangeLog010064400017500000012000000243071051746235000140540ustar00ericusers2006-10-24 Eric Faurot * pyvorbisfile.c: Memory leak and double free fixes. These issues were tracked down and patched by Greg Ward. 2003-12-18 Andrew H. Chatham * pyvorbisinfo.c: Incoporate John Morton's explanations about what all those arguments mean. Now everything that takes a logical stream index says so. * pyvorbisinfo.c: Provide str() methods for VorbisComment and VorbisInfo objects. Now they print out all pretty and stuff. Now VorbisFile could still use one. 2003-09-08 Andrew H. Chatham * pyvorbisfile.c, pyvorbisinfo.c: Fix an exception leak (the exceptions would show up later, even though things worked OK) 2003-9-01 Andrew H. Chatham * pyvorbisfile.c (py_ov_file_dealloc) Fix a file descriptor leak. 2003-5-31 Andrew H. Chatham * pyvorbisinfo.c (py_comment_subscript) Applied patch from Brian Warner to fix a bug where I wasn't clearing the Python error correctly in unicode conversion. * pyvorbisinfo.c (write_comments) Applied patch from Csaba Henk to fix comment modification in Windows. 2003-5-13 Andrew H. Chatham * pyvorbisinfo.c (py_info_new): Applied patch from Andrew Mahone to allow negative quality values * pyvorbisfile.c (is_big_endian): Use runtime endian test rather than try to figure out where everyone keeps endian.h * pyvorbiscodec.c (py_dsp_write_wav): Applied patch from Andrew Mahone to fix a truncation bug with weird wav files. 2003-2-07 Andrew H. Chatham * Applied another patch from Nicodemus to fix things windows. Pass the "b" flag to all file open commands. 2003-1-18 Andrew H. Chatham * Applied a patch from Nicodemus to get this to build on windows. 2002-09-24 Andrew H. Chatham * Changes from Neil Blakey-Milner * setup.py - fixed regular expression * pyvorbisfile.c: Used more portable endian-test code. 2002-09-12 Andrew H. Chatham * pyvorbisinfo.c: (assign_tag) Removed a printf I accidentally left in there. 2002-09-12 Andrew H. Chatham * setup.py: Bumped to version 1.1 (may not release until I verify another bug report) * pyvorbisinfo.c: (py_comment_new_empty) Made static and fixed the case when using unicode strings with VorbisComment. Also now capitalize the key for comments. * pyvorbisfile.c: Added patch so that passing in PyFile objects to a VorbisFile object won't _necessarily_ crash and burn, though it's still not a good idea. A much better way of doing this is the next planned feature. 2002-07-23 Andrew H. Chatham * README - documented new comment interface * Bumped to 1.0 to match Vorbis * pyvorbisinfo.c: Removed printf 2002-07-16 Andrew H. Chatham * pyvorbisinfo.c: Can now create comments from dictionaries (a MUCH better interface) * vorbismodule.h: Removed unneeded declarations 2002-05-21 Andrew H. Chatham * pyvorbisinfo.c: Don't crash if comments are not valid UTF-8 * vorbismodule.c: Include some more headers 2002-02-17 Andrew H. Chatham * pyvorbisfile.c: (py_ov_open): Fixed fd leak pointed out by Harald Meland. Also correctly incref file objects passed in to keep them open. * vorbismodule.c, pyvorbisfile.c, pyvorbiscodec.c, pyvorbisinfo.c: Set the ob_types in the init method instead of statically, as MSVC complains. 2002-01-27 Andrew H. Chatham * pyvorbisinfo.c (del_comment): Set parent to NULL after decref 2002-01-27 Andrew H. Chatham * test/comment.py: Added * pyvorbisinfo.c (del_comment), (find_tag_insensitive): Added. You can now delete comments. * README: Explain how to delete comments 2002-01-27 Andrew H. Chatham * bump to version 0.5 2002-01-27 Andrew H. Chatham * pyvorbiscodec.c (py_dsp_write_wav), (parse_wav_data): Added * pyvorbiscodec.c (py_dsp_write): Write 0 if None * pyvorbisinfo.c: Removed some unused variables * pyvorbisinfo.c (py_info_new): Parse the quality option * pyvorbisinfo.c (py_vorbis_info_blocksize): Added * test/enc.py: Updated to do new encode process (with quality setting) * test/enc2.py: Updated to do quality setting and use write_wav 2002-01-21 Andrew H. Chatham * pyvorbisinfo.c: Comment objects now store pointers to the comment structures, not the structure itself. Helps with dealloc. * pyvorbisinfo.c (write_comments), (py_comment_append_to), (py_comment_write_to): Added * pyvorbisinfo.c (py_comment_assign): Catch del on a comment object. Returns not implemented exception for now * README: Explain how to use comments * vcedit.h Copied in from vorbiscomment * vcedit.c: Copied in from vorbiscomment 2001-12-09 Andrew H. Chatham * config_unix.py: Better logging and finer-grained path arguments 2001-09-02 Andrew H. Chatham * setup.py: bumped version number to 0.4 * Changelog: start using the same dating scheme from ogg-python's Changelog 8-30-2001 Andrew H. Chatham * src/pyvorbisfile.c (py_ov_pcm_seek[_page]) Use the implementation of arg_to_int64 provided by the ogg module * test/*.py: updated to use the new ao module's API 6-01-2001 Andrew H. Chatham * src/pyvorbisinfo.c (py_comment_as_dict): Fixed call with args=NULL ogg123.py works now * src/*.h src/*.c: Changed to C-style comments * test/ogg123.py: Removed stupid print statement 5-14-2001 Andrew H. Chatham * setup.py: Bumped to version 0.3 * src/general.[ch]: Removed arg_to_64 and use ogg-python's arg_to_int64 * src/general.h: Fixed preprocessor warnings * src/py*.c: Methods which take no arguments now require no arguments Made functions match Python-expected signatures * test/short.py: Fixed to match new Python ao module. I think I broke something, so test/ogg123.py doesn't work at the moment 1-17-2001 Andrew H. Chatham * All was essentially created, since this is the first separation of pyvorbis and pyogg 11-29-2000 Andrew H. Chatham * test/ogg123.py: Added support for linuxaudiodev. Factored parts of Player class into a superclass and made separate AOPlayer and LADPlayer subclasses. * test/short.py: added 11-28-2000 Andrew H. Chatham * src/_oggmodule.c (init_ogg): Stuff PyOgg_Error into a Py_CObject. * src/vorbismodule.c (initvorbis): Get PyOgg_Error back out to inherit from. * test/ogg123.py: Change to use new module arrangement. 11-28-2000 Andrew H. Chatham * setup.py: Changed leftover MySQLdb reference. Went back to having a separate _oggmodule and vorismodule. * oggmodule.[ch]: Moved to _oggmodule.[ch] * general.[ch]: Created to house any functions needed by more than one module. Currentnly houses arg_to_64. * src/pyvorbisinfo.c: Changed reference to mappingmethod struct in initializer to a pointer. Removed unused variables (mostly casts of *self) (py_comment_subscript): Added unicode support (py_comment_assign): Added unicode support (get_caps_key): Changed to (make_caps_key). Now takes size argument. (py_comment_as_dict): Fixed case of NULL vendor variable. 11-28-2000 Andrew H. Chatham * src/vorbis*.[ch]: Moved to src/pyvorbis*.[ch] 11-28-2000 Andrew H. Chatham * src/vorbiscodec.[ch]: * src/vorbisfile.[ch]: * src/vorbisinfo.[ch]: Moved type definitions into .c files, declarations into .h files. Removed src/objects/*. 11-28-2000 Andrew H. Chatham * src/oggmodule.h: Removed docstrings and type variables. Moved to separate C files. * src/vorbiscodec.c: (py_codec_new) (py_codec_dealloc) Added. Docstrings added. * src/vorbisfile.c: Docstrings added. * src/vorbisinfo.c: Docstrings added. (py_ov_info_getattr): Removed attributes which are no longer in Vorbis header file. 10-28-2000 Andrew H. Chatham * src/vorbis/vorbisinfo.c: (py_comment_keys), (py_comment_items), (py_comment_values), (py_comment_as_dict): Fixed reference leaks. 10-28-2000 Andrew H. Chatham * src/vorbis/vorbisinfo.[ch]: Added * src/vorbis/vorbisinfo.c: Made the VorbisComment object and added all it's member functions so that it will behave similarly to a Python dictionary. 10-28-2000 Andrew H. Chatham * src/vorbis/vorbisfile.h: Changed all definitions to use FDEF macro. * src/vorbis/vorbisfile.c: Added VorbisComment object. 10-27-2000 Andrew H. Chatham * Refactored into pyvorbismodule.c and pyvorbisfile.c 10-27-2000 Andrew H. Chatham * README: Added first text. * src/vorbis/vorbismodule.c (py_ov_raw_total) (py_ov_pcm_total) (py_ov_raw_tell) (py_ov_pcm_tell): Changed PyLong_FromLong to PyLong_FromLongLong * src/vorbis/vorbismodule.c (arg_to_64): Added. * src/vorbis/vorbismodule.c (py_ov_pcm_seek) (py_ov_pcm_seek_page): Added call to (arg_to_64) * src/vorbis/vorbismodule.c (py_ov_comment): Took ! out of call to get_caps_key and changed initial size of list to 0. 10-26-2000 Andrew H. Chatham * src/vorbis/vorbismodule.c (py_ov_comment) (get_caps_key): Added (untested) support for unicode strings and made all keys uppercase. * src/vorbis/vorbismodule.c (py_ov_info): Added error handling for when ov_info fails. * src/vorbis/vorbismodule.c (py_info_dealloc): Don't free the vorbis_info*. It doesn't belong to us. * test/ogg123.py: Separated things out in an aborted attempt to support socket arguments. The wrapper's not up to that yet. 10-26-2000 Andrew H. Chatham * src/vorbis/vorbismodule.h: Added docstrings for all functions, however inaccurate they may be. * src/vorbis/vorbismodule.c (py_ov_read): Changed default value for length from 1000 to 4096. 10-25-2000 Andrew H. Chatham * Created. pyvorbis-1.5a/MANIFEST010064400017500000012000000006121051746235000134240ustar00ericusersAUTHORS COPYING ChangeLog MANIFEST MANIFEST.in NEWS README config_unix.py prebuild.sh setup.cfg setup.py ./setup.py src/general.c src/general.h src/pyvorbiscodec.c src/pyvorbiscodec.h src/pyvorbisfile.c src/pyvorbisfile.h src/pyvorbisinfo.c src/pyvorbisinfo.h src/vcedit.c src/vcedit.h src/vorbismodule.c src/vorbismodule.h test/comment.py test/enc.py test/enc2.py test/ogg123.py test/short.py pyvorbis-1.5a/MANIFEST.in010064400017500000012000000003011051746235000140240ustar00ericusersinclude ChangeLog README COPYING AUTHORS NEWS setup.py config_unix.py MANIFEST MANIFEST.in prebuild.sh recursive-include src/ *.c *.h *.py recursive-include test/ *.py recursive-include debian pyvorbis-1.5a/NEWS010064400017500000012000000000701051746235000127700ustar00ericusers0.2 - 1/18/2001 * First version as a separate module pyvorbis-1.5a/README010064400017500000012000000105501051746235000131550ustar00ericuserspyvorbis - a Python wrapper for the Ogg/Vorbis library Ogg/Vorbis is available at http://www.xiph.org This is the Vorbis module. You will need to download and install the Python ogg module (available wherever you got this) before you can build the vorbis module. Access this module via "import ogg.vorbis" or "from ogg.vorbis import *". You can now write Python programs to encode and decode Ogg Vorbis files (encoding is quite a bit more involved). The module is self-documenting, though I need to update quite a bit of it. Look at test/ogg123.py, test/short.py, and test/enc.py for very simple demonstrations of the module interface. And if anyone is wondering why I have things separated into a main module "ogg" and a submodule "ogg.vorbis", vorbis is the audio subset of the ogg bitstream. In the future there will likely be a video part of the ogg bistream, and nothing in the ogg modulue really has to know about anything specific in the vorbis module. 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 config_unix.py first to generate a Setup file. Then run "python setup.py build" to build and then as root run "python setup.py install". You may need to run config_unix.py with a "--prefix" option if you installed your ogg or vorbis libraries in a weird place. You can also pass --with-ogg-dir and --with-vorbis-dir arguments if they're installed separately. If you have problems with the configure script, check the output of conifg.log for specific errors. To decode, you'll basically want to create a VorbisFile object and read data from that. You can then write the data to a sound device. I've used both the pyao wrapper (also by me) and the linuxsounddev module present in Python2.0. To encode, you need to feed a VorbisDSPState object PCM data as one array of floating point values ranging from -1.0 ... 1.0 per channel. You can do this in pure Python, but it almost doubles the time it takes to encode. The other option is to read data using the python "wave" module and write it to the VorbisDSPState directly using the x.write_wav(mywave.readframes(n)) call. This will only work with 16-bit Wave files. Perhaps you are wondering how much of a performance hit you'll be taking using the Python bindings versus straight C. Well, I've tried to make things as fast as possible, but of course nothing's perfect. Decoding a file, top reports about the same CPU usage for my ogg123.py and the C implementation of ogg123. For encoding, it's about twice as slow as oggenc if you're using my test enc.py file (parsing the wave file somewhat by hand). If you use the write_wav function, it's only about 3% slower than oggenc. Vorbis Comment -------------- A frequent question is how to edit and then write comments. This was not possible until recently. To implement this, I have taken the code from the vorbiscomment program, which is by Michael Smith and released under the LGPL. It has not been modified by me (Andrew). There was an old way of dealing with VorbisComment objects, which sucked, so I won't tell you how to use it. It still works but is deprecated. The current way of using VorbisComment objects is just to convert to and from Python dictionaries. Note that there can be multiple entries per key and that keys are case-insensitive 7-bit ASCII, because that's how vorbis comments work. So I might do: >>> import ogg.vorbis >>> v = {'mykey' : ['myval1', 'myval2']} >>> v['artist'] = u'andrew' # Unicode string for Python >= 1.6 >>> print v {'artist': 'andrew', 'mykey': ['myval1', 'myval2']} >>> comments = ogg.vorbis.VorbisComment(v) There, we made a comment object from a dictionary. The values of the dictionary are either strings or lists or strings. We can also convert back to a dictionary, though it'll look a little different: >>> print comments.as_dict() {'ARTIST': [u'andrew'], 'MYKEY': ['myval1', 'myval2']} We could also have gotten a comment object from a vorbis file: >>> import ogg.vorbis >>> f = ogg.vorbis.VorbisFile('test.ogg') >>> print f.comment().as_dict() To write the comments to an existing ogg/vorbis file, call v.write_to or v.append_to. The former will add lots of keys, so if you already have an artist key, and you add another, you now have two arist keys in that file. Note that currently the VENDOR tag (which is special) doesn't get written to the file. I'll have to look into that. pyvorbis-1.5a/config_unix.py010075500017500000012000000117411051746235000151650ustar00ericusers#!/usr/bin/env python import string import os import sys import exceptions log_name = 'config.log' if os.path.isfile(log_name): os.unlink(log_name) def write_log(msg): log_file = open(log_name, 'a') log_file.write(msg) log_file.write('\n') log_file.close() def exit(code=0): sys.exit(code) def msg_checking(msg): print "Checking", msg, "...", def execute(cmd): write_log("Execute: %s" % cmd) full_cmd = '%s 1>>%s 2>&1' % (cmd, log_name) return os.system(full_cmd) def run_test(input, flags = ''): try: f = open('_temp.c', 'w') f.write(input) f.close() compile_cmd = '%s -o _temp _temp.c %s' % (os.environ.get('CC', 'cc'), flags) write_log("executing test: %s" % compile_cmd) if not execute(compile_cmd): execute('./_temp') finally: execute('rm -f _temp.c _temp') ogg_test_program = ''' #include #include #include #include int main () { system("touch conf.oggtest"); return 0; } ''' def find_ogg(ogg_prefix = '/usr/local', enable_oggtest = 1): """A rough translation of ogg.m4""" ogg_include_dir = ogg_prefix + '/include' ogg_lib_dir = ogg_prefix + '/lib' ogg_libs = 'ogg' msg_checking('for Ogg') if enable_oggtest: execute('rm -f conf.oggtest') try: run_test(ogg_test_program, flags="-I" + ogg_include_dir) if not os.path.isfile('conf.oggtest'): raise RuntimeError, "Did not produce output" execute('rm conf.oggtest') except: print "test program failed" return None print "success" return {'ogg_libs' : ogg_libs, 'ogg_lib_dir' : ogg_lib_dir, 'ogg_include_dir' : ogg_include_dir} vorbis_test_program = ''' #include #include #include #include int main () { system("touch conf.vorbistest"); return 0; } ''' def find_vorbis(ogg_data, vorbis_prefix = '/usr/local', enable_vorbistest = 1): """A rough translation of vorbis.m4""" ogg_libs = ogg_data['ogg_libs'] ogg_lib_dir = ogg_data['ogg_lib_dir'] ogg_include_dir = ogg_data['ogg_include_dir'] vorbis_include_dir = vorbis_prefix + '/include' vorbis_lib_dir = vorbis_prefix + '/lib' vorbis_libs = 'vorbis vorbisfile vorbisenc' msg_checking('for Vorbis') if enable_vorbistest: execute('rm -f conf.vorbistest') try: run_test(vorbis_test_program, flags = "-I%s -I%s" % (vorbis_include_dir, ogg_include_dir)) if not os.path.isfile('conf.vorbistest'): raise RuntimeError, "Did not produce output" execute('rm conf.vorbistest') except: print "test program failed" return None print "success" return {'vorbis_libs' : vorbis_libs, 'vorbis_lib_dir' : vorbis_lib_dir, 'vorbis_include_dir' : vorbis_include_dir} def write_data(data): f = open('Setup', 'w') for item in data.items(): f.write('%s = %s\n' % item) f.close() print "Wrote Setup file" def print_help(): print '''%s --prefix Give the prefix in which vorbis was installed. --with-ogg-dir [dir] Give the directory for ogg files (separated by a space) --with-vorbis-dir [dir] Give the directory for vorbis files''' % sys.argv[0] exit() def parse_args(): def arg_check(data, argv, pos, arg_type, key): "Register an command line arg which takes an argument" if len(argv) == pos: print arg_type, "needs an argument" exit(1) data[key] = argv[pos] data = {} argv = sys.argv for pos in range(len(argv)): if argv[pos] == '--help': print_help() if argv[pos] == '--with-ogg-dir': pos = pos + 1 arg_check(data, argv, pos, "Ogg dir", 'ogg_prefix') if argv[pos] == '--with-vorbis-dir': pos = pos + 1 arg_check(data, argv, pos, "Vorbis dir", 'vorbis_prefix') if argv[pos] == '--prefix': pos = pos + 1 arg_check(data, argv, pos, "Prefix", 'prefix') return data def main(): args = parse_args() prefix = args.get('prefix', '/usr/local') vorbis_prefix = args.get('vorbis_prefix', prefix) ogg_prefix = args.get('ogg_prefix', prefix) data = find_ogg(ogg_prefix = ogg_prefix) if not data: print "Config failure" exit(1) vorbis_data = find_vorbis(ogg_data = data, vorbis_prefix = vorbis_prefix) if not vorbis_data: print "Config failure" exit(1) data.update(vorbis_data) write_data(data) if __name__ == '__main__': main() pyvorbis-1.5a/prebuild.sh010064400017500000012000000003071051746235000144360ustar00ericusers#!/bin/sh # This is just a simple script to be run before any automatic # binary distribution building (like bdist or bdist_rpm). You # probably don't have to worry about it. python config_unix.py pyvorbis-1.5a/setup.cfg010064400017500000012000000000771051746235000141210ustar00ericusers[bdist_rpm] requires=libogg,libvorbis build_script=prebuild.sh pyvorbis-1.5a/setup.py010075500017500000012000000045101051746235000140110ustar00ericusers#!/usr/bin/env python """Setup script for the Vorbis module distribution.""" import os, re, sys, string from distutils.core import setup from distutils.extension import Extension VERSION_MAJOR = 1 VERSION_MINOR = 5 pyvorbis_version = str(VERSION_MAJOR) + '.' + str(VERSION_MINOR) try: import ogg._ogg except ImportError: print '''You must have the Ogg Python bindings installed in order to build and install these bindings. Import of ogg._ogg failed.''' sys.exit(1) def get_setup(): data = {} r = re.compile(r'(\S+)\s*?=\s*(.+)') if not os.path.isfile('Setup'): print "No 'Setup' file. Perhaps you need to run the configure script." sys.exit(1) f = open('Setup', 'r') for line in f.readlines(): m = r.search(line) if not m: print "Error in setup file:", line sys.exit(1) key = m.group(1) val = m.group(2) data[key] = val return data data = get_setup() vorbis_include_dir = data['vorbis_include_dir'] vorbis_lib_dir = data['vorbis_lib_dir'] vorbis_libs = string.split(data['vorbis_libs']) ogg_include_dir = data['ogg_include_dir'] ogg_lib_dir = data['ogg_lib_dir'] vorbismodule = Extension(name='vorbis', sources=['src/vorbismodule.c', 'src/pyvorbisfile.c', 'src/pyvorbiscodec.c', 'src/pyvorbisinfo.c', 'src/vcedit.c', 'src/general.c'], define_macros = [('VERSION', '"%s"' % pyvorbis_version)], include_dirs=[vorbis_include_dir, ogg_include_dir], library_dirs=[vorbis_lib_dir, ogg_lib_dir], libraries=vorbis_libs) setup ( name = "pyvorbis", version = pyvorbis_version, description = "A wrapper for the Vorbis libraries.", author = "Andrew Chatham", author_email = "andrew.chatham@duke.edu", url = "http://dulug.duke.edu/~andrew/pyogg", packages = ['ogg'], package_dir = {'ogg' : 'src'}, ext_package = 'ogg', ext_modules = [vorbismodule]) pyvorbis-1.5a/PKG-INFO010064400017500000012000000004051051746235000133700ustar00ericusersMetadata-Version: 1.0 Name: pyvorbis Version: 1.5 Summary: A wrapper for the Vorbis libraries. Home-page: http://ekyo.nerim.net/software/pyogg/ Author: Andrew Chatham Author-email: andrew.chatham@duke.edu License: UNKNOWN Description: UNKNOWN Platform: UNKNOWN pyvorbis-1.5a/AUTHORS010064400017500000012000000000511051746235000133400ustar00ericusersAndrew Chatham