38ecb9f9d384818c84df6a0e96b85274fdd34767
[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) || ferror (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) || ferror (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                 if (feof (s->in) || ferror (s->in)) {
322                         ret = VCEDIT_ERR_INVAL;
323                         goto err;
324                 }
325
326                 while (i < 2) {
327                         int result;
328
329                         result = ogg_sync_pageout (&s->oy, &og);
330                         if (!result)
331                                 break; /* Too little data so far */
332
333                         if (result != 1)
334                                 continue;
335
336                         ogg_stream_pagein (&s->os, &og);
337
338                         while (i < 2) {
339                                 result = ogg_stream_packetout (&s->os, header);
340                                 if (!result)
341                                         break;
342
343                                 if (result != 1) {
344                                         ret = VCEDIT_ERR_INVAL;
345                                         goto err;
346                                 }
347
348                                 vorbis_synthesis_headerin (&s->vi, &s->vc, header);
349
350                                 if (i++ == 1) {
351                                         s->booklen = header->bytes;
352                                         s->bookbuf = malloc (s->booklen);
353                                         memcpy (s->bookbuf, header->packet, header->bytes);
354                                 }
355
356                                 header = &header_codebooks;
357                         }
358                 }
359
360                 buffer = ogg_sync_buffer (&s->oy, CHUNKSIZE);
361
362                 bytes = fread (buffer, 1, CHUNKSIZE, s->in);
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         bool success = false;
407         int fd, result, bytes, needflush = 0, needout = 0;
408
409         if (!s->opened)
410                 return VCEDIT_ERR_INVAL;
411
412         strcpy (tmpfile, s->filename);
413         strcat (tmpfile, ".XXXXXX");
414
415         fd = mkstemp (tmpfile);
416         if (fd == -1)
417                 return VCEDIT_ERR_TMPFILE;
418
419         out = fdopen (fd, "wb");
420         if (!out) {
421                 unlink (tmpfile);
422                 close (fd);
423
424                 return VCEDIT_ERR_TMPFILE;
425         }
426
427         s->prevW = s->extrapage = s->eosin = 0;
428
429         header_main.bytes = s->mainlen;
430         header_main.packet = s->mainbuf;
431         header_main.b_o_s = 1;
432         header_main.e_o_s = 0;
433         header_main.granulepos = 0;
434
435         header_codebooks.bytes = s->booklen;
436         header_codebooks.packet = s->bookbuf;
437         header_codebooks.b_o_s = 0;
438         header_codebooks.e_o_s = 0;
439         header_codebooks.granulepos = 0;
440
441         ogg_stream_init (&streamout, s->serial);
442
443         _commentheader_out (&s->vc, s->vendor, &header_comments);
444
445         ogg_stream_packetin (&streamout, &header_main);
446         ogg_stream_packetin (&streamout, &header_comments);
447         ogg_stream_packetin (&streamout, &header_codebooks);
448
449         while ((result = ogg_stream_flush (&streamout, &ogout))) {
450                 if (!write_data (ogout.header, 1, ogout.header_len, out))
451                         goto cleanup;
452
453                 if (!write_data (ogout.body, 1, ogout.body_len, out))
454                         goto cleanup;
455         }
456
457         while (_fetch_next_packet (s, &op, &ogin)) {
458                 int size;
459
460                 size = _blocksize (s, &op);
461                 granpos += size;
462
463                 if (needflush) {
464                         if (ogg_stream_flush (&streamout, &ogout)) {
465                                 if (!write_data (ogout.header, 1, ogout.header_len, out))
466                                         goto cleanup;
467
468                                 if (!write_data (ogout.body, 1, ogout.body_len, out))
469                                         goto cleanup;
470                         }
471                 } else if (needout) {
472                         if (ogg_stream_pageout (&streamout, &ogout)) {
473                                 if (!write_data (ogout.header, 1, ogout.header_len, out))
474                                         goto cleanup;
475
476                                 if (!write_data (ogout.body, 1, ogout.body_len, out))
477                                         goto cleanup;
478                         }
479                 }
480
481                 needflush = needout = 0;
482
483                 if (op.granulepos == -1) {
484                         op.granulepos = granpos;
485                         ogg_stream_packetin (&streamout, &op);
486                 } else {
487                         /* granulepos is set, validly. Use it, and force a flush to
488                          * account for shortened blocks (vcut) when appropriate
489                          */
490                         if (granpos > op.granulepos) {
491                                 granpos = op.granulepos;
492                                 ogg_stream_packetin (&streamout, &op);
493                                 needflush = 1;
494                         } else {
495                                 ogg_stream_packetin (&streamout, &op);
496                                 needout = 1;
497                         }
498                 }
499         }
500
501         streamout.e_o_s = 1;
502
503         while (ogg_stream_flush (&streamout, &ogout)) {
504                 if (!write_data (ogout.header, 1, ogout.header_len, out))
505                         goto cleanup;
506
507                 if (!write_data (ogout.body, 1, ogout.body_len, out))
508                         goto cleanup;
509         }
510
511         if (s->extrapage) {
512                 if (!write_data (ogin.header, 1, ogin.header_len, out))
513                         goto cleanup;
514
515                 if (!write_data (ogin.body, 1, ogin.body_len, out))
516                         goto cleanup;
517         }
518
519         /* clear it, because not all paths to here do */
520         s->eosin = 0;
521
522         do {
523                 /* We copy the rest of the stream (other logical streams)
524                  * through, a page at a time.
525                  */
526                 while ((result = ogg_sync_pageout (&s->oy, &ogout))) {
527                         if (result != 1)
528                                 continue;
529
530                         /* Don't bother going through the rest, we can just
531                          * write the page out now
532                          */
533                         if (!write_data (ogout.header, 1, ogout.header_len, out))
534                                 goto cleanup;
535
536                         if (!write_data (ogout.body, 1, ogout.body_len, out))
537                                 goto cleanup;
538                 }
539
540                 buffer = ogg_sync_buffer (&s->oy, CHUNKSIZE);
541                 bytes = fread (buffer, 1, CHUNKSIZE, s->in);
542                 ogg_sync_wrote (&s->oy, bytes);
543
544                 if (ferror (s->in))
545                         goto cleanup;
546
547                 s->eosin = !bytes && feof (s->in);
548         } while (!s->eosin);
549
550         success = true;
551
552 cleanup:
553         fclose (s->in);
554
555         if (!success) {
556                 unlink (tmpfile);
557                 fclose (out);
558         } else {
559                 fclose (out);
560                 unlink (s->filename);
561                 rename (tmpfile, s->filename);
562         }
563
564         ogg_stream_clear (&streamout);
565
566     /* We don't ogg_packet_clear() this, because the memory was
567          * allocated in _commentheader_out(), so we mirror that here
568          */
569     _ogg_free (header_comments.packet);
570
571         free (s->mainbuf);
572         free (s->bookbuf);
573
574     s->mainbuf = s->bookbuf = NULL;
575
576         if (!s->eosin)
577                 return VCEDIT_ERR_INVAL;
578
579         vcedit_clear_internals (s);
580
581         return (vcedit_open (s) == VCEDIT_ERR_SUCCESS) ?
582                VCEDIT_ERR_SUCCESS : VCEDIT_ERR_REOPEN;
583 }