ce5cb10b56ee9ecadd2a4829b496a2ea990a491a
[ruby-vorbistagger.git] / ext / vcedit.c
1 /*
2  * Copyright (C) 2000-2001 Michael Smith (msmith at xiph org)
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation, version 2.
7  *
8  * This library is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * Lesser General Public License for more details.
12  *
13  * You should have received a copy of the GNU Lesser General Public
14  * License along with this library; if not, write to the Free Software
15  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
16  * MA 02110-1301 USA
17  */
18
19 #include <stdio.h>
20 #include <stdbool.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <errno.h>
24 #include <limits.h>
25 #include <unistd.h>
26 #include <ogg/ogg.h>
27 #include <vorbis/codec.h>
28 #include <assert.h>
29
30 #include "vcedit.h"
31
32 #define CHUNKSIZE 4096
33
34 struct vcedit_state_St {
35         int refcount;
36
37         ogg_sync_state oy;
38         ogg_stream_state os;
39
40         vorbis_comment vc;
41         vorbis_info vi;
42
43         FILE *in;
44         bool opened;
45         long serial;
46         unsigned char *mainbuf;
47         unsigned char *bookbuf;
48         int     mainlen;
49         int     booklen;
50         char *vendor;
51         int prevW;
52         int extrapage;
53         int eosin;
54
55         char filename[0];
56 };
57
58 static void
59 vcedit_state_free (vcedit_state *s)
60 {
61         free (s->mainbuf);
62         free (s->bookbuf);
63         free (s->vendor);
64
65         if (s->in) {
66                 fclose (s->in);
67                 s->in = NULL;
68         }
69
70         free (s);
71 }
72
73 static bool
74 vcedit_state_init (vcedit_state *s, const char *filename)
75 {
76         s->refcount = 1;
77
78         strcpy (s->filename, filename);
79
80         return true;
81 }
82
83 vcedit_state *
84 vcedit_state_new (const char *filename)
85 {
86         vcedit_state *s;
87         size_t len;
88
89         len = strlen (filename);
90         if (len > PATH_MAX)
91                 return NULL;
92
93         s= malloc (sizeof (vcedit_state) + len + 1);
94         if (!s)
95                 return NULL;
96
97         memset (s, 0, sizeof (vcedit_state));
98
99         if (!vcedit_state_init (s, filename)) {
100                 vcedit_state_free (s);
101                 return NULL;
102         }
103
104         return s;
105 }
106
107 vorbis_comment *
108 vcedit_comments (vcedit_state *s)
109 {
110         return s->opened ? &s->vc : NULL;
111 }
112
113 static void
114 vcedit_clear_internals (vcedit_state *s)
115 {
116         ogg_stream_clear (&s->os);
117         ogg_sync_clear (&s->oy);
118
119         vorbis_info_clear (&s->vi);
120         vorbis_comment_clear (&s->vc);
121
122         free (s->vendor);
123         s->vendor = NULL;
124
125         free (s->mainbuf);
126         s->mainbuf = NULL;
127         s->mainlen = 0;
128
129         free (s->bookbuf);
130         s->bookbuf = NULL;
131         s->booklen = 0;
132
133         s->serial = 0;
134         s->opened = false;
135 }
136
137 void
138 vcedit_state_ref (vcedit_state *s)
139 {
140         s->refcount++;
141 }
142
143 void
144 vcedit_state_unref (vcedit_state *s)
145 {
146         if (--s->refcount)
147                 return;
148
149         if (s->opened)
150                 vcedit_clear_internals (s);
151
152         vcedit_state_free (s);
153 }
154
155 /* Next two functions pulled straight from libvorbis, apart from one change
156  * - we don't want to overwrite the vendor string.
157  */
158 static void
159 _v_writestring (oggpack_buffer *o, char *s, int len)
160 {
161         while (len--)
162                 oggpack_write (o, *s++, 8);
163 }
164
165 static int
166 _commentheader_out (vorbis_comment *vc, char *vendor, ogg_packet *op)
167 {
168         int i;
169
170         oggpack_buffer opb;
171
172         oggpack_writeinit (&opb);
173
174         /* preamble */
175         oggpack_write (&opb, 0x03, 8);
176         _v_writestring (&opb, "vorbis", 6);
177
178         /* vendor */
179         oggpack_write (&opb, strlen (vendor), 32);
180         _v_writestring (&opb, vendor, strlen (vendor));
181
182         /* comments */
183         oggpack_write (&opb, vc->comments, 32);
184
185         for (i = 0; i < vc->comments; i++) {
186                 if (!vc->user_comments[i])
187                         oggpack_write (&opb, 0, 32);
188                 else {
189                         oggpack_write (&opb, vc->comment_lengths[i], 32);
190                         _v_writestring (&opb, vc->user_comments[i],
191                                         vc->comment_lengths[i]);
192                 }
193         }
194
195         oggpack_write (&opb, 1, 1);
196
197         op->packet = _ogg_malloc (oggpack_bytes (&opb));
198         memcpy (op->packet, opb.buffer, oggpack_bytes (&opb));
199
200         op->bytes = oggpack_bytes (&opb);
201         op->b_o_s = 0;
202         op->e_o_s = 0;
203         op->granulepos = 0;
204
205         oggpack_writeclear (&opb);
206
207         return 0;
208 }
209
210 static int
211 _blocksize (vcedit_state *s, ogg_packet *p)
212 {
213         int this, ret = 0;
214
215         this = vorbis_packet_blocksize (&s->vi, p);
216
217         if (s->prevW)
218                 ret = (this + s->prevW) / 4;
219
220         s->prevW = this;
221
222         return ret;
223 }
224
225 static int
226 _fetch_next_packet (vcedit_state *s, ogg_packet *p, ogg_page *page)
227 {
228         char *buffer;
229         int result, bytes;
230
231         result = ogg_stream_packetout (&s->os, p);
232         if (result == 1)
233                 return 1;
234
235         if (s->eosin)
236                 return 0;
237
238         while (ogg_sync_pageout (&s->oy, page) != 1) {
239                 buffer = ogg_sync_buffer (&s->oy, CHUNKSIZE);
240                 bytes = fread (buffer, 1, CHUNKSIZE, s->in);
241                 ogg_sync_wrote (&s->oy, bytes);
242
243                 if (!bytes && feof (s->in))
244                         return 0;
245         }
246
247         if (ogg_page_eos (page))
248                 s->eosin = 1;
249         else if (ogg_page_serialno (page) != s->serial) {
250                 s->eosin = 1;
251                 s->extrapage = 1;
252                 return 0;
253         }
254
255         ogg_stream_pagein (&s->os, page);
256
257         return _fetch_next_packet (s, p, page);
258 }
259
260 vcedit_error
261 vcedit_open (vcedit_state *s)
262 {
263         vcedit_error ret;
264         ogg_packet *header;
265         ogg_packet header_main, header_comments, header_codebooks;
266         ogg_page og;
267         char *buffer;
268         size_t bytes, total = 0;
269         int i = 0;
270
271         s->in = fopen (s->filename, "rb");
272         if (!s->in)
273                 return VCEDIT_ERR_OPEN;
274
275         ogg_sync_init (&s->oy);
276
277         do {
278                 /* Bail if we don't find data in the first 40 kB */
279                 if (feof (s->in) || total >= (CHUNKSIZE * 10)) {
280                         ogg_sync_clear (&s->oy);
281
282                         return VCEDIT_ERR_INVAL;
283                 }
284
285                 buffer = ogg_sync_buffer (&s->oy, CHUNKSIZE);
286
287                 bytes = fread (buffer, 1, CHUNKSIZE, s->in);
288                 total += bytes;
289
290                 ogg_sync_wrote (&s->oy, bytes);
291         } while (ogg_sync_pageout (&s->oy, &og) != 1);
292
293         s->serial = ogg_page_serialno (&og);
294
295         ogg_stream_init (&s->os, s->serial);
296         vorbis_info_init (&s->vi);
297         vorbis_comment_init (&s->vc);
298
299         if (ogg_stream_pagein (&s->os, &og) < 0) {
300                 ret = VCEDIT_ERR_INVAL;
301                 goto err;
302         }
303
304         if (ogg_stream_packetout (&s->os, &header_main) != 1) {
305                 ret = VCEDIT_ERR_INVAL;
306                 goto err;
307         }
308
309         if (vorbis_synthesis_headerin (&s->vi, &s->vc, &header_main) < 0) {
310                 ret = VCEDIT_ERR_INVAL;
311                 goto err;
312         }
313
314         s->mainlen = header_main.bytes;
315         s->mainbuf = malloc (s->mainlen);
316         memcpy (s->mainbuf, header_main.packet, header_main.bytes);
317
318         header = &header_comments;
319
320         while (i < 2) {
321                 while (i < 2) {
322                         int result;
323
324                         result = ogg_sync_pageout (&s->oy, &og);
325                         if (!result)
326                                 break; /* Too little data so far */
327
328                         if (result != 1)
329                                 continue;
330
331                         ogg_stream_pagein (&s->os, &og);
332
333                         while (i < 2) {
334                                 result = ogg_stream_packetout (&s->os, header);
335                                 if (!result)
336                                         break;
337
338                                 if (result != 1) {
339                                         ret = VCEDIT_ERR_INVAL;
340                                         goto err;
341                                 }
342
343                                 vorbis_synthesis_headerin (&s->vi, &s->vc, header);
344
345                                 if (i++ == 1) {
346                                         s->booklen = header->bytes;
347                                         s->bookbuf = malloc (s->booklen);
348                                         memcpy (s->bookbuf, header->packet, header->bytes);
349                                 }
350
351                                 header = &header_codebooks;
352                         }
353                 }
354
355                 buffer = ogg_sync_buffer (&s->oy, CHUNKSIZE);
356                 bytes = fread (buffer, 1, CHUNKSIZE, s->in);
357
358                 if (!bytes && feof (s->in) && i < 2) {
359                         ret = VCEDIT_ERR_INVAL;
360                         goto err;
361                 }
362
363                 ogg_sync_wrote (&s->oy, bytes);
364         }
365
366         /* Copy the vendor tag */
367         s->vendor = strdup (s->vc.vendor);
368
369         /* Headers are done! */
370         s->opened = true;
371
372         return VCEDIT_ERR_SUCCESS;
373
374 err:
375         vcedit_clear_internals (s);
376
377         return ret;
378 }
379
380 static int
381 write_data (const void *buf, size_t size, size_t nmemb, FILE *stream)
382 {
383         while (nmemb > 0) {
384                 size_t w;
385
386                 w = fwrite (buf, size, nmemb, stream);
387                 if (!w && ferror (stream))
388                         return 0;
389
390                 nmemb -= w;
391                 buf += size * w;
392         }
393
394         return 1;
395 }
396
397 vcedit_error
398 vcedit_write (vcedit_state *s)
399 {
400         ogg_stream_state streamout;
401         ogg_packet header_main, header_comments, header_codebooks, op;
402         ogg_page ogout, ogin;
403         ogg_int64_t granpos = 0;
404         FILE *out;
405         char *buffer, tmpfile[PATH_MAX];
406         int fd, result, bytes, needflush = 0, needout = 0;
407
408         if (!s->opened)
409                 return VCEDIT_ERR_INVAL;
410
411         strcpy (tmpfile, s->filename);
412         strcat (tmpfile, ".XXXXXX");
413
414         fd = mkstemp (tmpfile);
415         if (fd == -1)
416                 return VCEDIT_ERR_TMPFILE;
417
418         out = fdopen (fd, "wb");
419         if (!out) {
420                 unlink (tmpfile);
421                 close (fd);
422
423                 return VCEDIT_ERR_TMPFILE;
424         }
425
426         s->prevW = s->extrapage = s->eosin = 0;
427
428         header_main.bytes = s->mainlen;
429         header_main.packet = s->mainbuf;
430         header_main.b_o_s = 1;
431         header_main.e_o_s = 0;
432         header_main.granulepos = 0;
433
434         header_codebooks.bytes = s->booklen;
435         header_codebooks.packet = s->bookbuf;
436         header_codebooks.b_o_s = 0;
437         header_codebooks.e_o_s = 0;
438         header_codebooks.granulepos = 0;
439
440         ogg_stream_init (&streamout, s->serial);
441
442         _commentheader_out (&s->vc, s->vendor, &header_comments);
443
444         ogg_stream_packetin (&streamout, &header_main);
445         ogg_stream_packetin (&streamout, &header_comments);
446         ogg_stream_packetin (&streamout, &header_codebooks);
447
448         while ((result = ogg_stream_flush (&streamout, &ogout))) {
449                 if (!write_data (ogout.header, 1, ogout.header_len, out))
450                         goto cleanup;
451
452                 if (!write_data (ogout.body, 1, ogout.body_len, out))
453                         goto cleanup;
454         }
455
456         while (_fetch_next_packet (s, &op, &ogin)) {
457                 int size;
458
459                 size = _blocksize (s, &op);
460                 granpos += size;
461
462                 if (needflush) {
463                         if (ogg_stream_flush (&streamout, &ogout)) {
464                                 if (!write_data (ogout.header, 1, ogout.header_len, out))
465                                         goto cleanup;
466
467                                 if (!write_data (ogout.body, 1, ogout.body_len, out))
468                                         goto cleanup;
469                         }
470                 } else if (needout) {
471                         if (ogg_stream_pageout (&streamout, &ogout)) {
472                                 if (!write_data (ogout.header, 1, ogout.header_len, out))
473                                         goto cleanup;
474
475                                 if (!write_data (ogout.body, 1, ogout.body_len, out))
476                                         goto cleanup;
477                         }
478                 }
479
480                 needflush = needout = 0;
481
482                 if (op.granulepos == -1) {
483                         op.granulepos = granpos;
484                         ogg_stream_packetin (&streamout, &op);
485                 } else {
486                         /* granulepos is set, validly. Use it, and force a flush to
487                          * account for shortened blocks (vcut) when appropriate
488                          */
489                         if (granpos > op.granulepos) {
490                                 granpos = op.granulepos;
491                                 ogg_stream_packetin (&streamout, &op);
492                                 needflush = 1;
493                         } else {
494                                 ogg_stream_packetin (&streamout, &op);
495                                 needout = 1;
496                         }
497                 }
498         }
499
500         streamout.e_o_s = 1;
501
502         while (ogg_stream_flush (&streamout, &ogout)) {
503                 if (!write_data (ogout.header, 1, ogout.header_len, out))
504                         goto cleanup;
505
506                 if (!write_data (ogout.body, 1, ogout.body_len, out))
507                         goto cleanup;
508         }
509
510         if (s->extrapage) {
511                 if (!write_data (ogin.header, 1, ogin.header_len, out))
512                         goto cleanup;
513
514                 if (!write_data (ogin.body, 1, ogin.body_len, out))
515                         goto cleanup;
516         }
517
518         /* clear it, because not all paths to here do */
519         s->eosin = 0;
520
521         do {
522                 /* We copy the rest of the stream (other logical streams)
523                  * through, a page at a time.
524                  */
525                 while ((result = ogg_sync_pageout (&s->oy, &ogout))) {
526                         if (result != 1)
527                                 continue;
528
529                         /* Don't bother going through the rest, we can just
530                          * write the page out now
531                          */
532                         if (!write_data (ogout.header, 1, ogout.header_len, out))
533                                 goto cleanup;
534
535                         if (!write_data (ogout.body, 1, ogout.body_len, out))
536                                 goto cleanup;
537                 }
538
539                 buffer = ogg_sync_buffer (&s->oy, CHUNKSIZE);
540                 bytes = fread (buffer, 1, CHUNKSIZE, s->in);
541                 ogg_sync_wrote (&s->oy, bytes);
542
543                 s->eosin = !bytes && feof (s->in);
544         } while (!s->eosin);
545
546         fclose (out);
547         fclose (s->in);
548
549         unlink (s->filename);
550         rename (tmpfile, s->filename);
551
552 cleanup:
553         ogg_stream_clear (&streamout);
554
555     /* We don't ogg_packet_clear() this, because the memory was
556          * allocated in _commentheader_out(), so we mirror that here
557          */
558     _ogg_free (header_comments.packet);
559
560         free (s->mainbuf);
561         free (s->bookbuf);
562
563     s->mainbuf = s->bookbuf = NULL;
564
565         if (!s->eosin)
566                 return VCEDIT_ERR_INVAL;
567
568         vcedit_clear_internals (s);
569
570         return (vcedit_open (s) == VCEDIT_ERR_SUCCESS) ?
571                VCEDIT_ERR_SUCCESS : VCEDIT_ERR_REOPEN;
572 }