spudec.c: Remove useless NULL checks before free()
[mplayer/glamo.git] / libao2 / ao_sun.c
blob02ffa1edb6625e4b3e4f25970399b433b6a1ddc9
1 /*
2 * SUN audio output driver
4 * This file is part of MPlayer.
6 * MPlayer is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * MPlayer is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with MPlayer; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <errno.h>
28 #include <sys/ioctl.h>
29 #include <sys/time.h>
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <sys/audioio.h>
33 #ifdef AUDIO_SWFEATURE_MIXER /* solaris8 or newer? */
34 # define HAVE_SYS_MIXER_H 1
35 #endif
36 #if HAVE_SYS_MIXER_H
37 # include <sys/mixer.h>
38 #endif
39 #ifdef __svr4__
40 #include <stropts.h>
41 #endif
43 #include "config.h"
44 #include "mixer.h"
46 #include "audio_out.h"
47 #include "audio_out_internal.h"
48 #include "libaf/af_format.h"
49 #include "mp_msg.h"
51 static const ao_info_t info =
53 "Sun audio output",
54 "sun",
55 "Juergen Keil",
59 LIBAO_EXTERN(sun)
62 /* These defines are missing on NetBSD */
63 #ifndef AUDIO_PRECISION_8
64 #define AUDIO_PRECISION_8 8
65 #define AUDIO_PRECISION_16 16
66 #endif
67 #ifndef AUDIO_CHANNELS_MONO
68 #define AUDIO_CHANNELS_MONO 1
69 #define AUDIO_CHANNELS_STEREO 2
70 #endif
73 static char *sun_mixer_device = NULL;
74 static char *audio_dev = NULL;
75 static int queued_bursts = 0;
76 static int queued_samples = 0;
77 static int bytes_per_sample = 0;
78 static int byte_per_sec = 0;
79 static int audio_fd = -1;
80 static enum {
81 RTSC_UNKNOWN = 0,
82 RTSC_ENABLED,
83 RTSC_DISABLED
84 } enable_sample_timing;
87 static void flush_audio(int fd) {
88 #ifdef AUDIO_FLUSH
89 ioctl(fd, AUDIO_FLUSH, 0);
90 #elif defined(__svr4__)
91 ioctl(fd, I_FLUSH, FLUSHW);
92 #endif
95 // convert an OSS audio format specification into a sun audio encoding
96 static int af2sunfmt(int format)
98 switch (format){
99 case AF_FORMAT_MU_LAW:
100 return AUDIO_ENCODING_ULAW;
101 case AF_FORMAT_A_LAW:
102 return AUDIO_ENCODING_ALAW;
103 case AF_FORMAT_S16_NE:
104 return AUDIO_ENCODING_LINEAR;
105 #ifdef AUDIO_ENCODING_LINEAR8 // Missing on SunOS 5.5.1...
106 case AF_FORMAT_U8:
107 return AUDIO_ENCODING_LINEAR8;
108 #endif
109 case AF_FORMAT_S8:
110 return AUDIO_ENCODING_LINEAR;
111 #ifdef AUDIO_ENCODING_DVI // Missing on NetBSD...
112 case AF_FORMAT_IMA_ADPCM:
113 return AUDIO_ENCODING_DVI;
114 #endif
115 default:
116 return AUDIO_ENCODING_NONE;
120 // try to figure out, if the soundcard driver provides usable (precise)
121 // sample counter information
122 static int realtime_samplecounter_available(char *dev)
124 int fd = -1;
125 audio_info_t info;
126 int rtsc_ok = RTSC_DISABLED;
127 int len;
128 void *silence = NULL;
129 struct timeval start, end;
130 struct timespec delay;
131 int usec_delay;
132 unsigned last_samplecnt;
133 unsigned increment;
134 unsigned min_increment;
136 len = 44100 * 4 / 4; /* amount of data for 0.25sec of 44.1khz, stereo,
137 * 16bit. 44kbyte can be sent to all supported
138 * sun audio devices without blocking in the
139 * "write" below.
141 silence = calloc(1, len);
142 if (silence == NULL)
143 goto error;
145 if ((fd = open(dev, O_WRONLY)) < 0)
146 goto error;
148 AUDIO_INITINFO(&info);
149 info.play.sample_rate = 44100;
150 info.play.channels = AUDIO_CHANNELS_STEREO;
151 info.play.precision = AUDIO_PRECISION_16;
152 info.play.encoding = AUDIO_ENCODING_LINEAR;
153 info.play.samples = 0;
154 if (ioctl(fd, AUDIO_SETINFO, &info)) {
155 if ( mp_msg_test(MSGT_AO,MSGL_V) )
156 mp_tmsg(MSGT_AO, MSGL_ERR, "[AO SUN] rtsc: SETINFO failed.\n");
157 goto error;
160 if (write(fd, silence, len) != len) {
161 if ( mp_msg_test(MSGT_AO,MSGL_V) )
162 mp_tmsg(MSGT_AO, MSGL_ERR, "[AO SUN] rtsc: write failed.\n");
163 goto error;
166 if (ioctl(fd, AUDIO_GETINFO, &info)) {
167 if ( mp_msg_test(MSGT_AO,MSGL_V) )
168 perror("rtsc: GETINFO1");
169 goto error;
172 last_samplecnt = info.play.samples;
173 min_increment = ~0;
175 gettimeofday(&start, NULL);
176 for (;;) {
177 delay.tv_sec = 0;
178 delay.tv_nsec = 10000000;
179 nanosleep(&delay, NULL);
180 gettimeofday(&end, NULL);
181 usec_delay = (end.tv_sec - start.tv_sec) * 1000000
182 + end.tv_usec - start.tv_usec;
184 // stop monitoring sample counter after 0.2 seconds
185 if (usec_delay > 200000)
186 break;
188 if (ioctl(fd, AUDIO_GETINFO, &info)) {
189 if ( mp_msg_test(MSGT_AO,MSGL_V) )
190 perror("rtsc: GETINFO2 failed");
191 goto error;
193 if (info.play.samples < last_samplecnt) {
194 if ( mp_msg_test(MSGT_AO,MSGL_V) )
195 mp_msg(MSGT_AO,MSGL_V,"rtsc: %d > %d?\n", last_samplecnt, info.play.samples);
196 goto error;
199 if ((increment = info.play.samples - last_samplecnt) > 0) {
200 if ( mp_msg_test(MSGT_AO,MSGL_V) )
201 mp_msg(MSGT_AO,MSGL_V,"ao_sun: sample counter increment: %d\n", increment);
202 if (increment < min_increment) {
203 min_increment = increment;
204 if (min_increment < 2000)
205 break; // looks good
208 last_samplecnt = info.play.samples;
212 * For 44.1kkz, stereo, 16-bit format we would send sound data in 16kbytes
213 * chunks (== 4096 samples) to the audio device. If we see a minimum
214 * sample counter increment from the soundcard driver of less than
215 * 2000 samples, we assume that the driver provides a useable realtime
216 * sample counter in the AUDIO_INFO play.samples field. Timing based
217 * on sample counts should be much more accurate than counting whole
218 * 16kbyte chunks.
220 if (min_increment < 2000)
221 rtsc_ok = RTSC_ENABLED;
223 if ( mp_msg_test(MSGT_AO,MSGL_V) )
224 mp_msg(MSGT_AO,MSGL_V,"ao_sun: minimum sample counter increment per 10msec interval: %d\n"
225 "\t%susing sample counter based timing code\n",
226 min_increment, rtsc_ok == RTSC_ENABLED ? "" : "not ");
229 error:
230 if (silence != NULL) free(silence);
231 if (fd >= 0) {
232 // remove the 0 bytes from the above measurement from the
233 // audio driver's STREAMS queue
234 flush_audio(fd);
235 close(fd);
238 return rtsc_ok;
242 // match the requested sample rate |sample_rate| against the
243 // sample rates supported by the audio device |dev|. Return
244 // a supported sample rate, if that sample rate is close to
245 // (< 1% difference) the requested rate; return 0 otherwise.
247 #define MAX_RATE_ERR 1
249 static unsigned
250 find_close_samplerate_match(int dev, unsigned sample_rate)
252 #if HAVE_SYS_MIXER_H
253 am_sample_rates_t *sr;
254 unsigned i, num, err, best_err, best_rate;
256 for (num = 16; num < 1024; num *= 2) {
257 sr = malloc(AUDIO_MIXER_SAMP_RATES_STRUCT_SIZE(num));
258 if (!sr)
259 return 0;
260 sr->type = AUDIO_PLAY;
261 sr->flags = 0;
262 sr->num_samp_rates = num;
263 if (ioctl(dev, AUDIO_MIXER_GET_SAMPLE_RATES, sr)) {
264 free(sr);
265 return 0;
267 if (sr->num_samp_rates <= num)
268 break;
269 free(sr);
272 if (sr->flags & MIXER_SR_LIMITS) {
274 * HW can playback any rate between
275 * sr->samp_rates[0] .. sr->samp_rates[1]
277 free(sr);
278 return 0;
279 } else {
280 /* HW supports fixed sample rates only */
282 best_err = 65535;
283 best_rate = 0;
285 for (i = 0; i < sr->num_samp_rates; i++) {
286 err = abs(sr->samp_rates[i] - sample_rate);
287 if (err == 0) {
289 * exact supported sample rate match, no need to
290 * retry something else
292 best_rate = 0;
293 break;
295 if (err < best_err) {
296 best_err = err;
297 best_rate = sr->samp_rates[i];
301 free(sr);
303 if (best_rate > 0 && (100/MAX_RATE_ERR)*best_err < sample_rate) {
304 /* found a supported sample rate with <1% error? */
305 return best_rate;
307 return 0;
309 #else /* old audioio driver, cannot return list of supported rates */
310 /* XXX: hardcoded sample rates */
311 unsigned i, err;
312 unsigned audiocs_rates[] = {
313 5510, 6620, 8000, 9600, 11025, 16000, 18900, 22050,
314 27420, 32000, 33075, 37800, 44100, 48000, 0
317 for (i = 0; audiocs_rates[i]; i++) {
318 err = abs(audiocs_rates[i] - sample_rate);
319 if (err == 0) {
321 * exact supported sample rate match, no need to
322 * retry something elise
324 return 0;
326 if ((100/MAX_RATE_ERR)*err < audiocs_rates[i]) {
327 /* <1% error? */
328 return audiocs_rates[i];
332 return 0;
333 #endif
337 // return the highest sample rate supported by audio device |dev|.
338 static unsigned
339 find_highest_samplerate(int dev)
341 #if HAVE_SYS_MIXER_H
342 am_sample_rates_t *sr;
343 unsigned i, num, max_rate;
345 for (num = 16; num < 1024; num *= 2) {
346 sr = malloc(AUDIO_MIXER_SAMP_RATES_STRUCT_SIZE(num));
347 if (!sr)
348 return 0;
349 sr->type = AUDIO_PLAY;
350 sr->flags = 0;
351 sr->num_samp_rates = num;
352 if (ioctl(dev, AUDIO_MIXER_GET_SAMPLE_RATES, sr)) {
353 free(sr);
354 return 0;
356 if (sr->num_samp_rates <= num)
357 break;
358 free(sr);
361 if (sr->flags & MIXER_SR_LIMITS) {
363 * HW can playback any rate between
364 * sr->samp_rates[0] .. sr->samp_rates[1]
366 max_rate = sr->samp_rates[1];
367 } else {
368 /* HW supports fixed sample rates only */
369 max_rate = 0;
370 for (i = 0; i < sr->num_samp_rates; i++) {
371 if (sr->samp_rates[i] > max_rate)
372 max_rate = sr->samp_rates[i];
375 free(sr);
376 return max_rate;
378 #else /* old audioio driver, cannot return list of supported rates */
379 return 44100; /* should be supported even on old ISA SB cards */
380 #endif
384 static void setup_device_paths(void)
386 if (audio_dev == NULL) {
387 if ((audio_dev = getenv("AUDIODEV")) == NULL)
388 audio_dev = "/dev/audio";
391 if (sun_mixer_device == NULL) {
392 if ((sun_mixer_device = mixer_device) == NULL || !sun_mixer_device[0]) {
393 sun_mixer_device = malloc(strlen(audio_dev) + 4);
394 strcpy(sun_mixer_device, audio_dev);
395 strcat(sun_mixer_device, "ctl");
399 if (ao_subdevice) audio_dev = ao_subdevice;
402 // to set/get/query special features/parameters
403 static int control(int cmd,void *arg){
404 switch(cmd){
405 case AOCONTROL_SET_DEVICE:
406 audio_dev=(char*)arg;
407 return CONTROL_OK;
408 case AOCONTROL_QUERY_FORMAT:
409 return CONTROL_TRUE;
410 case AOCONTROL_GET_VOLUME:
412 int fd;
414 if ( !sun_mixer_device ) /* control function is used before init? */
415 setup_device_paths();
417 fd=open( sun_mixer_device,O_RDONLY );
418 if ( fd != -1 )
420 ao_control_vol_t *vol = (ao_control_vol_t *)arg;
421 float volume;
422 struct audio_info info;
423 ioctl( fd,AUDIO_GETINFO,&info);
424 volume = info.play.gain * 100. / AUDIO_MAX_GAIN;
425 if ( info.play.balance == AUDIO_MID_BALANCE ) {
426 vol->right = vol->left = volume;
427 } else if ( info.play.balance < AUDIO_MID_BALANCE ) {
428 vol->left = volume;
429 vol->right = volume * info.play.balance / AUDIO_MID_BALANCE;
430 } else {
431 vol->left = volume * (AUDIO_RIGHT_BALANCE-info.play.balance)
432 / AUDIO_MID_BALANCE;
433 vol->right = volume;
435 close( fd );
436 return CONTROL_OK;
438 return CONTROL_ERROR;
440 case AOCONTROL_SET_VOLUME:
442 ao_control_vol_t *vol = (ao_control_vol_t *)arg;
443 int fd;
445 if ( !sun_mixer_device ) /* control function is used before init? */
446 setup_device_paths();
448 fd=open( sun_mixer_device,O_RDONLY );
449 if ( fd != -1 )
451 struct audio_info info;
452 float volume;
453 AUDIO_INITINFO(&info);
454 volume = vol->right > vol->left ? vol->right : vol->left;
455 if ( volume != 0 ) {
456 info.play.gain = volume * AUDIO_MAX_GAIN / 100;
457 if ( vol->right == vol->left )
458 info.play.balance = AUDIO_MID_BALANCE;
459 else
460 info.play.balance = (vol->right - vol->left + volume) * AUDIO_RIGHT_BALANCE / (2*volume);
462 #if !defined (__OpenBSD__) && !defined (__NetBSD__)
463 info.output_muted = (volume == 0);
464 #endif
465 ioctl( fd,AUDIO_SETINFO,&info );
466 close( fd );
467 return CONTROL_OK;
469 return CONTROL_ERROR;
472 return CONTROL_UNKNOWN;
475 // open & setup audio device
476 // return: 1=success 0=fail
477 static int init(int rate,int channels,int format,int flags){
479 audio_info_t info;
480 int pass;
481 int ok;
482 int convert_u8_s8;
484 setup_device_paths();
486 if (enable_sample_timing == RTSC_UNKNOWN
487 && !getenv("AO_SUN_DISABLE_SAMPLE_TIMING")) {
488 enable_sample_timing = realtime_samplecounter_available(audio_dev);
491 mp_msg(MSGT_AO,MSGL_STATUS,"ao2: %d Hz %d chans %s [0x%X]\n",
492 rate,channels,af_fmt2str_short(format),format);
494 audio_fd=open(audio_dev, O_WRONLY);
495 if(audio_fd<0){
496 mp_tmsg(MSGT_AO, MSGL_ERR, "[AO SUN] Can't open audio device %s, %s -> nosound.\n", audio_dev, strerror(errno));
497 return 0;
500 if (af2sunfmt(format) == AUDIO_ENCODING_NONE)
501 format = AF_FORMAT_S16_NE;
503 for (ok = pass = 0; pass <= 5; pass++) { /* pass 6&7 not useful */
505 AUDIO_INITINFO(&info);
506 info.play.encoding = af2sunfmt(ao_data.format = format);
507 info.play.precision =
508 (format==AF_FORMAT_S16_NE
509 ? AUDIO_PRECISION_16
510 : AUDIO_PRECISION_8);
511 info.play.channels = ao_data.channels = channels;
512 info.play.sample_rate = ao_data.samplerate = rate;
514 convert_u8_s8 = 0;
516 if (pass & 1) {
518 * on some sun audio drivers, 8-bit unsigned LINEAR8 encoding is
519 * not supported, but 8-bit signed encoding is.
521 * Try S8, and if it works, use our own U8->S8 conversion before
522 * sending the samples to the sound driver.
524 #ifdef AUDIO_ENCODING_LINEAR8
525 if (info.play.encoding != AUDIO_ENCODING_LINEAR8)
526 #endif
527 continue;
528 info.play.encoding = AUDIO_ENCODING_LINEAR;
529 convert_u8_s8 = 1;
532 if (pass & 2) {
534 * on some sun audio drivers, only certain fixed sample rates are
535 * supported.
537 * In case the requested sample rate is very close to one of the
538 * supported rates, use the fixed supported rate instead.
540 if (!(info.play.sample_rate =
541 find_close_samplerate_match(audio_fd, rate)))
542 continue;
545 * I'm not returning the correct sample rate in
546 * |ao_data.samplerate|, to avoid software resampling.
548 * ao_data.samplerate = info.play.sample_rate;
552 if (pass & 4) {
553 /* like "pass & 2", but use the highest supported sample rate */
554 if (!(info.play.sample_rate
555 = ao_data.samplerate
556 = find_highest_samplerate(audio_fd)))
557 continue;
560 ok = ioctl(audio_fd, AUDIO_SETINFO, &info) >= 0;
561 if (ok) {
562 /* audio format accepted by audio driver */
563 break;
567 * format not supported?
568 * retry with different encoding and/or sample rate
572 if (!ok) {
573 char buf[128];
574 mp_tmsg(MSGT_AO, MSGL_ERR, "[AO SUN] audio_setup: your card doesn't support %d channel, %s, %d Hz samplerate.\n",
575 channels, af_fmt2str(format, buf, 128), rate);
576 return 0;
579 if (convert_u8_s8)
580 ao_data.format = AF_FORMAT_S8;
582 bytes_per_sample = channels * info.play.precision / 8;
583 ao_data.bps = byte_per_sec = bytes_per_sample * ao_data.samplerate;
584 ao_data.outburst = byte_per_sec > 100000 ? 16384 : 8192;
586 reset();
588 return 1;
591 // close audio device
592 static void uninit(int immed){
593 // throw away buffered data in the audio driver's STREAMS queue
594 if (immed)
595 flush_audio(audio_fd);
596 else
597 ioctl(audio_fd, AUDIO_DRAIN, 0);
598 close(audio_fd);
601 // stop playing and empty buffers (for seeking/pause)
602 static void reset(void){
603 audio_info_t info;
604 flush_audio(audio_fd);
606 AUDIO_INITINFO(&info);
607 info.play.samples = 0;
608 info.play.eof = 0;
609 info.play.error = 0;
610 ioctl(audio_fd, AUDIO_SETINFO, &info);
612 queued_bursts = 0;
613 queued_samples = 0;
616 // stop playing, keep buffers (for pause)
617 static void audio_pause(void)
619 struct audio_info info;
620 AUDIO_INITINFO(&info);
621 info.play.pause = 1;
622 ioctl(audio_fd, AUDIO_SETINFO, &info);
625 // resume playing, after audio_pause()
626 static void audio_resume(void)
628 struct audio_info info;
629 AUDIO_INITINFO(&info);
630 info.play.pause = 0;
631 ioctl(audio_fd, AUDIO_SETINFO, &info);
635 // return: how many bytes can be played without blocking
636 static int get_space(void){
637 audio_info_t info;
639 // check buffer
640 #ifdef HAVE_AUDIO_SELECT
642 fd_set rfds;
643 struct timeval tv;
644 FD_ZERO(&rfds);
645 FD_SET(audio_fd, &rfds);
646 tv.tv_sec = 0;
647 tv.tv_usec = 0;
648 if(!select(audio_fd+1, NULL, &rfds, NULL, &tv)) return 0; // not block!
650 #endif
652 ioctl(audio_fd, AUDIO_GETINFO, &info);
653 #if !defined (__OpenBSD__) && !defined(__NetBSD__)
654 if (queued_bursts - info.play.eof > 2)
655 return 0;
656 return ao_data.outburst;
657 #else
658 return info.hiwat * info.blocksize - info.play.seek;
659 #endif
663 // plays 'len' bytes of 'data'
664 // it should round it down to outburst*n
665 // return: number of bytes played
666 static int play(void* data,int len,int flags){
667 if (len < ao_data.outburst) return 0;
668 len /= ao_data.outburst;
669 len *= ao_data.outburst;
671 len = write(audio_fd, data, len);
672 if(len > 0) {
673 queued_samples += len / bytes_per_sample;
674 if (write(audio_fd,data,0) < 0)
675 perror("ao_sun: send EOF audio record");
676 else
677 queued_bursts ++;
679 return len;
683 // return: delay in seconds between first and last sample in buffer
684 static float get_delay(void){
685 audio_info_t info;
686 ioctl(audio_fd, AUDIO_GETINFO, &info);
687 #if defined (__OpenBSD__) || defined(__NetBSD__)
688 return (float) info.play.seek/ (float)byte_per_sec ;
689 #else
690 if (info.play.samples && enable_sample_timing == RTSC_ENABLED)
691 return (float)(queued_samples - info.play.samples) / (float)ao_data.samplerate;
692 else
693 return (float)((queued_bursts - info.play.eof) * ao_data.outburst) / (float)byte_per_sec;
694 #endif