Debian Codegraph @

speexin~.c

raw symbols ◀ ▶ SCIP
3 Debian patches touch this file
1 /* ------------------------ speexin~ ------------------------------------------ */
2 /* */
3 /* Object to receive a speex encoded stream sent by a peer using speexin~. */
4 /* Written by Yves Degoyon ([email protected]). */
5 /* Tarballs and updates @ http://ydegoyon.free.fr */
6 /* */
7 /* This program is free software; you can redistribute it and/or */
8 /* modify it under the terms of the GNU General Public License */
9 /* as published by the Free Software Foundation; either version 2 */
10 /* of the License, or (at your option) any later version. */
11 /* */
12 /* See file LICENSE for further informations on licensing terms. */
13 /* */
14 /* This program is distributed in the hope that it will be useful, */
15 /* but WITHOUT ANY WARRANTY; without even the implied warranty of */
16 /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
17 /* GNU General Public License for more details. */
18 /* */
19 /* You should have received a copy of the GNU General Public License */
20 /* along with this program; if not, write to the Free Software */
21 /* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
22 /* */
23 /* Based on PureData by Miller Puckette and others. */
24 /* Uses the Speex voice quality encoding library which can */
25 /* be found at http://speex.sourceforge.net. */
26 /* */
27 /* ---------------------------------------------------------------------------- */
28
29
30 #include <m_pd.h>
31 #include <g_canvas.h>
32
•33 #if PD_MINOR_VERSION >= 37
34 #include "s_stuff.h"
35 #endif
36
37 #include <sys/types.h>
38 #include <string.h>
39 #include <stdlib.h>
40 #ifdef _WIN32
41 #include <io.h>
42 #include <winsock.h>
43 #else
44 #include <sys/socket.h>
45 #include <errno.h>
46 #include <netinet/in.h>
47 #include <netinet/tcp.h>
48 #include <arpa/inet.h>
49 #include <netdb.h>
50 #include <sys/time.h>
51 #include <unistd.h>
52 #include <fcntl.h>
53 #include <stdio.h>
54 #define SOCKET_ERROR -1
55 #endif
56
57 #if defined(__APPLE__) || defined(_WIN32)
58 #define MSG_NOSIGNAL 0
59 #define SOL_TCP IPPROTO_TCP
60 #endif
61
62 #include <speex/speex.h> /* speex decoder stuff */
63 #include <speex/speex_bits.h> /* speex decoder stuff */
64
65 #ifdef _MSC_VER
66 #pragma warning( disable : 4244 )
67 #pragma warning( disable : 4305 )
68 #endif
69
70 #define MIN_AUDIO_INPUT 1024 // we must a least have 8 chunks to play a correct sound
71 #define INPUT_BUFFER_SIZE 32768
72 #define OUTPUT_BUFFER_SIZE 32768 /* 32k */
73 #define BARHEIGHT 10
74
75 #define SPEEX_NB_MODE 0 /* audio data must be 8kHz */
76 #define SPEEX_WB_MODE 1 /* audio data must be 16kHz */
77
78 //#define DATADEBUG
79
80 typedef void (*t_fdpollfn)(void *ptr, int fd);
81 extern void sys_rmpollfn(int fd);
82 extern void sys_addpollfn(int fd, t_fdpollfn fn, void *ptr);
83
84 /* time-out used for select() call */
85 static struct timeval ztout;
86
87 static char *speexin_version = "speexin~: speex voice quality streamer version 0.2, written by [email protected]";
88
89 void speexin_closesocket(int fd)
90 {
91 #ifndef _WIN32
92 if ( close(fd) < 0 )
93 {
94 perror( "close" );
95 }
96 else
97 {
98 post( "speexin~ : closed socket : %d", fd );
99 }
100 #endif
101 #ifdef _WIN32
102 closesocket(fd);
103 #endif
104 sys_rmpollfn(fd);
105 }
106
107 int setsocketoptions(int sockfd)
108 {
109 int sockopt = 1;
110 if (setsockopt(sockfd, SOL_TCP, TCP_NODELAY, (const char*) &sockopt, sizeof(int)) < 0)
111 {
112 post("speexin~ : setsockopt TCP_NODELAY failed");
113 perror( "setsockopt" );
114 return -1;
115 }
116 else
117 {
118 post("speexin~ : TCP_NODELAY set");
119 }
120
121 #ifdef _WIN32
122 sockopt = 1;
123 if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &sockopt, sizeof(int)) < 0)
124 {
125 post("speexin~ : setsockopt SO_REUSEADDR failed");
126 perror( "setsockopt" );
127 return -1;
128 }
129 else
130 {
131 post("speexin~ : setsockopt SO_REUSEADDR done.");
132 }
133 #endif
134 return 0;
135 }
136
137
138 /* ------------------------ speexin~ ----------------------------- */
139
140 static t_class *speexin_class;
141
142 typedef struct _speexin
143 {
144 t_object x_obj;
145 t_int x_socket;
146 t_outlet *x_connectionip;
147 t_int x_serversocket;
148 t_int x_samplerate;
149
150 /* Speex stuff */
151 SpeexBits x_bits; /* bits packing structure */
152 void *x_decstate; /* decoder state */
153 t_int x_framesize; /* frame size */
154 t_int x_mode; /* Narrow or Wide Band */
155 int x_quality; /* encoding quality ( 0 to 10 ) */
156
157 t_int x_inpackets; /* number of packets received */
158 t_int x_dpacket; /* displayed packet in status bar */
159 t_int x_packetsize; /* size of the packets */
160 t_int x_pblocks; /* processed blocks */
161 t_int x_graphic; /* indicates if we show a graphic bar */
162
163 void *x_inbuffer; /* accumulation buffer for incoming speex frames */
164 t_int x_inwritepos; /* accumulation buffer for incoming speex frames */
165 t_int x_encsize;
166 t_int x_inbuffersize;
167
168 t_float *x_outbuffer; /* buffer to store audio decoded data */
169 t_int x_oinp;
170 t_int x_ooutp;
171 t_int x_outunread;
172 t_int x_outbuffersize;
173 t_float *x_decchunk;
174
175 t_canvas *x_canvas;
176
177 t_int x_stream; /* indicates if a stream is connected ( meaning correct input flow ) */
178 t_int x_newstream; /* at first, the stream must provide enough data to start */
179
180 } t_speexin;
181
182 void speexin_tilde_speex_init(t_speexin *x)
183 {
184 int ret;
185 int pf=1;
186
187 speex_bits_init(&x->x_bits);
188
189 switch ( x->x_mode )
190 {
191 case SPEEX_NB_MODE :
192 x->x_decstate = speex_decoder_init(&speex_nb_mode);
193 break;
194
195 case SPEEX_WB_MODE :
196 x->x_decstate = speex_decoder_init(&speex_wb_mode);
197 break;
198
199 default :
•200 pd_error(x, "speexin~ : severe error : decoding scheme is unknown" );
201 break;
202 }
203
204 speex_decoder_ctl(x->x_decstate, SPEEX_GET_FRAME_SIZE, (void*)&x->x_framesize);
205
206 speex_decoder_ctl(x->x_decstate, SPEEX_SET_PF, &pf);
207
208 post( "speexin~ : frame size : %d", x->x_framesize );
209
210 }
211
212 static void speexin_decode_input(t_speexin *x)
213 {
214 int i;
215 int alength = 0;
216 static char out[8192];
217 signed short int *p = (signed short int *) out;
218 int pbytes;
219 int ret;
220 int flength = 0;
221
222 if ( x->x_encsize > 0 )
223 {
224
225 while ( x->x_encsize > *(char *)(x->x_inbuffer) )
226 {
227
228 flength = *(char *)(x->x_inbuffer );
229
230 // post( "speexin~ : reading bits from 1 to : %d", flength+1 );
231 speex_bits_read_from(&x->x_bits, x->x_inbuffer+1, flength);
232
233 #ifdef DATADEBUG
234 {
235 t_int si;
236
237 printf( "speexin~ : decoding : " );
238 for ( si=0; si<flength; si++ )
239 {
240 printf( "%d ", *(char *)(x->x_inbuffer+1+si) );
241 }
242 printf( "\n" );
243 }
244 #endif
245
246 {
247 t_int sp=0, rp=0;
248
249 speex_decode(x->x_decstate, &x->x_bits, x->x_decchunk);
250
251 while( sp < x->x_framesize )
252 {
253 rp=(x->x_oinp+sp)%x->x_outbuffersize;
254 // if ( rp == x->x_outbuffersize - 1 ) post( "speexin~ : write at the end of audio buffer" );
255 // post( "speexin~ : sp=%d : rp=%d", sp, rp );
256 x->x_outbuffer[ rp ] = x->x_decchunk[sp++];
257 }
258 x->x_oinp = rp+1;
259 }
260 x->x_outunread += x->x_framesize;
261 memcpy( x->x_inbuffer, x->x_inbuffer+flength+1, x->x_inbuffersize-flength-1 );
262 x->x_encsize -= flength+1;
263 x->x_inwritepos -= flength+1;
264
265 }
266
267 }
268
269 if ( x->x_graphic && glist_isvisible( x->x_canvas ) )
270 {
271 /* update graphical read status */
272 if ( x->x_inpackets != x->x_dpacket )
273 {
274 char color[32];
275 int minpackets = ( MIN_AUDIO_INPUT/x->x_framesize)-2; // audio loop has eaten some already
276
277
278 sys_vgui(".x%lx.c delete rectangle %xSTATUS\n", x->x_canvas, x );
279 sys_vgui(".x%lx.c delete line %xTHRESHOLD\n", x->x_canvas, x );
280 if ( x->x_outunread > 0 )
281 {
282 t_int width;
283
284 if ( x->x_inpackets < (MIN_AUDIO_INPUT/x->x_framesize)/2 )
285 {
286 strcpy( color, "red" );
287 }
288 else
289 {
290 strcpy( color, "lightgreen" );
291 }
292 width = rtext_width( glist_findrtext( (t_glist*)x->x_canvas, (t_text *)x ) );
293 sys_vgui(".x%lx.c create rectangle %d %d %d %d -fill %s -tags %xSTATUS\n",
294 x->x_canvas, x->x_obj.te_xpix, x->x_obj.te_ypix-BARHEIGHT-1,
295 x->x_obj.te_xpix+(x->x_inpackets*x->x_packetsize*width)/INPUT_BUFFER_SIZE,
296 x->x_obj.te_ypix - 1, color, x );
297 sys_vgui(".x%lx.c create line %d %d %d %d -fill red -tags %xTHRESHOLD\n",
298 x->x_canvas, x->x_obj.te_xpix+(minpackets*x->x_packetsize*width)/INPUT_BUFFER_SIZE,
299 x->x_obj.te_ypix-BARHEIGHT-1,
300 x->x_obj.te_xpix+(minpackets*x->x_packetsize*width)/INPUT_BUFFER_SIZE,
301 x->x_obj.te_ypix-1, x );
302 x->x_dpacket = x->x_inpackets;
303 }
304 }
305
306 }
307
308 }
309
310 static void speexin_recv(t_speexin *x)
311 {
312 int ret;
313
314 if ( x->x_inwritepos > x->x_inbuffersize - 1024 )
315 {
316 post( "speexin~ : input buffer is full" );
317 return;
318 }
319 if ( ( ret = recv(x->x_socket, (void*) x->x_inbuffer + x->x_inwritepos,
320 (size_t)x->x_inbuffersize,
321 MSG_NOSIGNAL) ) < 0 )
322 {
323 post( "speexin~ : receive error" );
324 perror( "recv" );
325 return;
326 }
327 else
328 {
329 // post( "speexin~ : received %d bytes at %d on %d ( up to %d)",
330 // ret, x->x_inwritepos, x->x_socket,
331 // x->x_inbuffersize );
332
333 if ( ret == 0 )
334 {
335 post( "speexin~ : closing connection ( s=%d )", x->x_socket );
336 speexin_closesocket(x->x_socket);
337 x->x_socket = -1;
338 sys_vgui(".x%lx.c delete rectangle %xPBAR\n", x->x_canvas, x );
339 sys_vgui(".x%lx.c delete line %xTHRESHOLD\n", x->x_canvas, x );
340 sys_vgui(".x%lx.c delete rectangle %xSTATUS\n", x->x_canvas, x );
341 outlet_symbol( x->x_connectionip, gensym("") );
342 }
343 else
344 {
345 x->x_inpackets++;
346 }
347
348 x->x_encsize += ret;
349 x->x_inwritepos += ret;
350
351 speexin_decode_input(x);
352 }
353 }
354
355 static void speexin_acceptconnection(t_speexin *x)
356 {
357 struct sockaddr_in incomer_address;
358 int sockaddrl = (int) sizeof( struct sockaddr );
359
360 int fd = accept(x->x_serversocket, (struct sockaddr*)&incomer_address, &sockaddrl );
361 post("speexin~: accepted incomer : %d.", fd );
362
363 if (fd < 0)
364 {
365 post("speexin~: accept failed");
366 return;
367 }
368
369 if (x->x_socket > 0)
370 {
371 post("speexin~: the source has changed to %s ( new socket = %d ).",
372 inet_ntoa( incomer_address.sin_addr ), fd );
373 speexin_closesocket(x->x_socket);
374 }
375
376 x->x_socket = fd;
377 sys_addpollfn(x->x_socket, (t_fdpollfn)speexin_recv, x);
378 outlet_symbol( x->x_connectionip, gensym( inet_ntoa( incomer_address.sin_addr) ) );
379
380 if ( x->x_graphic && glist_isvisible( x->x_canvas ) )
381 {
382 t_int width;
383
384 width = rtext_width( glist_findrtext( (t_glist*)x->x_canvas, (t_text *)x ) );
385 sys_vgui(".x%lx.c create rectangle %d %d %d %d -fill lightblue -tags %xPBAR\n",
386 x->x_canvas, x->x_obj.te_xpix, x->x_obj.te_ypix-BARHEIGHT-1,
387 x->x_obj.te_xpix + width, x->x_obj.te_ypix - 1, x );
388 }
389 x->x_stream = 0;
390 x->x_newstream = 1;
391
392 }
393
394
395 static int speexin_startservice(t_speexin* x, int portno)
396 {
397 struct sockaddr_in server;
398 int sockfd;
399
400 /* create a socket */
401 sockfd = socket(AF_INET, SOCK_STREAM, 0);
402
403 if (sockfd < 0)
404 {
405 sys_sockerror("socket");
406 return (0);
407 }
408 server.sin_family = AF_INET;
409 server.sin_addr.s_addr = INADDR_ANY;
410
411 /* assign server port number */
412 server.sin_port = htons((u_short)portno);
413 post("listening to port number %d", portno);
414
415 setsocketoptions(sockfd);
416
417 /* name the socket */
418 if (bind(sockfd, (struct sockaddr *)&server, sizeof(server)) < 0)
419 {
420 sys_sockerror("bind");
421 speexin_closesocket(sockfd);
422 return (0);
423 }
424
425 if (listen(sockfd, 5) < 0)
426 {
427 sys_sockerror("listen");
428 speexin_closesocket(sockfd);
429 }
430 else
431 {
432 x->x_serversocket = sockfd;
433 sys_addpollfn(x->x_serversocket, (t_fdpollfn)speexin_acceptconnection, x);
434 }
435
436 return 1;
437 }
438
439 static void speexin_free(t_speexin *x)
440 {
441 post( "speexin~ : free %x", x );
442 if (x->x_serversocket > 0)
443 {
444 post( "speexin~ : closing server socket" );
445 speexin_closesocket(x->x_serversocket);
446 x->x_serversocket = -1;
447 }
448 if (x->x_socket > 0)
449 {
450 post( "speexin~ : closing socket" );
451 speexin_closesocket(x->x_socket);
452 x->x_socket = -1;
453 }
454 if ( x->x_inbuffer ) freebytes( x->x_inbuffer, x->x_inbuffersize );
455 if ( x->x_outbuffer ) freebytes( x->x_outbuffer, x->x_outbuffersize*sizeof(t_float) );
456 if ( x->x_decchunk ) freebytes(x->x_decchunk, x->x_framesize*sizeof(t_float));
457 }
458
459 static t_int *speexin_perform(t_int *w)
460 {
461 t_speexin *x = (t_speexin*) (w[1]);
462 t_float *out = (t_float *)(w[2]);
463 t_int n = (int)(w[3]);
464 t_int bsize = n;
465 t_int ret;
466 t_int i = 0;
467 t_int j = 0;
468 t_int sp = 0;
469 t_int sratio;
470
471 // samplerate is supposed to be above 16kHz, thus sratio>1
472 if ( x->x_mode == SPEEX_NB_MODE )
473 {
474 sratio = x->x_samplerate / 8000;
475 }
476 else
477 {
478 sratio = x->x_samplerate / 16000;
479 }
480 // post( "speexin~ : ratio : %d", sratio );
481
482 memset( out, 0x0, n*sizeof(t_float ) );
483
484 sp = 0;
485 while( sp < n )
486 {
487 if ( ( ( x->x_outunread > MIN_AUDIO_INPUT ) && x->x_newstream ) || // wait the buffer to load
488 ( x->x_stream ) // check that the stream provides enough data
489 )
490 {
491 if ( x->x_newstream )
492 {
493 x->x_newstream = 0;
494 x->x_stream = 1;
495 }
496 /* resampling */
497 for ( j=0; j<sratio; j++ )
498 {
499 *(out+sp)=*(x->x_outbuffer+x->x_ooutp)/8000; // input has been scaled
500 //*(x->x_outbuffer+x->x_ooutp)=0.0; // data read, now zeroed
501 sp++;
502 if ( sp >= n ) break;
503 }
504 x->x_ooutp = (x->x_ooutp + 1)%x->x_outbuffersize;
505 // if ( x->x_ooutp == x->x_outbuffersize - 1 ) post( "speexin~ : end of audio buffer" );
506 x->x_outunread-=1;
507 }
508 else
509 {
510 for ( j=0; j<sratio; j++ )
511 {
512 *(out+sp)=0.0;
513 sp++;
514 if ( sp >= n ) break;
515 }
516 }
517 }
518 x->x_pblocks++;
519
520 if ( ( x->x_outunread <= MIN_AUDIO_INPUT/10 ) && ( x->x_stream ) )
521 {
522 // post( "speexin~ : stream lost (too little input)" );
523 x->x_stream = 0;
524 x->x_newstream = 1; // waiting for a new stream
525 }
526
527 if ( x->x_pblocks == x->x_framesize/bsize )
528 {
529 x->x_inpackets--;
530 x->x_pblocks = 0;
531 }
532
533 return (w+4);
534 }
535
536 static void speexin_dsp(t_speexin *x, t_signal **sp)
537 {
538 dsp_add(speexin_perform, 3, x, sp[0]->s_vec, sp[0]->s_n);
539 }
540
541
542 static void *speexin_new(t_floatarg fportno, t_floatarg fdographics)
543 {
544 t_speexin *x;
545 int i;
546
547 if ( fportno < 0 || fportno > 65535 )
548 {
549 post( "speexin~ : error : wrong portnumber : %d", (int)fportno );
550 return NULL;
551 }
552 if ( ((int)fdographics != 0) && ((int)fdographics != 1.) )
553 {
554 post( "speexin~ : error : constructor : speexin~ <portnumber> [graphic flag = 0 | 1 ] ( got = %f)", fdographics );
555 return NULL;
556 }
557
558 x = (t_speexin *)pd_new(speexin_class);
559 outlet_new(&x->x_obj, &s_signal);
560 x->x_connectionip = outlet_new(&x->x_obj, &s_symbol);
561
562 x->x_serversocket = -1;
563 x->x_socket = -1;
564 x->x_inpackets = 0;
565 x->x_inwritepos = 0;
566 x->x_dpacket = -1;
567 x->x_mode = SPEEX_NB_MODE;
568 x->x_samplerate = sys_getsr();
569
570 x->x_canvas = canvas_getcurrent();
571
572 x->x_inbuffersize = INPUT_BUFFER_SIZE;
573 x->x_outbuffersize = OUTPUT_BUFFER_SIZE;
574 x->x_inbuffer = (char*) getbytes( x->x_inbuffersize );
575 memset( x->x_inbuffer, 0x0, INPUT_BUFFER_SIZE );
576 x->x_outbuffer = (t_float*) getbytes( x->x_outbuffersize*sizeof(t_float) );
577 memset( x->x_outbuffer, 0x0, OUTPUT_BUFFER_SIZE*sizeof(t_float) );
578
579 if ( !x->x_inbuffer || !x->x_outbuffer )
580 {
581 post( "speexin~ : could not allocate buffers." );
582 return NULL;
583 }
584
585 x->x_encsize = 0;
586 x->x_oinp = 0;
587 x->x_ooutp = 0;
588
589 ztout.tv_sec = 0;
590 ztout.tv_usec = 0;
591
592 x->x_graphic = (int)fdographics;
593
594 post( "speexin~ : starting service on port %d", (int)fportno );
595 speexin_startservice(x, (int)fportno);
596
597 // init speex decoder
598 speexin_tilde_speex_init(x);
599
600 x->x_decchunk = (t_float*)getbytes(x->x_framesize*sizeof(t_float));
601 if (!x->x_decchunk) /* check allocation... */
602 {
•603 pd_error(x, "speexin~ : cannot allocate chunk");
604 return NULL;
605 }
606
607 return (x);
608 }
609
610
611 void speexin_tilde_setup(void)
612 {
•613 logpost(NULL, 4, "%s", speexin_version );
614 speexin_class = class_new(gensym("speexin~"),
615 (t_newmethod) speexin_new, (t_method) speexin_free,
616 sizeof(t_speexin), CLASS_NOINLET, A_DEFFLOAT, A_DEFFLOAT, A_NULL);
617
618 class_addmethod(speexin_class, nullfn, gensym("signal"), 0);
619 class_addmethod(speexin_class, (t_method) speexin_dsp, gensym("dsp"), 0);
620 }