af_scaletempo: fix crash after channel reconfiguration
[mplayer.git] / libao2 / ao_sun.c
blobecdb23d4afac961fa2e1975877950d131665b85b
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 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_GET_VOLUME:
407 int fd;
409 if ( !sun_mixer_device ) /* control function is used before init? */
410 setup_device_paths();
412 fd=open( sun_mixer_device,O_RDONLY );
413 if ( fd != -1 )
415 ao_control_vol_t *vol = (ao_control_vol_t *)arg;
416 float volume;
417 struct audio_info info;
418 ioctl( fd,AUDIO_GETINFO,&info);
419 volume = info.play.gain * 100. / AUDIO_MAX_GAIN;
420 if ( info.play.balance == AUDIO_MID_BALANCE ) {
421 vol->right = vol->left = volume;
422 } else if ( info.play.balance < AUDIO_MID_BALANCE ) {
423 vol->left = volume;
424 vol->right = volume * info.play.balance / AUDIO_MID_BALANCE;
425 } else {
426 vol->left = volume * (AUDIO_RIGHT_BALANCE-info.play.balance)
427 / AUDIO_MID_BALANCE;
428 vol->right = volume;
430 close( fd );
431 return CONTROL_OK;
433 return CONTROL_ERROR;
435 case AOCONTROL_SET_VOLUME:
437 ao_control_vol_t *vol = (ao_control_vol_t *)arg;
438 int fd;
440 if ( !sun_mixer_device ) /* control function is used before init? */
441 setup_device_paths();
443 fd=open( sun_mixer_device,O_RDONLY );
444 if ( fd != -1 )
446 struct audio_info info;
447 float volume;
448 AUDIO_INITINFO(&info);
449 volume = vol->right > vol->left ? vol->right : vol->left;
450 if ( volume != 0 ) {
451 info.play.gain = volume * AUDIO_MAX_GAIN / 100;
452 if ( vol->right == vol->left )
453 info.play.balance = AUDIO_MID_BALANCE;
454 else
455 info.play.balance = (vol->right - vol->left + volume) * AUDIO_RIGHT_BALANCE / (2*volume);
457 #if !defined (__OpenBSD__) && !defined (__NetBSD__)
458 info.output_muted = (volume == 0);
459 #endif
460 ioctl( fd,AUDIO_SETINFO,&info );
461 close( fd );
462 return CONTROL_OK;
464 return CONTROL_ERROR;
467 return CONTROL_UNKNOWN;
470 // open & setup audio device
471 // return: 1=success 0=fail
472 static int init(int rate,int channels,int format,int flags){
474 audio_info_t info;
475 int pass;
476 int ok;
477 int convert_u8_s8;
479 setup_device_paths();
481 if (enable_sample_timing == RTSC_UNKNOWN
482 && !getenv("AO_SUN_DISABLE_SAMPLE_TIMING")) {
483 enable_sample_timing = realtime_samplecounter_available(audio_dev);
486 mp_msg(MSGT_AO,MSGL_STATUS,"ao2: %d Hz %d chans %s [0x%X]\n",
487 rate,channels,af_fmt2str_short(format),format);
489 audio_fd=open(audio_dev, O_WRONLY);
490 if(audio_fd<0){
491 mp_tmsg(MSGT_AO, MSGL_ERR, "[AO SUN] Can't open audio device %s, %s -> nosound.\n", audio_dev, strerror(errno));
492 return 0;
495 if (af2sunfmt(format) == AUDIO_ENCODING_NONE)
496 format = AF_FORMAT_S16_NE;
498 for (ok = pass = 0; pass <= 5; pass++) { /* pass 6&7 not useful */
500 AUDIO_INITINFO(&info);
501 info.play.encoding = af2sunfmt(ao_data.format = format);
502 info.play.precision =
503 (format==AF_FORMAT_S16_NE
504 ? AUDIO_PRECISION_16
505 : AUDIO_PRECISION_8);
506 info.play.channels = ao_data.channels = channels;
507 info.play.sample_rate = ao_data.samplerate = rate;
509 convert_u8_s8 = 0;
511 if (pass & 1) {
513 * on some sun audio drivers, 8-bit unsigned LINEAR8 encoding is
514 * not supported, but 8-bit signed encoding is.
516 * Try S8, and if it works, use our own U8->S8 conversion before
517 * sending the samples to the sound driver.
519 #ifdef AUDIO_ENCODING_LINEAR8
520 if (info.play.encoding != AUDIO_ENCODING_LINEAR8)
521 #endif
522 continue;
523 info.play.encoding = AUDIO_ENCODING_LINEAR;
524 convert_u8_s8 = 1;
527 if (pass & 2) {
529 * on some sun audio drivers, only certain fixed sample rates are
530 * supported.
532 * In case the requested sample rate is very close to one of the
533 * supported rates, use the fixed supported rate instead.
535 if (!(info.play.sample_rate =
536 find_close_samplerate_match(audio_fd, rate)))
537 continue;
540 * I'm not returning the correct sample rate in
541 * |ao_data.samplerate|, to avoid software resampling.
543 * ao_data.samplerate = info.play.sample_rate;
547 if (pass & 4) {
548 /* like "pass & 2", but use the highest supported sample rate */
549 if (!(info.play.sample_rate
550 = ao_data.samplerate
551 = find_highest_samplerate(audio_fd)))
552 continue;
555 ok = ioctl(audio_fd, AUDIO_SETINFO, &info) >= 0;
556 if (ok) {
557 /* audio format accepted by audio driver */
558 break;
562 * format not supported?
563 * retry with different encoding and/or sample rate
567 if (!ok) {
568 char buf[128];
569 mp_tmsg(MSGT_AO, MSGL_ERR, "[AO SUN] audio_setup: your card doesn't support %d channel, %s, %d Hz samplerate.\n",
570 channels, af_fmt2str(format, buf, 128), rate);
571 return 0;
574 if (convert_u8_s8)
575 ao_data.format = AF_FORMAT_S8;
577 bytes_per_sample = channels * info.play.precision / 8;
578 ao_data.bps = byte_per_sec = bytes_per_sample * ao_data.samplerate;
579 ao_data.outburst = byte_per_sec > 100000 ? 16384 : 8192;
581 reset();
583 return 1;
586 // close audio device
587 static void uninit(int immed){
588 // throw away buffered data in the audio driver's STREAMS queue
589 if (immed)
590 flush_audio(audio_fd);
591 else
592 ioctl(audio_fd, AUDIO_DRAIN, 0);
593 close(audio_fd);
596 // stop playing and empty buffers (for seeking/pause)
597 static void reset(void){
598 audio_info_t info;
599 flush_audio(audio_fd);
601 AUDIO_INITINFO(&info);
602 info.play.samples = 0;
603 info.play.eof = 0;
604 info.play.error = 0;
605 ioctl(audio_fd, AUDIO_SETINFO, &info);
607 queued_bursts = 0;
608 queued_samples = 0;
611 // stop playing, keep buffers (for pause)
612 static void audio_pause(void)
614 struct audio_info info;
615 AUDIO_INITINFO(&info);
616 info.play.pause = 1;
617 ioctl(audio_fd, AUDIO_SETINFO, &info);
620 // resume playing, after audio_pause()
621 static void audio_resume(void)
623 struct audio_info info;
624 AUDIO_INITINFO(&info);
625 info.play.pause = 0;
626 ioctl(audio_fd, AUDIO_SETINFO, &info);
630 // return: how many bytes can be played without blocking
631 static int get_space(void){
632 audio_info_t info;
634 // check buffer
635 #ifdef HAVE_AUDIO_SELECT
637 fd_set rfds;
638 struct timeval tv;
639 FD_ZERO(&rfds);
640 FD_SET(audio_fd, &rfds);
641 tv.tv_sec = 0;
642 tv.tv_usec = 0;
643 if(!select(audio_fd+1, NULL, &rfds, NULL, &tv)) return 0; // not block!
645 #endif
647 ioctl(audio_fd, AUDIO_GETINFO, &info);
648 #if !defined (__OpenBSD__) && !defined(__NetBSD__)
649 if (queued_bursts - info.play.eof > 2)
650 return 0;
651 return ao_data.outburst;
652 #else
653 return info.hiwat * info.blocksize - info.play.seek;
654 #endif
658 // plays 'len' bytes of 'data'
659 // it should round it down to outburst*n
660 // return: number of bytes played
661 static int play(void* data,int len,int flags){
662 if (!(flags & AOPLAY_FINAL_CHUNK)) {
663 len /= ao_data.outburst;
664 len *= ao_data.outburst;
666 if (len <= 0) return 0;
668 len = write(audio_fd, data, len);
669 if(len > 0) {
670 queued_samples += len / bytes_per_sample;
671 if (write(audio_fd,data,0) < 0)
672 perror("ao_sun: send EOF audio record");
673 else
674 queued_bursts ++;
676 return len;
680 // return: delay in seconds between first and last sample in buffer
681 static float get_delay(void){
682 audio_info_t info;
683 ioctl(audio_fd, AUDIO_GETINFO, &info);
684 #if defined (__OpenBSD__) || defined(__NetBSD__)
685 return (float) info.play.seek/ (float)byte_per_sec ;
686 #else
687 if (info.play.samples && enable_sample_timing == RTSC_ENABLED)
688 return (float)(queued_samples - info.play.samples) / (float)ao_data.samplerate;
689 else
690 return (float)((queued_bursts - info.play.eof) * ao_data.outburst) / (float)byte_per_sec;
691 #endif