1 /*
2     TiMidity++ -- MIDI to WAVE converter and player
3     Copyright (C) 1999-2002 Masanao Izumo <mo@goice.co.jp>
4     Copyright (C) 1995 Tuukka Toivonen <tt@cgs.fi>
5 
6     This program 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.
10 
11     This program 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.
15 
16     You should have received a copy of the GNU General Public License
17     along with this program; if not, write to the Free Software
18     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19 
20     aq.c - Audio queue.
21 	      Written by Masanao Izumo <mo@goice.co.jp>
22 */
23 
24 #ifdef HAVE_CONFIG_H
25 #include "config.h"
26 #endif /* HAVE_CONFIG_H */
27 
28 #ifdef __POCC__
29 #include <sys/types.h>
30 #endif //for off_t
31 #include <stdio.h>
32 #include <stdlib.h>
33 #ifdef HAVE_UNISTD_H
34 #include <unistd.h>
35 #endif /* HAVE_UNISTD_H */
36 
37 #ifndef NO_STRING_H
38 #include <string.h>
39 #else
40 #include <strings.h>
41 #endif
42 
43 #include "timidity.h"
44 #include "common.h"
45 #include "output.h"
46 #include "aq.h"
47 #include "timer.h"
48 #include "controls.h"
49 #include "miditrace.h"
50 #include "instrum.h"
51 #include "playmidi.h"
52 
53 
54 #define TEST_SPARE_RATE 0.9
55 #define MAX_BUCKET_TIME 0.2
56 #define MAX_FILLED_TIME 2.0
57 
58 static int32 device_qsize;
59 static int Bps;	/* Bytes per sample frame */
60 static int bucket_size;
61 static int nbuckets = 0;
62 static double bucket_time;
63 int aq_fill_buffer_flag = 0;
64 static int32 aq_start_count;
65 static int32 aq_add_count;
66 
67 static int32 play_counter, play_offset_counter;
68 static double play_start_time;
69 
70 typedef struct _AudioBucket
71 {
72     char *data;
73     int len;
74     struct _AudioBucket *next;
75 } AudioBucket;
76 
77 static AudioBucket *base_buckets = NULL;
78 static AudioBucket *allocated_bucket_list = NULL;
79 static AudioBucket *head = NULL;
80 static AudioBucket *tail = NULL;
81 
82 static void alloc_soft_queue(void);
83 static void set_bucket_size(int size);
84 static int add_play_bucket(const char *buf, int n);
85 static void reuse_audio_bucket(AudioBucket *bucket);
86 static AudioBucket *next_allocated_bucket(void);
87 static void flush_buckets(void);
88 static int aq_fill_one(void);
89 static void aq_wait_ticks(void);
90 static int32 estimate_queue_size(void);
91 
92 /* effect.c */
93 extern void init_effect(void);
94 extern void do_effect(int32* buf, int32 count);
95 
aq_calc_fragsize(void)96 int aq_calc_fragsize(void)
97 {
98     int ch, bps, bs;
99     double dq, bt;
100 
101     if(play_mode->encoding & PE_MONO)
102 	ch = 1;
103     else
104 	ch = 2;
105     if(play_mode->encoding & PE_24BIT)
106 	bps = ch * 3;
107     else if(play_mode->encoding & PE_16BIT)
108 	bps = ch * 2;
109     else
110 	bps = ch;
111 
112     bs = audio_buffer_size * bps;
113     dq = play_mode->rate * MAX_FILLED_TIME * bps;
114     while(bs * 2 > dq)
115 	bs /= 2;
116 
117     bt = (double)bs / bps / play_mode->rate;
118     while(bt > MAX_BUCKET_TIME)
119     {
120 	bs /= 2;
121 	bt = (double)bs / bps / play_mode->rate;
122     }
123 
124     return bs;
125 }
126 
aq_setup(void)127 void aq_setup(void)
128 {
129     int ch, frag_size;
130 
131     /* Initialize Bps, bucket_size, device_qsize, and bucket_time */
132 
133     if(play_mode->encoding & PE_MONO)
134 	ch = 1;
135     else
136 	ch = 2;
137     if(play_mode->encoding & PE_24BIT)
138 	Bps = 3 * ch;
139     else if(play_mode->encoding & PE_16BIT)
140 	Bps = 2 * ch;
141     else
142 	Bps = ch;
143 
144     if(play_mode->acntl(PM_REQ_GETFRAGSIZ, &frag_size) == -1)
145 	frag_size = audio_buffer_size * Bps;
146     set_bucket_size(frag_size);
147     bucket_time = (double)bucket_size / Bps / play_mode->rate;
148 
149     if(IS_STREAM_TRACE)
150     {
151 	if(play_mode->acntl(PM_REQ_GETQSIZ, &device_qsize) == -1)
152 	    device_qsize = estimate_queue_size();
153 	if(bucket_size * 2 > device_qsize) {
154 	  ctl->cmsg(CMSG_WARNING, VERB_VERBOSE,
155 		    "Warning: Audio buffer is too small.");
156 	  device_qsize = 0;
157 	} else {
158 	  device_qsize -= device_qsize % Bps; /* Round Bps */
159 	  ctl->cmsg(CMSG_INFO, VERB_DEBUG,
160 		    "Audio device queue size: %d bytes", device_qsize);
161 	  ctl->cmsg(CMSG_INFO, VERB_DEBUG,
162 		    "Write bucket size: %d bytes (%d msec)",
163 		    bucket_size, (int)(bucket_time * 1000 + 0.5));
164 	}
165     }
166     else
167     {
168 	device_qsize = 0;
169 	free_soft_queue();
170 	nbuckets = 0;
171     }
172 
173     init_effect();
174     aq_add_count = 0;
175 }
176 
aq_set_soft_queue(double soft_buff_time,double fill_start_time)177 void aq_set_soft_queue(double soft_buff_time, double fill_start_time)
178 {
179     static double last_soft_buff_time, last_fill_start_time;
180     int nb;
181 
182     /* for re-initialize */
183     if(soft_buff_time < 0)
184 	soft_buff_time = last_soft_buff_time;
185     if(fill_start_time < 0)
186 	fill_start_time = last_fill_start_time;
187 
188     nb = (int)(soft_buff_time / bucket_time);
189     if(nb == 0)
190 	aq_start_count = 0;
191     else
192 	aq_start_count = (int32)(fill_start_time * play_mode->rate);
193     aq_fill_buffer_flag = (aq_start_count > 0);
194 
195     if(nbuckets != nb)
196     {
197 	nbuckets = nb;
198 	alloc_soft_queue();
199     }
200 
201     last_soft_buff_time = soft_buff_time;
202     last_fill_start_time = fill_start_time;
203 }
204 
205 /* Estimates the size of audio device queue.
206  * About sun audio, there are long-waiting if buffer of device audio is full.
207  * So it is impossible to completely estimate the size.
208  */
estimate_queue_size(void)209 static int32 estimate_queue_size(void)
210 {
211     char *nullsound;
212     double tb, init_time, chunktime;
213     int32 qbytes, max_qbytes;
214     int ntries;
215 
216     nullsound = (char *)safe_malloc(bucket_size);
217     memset(nullsound, 0, bucket_size);
218     if(play_mode->encoding & (PE_ULAW|PE_ALAW))
219 	general_output_convert((int32 *)nullsound, bucket_size/Bps);
220     tb = play_mode->rate * Bps * TEST_SPARE_RATE;
221     ntries = 1;
222     max_qbytes = play_mode->rate * MAX_FILLED_TIME * Bps;
223 
224   retry:
225     chunktime = (double)bucket_size / Bps / play_mode->rate;
226     qbytes = 0;
227 
228     init_time = get_current_calender_time();	/* Start */
229     for(;;)
230     {
231 	double start, diff;
232 
233 	start = get_current_calender_time();
234 	if(start - init_time > 1.0) /* ?? */
235 	{
236 	    ctl->cmsg(CMSG_WARNING, VERB_DEBUG,
237 		      "Warning: Audio test is terminated");
238 	    break;
239 	}
240 	play_mode->output_data(nullsound, bucket_size);
241 	diff = get_current_calender_time() - start;
242 
243 	if(diff > chunktime/2 || qbytes > 1024*512 || chunktime < diff)
244 	    break;
245 	qbytes += (int32)((chunktime - diff) * tb);
246 
247 	if(qbytes > max_qbytes)
248 	{
249 	    qbytes = max_qbytes;
250 	    break;
251 	}
252     }
253     play_mode->acntl(PM_REQ_DISCARD, NULL);
254 
255     if(bucket_size * 2 > qbytes)
256     {
257 	if(ntries == 4)
258 	{
259 	    ctl->cmsg(CMSG_ERROR, VERB_NOISY,
260 		      "Can't estimate audio queue length");
261 	    set_bucket_size(audio_buffer_size * Bps);
262 	    free(nullsound);
263 	    return 2 * audio_buffer_size * Bps;
264 	}
265 
266 	ctl->cmsg(CMSG_WARNING, VERB_DEBUG,
267 		  "Retry to estimate audio queue length (%d times)",
268 		  ntries);
269 	set_bucket_size(bucket_size / 2);
270 	ntries++;
271 	goto retry;
272     }
273 
274     free(nullsound);
275 
276     return qbytes;
277 }
278 
279 /* Send audio data to play_mode->output_data() */
aq_output_data(char * buff,int nbytes)280 static int aq_output_data(char *buff, int nbytes)
281 {
282     int i;
283 
284     play_counter += nbytes / Bps;
285 
286     while(nbytes > 0)
287     {
288 	i = nbytes;
289 	if(i > bucket_size)
290 	    i = bucket_size;
291 	if(play_mode->output_data(buff, i) == -1)
292 	    return -1;
293 	nbytes -= i;
294 	buff += i;
295     }
296 
297     return 0;
298 }
299 
aq_add(int32 * samples,int32 count)300 int aq_add(int32 *samples, int32 count)
301 {
302     int32 nbytes, i;
303     char *buff;
304 
305     if(!(play_mode->flag & PF_PCM_STREAM))
306 	return 0;
307 
308     if(!count)
309     {
310 	if(!aq_fill_buffer_flag)
311 	    return aq_fill_nonblocking();
312 	return 0;
313     }
314 
315     aq_add_count += count;
316     do_effect(samples, count);
317     nbytes = general_output_convert(samples, count);
318     buff = (char *)samples;
319 
320     if(device_qsize == 0)
321       return play_mode->output_data(buff, nbytes);
322 
323     aq_fill_buffer_flag = (aq_add_count <= aq_start_count);
324 
325     if(!aq_fill_buffer_flag)
326 	if(aq_fill_nonblocking() == -1)
327 	    return -1;
328 
329     if(!ctl->trace_playing)
330     {
331 	while((i = add_play_bucket(buff, nbytes)) < nbytes)
332 	{
333 	    buff += i;
334 	    nbytes -= i;
335 	    if(head && head->len == bucket_size)
336 	    {
337 		if(aq_fill_one() == -1)
338 		    return -1;
339 	    }
340 	    aq_fill_buffer_flag = 0;
341 	}
342 	return 0;
343     }
344 
345     trace_loop();
346     while((i = add_play_bucket(buff, nbytes)) < nbytes)
347     {
348 	/* Software buffer is full.
349 	 * Write one bucket to audio device.
350 	 */
351 	buff += i;
352 	nbytes -= i;
353 	aq_wait_ticks();
354 	trace_loop();
355 	if(aq_fill_nonblocking() == -1)
356 	    return -1;
357 	aq_fill_buffer_flag = 0;
358     }
359     return 0;
360 }
361 
set_bucket_size(int size)362 static void set_bucket_size(int size)
363 {
364     if (size == bucket_size)
365 	return;
366     bucket_size = size;
367     if (nbuckets != 0)
368 	alloc_soft_queue();
369 }
370 
371 /* alloc_soft_queue() (re-)initializes audio buckets. */
alloc_soft_queue(void)372 static void alloc_soft_queue(void)
373 {
374     int i;
375     char *base;
376 
377     free_soft_queue();
378 
379     base_buckets = (AudioBucket *)safe_malloc(nbuckets * sizeof(AudioBucket));
380     base = (char *)safe_malloc(nbuckets * bucket_size);
381     for(i = 0; i < nbuckets; i++)
382 	base_buckets[i].data = base + i * bucket_size;
383     flush_buckets();
384 }
385 
free_soft_queue(void)386 void free_soft_queue(void)
387 {
388     if(base_buckets)
389     {
390 	free(base_buckets[0].data);
391 	free(base_buckets);
392 	base_buckets = NULL;
393     }
394 }
395 
396 /* aq_fill_one() transfers one audio bucket to device. */
aq_fill_one(void)397 static int aq_fill_one(void)
398 {
399     AudioBucket *tmp;
400 
401     if(head == NULL)
402 	return 0;
403     if(aq_output_data(head->data, bucket_size) == -1)
404 	return -1;
405     tmp = head;
406     head = head->next;
407     reuse_audio_bucket(tmp);
408     return 0;
409 }
410 
411 /* aq_fill_nonblocking() transfers some audio buckets to device.
412  * This function is non-blocking.  But it is possible to block because
413  * of miss-estimated aq_fillable() calculation.
414  */
aq_fill_nonblocking(void)415 int aq_fill_nonblocking(void)
416 {
417     int32 i, nfills;
418     AudioBucket *tmp;
419 
420     if(head == NULL || head->len != bucket_size || !IS_STREAM_TRACE)
421 	return 0;
422 
423     nfills = (aq_fillable() * Bps) / bucket_size;
424     for(i = 0; i < nfills; i++)
425     {
426 	if(head == NULL || head->len != bucket_size)
427 	    break;
428 	if(aq_output_data(head->data, bucket_size) == -1)
429 	    return RC_ERROR;
430 	tmp = head;
431 	head = head->next;
432 	reuse_audio_bucket(tmp);
433     }
434     return 0;
435 }
436 
aq_samples(void)437 int32 aq_samples(void)
438 {
439     double realtime, es;
440     int s;
441 
442     if(play_mode->acntl(PM_REQ_GETSAMPLES, &s) != -1)
443     {
444 	/* Reset counter & timer */
445 	if(play_counter)
446 	{
447 	    play_start_time = get_current_calender_time();
448 	    play_offset_counter = s;
449 	    play_counter = 0;
450 	}
451 	return s;
452     }
453 
454     if(!IS_STREAM_TRACE)
455 	return -1;
456 
457     realtime = get_current_calender_time();
458     if(play_counter == 0)
459     {
460 	play_start_time = realtime;
461 	return play_offset_counter;
462     }
463     es = play_mode->rate * (realtime - play_start_time);
464     if(es >= play_counter)
465     {
466 	/* Ouch!
467 	 * Audio device queue may be empty!
468 	 * Reset counters.
469 	 */
470 
471 	play_offset_counter += play_counter;
472 	play_counter = 0;
473 	play_start_time = realtime;
474 	return play_offset_counter;
475     }
476 
477     return (int32)es + play_offset_counter;
478 }
479 
aq_filled(void)480 int32 aq_filled(void)
481 {
482     double realtime, es;
483     int filled;
484 
485     if(!IS_STREAM_TRACE)
486 	return 0;
487 
488     if(play_mode->acntl(PM_REQ_GETFILLED, &filled) != -1)
489       return filled;
490 
491     realtime = get_current_calender_time();
492     if(play_counter == 0)
493     {
494 	play_start_time = realtime;
495 	return 0;
496     }
497     es = play_mode->rate * (realtime - play_start_time);
498     if(es >= play_counter)
499     {
500 	/* out of play counter */
501 	play_offset_counter += play_counter;
502 	play_counter = 0;
503 	play_start_time = realtime;
504 	return 0;
505     }
506     return play_counter - (int32)es;
507 }
508 
aq_soft_filled(void)509 int32 aq_soft_filled(void)
510 {
511     int32 bytes;
512     AudioBucket *cur;
513 
514     bytes = 0;
515     for(cur = head; cur != NULL; cur = cur->next)
516 	bytes += cur->len;
517     return bytes / Bps;
518 }
519 
aq_fillable(void)520 int32 aq_fillable(void)
521 {
522     int fillable;
523     if(!IS_STREAM_TRACE)
524 	return 0;
525     if(play_mode->acntl(PM_REQ_GETFILLABLE, &fillable) != -1)
526 	return fillable;
527     return device_qsize / Bps - aq_filled();
528 }
529 
aq_filled_ratio(void)530 double aq_filled_ratio(void)
531 {
532     double ratio;
533 
534     if(!IS_STREAM_TRACE)
535 	return 1.0;
536     ratio = (double)aq_filled() * Bps / device_qsize;
537     if(ratio > 1.0)
538 	return 1.0; /* for safety */
539     return ratio;
540 }
541 
aq_get_dev_queuesize(void)542 int aq_get_dev_queuesize(void)
543 {
544     if(!IS_STREAM_TRACE)
545 	return 0;
546     return device_qsize / Bps;
547 }
548 
aq_soft_flush(void)549 int aq_soft_flush(void)
550 {
551     int rc;
552 
553     while(head)
554     {
555 	if(head->len < bucket_size)
556 	{
557 	    /* Add silence code */
558 	    memset (head->data + head->len, 0, bucket_size - head->len);
559 	    head->len = bucket_size;
560 	}
561 	if(aq_fill_one() == -1)
562 	    return RC_ERROR;
563 	trace_loop();
564 	rc = check_apply_control();
565 	if(RC_IS_SKIP_FILE(rc))
566 	{
567 	    play_mode->acntl(PM_REQ_DISCARD, NULL);
568 	    flush_buckets();
569 	    return rc;
570 	}
571     }
572     play_mode->acntl(PM_REQ_OUTPUT_FINISH, NULL);
573     return RC_NONE;
574 }
575 
aq_flush(int discard)576 int aq_flush(int discard)
577 {
578     int rc;
579     int more_trace;
580 
581     /* to avoid infinite loop */
582     double t, timeout_expect;
583 
584     aq_add_count = 0;
585     init_effect();
586 
587     if(discard)
588     {
589 	trace_flush();
590 	if(play_mode->acntl(PM_REQ_DISCARD, NULL) != -1)
591 	{
592 	    flush_buckets();
593 	    return RC_NONE;
594 	}
595 	ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
596 		  "ERROR: Can't discard audio buffer");
597     }
598 
599     if(!IS_STREAM_TRACE)
600     {
601 	play_mode->acntl(PM_REQ_FLUSH, NULL);
602 	play_counter = play_offset_counter = 0;
603 	return RC_NONE;
604     }
605 
606     rc = aq_soft_flush();
607     if(RC_IS_SKIP_FILE(rc))
608 	return rc;
609 
610     more_trace = 1;
611     t = get_current_calender_time();
612     timeout_expect = t + (double)aq_filled() / play_mode->rate;
613 
614     while(more_trace || aq_filled() > 0)
615     {
616 	rc = check_apply_control();
617 	if(RC_IS_SKIP_FILE(rc))
618 	{
619 	    play_mode->acntl(PM_REQ_DISCARD, NULL);
620 	    flush_buckets();
621 	    return rc;
622 	}
623 	more_trace = trace_loop();
624 
625 	t = get_current_calender_time();
626 	if(t >= timeout_expect - 0.1)
627 	  break;
628 
629 	if(!more_trace)
630 	  usleep((unsigned long)((timeout_expect - t) * 1000000));
631 	else
632 	  aq_wait_ticks();
633     }
634 
635     trace_flush();
636     play_mode->acntl(PM_REQ_FLUSH, NULL);
637     flush_buckets();
638     return RC_NONE;
639 }
640 
641 /* Wait a moment */
aq_wait_ticks(void)642 static void aq_wait_ticks(void)
643 {
644     int32 trace_wait, wait_samples;
645 
646     if(device_qsize == 0 ||
647        (trace_wait = trace_wait_samples()) == 0)
648 	return; /* No wait */
649     wait_samples = (device_qsize / Bps) / 5; /* 20% */
650     if(trace_wait != -1 && /* There are more trace events */
651        trace_wait < wait_samples)
652 	wait_samples = trace_wait;
653     usleep((unsigned int)((double)wait_samples / play_mode->rate * 1000000.0));
654 }
655 
656 /* add_play_bucket() attempts to add buf to audio bucket.
657  * It returns actually added bytes.
658  */
add_play_bucket(const char * buf,int n)659 static int add_play_bucket(const char *buf, int n)
660 {
661     int total;
662 
663     if(n == 0)
664 	return 0;
665 
666     if(!nbuckets) {
667       play_mode->output_data((char *)buf, n);
668       return n;
669     }
670 
671     if(head == NULL)
672 	head = tail = next_allocated_bucket();
673 
674     total = 0;
675     while(n > 0)
676     {
677 	int i;
678 
679 	if(tail->len == bucket_size)
680 	{
681 	    AudioBucket *b;
682 	    if((b = next_allocated_bucket()) == NULL)
683 		break;
684 	    if(head == NULL)
685 		head = tail = b;
686 	    else
687 		tail = tail->next = b;
688 	}
689 
690 	i = bucket_size - tail->len;
691 	if(i > n)
692 	    i = n;
693 	memcpy(tail->data + tail->len, buf + total, i);
694 	total += i;
695 	n     -= i;
696 	tail->len += i;
697     }
698 
699     return total;
700 }
701 
702 /* Flush and clear audio bucket */
flush_buckets(void)703 static void flush_buckets(void)
704 {
705     int i;
706 
707     allocated_bucket_list = NULL;
708     for(i = 0; i < nbuckets; i++)
709 	reuse_audio_bucket(&base_buckets[i]);
710     head = tail = NULL;
711     aq_fill_buffer_flag = (aq_start_count > 0);
712     play_counter = play_offset_counter = 0;
713 }
714 
715 /* next_allocated_bucket() gets free bucket.  If all buckets is used, it
716  * returns NULL.
717  */
next_allocated_bucket(void)718 static AudioBucket *next_allocated_bucket(void)
719 {
720     AudioBucket *b;
721 
722     if(allocated_bucket_list == NULL)
723 	return NULL;
724     b = allocated_bucket_list;
725     allocated_bucket_list = allocated_bucket_list->next;
726     b->len = 0;
727     b->next = NULL;
728     return b;
729 }
730 
731 /* Reuse specified bucket */
reuse_audio_bucket(AudioBucket * bucket)732 static void reuse_audio_bucket(AudioBucket *bucket)
733 {
734     bucket->next = allocated_bucket_list;
735     allocated_bucket_list = bucket;
736 }
737