Debian Codegraph @

src/libsyn123/libsyn123.c

raw
1 /*
2 libsyn123: libsyn123 entry code and wave generators
3
4 copyright 2017-2023 by the mpg123 project
5 licensed under the terms of the LGPL 2.1
6 see COPYING and AUTHORS files in distribution or http://mpg123.org
7
8 initially written by Thomas Orgis
9
10 This code directly contains wave generators and the generic entry
11 code for libsyn123. The waves started the whole thing and stay here
12 for now. Other signal generators go into separate files.
13
14 This code is testament to the ultimate programmer hybris: Just add
15 something because it looks easy, a fun dirty hack. Then spend days
16 doing it properly, including fun like squeezing multiple waves of
17 differing shapes into periodic packets. Oh, and caring about
18 vectorization for the heck of it. Offering sample formats down to
19 8 bit alaw. Madness.
20 */
21
22 #include "syn123_int.h"
23 #include "../version.h"
24 #include "../common/sample.h"
25 #include "../common/debug.h"
26
27 const char * attribute_align_arg syn123_distversion(unsigned int *major, unsigned int *minor, unsigned int *patch)
28 {
29 if(major)
30 *major = MPG123_MAJOR;
31 if(minor)
32 *minor = MPG123_MINOR;
33 if(patch)
34 *patch = MPG123_PATCH;
35 return MPG123_VERSION;
36 }
37
38 unsigned int attribute_align_arg syn123_libversion(unsigned int *patch)
39 {
40 if(patch)
41 *patch = SYN123_PATCHLEVEL;
42 return SYN123_API_VERSION;
43 }
44
45 static const double freq_error = 1e-4;
46 /* For our precisions, that value will always be good enough. */
47 static const double twopi = 2.0*3.14159265358979323846;
48 static struct syn123_wave defwave = { SYN123_WAVE_SINE, FALSE, 440., 0. };
49
50 /* round floating point to size_t */
51 static size_t round2size(double a)
52 {
53 return a < 0 ? 0 : (size_t)(a+0.5);
54 }
55
56 /* fractional part, relating to frequencies (so long matches) */
57 static double myfrac(double a)
58 {
59 return a-(long)a;
60 }
61
62 /* arbitrary phase -> [0..1) */
63 static double phasefrac(double p)
64 {
65 return p-floor(p);
66 }
67
68 /*
69 Given a set of wave frequencies, compute an approximate common
70 period for the combined signal. Invalid frequencies are set to
71 the error bound for some sanity.
72 TODO: sort waves and begin with highest freq for stable/best result
73 */
74 static double common_samples_per_period( long rate, size_t count
75 , struct syn123_wave *waves, size_t size_limit )
76 {
77 double spp = 0;
78 size_t i;
79 for(i=0; i<count; ++i)
80 {
81 double sppi;
82 size_t periods = 1;
83 /* Limiting sensible frequency range. */
84 if(waves[i].freq < freq_error)
85 waves[i].freq = freq_error;
86 if(waves[i].freq > rate/2)
87 waves[i].freq = rate/2;
88 sppi = fabs((double)rate/waves[i].freq);
89 debug2("freq=%g sppi=%g", waves[i].freq, sppi);
90 if(spp == 0)
91 spp = sppi;
92 while
93 (
94 (periods+1)*spp <= size_limit &&
95 fabs( myfrac(periods*spp / sppi) ) > freq_error
96 )
97 periods++;
98 spp*=periods;
99 debug3( "samples_per_period + %f Hz = %g (%zu periods)"
100 , waves[i].freq, spp, periods );
101 }
102 return spp;
103 }
104
105 /* Compute a good size of a table covering the common period for all waves. */
106 static size_t tablesize( long rate, size_t count
107 , struct syn123_wave *waves, size_t size_limit )
108 {
109 size_t ts, nts;
110 double fts, tolerance;
111 double samples_per_period;
112 size_t periods;
113
114 samples_per_period = common_samples_per_period( rate, count
115 , waves, size_limit );
116 tolerance = freq_error*samples_per_period;
117
118 periods = 0;
119 do
120 {
121 periods++;
122 fts = periods*samples_per_period;
123 ts = round2size(fts);
124 nts = round2size((periods+1)*samples_per_period);
125 }
126 while(fabs(fts-ts) > periods*tolerance && nts <= size_limit);
127
128 /* Ensure size limit. Even it is ridiculous. */
129 ts = smin(ts, size_limit);
130 debug1("table size: %zu", ts);
131 return ts;
132 }
133
134 /* The wave functions. Argument is the phase normalised to the period. */
135 /* The argument is guaranteed to be 0 <= p < 1. */
136
137 /* _________ */
138 /* */
139 static double wave_none(double p)
140 {
141 return 0;
142 }
143
144 /* __ */
145 /* / \ */
146 /* \__/ */
147 static double wave_sine(double p)
148 {
149 return sin(twopi*p);
150 }
151
152 /* ___ */
153 /* ___| */
154 static double wave_square(double p)
155 {
156 return (p < 0.5 ? -1 : 1);
157 }
158
159 /* 1234 Avoid jump from zero at beginning. */
160 /* /\ */
161 /* \/ */
162 static double wave_triangle(double p)
163 {
164 return 4*p < 1
165 ? 4*p /* 1 */
166 : ( 4*p < 3
167 ? 2.-4*p /* 2 and 3 */
168 : -4+4*p /* 4 */
169 );
170 }
171
172 /* /| Avoid jump from zero ... */
173 /* |/ */
174 static double wave_sawtooth(double p)
175 {
176 return 2*p < 1 ? 2*p : -2+2*p;
177 }
178
179 /* _ */
180 /* __/ \__ */
181 /* */
182 static double wave_gauss(double p)
183 {
184 double v = p-0.5;
185 return exp(-30*v*v);
186 }
187
188 /* _ */
189 /* _/ -___ */
190 /* */
191 /* p**2*exp(-a*p**2) */
192 /* Scaling: maximum at sqrt(1/a), value 1/a*exp(-1). */
193 static double wave_pulse(double p)
194 {
195 return p*p*exp(-50*p*p)/0.00735758882342885;
196 }
197
198 /* _ */
199 /* / -___ */
200 /* */
201 /* p**2*exp(-a*p) */
202 /* Scaling: maximum at 4/a, value 4/a**2*exp(-2). */
203 static double wave_shot(double p)
204 {
205 return p*p*exp(-100*p)/5.41341132946451e-05;
206 }
207
208 // Actual wave worker function, to be used to give up to
209 // bufblock samples in one go. This takes a vector of phases
210 // and multiplies the resulting amplitudes into the output buffer.
211 static void evaluate_wave( double outbuf[bufblock], size_t samples
212 , enum syn123_wave_id id, double phase[bufblock] )
213 {
214 // Ensuring that the inner loop is inside the switch.
215 // Compilers might be smart enough, but it is not hard
216 // to write it down the right way from the beginning.
217 #define PHASE phase[pi]
218 #define PI_LOOP( code ) \
219 for(size_t pi=0; pi<samples; ++pi) \
220 outbuf[pi] *= code;
221 switch(id)
222 {
223 case SYN123_WAVE_FLAT:
224 PI_LOOP( wave_none(PHASE) )
225 break;
226 case SYN123_WAVE_SINE:
227 PI_LOOP( wave_sine(PHASE) )
228 break;
229 case SYN123_WAVE_SQUARE:
230 PI_LOOP( wave_square(PHASE) )
231 break;
232 case SYN123_WAVE_TRIANGLE:
233 PI_LOOP( wave_triangle(PHASE) )
234 break;
235 case SYN123_WAVE_SAWTOOTH:
236 PI_LOOP( wave_sawtooth(PHASE) )
237 break;
238 case SYN123_WAVE_GAUSS:
239 PI_LOOP( wave_gauss(PHASE) )
240 break;
241 case SYN123_WAVE_PULSE:
242 PI_LOOP( wave_pulse(PHASE) )
243 break;
244 case SYN123_WAVE_SHOT:
245 PI_LOOP( wave_shot(PHASE) )
246 break;
247 default:
248 PI_LOOP( wave_none(PHASE) )
249 }
250 #undef PI_LOOP
251 #undef PHASE
252 }
253
254 static const char* wave_names[] =
255 {
256 "flat", "sine", "square", "triangle"
257 , "sawtooth", "gauss", "pulse", "shot"
258 };
259
260 const char* attribute_align_arg
261 syn123_wave_name(int id)
262 {
263 if(id < 0 || id >= sizeof(wave_names)/sizeof(char*))
264 return "???";
265 else
266 return wave_names[id];
267 }
268
269 int attribute_align_arg
270 syn123_wave_id(const char *name)
271 {
272 if(name)
273 for(int i=0; i<sizeof(wave_names)/sizeof(char*); ++i)
274 if(!strcmp(name, wave_names[i]))
275 return i;
276 return SYN123_WAVE_INVALID;
277 }
278
279 const char* syn123_strerror(int errcode)
280 {
281 switch(errcode)
282 {
283 case SYN123_OK:
284 return "no error";
285 case SYN123_BAD_HANDLE:
286 return "bad handle";
287 case SYN123_BAD_FMT:
288 return "bad format";
289 case SYN123_BAD_ENC:
290 return "bad encoding";
291 case SYN123_BAD_CONV:
292 return "unsupported conversion";
293 case SYN123_BAD_SIZE:
294 return "wrong buffer size";
295 case SYN123_BAD_BUF:
296 return "bad buffer pointer";
297 case SYN123_BAD_CHOP:
298 return "byte count not matching sample boundaries";
299 case SYN123_DOOM:
300 return "out of memory";
301 case SYN123_WEIRD:
302 return "Call the Ghostbusters!";
303 case SYN123_BAD_FREQ:
304 return "Bad signal frequency given.";
305 case SYN123_BAD_SWEEP:
306 return "Invalid sweep curve given.";
307 case SYN123_OVERFLOW:
308 return "An integer overflow occured.";
309 case SYN123_NO_DATA:
310 return "Not enough data.";
311 case SYN123_BAD_DATA:
312 return "Bad data given.";
313 default:
314 return "unkown error";
315 }
316 }
317
318 // I first introduced the vectorization-friendly aproach with a precomputed
319 // buffer of phases as a (premature) optimization, but it turns out that
320 // this separation is really useful for computing frequency sweeps.
321 // The computation of phases, including varying frequency, really is a separate
322 // task from actually evaluating the wave functions.
323 // The code is actually smaller and better abstracted that way.
324
325 static void add_some_wave( double outbuf[bufblock], size_t samples
326 , enum syn123_wave_id id, double pps, double phase
327 , double workbuf[bufblock] )
328 {
329 for(size_t pi=0; pi<samples; ++pi)
330 workbuf[pi] = phasefrac(pi*pps+phase);
331 evaluate_wave(outbuf, samples, id, workbuf);
332 }
333
334 // Fit waves into given table size.
335 static void wave_fit_table( size_t samples
336 , long rate, struct syn123_wave *wave )
337 {
338 double pps = wave->freq/rate;
339 debug3("wave_fit_table %zu %ld %g", samples, rate, wave->freq);
340 size_t periods = smax(round2size(pps*samples), 1);
341 pps = (double)periods/samples;
342 wave->freq = pps*rate;
343 debug4( "final wave: %c %i @ %g Hz + %g"
344 , wave->backwards ? '<' : '>', wave->id, wave->freq, wave->phase );
345 }
346
347 // Evaluate an additional wave into the given buffer (multiplying
348 // with existing values in output.
349 static void wave_add_buffer( double outbuf[bufblock], size_t samples
350 , long rate, struct syn123_wave *wave, double workbuf[bufblock] )
351 {
352 double pps = wave->freq/rate;
353 debug3("wave_add_buffer %zu %ld %g", samples, rate, wave->freq);
354 debug4( "adding wave: %c %i @ %g Hz + %g"
355 , wave->backwards ? '<' : '>', wave->id, wave->freq, wave->phase );
356 if(wave->backwards)
357 pps = -pps;
358 add_some_wave( outbuf, samples
359 , wave->id, pps, wave->phase, workbuf );
360 // Advance the wave.
361 wave->phase = phasefrac(wave->phase+samples*pps);
362 }
363
364 // The most basic generator of all.
365 static void silence_generator(syn123_handle *sh, int samples)
366 {
367 for(int i=0; i<samples; ++i)
368 sh->workbuf.f64[1][i] = 0;
369 }
370
371 // Clear the handle of generator data structures.
372 // Well, except the one generating silence.
373 int attribute_align_arg
374 syn123_setup_silence(syn123_handle *sh)
375 {
376 if(!sh)
377 return SYN123_BAD_HANDLE;
378 sh->generator = silence_generator;
379 if(sh->wave_count && sh->waves)
380 free(sh->waves);
381 sh->waves = NULL;
382 sh->wave_count = 0;
383 if(sh->handle)
384 free(sh->handle);
385 sh->handle = NULL;
386 sh->samples = 0;
387 sh->offset = 0;
388 return SYN123_OK;
389 }
390
391 // The generator function is called upon to fill sh->workbuf[1] with the
392 // given number of samples in double precision. It may use sh->workbuf[0]
393 // for its own purposes.
394 static void wave_generator(syn123_handle *sh, int samples)
395 {
396 /* Initialise to zero amplitude. */
397 for(int i=0; i<samples; ++i)
398 sh->workbuf.f64[1][i] = 1;
399 /* Add individual waves. */
400 for(size_t c=0; c<sh->wave_count; ++c)
401 wave_add_buffer( sh->workbuf.f64[1], samples, sh->fmt.rate, sh->waves+c
402 , sh->workbuf.f64[0] );
403 }
404
405 /* Build internal table, allocate external table, convert to that one, */
406 /* adjusting sample storage format and channel count. */
407 int attribute_align_arg
408 syn123_setup_waves( syn123_handle *sh, size_t count
409 , int *id, double *freq, double *phase, int *backwards
410 , size_t *common_period )
411 {
412 int ret = SYN123_OK;
413
414 if(!sh)
415 return SYN123_BAD_HANDLE;
416 syn123_setup_silence(sh);
417
418 if(!count)
419 {
420 count = 1;
421 id = NULL;
422 freq = NULL;
423 phase = NULL;
424 backwards = NULL;
425 }
426
427 sh->waves = malloc(sizeof(struct syn123_wave)*count);
428 if(!sh->waves)
429 return SYN123_DOOM;
430 for(size_t c=0; c<count; ++c)
431 {
432 sh->waves[c].id = id ? id[c] : defwave.id;
433 sh->waves[c].backwards = backwards ? backwards[c] : defwave.backwards;
434 sh->waves[c].freq = freq ? freq[c] : defwave.freq;
435 sh->waves[c].phase = phase ? phase[c] : defwave.phase;
436 }
437 sh->wave_count = count;
438 sh->generator = wave_generator;
439
440 if(sh->maxbuf)
441 {
442 // 1. Determine buffer size to use.
443 size_t samplesize = MPG123_SAMPLESIZE(sh->fmt.encoding);
444 size_t size_limit = sh->maxbuf / samplesize;
445 size_t buffer_samples = tablesize(sh->fmt.rate, count, sh->waves
446 , size_limit);
447 // 2. Actually allocate the buffer.
448 grow_buf(sh, buffer_samples*samplesize);
449 if(sh->bufs/samplesize < buffer_samples)
450 {
451 ret = SYN123_DOOM;
452 goto setup_wave_end;
453 }
454 // 2. Adjust the waves to fit into the buffer.
455 for(size_t c=0; c<count; ++c)
456 {
457 wave_fit_table(buffer_samples, sh->fmt.rate, sh->waves+c);
458 if(freq)
459 freq[c] = sh->waves[c].freq;
460 }
461 // 3. fill the buffer using workbuf as intermediate. As long as
462 // the buffer is not ready, we can just use syn123_read() to fill it.
463 // Just need to ensure mono storage. Once sh->samples is set, the
464 // buffer is used.
465 int outchannels = sh->fmt.channels;
466 sh->fmt.channels = 1;
467 size_t buffer_bytes = syn123_read(sh, sh->buf, buffer_samples*samplesize);
468 sh->fmt.channels = outchannels;
469 // 4. Restore wave phases to the beginning, for tidyness.
470 for(size_t c=0; c<count; ++c)
471 sh->waves[c].phase = phase ? phase[c] : defwave.phase;
472 // 5. Last check for sanity.
473 if(buffer_bytes != buffer_samples*samplesize)
474 {
475 ret = SYN123_WEIRD;
476 goto setup_wave_end;
477 }
478 sh->samples = buffer_samples;
479 }
480
481 setup_wave_end:
482 if(ret != SYN123_OK)
483 syn123_setup_silence(sh);
484 else
485 {
486 if(common_period)
487 *common_period = sh->samples;
488 }
489 return ret;
490 }
491
492 int attribute_align_arg
493 syn123_query_waves( syn123_handle *sh, size_t *count
494 , int *id, double *freq, double *phase, int *backwards
495 , size_t *common_period )
496 {
497 if(!sh)
498 return SYN123_BAD_HANDLE;
499 if(count)
500 *count = sh->wave_count;
501 if((id || freq || phase || backwards || common_period) && !sh->waves)
502 return SYN123_NO_DATA;
503 for(size_t c=0; c<sh->wave_count; ++c)
504 {
505 if(id)
506 id[c] = sh->waves[c].id;
507 if(backwards)
508 backwards[c] = sh->waves[c].backwards;
509 if(freq)
510 freq[c] = sh->waves[c].freq;
511 if(phase)
512 phase[c] = sh->waves[c].phase;
513 }
514 if(common_period)
515 *common_period = sh->samples;
516 return SYN123_OK;
517 }
518
519 // Given time normalized to the sweep duration, return the
520 // current frequency.
521
522 // With the power of analytical integration, we can compute
523 // the proper phase instead of error-prone summing.
524 // Given the normalized time: t = i/d
525 // Wallclock time: w = i/r (100 samples with rate 100 Hz = 1 s time)
526 // Ratio: w = i/r = t*d/r
527 // dw = d/r dt
528 // dp = f(t) * dw = d/r f(t) dt
529 // p = (d-1)/r int_0^t f(t) dt = d/r (F(t) - F(0))
530 // linear: f(t) = f1 + t*(f2-f1); F = f1*t + t**2 * (f2-f1)/2
531 // quad: f(t) = f1 + t**2*(f2-f1); F = f1*t + t**3 * (f2-f1)/3
532 // exp: f(t) = exp(log(f1) + t*(log(f2)-log(f1)))
533 // F(t) = 1/(log(f2)-log(f1)) exp(log(f1) + t*(log(f2)-log(f1)))
534
535 // These are the unscaled expressions, just F(t)-F(0).
536
537 static double sweep_phase_lin(double t, double f1, double f2)
538 {
539 return f1*t + t*t*0.5*(f2-f1);
540 }
541
542 static double sweep_phase_quad(double t, double f1, double f2)
543 {
544 return f1*t+t*t*t*(1./3)*(f2-f1);
545 }
546
547 // Be sure to only call if f2-f1 has some minimal value.
548 static double sweep_phase_exp(double t, double logf1, double logf2)
549 {
550 return 1./(logf2-logf1) * (exp(logf1 + t*(logf2-logf1)) - exp(logf1));
551 }
552
553 // Return phases after given offset of samples from now, including
554 // phase recovery.
555 // This is the central logic for periodic sweeps.
556 static void sweep_phase( syn123_handle *sh, size_t off
557 , double buf[bufblock], int count )
558 {
559 struct syn123_sweep *sw = sh->handle;
560 // Working on a local offset, not touching sw->i.
561 mdebug("computing position: (%zu + %zu) %% (%zu + %zu)", sw->i, off, sw->d, sw->post);
562 size_t pos = (sw->i + off) % (sw->d + sw->post);
563 int boff = 0;
564 while(count)
565 {
566 // Finish the current sweep+post cycle.
567 // 0 <= sw->i < sw->d+sw->post
568 // 1. Fill phases for actual sweep, if some of it is left.
569 // This includes the endpoint, one sample after configured length,
570 // if so many samples are desired. Note that pos == sw->d will not
571 // happen unless sw->post > 0.
572 int sweep_s = pos <= sw->d
573 ? (int)smin(sw->d+1 - pos, count)
574 : 0;
575 // normalized time here to reduce code redundancy
576 for(int i=0; i<sweep_s; ++i)
577 buf[boff+i] = (double)pos++/sw->d;
578 // actual phase computation, with inner loops for auto-vectorization
579 switch(sw->id)
580 {
581 case SYN123_SWEEP_LIN:
582 for(int i=0; i<sweep_s; ++i)
583 buf[boff+i] = sweep_phase_lin(buf[boff+i], sw->f1, sw->f2);
584 break;
585 case SYN123_SWEEP_QUAD:
586 for(int i=0; i<sweep_s; ++i)
587 buf[boff+i] = sweep_phase_quad(buf[boff+i], sw->f1, sw->f2);
588 break;
589 case SYN123_SWEEP_EXP:
590 for(int i=0; i<sweep_s; ++i)
591 buf[boff+i] = sweep_phase_exp(buf[boff+i], sw->f1, sw->f2);
592 break;
593 default:
594 for(int i=0; i<sweep_s; ++i)
595 buf[boff+i] = 0;
596 }
597 // scaling from normalized time to sampled proper time
598 for(int i=0; i<sweep_s; ++i)
599 buf[boff++] *= (double)sw->d/sh->fmt.rate;
600 count -= sweep_s;
601 // 2. Fill phases for post sweep phase, if reached.
602 if(pos > sw->d)
603 {
604 int post_s = (int)smin(sw->d + sw->post - pos, count);
605 double pps = sw->wave.freq/sh->fmt.rate;
606 for(int i=0; i<post_s; ++i)
607 buf[boff++] = sw->endphase - sw->wave.phase + (pos++ - sw->d)*pps;
608 count -= post_s;
609 }
610 // Now we can possibly wrap around. Actually, we have to
611 // hit the boundary exactly.
612 if(pos == sw->d + sw->post)
613 pos = 0;
614 }
615 // Turn all phases into fractions and invert if going backwards.
616 if(sw->wave.backwards)
617 for(int i=0; i<boff; ++i)
618 buf[i] = phasefrac(-buf[i]-sw->wave.phase);
619 else
620 for(int i=0; i<boff; ++i)
621 buf[i] = phasefrac(buf[i]+sw->wave.phase);
622 }
623
624 static void sweep_generator(syn123_handle *sh, int samples)
625 {
626 struct syn123_sweep *sw = sh->handle;
627 // Precompute phases into work buffer.
628 sweep_phase(sh, 0, sh->workbuf.f64[0], samples);
629 // Initialise output to zero amplitude and multiply by the wave.
630 for(int i=0; i<samples; ++i)
631 sh->workbuf.f64[1][i] = 1.;
632 evaluate_wave(sh->workbuf.f64[1], samples, sw->wave.id, sh->workbuf.f64[0]);
633 // Advance.
634 sw->i = (sw->i+samples) % (sw->d + sw->post);
635 }
636
637 int attribute_align_arg
638 syn123_setup_sweep( syn123_handle* sh
639 , int wave_id, double phase, int backwards
640 , int sweep_id, double *f1, double *f2, int smooth, size_t duration
641 , double *endphase, size_t *period, size_t *buffer_period )
642 {
643 double real_f1;
644 int ret = SYN123_OK;
645 struct syn123_sweep *sw;
646 if(!sh)
647 return SYN123_BAD_HANDLE;
648 syn123_setup_silence(sh);
649 if(!duration) // Empty sweep is silence.
650 {
651 if(endphase)
652 *endphase = phase;
653 if(period)
654 *period = 0;
655 return SYN123_OK;
656 }
657 if( sweep_id != SYN123_SWEEP_LIN && sweep_id != SYN123_SWEEP_QUAD &&
658 sweep_id != SYN123_SWEEP_EXP )
659 return SYN123_BAD_SWEEP;
660
661 sh->handle = sw = malloc(sizeof(struct syn123_sweep));
662 if(!sh->handle)
663 {
664 ret = SYN123_DOOM;
665 goto setup_sweep_end;
666 }
667 sw->f1 = (!f1 || *f1 <= 0.) ? defwave.freq : *f1;
668 real_f1 = sw->f1;
669 sw->f2 = (!f2 || *f2 <= 0.) ? defwave.freq : *f2;
670 if( sw->f1 < freq_error || sw->f2 < freq_error )
671 {
672 ret = SYN123_BAD_FREQ;
673 goto setup_sweep_end;
674 }
675 // Also, don't try exp sweep for very small difference.
676 // We need 1/log(f2/f1) ...
677 if(sweep_id == SYN123_SWEEP_EXP && (fabs(sw->f2 - sw->f1) < freq_error))
678 {
679 ret = SYN123_BAD_FREQ;
680 goto setup_sweep_end;
681 }
682
683 sw->wave.id = wave_id;
684 sw->wave.backwards = 0; // Set to true value later.
685 sw->wave.freq = sw->f2; // We'll use that later for continuation.
686 sw->wave.phase = phase; // Beginning phase offset, not updated.
687 sw->id = sweep_id;
688 // Store the logarithms for exponential sweep.
689 if(sweep_id == SYN123_SWEEP_EXP)
690 {
691 sw->f1 = log(sw->f1);
692 sw->f2 = log(sw->f2);
693 }
694 sw->i = 0;
695 sw->d = duration;
696 sw->post = 1; // Needed to be set for end phases.
697 if(sw->d + sw->post < sw->d || sw->d + sw->post < sw->post)
698 {
699 ret = SYN123_OVERFLOW;
700 goto setup_sweep_end;
701 }
702 // The last phase served by the sweep, and the one after that that
703 // tryly concludes the sweep (f==f2, not infinitesimally smaller).
704 mdebug("computing endphase, with 2 points from %zu - 1 on", duration);
705 sweep_phase(sh, duration-1, sh->workbuf.f64[0], 2);
706 double before_endphase = sh->workbuf.f64[0][0];
707 sw->endphase = sh->workbuf.f64[0][1];
708 sw->post = 0; // Reset that again, only increasing if really needed.
709 // The phase that would smoothly continue the sweep, one sample
710 // after the last one.
711 // We want confirmed zero crossing between before_endphase and
712 // endphase. This only matters for resolved frequencies, though.
713 if(smooth && 2*sw->f2 < sh->fmt.rate &&
714 phasefrac(sw->endphase-phase) > phasefrac(before_endphase-phase) )
715 {
716 // Start from before_endphase on, to reach the actual point where
717 // the signal truly reaches f2. Anything on top is with constant
718 // f2.
719 double poststeps = phasefrac(1.-before_endphase+phase)
720 * ((double)sh->fmt.rate/sw->wave.freq);
721 // We want the integer part, except in the unlikely
722 // case that it is an exact integer: Then we want one less. The
723 // actual zero crossing is _after_ the post samples.
724 size_t prepos = (size_t)poststeps;
725 if(prepos && prepos == poststeps)
726 prepos--;
727 sw->post = prepos;
728 }
729 size_t fulldur = sw->d + sw->post;
730 if(fulldur < sw->d || fulldur < sw->post)
731 {
732 ret = SYN123_OVERFLOW;
733 goto setup_sweep_end;
734 }
735 // Now we can go backwards. Otherwise the above computation would
736 // be more confusing.
737 sw->wave.backwards = backwards;
738
739 sh->generator = sweep_generator;
740
741 size_t samplesize = MPG123_SAMPLESIZE(sh->fmt.encoding);
742 if(sh->maxbuf && sh->maxbuf >= samplesize*fulldur)
743 {
744 grow_buf(sh, samplesize*fulldur);
745 if(sh->bufs/samplesize < fulldur)
746 {
747 ret = SYN123_DOOM; // Actually, also overflow.
748 goto setup_sweep_end;
749 }
750 // Fill the buffer using workbuf as intermediate. As long as
751 // the buffer is not ready, we can just use syn123_read() to fill it.
752 // Just need to ensure mono storage. Once sh->samples is set, the
753 // buffer is used.
754 int outchannels = sh->fmt.channels;
755 sh->fmt.channels = 1;
756 size_t buffer_bytes = syn123_read(sh, sh->buf, fulldur*samplesize);
757 sh->fmt.channels = outchannels;
758 // Restore sweep state.
759 sw->i = 0;
760 // Last check for sanity.
761 if(buffer_bytes != fulldur*samplesize)
762 {
763 ret = SYN123_WEIRD;
764 goto setup_sweep_end;
765 }
766 sh->samples = fulldur;
767 }
768
769 setup_sweep_end:
770 if(ret != SYN123_OK)
771 syn123_setup_silence(sh);
772 else
773 {
774 mdebug("done with sweep setup %g %g", real_f1, sw->wave.freq);
775 if(period)
776 *period = fulldur;
777 if(endphase)
778 *endphase = sw->endphase;
779 if(f1)
780 *f1 = real_f1;
781 if(f2)
782 *f2 = sw->wave.freq;
783 if(buffer_period)
784 *buffer_period = sh->samples;
785 }
786 return ret;
787 }
788
789 syn123_handle* attribute_align_arg
790 syn123_new(long rate, int channels, int encoding
791 , size_t maxbuf, int *err)
792 {
793 int myerr = SYN123_OK;
794 syn123_handle *sh = NULL;
795 size_t sbytes = MPG123_SAMPLESIZE(encoding);
796
797 if(!sbytes)
798 {
799 myerr = SYN123_BAD_ENC;
800 goto syn123_new_end;
801 }
802 if(rate < 1 || channels < 1)
803 {
804 myerr = SYN123_BAD_FMT;
805 goto syn123_new_end;
806 }
807
808 sh = malloc(sizeof(syn123_handle));
809 if(!sh){ myerr = SYN123_DOOM; goto syn123_new_end; }
810
811 sh->fmt.rate = rate;
812 sh->fmt.channels = channels;
813 sh->fmt.encoding = encoding;
814 sh->buf = NULL;
815 sh->bufs = 0;
816 sh->maxbuf = maxbuf;
817 sh->samples = 0;
818 sh->offset = 0;
819 sh->wave_count = 0;
820 sh->waves = NULL;
821 sh->handle = NULL;
822 syn123_setup_silence(sh);
823 sh->rd = NULL;
824 sh->dither = 0;
825 sh->do_dither = 0;
826 sh->dither_seed = 0;
827 sh->fc.count = sh->fc.maxcount = 0;
828 sh->fc.df = NULL;
829 sh->fc.ff = NULL;
830
831 syn123_new_end:
832 if(err)
833 *err = myerr;
834 if(myerr)
835 {
836 syn123_del(sh);
837 sh = NULL;
838 }
839 return sh;
840 }
841
842 void attribute_align_arg
843 syn123_del(syn123_handle* sh)
844 {
845 if(!sh)
846 return;
847 syn123_setup_silence(sh);
848 syn123_setup_resample(sh, 0, 0, 0, 0, 0);
849 syn123_drop_filter(sh, sh->fc.count);
850 if(sh->fc.ff)
851 free(sh->fc.ff);
852 if(sh->fc.df)
853 free(sh->fc.df);
854 if(sh->buf)
855 free(sh->buf);
856 free(sh);
857 }
858
859 // Copy from period buffer or generate on the fly.
860 size_t attribute_align_arg
861 syn123_read( syn123_handle *sh, void *dest, size_t dest_bytes )
862 {
863 char *cdest = dest; /* Want to do arithmetic. */
864 size_t samplesize, framesize;
865 size_t dest_samples;
866 size_t extracted = 0;
867
868 if(!sh)
869 return 0;
870 samplesize = MPG123_SAMPLESIZE(sh->fmt.encoding);
871 framesize = samplesize*sh->fmt.channels;
872 dest_samples = dest_bytes/framesize;
873 if(sh->samples) // Got buffered samples to work with.
874 {
875 while(dest_samples)
876 {
877 size_t block = smin(dest_samples, sh->samples - sh->offset);
878 debug3("offset: %zu block: %zu out of %zu", sh->offset, block, sh->samples);
879 syn123_mono2many(cdest, (char*)sh->buf+sh->offset*samplesize
880 , sh->fmt.channels, samplesize, block );
881 cdest += framesize*block;
882 sh->offset += block;
883 sh->offset %= sh->samples;
884 dest_samples -= block;
885 extracted += block;
886 }
887 }
888 else // Compute directly, employing the work buffers.
889 {
890 while(dest_samples)
891 {
892 int block = (int)smin(dest_samples, bufblock);
893 debug2( "out offset: %ld block: %i"
894 , (long)(cdest-(char*)dest)/framesize, block );
895 // Compute data into workbuf[1], possibly using workbuf[0]
896 // in the process.
897 // TODO for the future: Compute only in single precision if
898 // it is enough. Right now generators always write to workbuf.f64[1].
899 sh->generator(sh, block);
900 // Convert to external format, mono. We are abusing workbuf[0] here,
901 // because it is big enough.
902 // The converter does not use workbuf if converting from float. Dither is
903 // added on the fly.
904 int err = syn123_conv(
905 sh->workbuf.c[0], sh->fmt.encoding, sizeof(sh->workbuf.c[0])
906 , sh->workbuf.c[1], MPG123_ENC_FLOAT_64, sizeof(double)*block
907 , NULL, NULL, NULL );
908 if(err)
909 {
910 debug1("conv error: %i", err);
911 break;
912 }
913 syn123_mono2many( cdest, sh->workbuf.c[0]
914 , sh->fmt.channels, samplesize, block );
915 cdest += framesize*block;
916 dest_samples -= block;
917 extracted += block;
918 }
919 }
920 debug1("extracted: %zu", extracted);
921 return extracted*framesize;
922 }
923
924 int attribute_align_arg
925 syn123_dither(syn123_handle *sh, int dither, unsigned long *seed)
926 {
927 if(!sh)
928 return SYN123_BAD_HANDLE;
929 // So far we only know 1 or 0 as choices.
930 sh->dither = dither ? 1 : 0;
931 sh->dither_seed = (seed && *seed) ? *seed : 2463534242UL;
932 if(seed)
933 *seed = sh->dither_seed;
934 return SYN123_OK;
935 }