Debian Codegraph @

mp3streamout~.c

raw symbols ◀ ▶ SCIP
2 Debian patches touch this file
1 /* ------------------------ mp3streamout~ ------------------------------------- */
2 /* */
3 /* Tilde object to send mp3-stream to a peer using mp3streamin~. */
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 LAME MPEG 1 Layer 3 encoding library (lame_enc.dll) which can */
25 /* be found at http://www.cdex.n3.net. */
26 /* */
27 /* "I'd sell my soul to god" */
28 /* "If it could take away the pain." */
29 /* Theo Hakola -- */
30 /* ---------------------------------------------------------------------------- */
31
32 #include <sys/types.h>
33 #include <string.h>
34 #include <stdio.h>
35 #include <errno.h>
36 #include <stdlib.h>
37 #include <fcntl.h>
38 #include <sys/stat.h>
39 #ifndef __APPLE__
40 #include <malloc.h>
41 #endif
42 #include <ctype.h>
43 #ifdef _WIN32
44 #include <io.h>
45 #include <windows.h>
46 #include <winsock.h>
47 #include <windef.h>
48 #else
49 #include <unistd.h>
50 #include <sys/socket.h>
51 #include <netinet/in.h>
52 #include <netdb.h>
53 #include <time.h>
54 #include <sys/time.h>
55 #define SOCKET_ERROR -1
56 #endif
57
58 #if defined(__APPLE__) || defined(_WIN32)
59 #define MSG_NOSIGNAL 0
60 #endif
61
62 #include <lame/lame.h> /* lame encoder stuff */
63
64 #include "m_pd.h" /* standard pd stuff */
65
66 #include "mpg123.h" /* sub-library MPGLIB included in lame */
67 /* useful debugging functions from mpglib */
68 extern int decode_header( struct frame* fr, unsigned long newhead );
69 extern void print_header_compact( struct frame* fr );
70 extern int head_check( unsigned long head, int check_layer );
71
72 #define MY_MP3_MALLOC_IN_SIZE 65536
73 /* max size taken from lame readme */
74 #define MY_MP3_MALLOC_OUT_SIZE 1.25*MY_MP3_MALLOC_IN_SIZE+7200
75
76 #define MAXDATARATE 320 /* maximum mp3 data rate is 320kbit/s */
77 #define STRBUF_SIZE 32
78
79 static char *mp3streamout_version = "mp3streamout~: mp3 peer-to-peer streamer version 0.3, written by [email protected]";
80
81 static t_class *mp3streamout_class;
82
83 typedef struct _mp3streamout
84 {
85 t_object x_obj;
86
87 /* LAME stuff */
88 int x_lame; /* info about encoder status */
89 int x_lamechunk; /* chunk size for LAME encoder */
90 int x_mp3size; /* number of returned mp3 samples */
91
92 /* buffer stuff */
93 unsigned short x_inp; /* in position for buffer */
94 unsigned short x_outp; /* out position for buffer*/
95 short *x_mp3inbuf; /* data to be sent to LAME */
96 char *x_mp3outbuf; /* data returned by LAME -> our mp3 stream */
97 short *x_buffer; /* data to be buffered */
98 int x_bytesbuffered; /* number of unprocessed bytes in buffer */
99 int x_start;
100
101 /* mp3 format stuff */
102 int x_samplerate;
103 int x_bitrate; /* bitrate of mp3 stream */
104 int x_mp3mode; /* mode (mono, joint stereo, stereo, dual mono) */
105 int x_mp3quality; /* quality of encoding */
106
107 /* connection data */
108 int x_fd; /* info about connection status */
109 int x_outpackets; /* mp3 packets sent */
110
111 t_float x_f; /* float needed for signal input */
112
113 lame_global_flags* lgfp;
114 } t_mp3streamout;
115
116
117 /* encode PCM data to mp3 stream */
118 static void mp3streamout_encode(t_mp3streamout *x)
119 {
120 unsigned short i, wp;
121 int err = -1;
122 int n = x->x_lamechunk;
123
124 #ifdef _WIN32
125 if(x->x_lamechunk < sizeof(x->x_mp3inbuf))
126 #else
127 if(x->x_lamechunk < (int)sizeof(x->x_mp3inbuf))
128 #endif
129 {
•130 pd_error(x, "not enough memory!");
131 return;
132 }
133
134 /* on start/reconnect set outpoint that it not interferes with inpoint */
135 if(x->x_start == -1)
136 {
137 post("mp3streamout~: initializing buffers");
138 /* we try to keep 2.5 times the data the encoder needs in the buffer */
139 if(x->x_inp > (2 * x->x_lamechunk))
140 {
141 x->x_outp = (short) x->x_inp - (2.5 * x->x_lamechunk);
142 }
143 else if(x->x_inp < (2 * x->x_lamechunk))
144 {
145 x->x_outp = (short) MY_MP3_MALLOC_IN_SIZE - (2.5 * x->x_lamechunk);
146 }
147 x->x_start = 1;
148 }
•149 if((unsigned short)(x->x_outp - x->x_inp) < x->x_lamechunk)pd_error(x, "mp3streamout~: buffers overlap!");
150
151 i = MY_MP3_MALLOC_IN_SIZE - x->x_outp;
152
153 /* read from buffer */
154 if(x->x_lamechunk <= i)
155 {
156 /* enough data until end of buffer */
157 for(n = 0; n < x->x_lamechunk; n++) /* fill encode buffer */
158 {
159 x->x_mp3inbuf[n] = x->x_buffer[n + x->x_outp];
160 }
161 x->x_outp += x->x_lamechunk;
162 }
163 else /* split data */
164 {
165 for(wp = 0; wp < i; wp++) /* data at end of buffer */
166 {
167 x->x_mp3inbuf[wp] = x->x_buffer[wp + x->x_outp];
168 }
169
170 for(wp = i; wp < x->x_lamechunk; wp++) /* write rest of data at beginning of buffer */
171 {
172 x->x_mp3inbuf[wp] = x->x_buffer[wp - i];
173 }
174 x->x_outp = x->x_lamechunk - i;
175 }
176
177 /* encode mp3 data */
178
179 x->x_mp3size = lame_encode_buffer_interleaved(x->lgfp, x->x_mp3inbuf,
180 x->x_lamechunk/lame_get_num_channels(x->lgfp),
181 x->x_mp3outbuf, MY_MP3_MALLOC_OUT_SIZE);
182 x->x_mp3size+=lame_encode_flush( x->lgfp, x->x_mp3outbuf+x->x_mp3size, MY_MP3_MALLOC_OUT_SIZE-x->x_mp3size );
183 // post( "mp3streamout~ : encoding returned %d frames", x->x_mp3size );
184
185 /* check result */
186 if(x->x_mp3size<0)
187 {
188 lame_close( x->lgfp );
•189 pd_error(x, "mp3streamout~: lame_encode_buffer_interleaved failed (%d)", x->x_mp3size);
190 x->x_lame = -1;
191 }
192 }
193
194 /* stream mp3 to the peer */
195 static void mp3streamout_stream(t_mp3streamout *x)
196 {
197 int count = -1, i;
198 struct frame hframe;
199
200 /* header needs to be included in each packet */
201
202 for( i=0; i<x->x_mp3size; i++ )
203 {
204 // track valid data
205 if ( head_check( *((unsigned long*)x->x_mp3outbuf+i), 3 ) )
206 {
207 // post( "valid header emitted @ %d (byte %d)", i, i*sizeof(unsigned long) );
208 }
209 }
210
211 count = send(x->x_fd, x->x_mp3outbuf, x->x_mp3size, MSG_NOSIGNAL);
212 if(count < 0)
213 {
•214 pd_error(x, "mp3streamout~: could not send encoded data to the peer (%d)", count);
215 lame_close( x->lgfp );
216 x->x_lame = -1;
217 #ifdef _WIN32
218 closesocket(x->x_fd);
219 #else
220 close(x->x_fd);
221 #endif
222 x->x_fd = -1;
223 outlet_float(x->x_obj.ob_outlet, 0);
224 }
225 else
226 {
227 x->x_outpackets++;
228 if ( x->x_outpackets%100 == 0 )
229 {
230 // post( "mp3streamout~ : emitted %d bytes (packets = %d)", count, x->x_outpackets );
231 }
232 }
233 if((count > 0)&&(count != x->x_mp3size))
234 {
•235 pd_error(x, "mp3streamout~: %d bytes skipped", x->x_mp3size - count);
236 }
237 }
238
239
240 /* buffer data as channel interleaved PCM */
241 static t_int *mp3streamout_perform(t_int *w)
242 {
243 t_float *in1 = (t_float *)(w[1]); /* left audio inlet */
244 t_float *in2 = (t_float *)(w[2]); /* right audio inlet */
245 t_mp3streamout *x = (t_mp3streamout *)(w[3]);
246 int n = (int)(w[4]); /* number of samples */
247 unsigned short i,wp;
248 float in;
249
250 /* copy the data into the buffer */
251 i = MY_MP3_MALLOC_IN_SIZE - x->x_inp; /* space left at the end of buffer */
252
253 n *= 2; /* two channels go into one buffer */
254
255 if( n <= i )
256 {
257 /* the place between inp and MY_MP3_MALLOC_IN_SIZE */
258 /* is big enough to hold the data */
259
260 for(wp = 0; wp < n; wp++)
261 {
262 if(wp%2)
263 {
264 in = *(in2++); /* right channel / inlet */
265 }
266 else
267 {
268 in = *(in1++); /* left channel / inlet */
269 }
270 if (in > 1.0)
271 {
272 in = 1.0;
273 }
274 if (in < -1.0)
275 {
276 in = -1.0;
277 }
278 x->x_buffer[wp + x->x_inp] = (short) (32767.0 * in);
279 }
280 x->x_inp += n; /* n more samples written to buffer */
281 }
282 else
283 {
284 /* the place between inp and MY_MP3_MALLOC_IN_SIZE is not */
285 /* big enough to hold the data */
286 /* writing will take place in two turns, one from */
287 /* x->x_inp -> MY_MP3_MALLOC_IN_SIZE, then from 0 on */
288
289 for(wp = 0; wp < i; wp++) /* fill up to end of buffer */
290 {
291 if(wp%2)
292 {
293 in = *(in2++);
294 }
295 else
296 {
297 in = *(in1++);
298 }
299 if (in > 1.0)
300 {
301 in = 1.0;
302 }
303 if (in < -1.0)
304 {
305 in = -1.0;
306 }
307 x->x_buffer[wp + x->x_inp] = (short) (32767.0 * in);
308 }
309 for(wp = i; wp < n; wp++) /* write rest at start of buffer */
310 {
311 if(wp%2)
312 {
313 in = *(in2++);
314 }
315 else
316 {
317 in = *(in1++);
318 }
319 if (in > 1.0)
320 {
321 in = 1.0;
322 }
323 if (in < -1.0)
324 {
325 in = -1.0;
326 }
327 x->x_buffer[wp - i] = (short) (32767.0 * in);
328 }
329 x->x_inp = n - i; /* new writeposition in buffer */
330 }
331
332 if((x->x_fd >= 0)&&(x->x_lame >= 0))
333 {
334 /* count buffered samples when things are running */
335 x->x_bytesbuffered += n;
336
337 /* encode and send to the peer */
338 if(x->x_bytesbuffered > x->x_lamechunk)
339 {
340 mp3streamout_encode(x); /* encode to mp3 */
341 mp3streamout_stream(x); /* stream mp3 to the peer */
342 x->x_bytesbuffered -= x->x_lamechunk;
343 }
344 }
345 else
346 {
347 x->x_start = -1;
348 }
349 return (w+5);
350 }
351
352 static void mp3streamout_dsp(t_mp3streamout *x, t_signal **sp)
353 {
354 dsp_add(mp3streamout_perform, 4, sp[0]->s_vec, sp[1]->s_vec, x, sp[0]->s_n);
355 }
356
357 /* initialize the lame library */
358 static void mp3streamout_tilde_lame_init(t_mp3streamout *x)
359 {
360 int ret;
361 x->lgfp = lame_init(); /* set default parameters for now */
362
363 #ifdef _WIN32
364 /* load lame_enc.dll library */
365 HINSTANCE dll;
366 dll=LoadLibrary("lame_enc.dll");
367 if(dll==NULL)
368 {
•369 pd_error(x, "mp3streamout~: error loading lame_enc.dll");
370 closesocket(x->x_fd);
371 x->x_fd = -1;
372 outlet_float(x->x_obj.ob_outlet, 0);
373 post("mp3streamout~: connection closed");
374 return;
375 }
376 #endif
377 {
378 const char *lameVersion = get_lame_version();
•379 logpost(NULL, 4, "%s", "mp3streamout~ : using lame version : %s", lameVersion );
380 }
381
382 /* setting lame parameters */
383 lame_set_num_channels( x->lgfp, 2);
384 lame_set_in_samplerate( x->lgfp, sys_getsr() );
385 lame_set_out_samplerate( x->lgfp, x->x_samplerate );
386 lame_set_brate( x->lgfp, x->x_bitrate );
387 lame_set_mode( x->lgfp, x->x_mp3mode );
388 lame_set_quality( x->lgfp, x->x_mp3quality );
389 lame_set_emphasis( x->lgfp, 1 );
390 lame_set_original( x->lgfp, 1 );
391 lame_set_copyright( x->lgfp, 1 ); /* viva free music societies !!! */
392 lame_set_disable_reservoir( x->lgfp, 0 );
393 //lame_set_padding_type( x->lgfp, PAD_NO ); /* deprecated in LAME */
394 ret = lame_init_params( x->lgfp );
395 if ( ret<0 )
396 {
397 post( "mp3streamout~ : error : lame params initialization returned : %d", ret );
398 }
399 else
400 {
401 x->x_lame=1;
402 /* magic formula copied from windows dll for MPEG-I */
403 x->x_lamechunk = 2*1152;
404
405 post( "mp3streamout~ : lame initialization done. (%d)", x->x_lame );
406 }
407 lame_init_bitstream( x->lgfp );
408 }
409
410 /* connect to the peer */
411 static void mp3streamout_connect(t_mp3streamout *x, t_symbol *hostname, t_floatarg fportno)
412 {
413 struct sockaddr_in csocket;
414 struct hostent *hp;
415 int portno = fportno; /* get port from message box */
416
417 /* variables used for communication with the peer */
418 const char *buf = 0;
419 char resp[STRBUF_SIZE];
420 unsigned int len;
421 int sockfd;
422
423 #ifdef _WIN32
424 unsigned int ret;
425 #else
426 int ret;
427 #endif
428
429 if (x->x_fd >= 0)
430 {
•431 pd_error(x, "mp3streamout~: already connected");
432 return;
433 }
434
435 sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
436 if (sockfd < 0)
437 {
•438 pd_error(x, "mp3streamout~: internal error while attempting to open socket");
439 return;
440 }
441
442 /* connect socket using hostname provided in command line */
443 csocket.sin_family = AF_INET;
444 hp = gethostbyname(hostname->s_name);
445 if (hp == 0)
446 {
447 post("mp3streamout~: bad host?");
448 #ifdef _WIN32
449 closesocket(sockfd);
450 #else
451 close(sockfd);
452 #endif
453 return;
454 }
455 memcpy((char *)&csocket.sin_addr, (char *)hp->h_addr, hp->h_length);
456
457 /* assign client port number */
458 csocket.sin_port = htons((unsigned short)portno);
459
460 /* try to connect. */
461 post("mp3streamout~: connecting to port %d", portno);
462 if (connect(sockfd, (struct sockaddr *) &csocket, sizeof (csocket)) < 0)
463 {
•464 pd_error(x, "mp3streamout~: connection failed!\n");
465 #ifdef _WIN32
466 closesocket(sockfd);
467 #else
468 close(sockfd);
469 #endif
470 return;
471 }
472
473 x->x_fd = sockfd;
474 x->x_outpackets = 0;
475 outlet_float( x->x_obj.ob_outlet, 1 );
476 post( "mp3streamout~ : connected to peer" );
477
478 mp3streamout_tilde_lame_init(x);
479
480 }
481
482 /* close connection to the peer */
483 static void mp3streamout_disconnect(t_mp3streamout *x)
484 {
485
486 int err = -1;
487 if(x->x_lame >= 0)
488 {
489 /* ignore remaining bytes */
490 if ( x->x_mp3size = lame_encode_flush( x->lgfp, x->x_mp3outbuf, 0) < 0 )
491 {
492 post( "mp3streamout~ : warning : remaining encoded bytes" );
493 }
494 lame_close( x->lgfp );
495 x->x_lame = -1;
496 post("mp3streamout~: encoder stream closed");
497 }
498
499 if(x->x_fd >= 0) /* close socket */
500 {
501 #ifdef _WIN32
502 closesocket(x->x_fd);
503 #else
504 close(x->x_fd);
505 #endif
506 x->x_fd = -1;
507 outlet_float( x->x_obj.ob_outlet, 0 );
508 post("mp3streamout~: connection closed");
509 }
510 }
511
512 /* settings for mp3 encoding */
513 static void mp3streamout_mpeg(t_mp3streamout *x, t_floatarg fbitrate,
514 t_floatarg fmode, t_floatarg fquality)
515 {
516 if ( fbitrate != 32 && fbitrate != 40 && fbitrate != 48 && fbitrate != 56 &&
517 fbitrate != 64 && fbitrate != 80 && fbitrate != 96 && fbitrate != 112 &&
518 fbitrate != 128 && fbitrate != 160 && fbitrate != 192 && fbitrate != 224 &&
519 fbitrate != 256 && fbitrate != 320 )
520 {
521 post( "mp3streamout~ : wrong bitrate." );
522 return;
523 }
524 if ( fmode <0 || fmode>2 )
525 {
526 post( "mp3streamout~ : wrong mp3 mode." );
527 if ( fmode == 3 )
528 {
529 post( "mp3streamout~ : mone is not supported by streamout~ for now." );
530 }
531 return;
532 }
533 /* there is a bug in lame 3.92 and quality below 5 will not work */
534 /* WAIT FOR A FIX */
535 if ( fquality <5 || fquality>9 )
536 {
537 post( "mp3streamout~ : wrong quality." );
538 return;
539 }
540 x->x_bitrate = fbitrate;
541 x->x_mp3mode = fmode;
542 x->x_mp3quality = (int)fquality;
543 post("mp3streamout~: setting mp3 stream to %dHz, %dkbit/s, mode %d, quality %d",
544 x->x_samplerate, x->x_bitrate, x->x_mp3mode, x->x_mp3quality);
545 mp3streamout_tilde_lame_init(x);
546 }
547
548 /* print settings */
549 static void mp3streamout_print(t_mp3streamout *x)
550 {
551 const char * buf = 0;
552
•553 logpost(NULL, 4, "%s", mp3streamout_version);
554 post(" LAME mp3 settings:\n"
555 " output sample rate: %d Hz\n"
556 " bitrate: %d kbit/s", x->x_samplerate, x->x_bitrate);
557 switch(x->x_mp3mode)
558 {
559 case 0 :
560 buf = "stereo";
561 break;
562 case 1 :
563 buf = "joint stereo";
564 break;
565 case 2 :
566 buf = "dual channel";
567 break;
568 case 3 :
569 buf = "mono";
570 break;
571 }
572 post(" mode: %s\n"
573 " quality: %d", buf, x->x_mp3quality);
574 #ifdef _WIN32
575 if(x->x_lamechunk!=0)post(" calculated mp3 chunk size: %d", x->x_lamechunk);
576 #else
577 post(" mp3 chunk size: %d", x->x_lamechunk);
578 #endif
579 if(x->x_samplerate!=sys_getsr())
580 {
581 post(" resampling from %d to %d Hz!", (int)sys_getsr(), x->x_samplerate);
582 }
583 }
584
585 /* clean up */
586 static void mp3streamout_free(t_mp3streamout *x)
587 {
588
589 if(x->x_lame >= 0)
590 lame_close( x->lgfp );
591
592 if(x->x_fd >= 0)
593 #ifdef _WIN32
594 closesocket(x->x_fd);
595 #else
596 close(x->x_fd);
597 #endif
598 freebytes(x->x_mp3inbuf, MY_MP3_MALLOC_IN_SIZE*sizeof(short));
599 freebytes(x->x_mp3outbuf, MY_MP3_MALLOC_OUT_SIZE);
600 freebytes(x->x_buffer, MY_MP3_MALLOC_IN_SIZE*sizeof(short));
601 }
602
603 static void *mp3streamout_new(void)
604 {
605 t_mp3streamout *x = (t_mp3streamout *)pd_new(mp3streamout_class);
606 inlet_new (&x->x_obj, &x->x_obj.ob_pd, gensym ("signal"), gensym ("signal"));
607 outlet_new( &x->x_obj, &s_float );
608 x->lgfp = NULL;
609 x->x_fd = -1;
610 x->x_outpackets = 0;
611 x->x_lame = -1;
612 x->x_samplerate = sys_getsr();
613 x->x_bitrate = 128;
614 x->x_mp3mode = 1;
615 x->x_mp3quality = 5;
616 x->x_mp3inbuf = getbytes(MY_MP3_MALLOC_IN_SIZE*sizeof(short)); /* buffer for encoder input */
617 x->x_mp3outbuf = getbytes(MY_MP3_MALLOC_OUT_SIZE); /* our mp3 stream */
618 x->x_buffer = getbytes(MY_MP3_MALLOC_IN_SIZE*sizeof(short)); /* what we get from pd, converted to PCM */
619 if ((!x->x_buffer)||(!x->x_mp3inbuf)||(!x->x_mp3outbuf)) /* check buffers... */
620 {
•621 pd_error(x, "out of memory!");
622 }
623 x->x_bytesbuffered = 0;
624 x->x_inp = 0;
625 x->x_outp = 0;
626 x->x_start = -1;
627 return(x);
628 }
629
630 void mp3streamout_tilde_setup(void)
631 {
•632 logpost(NULL, 4, "%s", mp3streamout_version);
633 mp3streamout_class = class_new(gensym("mp3streamout~"), (t_newmethod)mp3streamout_new, (t_method)mp3streamout_free,
634 sizeof(t_mp3streamout), 0, 0);
635 CLASS_MAINSIGNALIN(mp3streamout_class, t_mp3streamout, x_f );
636 class_addmethod(mp3streamout_class, (t_method)mp3streamout_dsp, gensym("dsp"), 0);
637 class_addmethod(mp3streamout_class, (t_method)mp3streamout_connect, gensym("connect"), A_SYMBOL, A_FLOAT, 0);
638 class_addmethod(mp3streamout_class, (t_method)mp3streamout_disconnect, gensym("disconnect"), 0);
639 class_addmethod(mp3streamout_class, (t_method)mp3streamout_mpeg, gensym("mpeg"), A_FLOAT, A_FLOAT, A_FLOAT, 0);
640 class_addmethod(mp3streamout_class, (t_method)mp3streamout_print, gensym("print"), 0);
641 }
642