Debian Codegraph @

src/libout123/wav.c

raw
1 /*
2 wav.c: write wav/au/cdr files (and headerless raw
3
4 copyright ?-2023 by the mpg123 project - free software under the terms of the LGPL 2.1
5 see COPYING and AUTHORS files in distribution or http://mpg123.org
6 initially written by Samuel Audet
7
8 Geez, why are WAV RIFF headers are so secret? I got something together,
9 but wow... anyway, I hope someone will find this useful.
10 - Samuel Audet
11
12 minor simplifications and ugly AU/CDR format stuff by MH
13
14 It's not a very clean code ... Fix this!
15
16 ThOr: The usage of stdio streams means we loose control over what data is actually written. On a full disk, fwrite() happily suceeds for ages, only a fflush fails.
17 Now: Do we want to fflush() after every write? That defeats the purpose of buffered I/O. So, switching to good old write() is an option (kernel doing disk buffering anyway).
18
19 ThOr: Again reworked things for libout123, with non-static state.
20 This set of builtin "modules" is what we can use in automated tests
21 of libout123. Code still not very nice, but I tried to keep modification
22 of what stood the test of time minimal. One still can add a module to
23 libout123 that uses sndfile and similar libraries for more choice on writing
24 output files.
25 */
26
27 #include "out123_int.h"
28 #include "wav.h"
29
30 #include <errno.h>
31 #include "../common/debug.h"
32
33 /* Create the two WAV headers. */
34
35 #define WAVE_FORMAT 1
36 #define RIFF_NAME riff_template
37 #define RIFF_STRUCT_NAME riff
38 #include "wavhead.h"
39
40 #undef WAVE_FORMAT
41 #undef RIFF_NAME
42 #undef RIFF_STRUCT_NAME
43 #define WAVE_FORMAT 3
44 #define RIFF_NAME riff_float_template
45 #define RIFF_STRUCT_NAME riff_float
46 #define FLOATOUT
47 #include "wavhead.h"
48
49 /* AU header struct... */
50
51 struct auhead {
52 byte magic[4];
53 byte headlen[4];
54 byte datalen[4];
55 byte encoding[4];
56 byte rate[4];
57 byte channels[4];
58 byte dummy[8];
59 } const auhead_template = {
60 { 0x2e,0x73,0x6e,0x64 } , { 0x00,0x00,0x00,0x20 } ,
61 { 0xff,0xff,0xff,0xff } , { 0,0,0,0 } , { 0,0,0,0 } , { 0,0,0,0 } ,
62 { 0,0,0,0,0,0,0,0 }};
63
64 struct wavdata
65 {
66 FILE *wavfp;
67 long datalen;
68 int flipendian;
69 int bytes_per_sample;
70 int floatwav; /* If we write a floating point WAV file. */
71 /*
72 Open routines only prepare a header, stored here and written on first
73 actual data write. If no data is written at all, proper files will
74 still get a header via the update at closing; non-seekable streams will
75 just have no no header if there is no data.
76 */
77 void *the_header;
78 size_t the_header_size;
79 };
80
81 static struct wavdata* wavdata_new(void)
82 {
83 struct wavdata *wdat = malloc(sizeof(struct wavdata));
84 if(wdat)
85 {
86 wdat->wavfp = NULL;
87 wdat->datalen = 0;
88 wdat->flipendian = 0;
89 wdat->bytes_per_sample = -1;
90 wdat->floatwav = 0;
91 wdat->the_header = NULL;
92 wdat->the_header_size = 0;
93 }
94 return wdat;
95 }
96
97 static void wavdata_del(struct wavdata *wdat)
98 {
99 if(!wdat) return;
100 if(wdat->wavfp && wdat->wavfp != stdout)
101 INT123_compat_fclose(wdat->wavfp);
102 if(wdat->the_header)
103 free(wdat->the_header);
104 free(wdat);
105 }
106
107 /* Pointer types are for pussies;-) */
108 static void* wavhead_new(void const *template, size_t size)
109 {
110 void *header = malloc(size);
111 if(header)
112 memcpy(header, template, size);
113 return header;
114 }
115
116 /* Convertfunctions: */
117 /* always little endian */
118
119 static void long2littleendian(long inval,byte *outval,int b)
120 {
121 int i;
122 for(i=0;i<b;i++) {
123 outval[i] = (inval>>(i*8)) & 0xff;
124 }
125 }
126
127 /* always big endian */
128 static void long2bigendian(long inval,byte *outval,int b)
129 {
130 int i;
131 for(i=0;i<b;i++) {
132 outval[i] = (inval>>((b-i-1)*8)) & 0xff;
133 }
134 }
135
136 static long from_little(byte *inval, int b)
137 {
138 long ret = 0;
139 int i;
140 for(i=0;i<b;++i) ret += ((long)inval[i])<<(i*8);
141
142 return ret;
143 }
144
145 static int testEndian(void)
146 {
147 long a=0,b=0,c=0;
148 int ret = 0;
149 size_t i;
150
151 for(i=0;i<sizeof(long);i++) {
152 ((byte *)&a)[i] = (byte)i;
153 b<<=8;
154 b |= i;
155 c |= i << (i*8);
156 }
157 if(a == b)
158 ret = 1;
159 else if(a != c) {
160 ret = -1;
161 }
162 return ret;
163 }
164
165 /* return: 0 is good, -1 is bad */
166 static int open_file(struct wavdata *wdat, char *filename)
167 {
168 debug2("open_file(%p, %s)", (void*)wdat, filename ? filename : "<nil>");
169 if(!wdat)
170 return -1;
171 if(!filename || !strcmp("-",filename) || !strcmp("", filename))
172 {
173 wdat->wavfp = stdout;
174 INT123_compat_binmode(STDOUT_FILENO, TRUE);
175 /* If stdout is redirected to a file, seeks suddenly can work.
176 Doing one here to ensure that such a file has the same output
177 it had when opening directly as such. */
178 fseek(wdat->wavfp, 0L, SEEK_SET);
179 return 0;
180 }
181 else
182 {
183 wdat->wavfp = INT123_compat_fopen(filename, "wb");
184 if(!wdat->wavfp)
185 return -1;
186 else
187 return 0;
188 }
189 }
190
191 /* return: 0 is good, -1 is bad
192 Works for any partial state of setup, especially should not complain if
193 ao->userptr == NULL. */
194 static int close_file(out123_handle *ao)
195 {
196 struct wavdata *wdat = ao->userptr;
197 int ret = 0;
198
199 if(wdat->wavfp != NULL && wdat->wavfp != stdout)
200 {
201 if(INT123_compat_fclose(wdat->wavfp))
202 {
203 if(!AOQUIET)
204 error1("problem closing the audio file, probably because of flushing to disk: %s\n", INT123_strerror(errno));
205 ret = -1;
206 }
207 }
208
209 /* Always cleanup here. */
210 wdat->wavfp = NULL;
211 wavdata_del(wdat);
212 ao->userptr = NULL;
213 return ret;
214 }
215
216 /* return: 0 is good, -1 is bad */
217 static int write_header(out123_handle *ao)
218 {
219 struct wavdata *wdat = ao->userptr;
220
221 if(!wdat)
222 return 0;
223
224 if(
225 wdat->the_header_size > 0
226 && (
227 fwrite(wdat->the_header, wdat->the_header_size, 1, wdat->wavfp) != 1
228 || fflush(wdat->wavfp)
229 )
230 )
231 {
232 if(!AOQUIET)
233 error1("cannot write header: %s", INT123_strerror(errno));
234 return -1;
235 }
236 else return 0;
237 }
238
239 int INT123_au_open(out123_handle *ao)
240 {
241 struct wavdata *wdat = NULL;
242 struct auhead *auhead = NULL;
243
244 if(ao->format < 0)
245 {
246 ao->rate = 44100;
247 ao->channels = 2;
248 ao->format = MPG123_ENC_SIGNED_16;
249 return 0;
250 }
251
252 if(ao->format & MPG123_ENC_FLOAT)
253 {
254 if(!AOQUIET)
255 error("AU file support for float values not there yet");
256 goto au_open_bad;
257 }
258
259 if(
260 !(wdat = wavdata_new())
261 || !(auhead = wavhead_new(&auhead_template, sizeof(auhead_template)))
262 )
263 {
264 ao->errcode = OUT123_DOOM;
265 goto au_open_bad;
266 }
267
268 wdat->the_header = auhead;
269 wdat->the_header_size = sizeof(*auhead);
270
271 wdat->flipendian = 0;
272
273 switch(ao->format)
274 {
275 case MPG123_ENC_SIGNED_16:
276 {
277 int endiantest = testEndian();
278 if(endiantest == -1)
279 goto au_open_bad;
280 wdat->flipendian = !endiantest; /* big end */
281 long2bigendian(3,auhead->encoding,sizeof(auhead->encoding));
282 }
283 break;
284 case MPG123_ENC_UNSIGNED_8:
285 ao->format = MPG123_ENC_ULAW_8;
286 case MPG123_ENC_ULAW_8:
287 long2bigendian(1,auhead->encoding,sizeof(auhead->encoding));
288 break;
289 default:
290 if(!AOQUIET)
291 error("AU output is only a hack. This audio mode isn't supported yet.");
292 goto au_open_bad;
293 }
294
295 long2bigendian(0xffffffff,auhead->datalen,sizeof(auhead->datalen));
296 long2bigendian(ao->rate,auhead->rate,sizeof(auhead->rate));
297 long2bigendian(ao->channels,auhead->channels,sizeof(auhead->channels));
298
299 if(open_file(wdat, ao->device) < 0)
300 goto au_open_bad;
301
302 wdat->datalen = 0;
303
304 ao->userptr = wdat;
305 return 0;
306
307 au_open_bad:
308 if(auhead)
309 free(auhead);
310 if(wdat)
311 {
312 wdat->the_header = NULL;
313 wavdata_del(wdat);
314 }
315 return -1;
316 }
317
318 int INT123_cdr_open(out123_handle *ao)
319 {
320 struct wavdata *wdat = NULL;
321
322 if(ao->format < 0)
323 {
324 ao->rate = 44100;
325 ao->channels = 2;
326 ao->format = MPG123_ENC_SIGNED_16;
327 return 0;
328 }
329
330 if(
331 ao->format != MPG123_ENC_SIGNED_16
332 || ao->rate != 44100
333 || ao->channels != 2
334 )
335 {
336 if(!AOQUIET)
337 error("Oops .. not forced to 16 bit, 44 kHz, stereo?");
338 goto cdr_open_bad;
339 }
340
341 if(!(wdat = wavdata_new()))
342 {
343 ao->errcode = OUT123_DOOM;
344 goto cdr_open_bad;
345 }
346
347 wdat->flipendian = !testEndian(); /* big end */
348
349 if(open_file(wdat, ao->device) < 0)
350 {
351 if(!AOQUIET)
352 error("cannot open file for writing");
353 goto cdr_open_bad;
354 }
355
356 ao->userptr = wdat;
357 return 0;
358 cdr_open_bad:
359 if(wdat)
360 wavdata_del(wdat);
361 return -1;
362 }
363
364 /* RAW files are headerless WAVs where the format does not matter. */
365 int INT123_raw_open(out123_handle *ao)
366 {
367 struct wavdata *wdat;
368
369 if(ao->format < 0)
370 {
371 ao->rate = 44100;
372 ao->channels = 2;
373 ao->format = MPG123_ENC_SIGNED_16;
374 return 0;
375 }
376
377 if(!(wdat = wavdata_new()))
378 {
379 ao->errcode = OUT123_DOOM;
380 goto raw_open_bad;
381 }
382
383 if(open_file(wdat, ao->device) < 0)
384 goto raw_open_bad;
385
386 ao->userptr = wdat;
387 return 1;
388 raw_open_bad:
389 if(wdat)
390 wavdata_del(wdat);
391 return -1;
392 }
393
394 int INT123_wav_open(out123_handle *ao)
395 {
396 int bps;
397 struct wavdata *wdat = NULL;
398 struct riff *inthead = NULL;
399 struct riff_float *floathead = NULL;
400
401 if(ao->format < 0)
402 {
403 ao->rate = 44100;
404 ao->channels = 2;
405 ao->format = MPG123_ENC_SIGNED_16;
406 return 0;
407 }
408
409 if(!(wdat = wavdata_new()))
410 {
411 ao->errcode = OUT123_DOOM;
412 goto wav_open_bad;
413 }
414
415 wdat->floatwav = (ao->format & MPG123_ENC_FLOAT);
416 if(wdat->floatwav)
417 {
418 if(!(floathead = wavhead_new( &riff_float_template
419 , sizeof(riff_float_template)) ))
420 {
421 ao->errcode = OUT123_DOOM;
422 goto wav_open_bad;
423 }
424 wdat->the_header = floathead;
425 wdat->the_header_size = sizeof(*floathead);
426 }
427 else
428 {
429 if(!(inthead = wavhead_new( &riff_template
430 , sizeof(riff_template)) ))
431 {
432 ao->errcode = OUT123_DOOM;
433 goto wav_open_bad;
434 }
435 wdat->the_header = inthead;
436 wdat->the_header_size = sizeof(*inthead);
437
438 /* standard MS PCM, and its format specific is BitsPerSample */
439 long2littleendian(1, inthead->WAVE.fmt.FormatTag
440 , sizeof(inthead->WAVE.fmt.FormatTag));
441 }
442
443 if(ao->format == MPG123_ENC_FLOAT_32)
444 {
445 long2littleendian(3, floathead->WAVE.fmt.FormatTag
446 , sizeof(floathead->WAVE.fmt.FormatTag));
447 long2littleendian(bps=32, floathead->WAVE.fmt.BitsPerSample
448 , sizeof(floathead->WAVE.fmt.BitsPerSample));
449 wdat->flipendian = testEndian();
450 }
451 else if(ao->format == MPG123_ENC_SIGNED_32)
452 {
453 long2littleendian(bps=32, inthead->WAVE.fmt.BitsPerSample
454 , sizeof(inthead->WAVE.fmt.BitsPerSample));
455 wdat->flipendian = testEndian();
456 }
457 else if(ao->format == MPG123_ENC_SIGNED_24)
458 {
459 long2littleendian(bps=24, inthead->WAVE.fmt.BitsPerSample
460 , sizeof(inthead->WAVE.fmt.BitsPerSample));
461 wdat->flipendian = testEndian();
462 }
463 else if(ao->format == MPG123_ENC_SIGNED_16)
464 {
465 long2littleendian(bps=16, inthead->WAVE.fmt.BitsPerSample
466 , sizeof(inthead->WAVE.fmt.BitsPerSample));
467 wdat->flipendian = testEndian();
468 }
469 else if(ao->format == MPG123_ENC_UNSIGNED_8)
470 long2littleendian(bps=8, inthead->WAVE.fmt.BitsPerSample
471 , sizeof(inthead->WAVE.fmt.BitsPerSample));
472 else
473 {
474 if(!AOQUIET)
475 error("Format not supported.");
476 goto wav_open_bad;
477 }
478
479 if(wdat->floatwav)
480 {
481 long2littleendian(ao->channels, floathead->WAVE.fmt.Channels
482 , sizeof(floathead->WAVE.fmt.Channels));
483 long2littleendian(ao->rate, floathead->WAVE.fmt.SamplesPerSec
484 , sizeof(floathead->WAVE.fmt.SamplesPerSec));
485 long2littleendian( (int)(ao->channels * ao->rate * bps)>>3
486 , floathead->WAVE.fmt.AvgBytesPerSec
487 , sizeof(floathead->WAVE.fmt.AvgBytesPerSec) );
488 long2littleendian( (int)(ao->channels * bps)>>3
489 , floathead->WAVE.fmt.BlockAlign
490 , sizeof(floathead->WAVE.fmt.BlockAlign) );
491 }
492 else
493 {
494 long2littleendian(ao->channels, inthead->WAVE.fmt.Channels
495 , sizeof(inthead->WAVE.fmt.Channels));
496 long2littleendian(ao->rate, inthead->WAVE.fmt.SamplesPerSec
497 , sizeof(inthead->WAVE.fmt.SamplesPerSec));
498 long2littleendian( (int)(ao->channels * ao->rate * bps)>>3
499 , inthead->WAVE.fmt.AvgBytesPerSec
500 ,sizeof(inthead->WAVE.fmt.AvgBytesPerSec) );
501 long2littleendian( (int)(ao->channels * bps)>>3
502 , inthead->WAVE.fmt.BlockAlign
503 , sizeof(inthead->WAVE.fmt.BlockAlign) );
504 }
505
506 if(open_file(wdat, ao->device) < 0)
507 goto wav_open_bad;
508
509 if(wdat->floatwav)
510 {
511 long2littleendian(wdat->datalen, floathead->WAVE.data.datalen
512 , sizeof(floathead->WAVE.data.datalen));
513 long2littleendian(wdat->datalen+sizeof(floathead->WAVE)
514 , floathead->WAVElen, sizeof(floathead->WAVElen));
515 }
516 else
517 {
518 long2littleendian(wdat->datalen, inthead->WAVE.data.datalen
519 , sizeof(inthead->WAVE.data.datalen));
520 long2littleendian( wdat->datalen+sizeof(inthead->WAVE)
521 , inthead->WAVElen
522 , sizeof(inthead->WAVElen) );
523 }
524
525 wdat->bytes_per_sample = bps>>3;
526
527 ao->userptr = wdat;
528 return 0;
529
530 wav_open_bad:
531 if(inthead)
532 free(inthead);
533 if(floathead)
534 free(floathead);
535 if(wdat)
536 {
537 wdat->the_header = NULL;
538 wavdata_del(wdat);
539 }
540 return -1;
541 }
542
543 int INT123_wav_write(out123_handle *ao, unsigned char *buf, int len)
544 {
545 struct wavdata *wdat = ao->userptr;
546 int temp;
547 int i;
548
549 if(!wdat || !wdat->wavfp)
550 return 0; /* Really? Zero? */
551
552 if(wdat->datalen == 0 && write_header(ao) < 0)
553 return -1;
554 // TODO: offer way to hand in big-endian data already, as libmpg123
555 // can enforce endianess now
556 /* Endianess conversion. Not fancy / optimized. */
557 if(wdat->flipendian)
558 {
559 if(wdat->bytes_per_sample == 4) /* 32 bit */
560 {
561 if(len & 3)
562 {
563 if(!AOQUIET)
564 error("Number of bytes no multiple of 4 (32bit)!");
565 return -1;
566 }
567 for(i=0;i<len;i+=4)
568 {
569 int j;
570 unsigned char tmp[4];
571 for(j = 0; j<=3; ++j) tmp[j] = buf[i+j];
572 for(j = 0; j<=3; ++j) buf[i+j] = tmp[3-j];
573 }
574 }
575 else /* 16 bit */
576 {
577 if(len & 1)
578 {
579 error("Odd number of bytes!");
580 return -1;
581 }
582 for(i=0;i<len;i+=2)
583 {
584 unsigned char tmp;
585 tmp = buf[i+0];
586 buf[i+0] = buf[i+1];
587 buf[i+1] = tmp;
588 }
589 }
590 }
591
592 temp = fwrite(buf, 1, len, wdat->wavfp);
593 if(temp <= 0) return temp;
594 /* That would kill it of early when running out of disk space. */
595 #if 0
596 if(fflush(wdat->wavfp))
597 {
598 if(!AOQUIET)
599 error1("flushing failed: %s\n", INT123_strerror(errno));
600 return -1;
601 }
602 #endif
603 wdat->datalen += temp;
604
605 return temp;
606 }
607
608 int INT123_wav_close(out123_handle *ao)
609 {
610 struct wavdata *wdat = ao->userptr;
611
612 if(!wdat) /* Special case: Opened only for format query. */
613 return 0;
614
615 if(!wdat || !wdat->wavfp)
616 return -1;
617
618 /* flush before seeking to catch out-of-disk explicitly at least at the end */
619 if(fflush(wdat->wavfp))
620 {
621 if(!AOQUIET)
622 error1("cannot flush WAV stream: %s", INT123_strerror(errno));
623 return close_file(ao);
624 }
625 if(fseek(wdat->wavfp, 0L, SEEK_SET) >= 0)
626 {
627 if(wdat->floatwav)
628 {
629 struct riff_float *floathead = wdat->the_header;
630 long2littleendian(wdat->datalen
631 , floathead->WAVE.data.datalen
632 , sizeof(floathead->WAVE.data.datalen));
633 long2littleendian(wdat->datalen+sizeof(floathead->WAVE)
634 , floathead->WAVElen
635 , sizeof(floathead->WAVElen));
636 long2littleendian( wdat->datalen
637 / (
638 from_little(floathead->WAVE.fmt.Channels,2)
639 * from_little(floathead->WAVE.fmt.BitsPerSample,2)/8
640 )
641 , floathead->WAVE.fact.samplelen
642 , sizeof(floathead->WAVE.fact.samplelen) );
643 }
644 else
645 {
646 struct riff *inthead = wdat->the_header;
647 long2littleendian(wdat->datalen, inthead->WAVE.data.datalen
648 , sizeof(inthead->WAVE.data.datalen));
649 long2littleendian(wdat->datalen+sizeof(inthead->WAVE), inthead->WAVElen
650 , sizeof(inthead->WAVElen));
651 }
652 /* Always (over)writing the header here; also for stdout, when
653 fseek worked, this overwrite works. */
654 write_header(ao);
655 }
656 else if(!AOQUIET)
657 warning("Cannot rewind WAV file. File-format isn't fully conform now.");
658
659 return close_file(ao);
660 }
661
662 int INT123_au_close(out123_handle *ao)
663 {
664 struct wavdata *wdat = ao->userptr;
665
666 if(!wdat) /* Special case: Opened only for format query. */
667 return 0;
668
669 if(!wdat->wavfp)
670 return -1;
671
672 /* flush before seeking to catch out-of-disk explicitly at least at the end */
673 if(fflush(wdat->wavfp))
674 {
675 if(!AOQUIET)
676 error1("cannot flush WAV stream: %s", INT123_strerror(errno));
677 return close_file(ao);
678 }
679 if(fseek(wdat->wavfp, 0L, SEEK_SET) >= 0)
680 {
681 struct auhead *auhead = wdat->the_header;
682 long2bigendian(wdat->datalen, auhead->datalen, sizeof(auhead->datalen));
683 /* Always (over)writing the header here; also for stdout, when
684 fseek worked, this overwrite works. */
685 write_header(ao);
686 }
687 else if(!AOQUIET)
688 warning("Cannot rewind AU file. File-format isn't fully conform now.");
689
690 return close_file(ao);
691 }
692
693 /* CDR data also uses that. */
694 int INT123_raw_close(out123_handle *ao)
695 {
696 struct wavdata *wdat = ao->userptr;
697
698 if(!wdat) /* Special case: Opened only for format query. */
699 return 0;
700
701 if(!wdat->wavfp)
702 return -1;
703
704 return close_file(ao);
705 }
706
707 /* Some trivial functions to interface with out123's module architecture. */
708
709 int INT123_cdr_formats(out123_handle *ao)
710 {
711 if(ao->rate == 44100 && ao->channels == 2)
712 return MPG123_ENC_SIGNED_16;
713 else
714 return 0;
715 }
716
717 int INT123_au_formats(out123_handle *ao)
718 {
719 return MPG123_ENC_SIGNED_16|MPG123_ENC_UNSIGNED_8|MPG123_ENC_ULAW_8;
720 }
721
722 int INT123_raw_formats(out123_handle *ao)
723 {
724 return MPG123_ENC_ANY;
725 }
726
727 int INT123_wav_formats(out123_handle *ao)
728 {
729 return
730 MPG123_ENC_SIGNED_16
731 | MPG123_ENC_UNSIGNED_8
732 | MPG123_ENC_FLOAT_32
733 | MPG123_ENC_SIGNED_24
734 | MPG123_ENC_SIGNED_32;
735 }
736
737 /* Draining is flushing to disk. Words do suck at times.
738 One could call fsync(), too, but to be safe, that would need to
739 be called on the directory, too. Also, apps randomly calling
740 fsync() can cause annoying issues in a system. */
741 void INT123_wav_drain(out123_handle *ao)
742 {
743 struct wavdata *wdat = ao->userptr;
744
745 if(!wdat)
746 return;
747
748 if(fflush(wdat->wavfp) && !AOQUIET)
749 error1("flushing failed: %s\n", INT123_strerror(errno));
750 }