1 /*
2  *  Copyright (C) 2009-2014  Christian Heckendorf <heckendorfc@gmail.com>
3  *
4  *  This program is free software: you can redistribute it and/or modify
5  *  it under the terms of the GNU General Public License as published by
6  *  the Free Software Foundation, either version 3 of the License, or
7  *  (at your option) any later version.
8  *
9  *  This program is distributed in the hope that it will be useful,
10  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *  GNU General Public License for more details.
13  *
14  *  You should have received a copy of the GNU General Public License
15  *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17 
18 #include <samplerate.h>
19 #include "jackutil.h"
20 #include "sndutil.h"
21 
22 pthread_mutex_t outbuf_lock;
23 
decimate(float * buf,int len,int M)24 int decimate(float *buf, int len, int M){
25 	int x;
26 	for(x=0;x<len;x++){
27 		buf[x]=buf[x*M];
28 	}
29 	return len/M;
30 }
31 
interpolate(float * buf,int len,int L)32 int interpolate(float *buf, int len, int L){
33 	int x,y;
34 	for(x=len;x>0;x--){
35 		buf[x*L]=buf[x];
36 		for(y=0;y<L;y++)
37 			buf[y+x]=0;
38 	}
39 	// TODO" Add FIR
40 	return len*L;
41 }
42 
resample(struct playerHandles * ph,int chi,int len,int maxlen,int in_rate,int out_rate,int chan)43 int resample(struct playerHandles *ph, int chi, int len, int maxlen, int in_rate, int out_rate, int chan){
44 	int err;
45 	SRC_DATA data;
46 
47 	if(in_rate==out_rate){
48 		memcpy(ph->tmpbuf_out,ph->tmpbuf,len*sizeof(*ph->tmpbuf));
49 		return len;
50 	}
51 
52 	data.data_in=ph->tmpbuf;
53 	data.data_out=ph->tmpbuf_out;
54 	data.input_frames=len;
55 	data.output_frames=maxlen;
56 	data.src_ratio=(double)out_rate/(double)in_rate;
57 	data.end_of_input=0;
58 
59 	if((err=src_process(ph->rs_state[chi],&data))){
60 		fprintf(stderr,"libresample process: %s",src_strerror(err));
61 		return 0;
62 	}
63 
64 	return data.output_frames_gen;
65 }
66 
homebrew_resample(jack_default_audio_sample_t * buf,int len,int maxlen,int in_rate,int out_rate)67 int homebrew_resample(jack_default_audio_sample_t *buf, int len, int maxlen, int in_rate, int out_rate){
68 	int L,M,newlen;
69 	if(in_rate==out_rate)return len;
70 	fprintf(stderr,"\nResampling\n");
71 	if(in_rate<out_rate){
72 		if(!(in_rate%out_rate)){ // Resampling not supported yet
73 			return len;
74 		}
75 
76 		L=out_rate/in_rate;
77 		if(len*L>maxlen){ // Buffer overflow
78 			return -(len*L);
79 		}
80 		newlen=interpolate(buf,len,L);
81 	}
82 	else{
83 		if(!(out_rate%in_rate)){ // Resampling not supported yet
84 			return len;
85 		}
86 
87 		M=in_rate/out_rate;
88 		newlen=decimate(buf,len,M);
89 	}
90 
91 	return newlen;
92 }
93 
char_to_float(float * f,const char * c,int len)94 int char_to_float(float *f, const char *c, int len){
95 	int i;
96 
97 	if(len%2){
98 		return -1;
99 	}
100 
101 	short *in = (short*)c;
102 	len>>=1;
103 	for (i=0; i<len; i++) {
104 		f[i] = in[i]/NORMFACT16;
105 	}
106 	return len;
107 }
108 
jack_err(const char * err)109 void jack_err(const char *err){
110 	fprintf(stderr,"JACK ERR: %s\n",err);
111 }
112 
jack_process(jack_nframes_t nframes,void * arg)113 int jack_process(jack_nframes_t nframes, void *arg){
114 	struct playerHandles *ph = (struct playerHandles*)arg;
115 	if(!ph->dechandle) return 0;
116 
117 	size_t actual = sizeof(jack_default_audio_sample_t)*nframes;
118 	size_t read;
119 	char *out1=(char *)jack_port_get_buffer(ph->out_port1,nframes);
120 	char *out2=(char *)jack_port_get_buffer(ph->out_port2,nframes);
121 
122 	if(!ph->pflag->mute){
123 		if(ph->dec_chan==1){
124 			read=jack_ringbuffer_read(ph->outbuf[0],out1,actual);
125 			if(read<actual){
126 				bzero(out1+read,actual-read);
127 			}
128 			memcpy(out2,out1,actual);
129 		}
130 		else{
131 			read=jack_ringbuffer_read(ph->outbuf[0],out1,actual);
132 			if(read<actual){
133 				bzero(out1+read,actual-read);
134 			}
135 			read=jack_ringbuffer_read(ph->outbuf[1],out2,actual);
136 			if(read<actual){
137 				bzero(out2+read,actual-read);
138 			}
139 		}
140 	}
141 	else{ // Fill with silence
142 		bzero(out1,actual);
143 		bzero(out2,actual);
144 	}
145 
146 	return 0;
147 }
148 
jack_srate(jack_nframes_t nframes,void * arg)149 int jack_srate(jack_nframes_t nframes, void *arg){
150 	struct playerHandles *ph = (struct playerHandles*)arg;
151 	ph->out_rate=nframes;
152 	fprintf(stderr,"JACK | set rate: %d\n",nframes);
153 	return 0;
154 }
155 
jack_shutdown(void * arg)156 void jack_shutdown(void *arg){
157 	fprintf(stderr,"JACK | Shutdown.\n");
158 }
159 
snd_init(struct playerHandles * ph)160 int snd_init(struct playerHandles *ph){
161 	//ph->pflag->update=0;
162 
163 	char client_name[255];
164 	ph->maxsize=40960;
165 	if(!(ph->outbuf=malloc(2*sizeof(*ph->outbuf)))
166 		|| !(ph->tmpbuf=malloc(sizeof(*ph->tmpbuf)))
167 		|| !(ph->tmpbuf_out=malloc(sizeof(*ph->tmpbuf_out)))
168 		){
169 		fprintf(stderr,"Malloc failed (jack buf).");
170 		return 1;
171 	}
172 
173 	pthread_mutex_init(&outbuf_lock,NULL);
174 	ph->out_gain=0;
175 	ph->vol_mod=1;
176 	jack_set_error_function(jack_err);
177 
178 	snprintf(client_name,255,"HARP-%d",getpid());
179 	if((ph->sndfd=jack_client_open(client_name,JackNullOption,NULL))==NULL){
180 		fprintf(stderr,"JACK | Jack server not running?\n");
181 		return 1;
182 	}
183 
184 	jack_set_process_callback(ph->sndfd,jack_process,ph);
185 	jack_set_sample_rate_callback(ph->sndfd,jack_srate,ph);
186 	jack_on_shutdown(ph->sndfd,jack_shutdown,ph);
187 
188 	if((ph->out_port1=jack_port_register(ph->sndfd,"output1",JACK_DEFAULT_AUDIO_TYPE,JackPortIsOutput,0))==NULL){
189 		fprintf(stderr,"JACK | Can't register output port.\n");
190 		return 1;
191 	}
192 	if((ph->out_port2=jack_port_register(ph->sndfd,"output2",JACK_DEFAULT_AUDIO_TYPE,JackPortIsOutput,0))==NULL){
193 		fprintf(stderr,"JACK | Can't register output port.\n");
194 		return 1;
195 	}
196 
197 	ph->maxsize=jack_get_sample_rate(ph->sndfd);
198 	fprintf(stderr,"Buffer: %d (x2)\n",ph->maxsize);
199 	ph->outbuf[0]=jack_ringbuffer_create(ph->maxsize);
200 	ph->outbuf[1]=jack_ringbuffer_create(ph->maxsize);
201 
202 	if(jack_activate(ph->sndfd)){
203 		fprintf(stderr,"JACK | Can't activate.\n");
204 		return 1;
205 	}
206 
207 	if((ph->jack_ports=jack_get_ports(ph->sndfd,NULL,NULL,JackPortIsPhysical|JackPortIsInput))==NULL){
208 		fprintf(stderr,"JACK | Can't find any physial output ports.\n");
209 		return 1;
210 	}
211 
212 	if(jack_connect(ph->sndfd, jack_port_name(ph->out_port1), ph->jack_ports[0])){
213 		fprintf (stderr, "JACK | Can't connect output ports 0\n");
214 	}
215 	if(jack_connect(ph->sndfd, jack_port_name(ph->out_port2), ph->jack_ports[1])){
216 		fprintf (stderr, "JACK | Can't connect output ports 0\n");
217 	}
218 
219 	ph->rs_state=NULL;
220 
221 	return 0;
222 }
223 
snd_param_init(struct playerHandles * ph,int * enc,int * channels,unsigned int * rate)224 int snd_param_init(struct playerHandles *ph, int *enc, int *channels, unsigned int *rate){
225 	int i,err;
226 
227 	if(ph->rs_state){
228 		if(ph->rs_state[0]){
229 			for(i=0;i<ph->dec_chan;i++)
230 				ph->rs_state[i]=src_delete(ph->rs_state[i]);
231 		}
232 		free(ph->rs_state);
233 	}
234 	if((ph->rs_state=malloc(sizeof(*ph->rs_state)*(*channels)))==NULL)
235 		return 1;
236 
237 	ph->dec_rate=*rate;
238 	ph->dec_chan=*channels;
239 	ph->dec_enc=*enc;
240 	for(i=0;i<ph->dec_chan;i++)
241 		if((ph->rs_state[i]=src_new(RESAMPLE_QUALITY,1,&err))==NULL){
242 			fprintf(stderr,"libresample src_new returned %d\n",err);
243 			return 1;
244 		}
245 	//src_set_ratio(ph->rs_state,(double)ph->out_rate/(double)ph->dec_rate);
246 	return 0;
247 }
248 
changeVolume(struct playerHandles * ph,int mod)249 void changeVolume(struct playerHandles *ph, int mod){
250 	char tail[OUTPUT_TAIL_SIZE];
251 	mod=mod>0?2:-2;
252 	ph->out_gain+=mod; // 5 DB increment is too much
253 	if(ph->out_gain>GAIN_MAX)ph->out_gain=GAIN_MAX;
254 	else if(ph->out_gain<GAIN_MIN)ph->out_gain=GAIN_MIN;
255 
256 	ph->vol_mod=powf(10.0f,(float)ph->out_gain*0.05f);
257 
258 	sprintf(tail,"Volume: %d%% (%dDb)",(int)((ph->out_gain-GAIN_MIN)*2),ph->out_gain);
259 	addStatusTail(tail,ph->outdetail);
260 }
261 
toggleMute(struct playerHandles * ph,int * mute)262 void toggleMute(struct playerHandles *ph, int *mute){
263 	if(*mute>0){ // Unmute and perform volume change
264 		char tail[OUTPUT_TAIL_SIZE];
265 		*mute=0;
266 		sprintf(tail,"Volume: %d%% (%dDb)",(int)((ph->out_gain-GAIN_MIN)*2),ph->out_gain);
267 		addStatusTail(tail,ph->outdetail);
268 	}
269 	else{ // Mute
270 		*mute=1;
271 		addStatusTail("Volume Muted",ph->outdetail);
272 	}
273 	fflush(stdout);
274 }
275 
snd_clear(struct playerHandles * ph)276 void snd_clear(struct playerHandles *ph){
277 	jack_ringbuffer_reset(ph->outbuf[0]);
278 	jack_ringbuffer_reset(ph->outbuf[1]);
279 }
280 
fill_buff_16(jack_default_audio_sample_t * tmpbuf,const char * out,const int c,const int dec_enc,const int samples,const int dec_chan,const int chan_shift,float vol_mod)281 void fill_buff_16(jack_default_audio_sample_t *tmpbuf, const char *out, const int c, const int dec_enc, const int samples, const int dec_chan, const int chan_shift, float vol_mod){
282 	int i;
283 	short *s_in = (short*)out;
284 	for (i=0; i<samples; i++)
285 		tmpbuf[i] = (s_in[(i<<chan_shift)+c]/NORMFACT16)*vol_mod;
286 }
287 
get_bytes_24(unsigned char * o_t)288 int get_bytes_24(unsigned char *o_t){
289 	return (((uint32_t)o_t[0])<<8)|(((uint32_t)o_t[1])<<16)|(((uint32_t)o_t[2])<<24);
290 }
291 
get_bytes_32(unsigned char * o_t)292 int get_bytes_32(unsigned char *o_t){
293 	return (((uint32_t)o_t[0]))|(((uint32_t)o_t[1])<<8)|(((uint32_t)o_t[2])<<16)|(((uint32_t)o_t[3])<<24);
294 }
295 
fill_buff_32(jack_default_audio_sample_t * tmpbuf,const char * out,const int c,const int dec_enc,const int samples,const int dec_chan,const int chan_shift,float vol_mod)296 void fill_buff_32(jack_default_audio_sample_t *tmpbuf, const char *out, const int c, const int dec_enc, const int samples, const int dec_chan, const int chan_shift, float vol_mod){
297 	int i;
298 	const int by=dec_enc/8;
299 	const int off=(4-by);
300 	const uint32_t norm = (uint32_t)INT32_MAX;
301 	int *s_in;
302 	int st;
303 	unsigned char *o_t;
304 	int (*gb)(unsigned char *);
305 
306 	if(by==3)
307 		gb=get_bytes_24;
308 	else
309 		gb=get_bytes_32;
310 
311 	for (i=0; i<samples; i++){
312 		s_in = (int*)(out+i*by*dec_chan+c*by);
313 		o_t=(unsigned char*)(out+i*by*dec_chan+c*by);
314 		st=gb(o_t);
315 		tmpbuf[i] = ((st)/((jack_default_audio_sample_t)norm+(st<=0)))*vol_mod;
316 	}
317 }
318 
buf_convert(jack_default_audio_sample_t * out,const char * in,int len,const float mod)319 int buf_convert(jack_default_audio_sample_t *out, const char *in, int len, const float mod){
320 	int i;
321 
322 	if(len%2){
323 		return -1;
324 	}
325 
326 	short *s_in = (short*)in;
327 	len>>=1;
328 	for (i=0; i<len; i++) {
329 		out[i] = (s_in[i]/NORMFACT16)*mod;
330 	}
331 	return len;
332 }
333 
writei_snd(struct playerHandles * ph,const char * out,const unsigned int size)334 int writei_snd(struct playerHandles *ph, const char *out, const unsigned int size){
335 	int c,i,ret,tmpbufsize;
336 	const int by=ph->dec_enc?ph->dec_enc/8:1;
337 	const int chan_shift=ph->dec_chan>>1;
338 	const int chan_size=size>>chan_shift;
339 	const int samples=chan_size/(by); /* for short -> float conversion */
340 
341 	if(ph->pflag->pause){ // Move this into process?
342 		size_t write[2],read[2];
343 		read[0]=ph->outbuf[0]->read_ptr;
344 		read[1]=ph->outbuf[1]->read_ptr;
345 		write[0]=ph->outbuf[0]->write_ptr;
346 		write[1]=ph->outbuf[1]->write_ptr;
347 		// Can't let all that beautiful music go to waste...
348 		snd_clear(ph);
349 		do{
350 			usleep(100000); // 0.1 seconds
351 		}
352 		while(ph->pflag->pause);
353 		ph->outbuf[0]->read_ptr=read[0];
354 		ph->outbuf[1]->read_ptr=read[1];
355 		ph->outbuf[0]->write_ptr=write[0];
356 		ph->outbuf[1]->write_ptr=write[1];
357 	}
358 
359 	if(size==0){
360 		return 0;
361 	}
362 
363 	tmpbufsize=samples*((double)ph->out_rate/(double)ph->dec_rate);
364 	if(!(ph->tmpbuf=realloc(ph->tmpbuf,samples*sizeof(*ph->tmpbuf)))){
365 		fprintf(stderr,"JACK | temp buffer failed reallocation to %d\n",samples);
366 		return 0;
367 	}
368 	if(!(ph->tmpbuf_out=realloc(ph->tmpbuf_out,tmpbufsize*sizeof(*ph->tmpbuf_out)))){
369 		fprintf(stderr,"JACK | temp out buffer failed reallocation to %d\n",tmpbufsize);
370 		return 0;
371 	}
372 
373 	i=tmpbufsize*sizeof(*ph->tmpbuf);
374 	for(c=0;c<ph->dec_chan;c++){
375 		while(jack_ringbuffer_write_space(ph->outbuf[c])<i){
376 			//fprintf(stderr,"buffer full\n");
377 			usleep(10000);
378 		}
379 	}
380 
381 	for(c=0;c<ph->dec_chan;c++){
382 		if(ph->dec_enc>16){
383 			fill_buff_32(ph->tmpbuf,out,c,ph->dec_enc,samples,ph->dec_chan,chan_shift,ph->vol_mod);
384 		}
385 		else{
386 			fill_buff_16(ph->tmpbuf,out,c,ph->dec_enc,samples,ph->dec_chan,chan_shift,ph->vol_mod);
387 		}
388 
389 tryresample:
390 		if((ret=resample(ph, c, samples, tmpbufsize, ph->dec_rate, ph->out_rate, ph->dec_chan))!=tmpbufsize){
391 			//fprintf(stderr,"\nResample size mismatch: samples %d %d->%d | ret %d | buf %d\n", samples, ph->dec_rate, ph->out_rate, ret, tmpbufsize);
392 			goto tryresample;
393 		}
394 		i=ret*sizeof(*ph->tmpbuf_out);
395 		//i=tmpbufsize*sizeof(*ph->tmpbuf_out);
396 		if((ret=jack_ringbuffer_write(ph->outbuf[c],(char*)ph->tmpbuf_out,i))<i)
397 			fprintf(stderr,"JACK | ringbuffer failed write. expected: %d | %ld ; got: %d \n",i,tmpbufsize*sizeof(*ph->tmpbuf),ret);
398 	}
399 
400 	return 0;
401 }
402 
snd_close(struct playerHandles * ph)403 void snd_close(struct playerHandles *ph){
404 	int i;
405 
406 	for(i=0;i<ph->dec_chan;i++)
407 		ph->rs_state[i]=src_delete(ph->rs_state[i]);
408 	free(ph->rs_state);
409 
410 	jack_client_close(ph->sndfd);
411 	jack_ringbuffer_free(ph->outbuf[0]);
412 	jack_ringbuffer_free(ph->outbuf[1]);
413 	free(ph->outbuf);
414 	free(ph->jack_ports);
415 	free(ph->tmpbuf);
416 	free(ph->tmpbuf_out);
417 }
418