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