]> diplodocus.org Git - flac-archive/blob - taglib.cc
dd6526bf8217baadf3e7524423481f999d77652c
[flac-archive] / taglib.cc
1 #include <attachedpictureframe.h>
2 #include <id3v2tag.h>
3 #include <mpegfile.h>
4
5 extern "C" {
6
7 #include <errno.h>
8
9 #include <Python.h>
10
11 static PyObject *taglib_error;
12
13 static PyObject *
14 taglib_apic(const char *fn, const char *image, int len,
15 int type, const char *mime_type)
16 {
17 TagLib::ByteVector *bv;
18 TagLib::ID3v2::AttachedPictureFrame *p;
19 TagLib::MPEG::File *f;
20 TagLib::ID3v2::Tag *t;
21
22 bv = new TagLib::ByteVector (image, len);
23 if (bv == 0) {
24 return PyErr_NoMemory();
25 }
26
27 p = new TagLib::ID3v2::AttachedPictureFrame;
28 if (p == 0) {
29 return PyErr_NoMemory();
30 }
31
32 /* Um, look at all these void-returning functions. I'm sure they
33 * can fail, i just have no way to detect it... */
34 p->setTextEncoding(TagLib::String::UTF8);
35 p->setType((TagLib::ID3v2::AttachedPictureFrame::Type)type);
36 p->setMimeType(mime_type);
37 p->setPicture(*bv);
38
39 /* GAH! Opening the file is entangled with allocating the object;
40 * if this fails, am i out of memory, or is there a problem with
41 * the file? Hate C++... */
42 f = new TagLib::MPEG::File (fn);
43 if (f == 0) {
44 return PyErr_NoMemory();
45 }
46
47 t = f->ID3v2Tag(true);
48 if (t == 0) {
49 PyErr_SetString(taglib_error, "taglib failed to return ID3v2");
50 return 0;
51 }
52
53 // another void-returning function that i bet fails
54 t->addFrame(p);
55
56 errno = 0;
57 if (!f->save()) {
58 if (errno != 0) {
59 PyErr_SetFromErrnoWithFilename(PyExc_IOError, (char *)fn);
60 } else {
61 PyErr_SetString(taglib_error, "taglib failed to save");
62 }
63 return 0;
64 }
65
66 Py_INCREF(Py_None);
67 return Py_None;
68 }
69
70 static PyObject *
71 add_apic_frame_to_mp3(PyObject *self, PyObject *args)
72 {
73 const char *fn, *image, *mime_type;
74 int len, type;
75
76 if (!PyArg_ParseTuple(args, "ss#is", &fn, &image, &len,
77 &type, &mime_type)) {
78 return 0;
79 }
80
81 return taglib_apic(fn, image, len, type, mime_type);
82 }
83
84 static
85 PyMethodDef methods[] = {
86 {"add_apic_frame_to_mp3", add_apic_frame_to_mp3, METH_VARARGS,
87 "document me"},
88 {0, 0, 0, 0}
89 };
90
91 PyMODINIT_FUNC
92 inittaglib(void)
93 {
94 PyObject *m = Py_InitModule("taglib", methods);
95 if (m == NULL) {
96 return;
97 }
98
99 taglib_error = PyErr_NewException("org.diplodocus.taglib.error", 0, 0);
100 if (taglib_error == 0) {
101 return;
102 }
103 PyModule_AddObject(m, "error", taglib_error);
104 }
105
106 }