Debian Codegraph @

mp3amp~.c

raw symbols ◀ ▶ SCIP
3 Debian patches touch this file
1 /* ------------------------- mp3amp~ ------------------------------------------ */
2 /* */
3 /* Tilde object to receive an mp3-stream from a shoutcast/icecast server. */
4 /* Written by Yves Degoyon ([email protected]). */
5 /* Get source at http://ydegoyon.free.fr */
6 /* */
7 /* This library is free software; you can redistribute it and/or */
8 /* modify it under the terms of the GNU Lesser General Public */
9 /* License as published by the Free Software Foundation; either */
10 /* version 2 of the License, or (at your option) any later version. */
11 /* */
12 /* This library is distributed in the hope that it will be useful, */
13 /* but WITHOUT ANY WARRANTY; without even the implied warranty of */
14 /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU */
15 /* Lesser General Public License for more details. */
16 /* */
17 /* You should have received a copy of the GNU Lesser General Public */
18 /* License along with this library; if not, write to the */
19 /* Free Software Foundation, Inc., 59 Temple Place - Suite 330, */
20 /* Boston, MA 02111-1307, USA. */
21 /* */
22 /* Based on PureData by Miller Puckette and others. */
23 /* Uses the LAME MPEG 1 Layer 3 encoding library which can be found at */
24 /* http://www.mp3dev.org */
25 /* */
26 /* ---------------------------------------------------------------------------- */
27
28 #include <m_pd.h>
29 #include "m_imp.h"
30 #include "g_canvas.h"
31 #include "s_stuff.h"
32 #include "pthread.h"
33
34 #include <sys/types.h>
35 #include <string.h>
36 #include <stdio.h>
37 #include <errno.h>
38 #include <fcntl.h>
39 #include "mpg123.h" /* mpg123 decoding library from lame 3.92 */
40 #include "mpglib.h" /* mpglib decoding library from lame 3.92 */
41 #include "interface.h" /* mpglib decoding library from lame 3.92 */
42 #ifdef _WIN32
43 #if !defined(__OBJC__) && !defined(__GNU_LIBOBJC__) && !defined(__objc_INCLUDE_GNU)
44 #define BOOL WINBOOL
45 #endif
46 #include <winsock.h>
47 #include <winbase.h>
48 #include <io.h>
49 #define strdup _strdup
50 #else
51 #include <sys/socket.h>
52 #include <netinet/in.h>
53 #include <netinet/tcp.h>
54 #include <arpa/inet.h>
55 #include <netdb.h>
56 #include <sys/time.h>
57 #include <unistd.h>
58 #include <unistd.h>
59 #include <ctype.h>
60 #include <stdlib.h>
61 #define SOCKET_ERROR -1
62 #endif /* _WIN32 */
63
64 #ifdef _MSC_VER
65 #pragma warning( disable : 4244 )
66 #pragma warning( disable : 4305 )
67 #endif
68
69 #if defined(__APPLE__) || defined(WIN32)
70 #define MSG_NOSIGNAL 0
71 #endif
72
73 #define LAME_AUDIO_CHUNK_SIZE 1152
74 #define MIN_AUDIO_INPUT 2*LAME_AUDIO_CHUNK_SIZE /* we must have at least n chunks to play a steady sound */
75 #define INPUT_BUFFER_SIZE 131072 /* data received on the socket : 128k */
76 #define OUTPUT_BUFFER_SIZE 131072 /* audio output buffer : 128k */
77 #define DECODE_PACKET_SIZE 131072 /* size of the data returned by mpglib : 128k */
78 #define STRBUF_SIZE 4096 /* char received from server on startup */
79 #define MAX_DECODERS 50
80 #define BARHEIGHT 10
81
82 static int guidebug=0;
83
84 #define SYS_VGUI2(a,b) if (guidebug) \
85 post(a,b);\
86 sys_vgui(a,b)
87
88 #define SYS_VGUI3(a,b,c) if (guidebug) \
89 post(a,b,c);\
90 sys_vgui(a,b,c)
91
92 #define SYS_VGUI4(a,b,c,d) if (guidebug) \
93 post(a,b,c,d);\
94 sys_vgui(a,b,c,d)
95
96 #define SYS_VGUI5(a,b,c,d,e) if (guidebug) \
97 post(a,b,c,d,e);\
98 sys_vgui(a,b,c,d,e)
99
100 #define SYS_VGUI6(a,b,c,d,e,f) if (guidebug) \
101 post(a,b,c,d,e,f);\
102 sys_vgui(a,b,c,d,e,f)
103
104 #define SYS_VGUI7(a,b,c,d,e,f,g) if (guidebug) \
105 post(a,b,c,d,e,f,g );\
106 sys_vgui(a,b,c,d,e,f,g)
107
108 #define SYS_VGUI8(a,b,c,d,e,f,g,h) if (guidebug) \
109 post(a,b,c,d,e,f,g,h );\
110 sys_vgui(a,b,c,d,e,f,g,h)
111
112 #define SYS_VGUI9(a,b,c,d,e,f,g,h,i) if (guidebug) \
113 post(a,b,c,d,e,f,g,h,i );\
114 sys_vgui(a,b,c,d,e,f,g,h,i)
115
116
117 /* useful debugging functions from mpglib */
118 extern int decode_header( struct frame* fr, unsigned long newhead );
119 extern void print_header_compact( struct frame* fr );
120 extern int head_check( unsigned long head, int check_layer );
121
122 static char *mp3amp_version = "mp3amp~: mp3 streaming client v0.12, written by Yves Degoyon";
123
124 /* ------------------------ mp3amp~ ----------------------------- */
125
126 static t_class *mp3amp_class;
127
128 /* too bad, this needs to be static,
129 handling an array to enable several decoders in pd */
130 static MPSTR mps[MAX_DECODERS]; /* decoder buffer */
131 static int nbinstances = 0;
132
133 extern const long freqs[9];
134
135 /* time-out used for select() call */
136 static struct timeval ztout;
137
138 typedef struct _mp3amp
139 {
140 t_object x_obj;
141 t_int x_instance; /* instance of the object */
142 t_outlet *x_connection;
143 t_int x_fd; /* the socket number */
144 t_int x_inframes; /* number of waiting frames */
145 t_int x_dframes; /* displayed frames in status bar */
146 t_int x_packetsize; /* size of the packets */
147 t_int x_pblocks; /* processed blocks */
148 t_int x_graphic; /* indicates if we show a graphic bar */
149 t_canvas *x_canvas; /* remember canvas */
150 t_int x_nbwaitloops; /* number of loops to wait */
151 t_int x_nbloops; /* number of loops processed */
152 t_int x_blocksize; /* size of a dsp block */
153 t_int x_resample; /* resampling factor (pd's sr / stream sr) */
154 t_int x_dsp; /* number of dsp calls, used to measure time */
155 t_int x_standby; /* flag to freeze decoding */
156 t_int x_nooutput; /* flag to avoid output of connection state */
157
158 #ifdef _WIN32
159 char *x_inbuffer; /* accumulation buffer for incoming mp3 frames */
160 #else
161 unsigned char *x_inbuffer; /* accumulation buffer for incoming mp3 frames */
162 #endif
163
164 t_int x_inwriteposition;
165 t_int x_inbuffersize;
166 t_int x_offset; /* offset used for start of decoding */
167
168 t_float *x_outbuffer; /* buffer to store audio decoded data */
169 t_int x_outwriteposition;
170 t_int x_outreadposition;
171 t_int x_outunread;
172 t_int x_outbuffersize;
173 char x_out[DECODE_PACKET_SIZE];
174
175 /* mp3 stuff */
176 t_int x_samplerate;
177 t_int x_bitrate; /* bitrate of mp3 stream read at connection time */
178 t_int x_bitrateindex; /* bitrate index for each frame, might change dynamically */
179 t_int x_mp3mode; /* mode (mono, joint stereo, stereo, dual mono) */
180 char* x_bcname; /* name of broadcast */
181 char* x_bcurl; /* url of broadcast */
182 char* x_bcgenre; /* genre of broadcast */
183 char* x_bcaim; /* aim of broadcast */
184 char* x_mountpoint; /* mountpoint for IceCast server */
185 char* x_hostname; /* hostname to connect to */
186 t_int x_port; /* port number to connect to */
187
188 t_int x_stream; /* indicates if a stream is connected ( meaning correct input flow ) */
189 } t_mp3amp;
190
191 static void mp3amp_recv(t_mp3amp *x);
192 static void mp3amp_disconnect(t_mp3amp *x);
193 static void mp3amp_connect_url(t_mp3amp *x, t_symbol *url);
194
195 static int strip_shout_header(char *head, int n)
196 {
197 int i;
198 for (i = 0; i < (n - 2); i++)
199 {
200 if (head[i] == 10 && head[i + 1] == 13)
201 break;
202 if (head[i] == '\n' && head[i + 1] == '\n')
203 break;
204 }
205 head[i + 1] = '\0';
206 return n - (i + 1);
207 }
208
209 static int strip_ice_header(char *head, int n)
210 {
211 int i;
212 for (i = 0; i < (n - 2); i++)
213 {
214 if ((head[i] == '\n') && (head[i + 1] == '\n'))
215 break;
216 }
217 head[i + 1] = '\0';
218 return n - (i + 1);
219 }
220
221 static void mp3amp_tilde_mpglib_init(t_mp3amp *x)
222 {
223 int ret;
224
225 InitMP3(&mps[x->x_instance]);
226 }
227
228 static int mp3amp_decode_input(t_mp3amp *x)
229 {
230 t_int i;
231 t_int alength = 0;
232 float resample = 0;
233 struct frame hframe;
234 unsigned int a,b,c,d;
235 unsigned long cheader;
236 signed short int *p = (signed short int *) x->x_out;
•237 int pbytes;
238 t_int ret, totlength=0;
239 t_int pframes = 0;
240
241 x->x_offset=0;
242 // search for an header to check dynamic bitrate
243 while ( x->x_offset < x->x_inwriteposition )
244 {
245 /* decode first 4 bytes as the header */
246 a = *((unsigned char*)x->x_inbuffer+x->x_offset);
247 b = *((unsigned char*)x->x_inbuffer+x->x_offset+1);
248 c = *((unsigned char*)x->x_inbuffer+x->x_offset+2);
249 d = *((unsigned char*)x->x_inbuffer+x->x_offset+3);
250
251 cheader = 0;
252 cheader = a;
253 cheader <<= 8;
254 cheader |= b;
255 cheader <<= 8;
256 cheader |= c;
257 cheader <<= 8;
258 cheader |= d;
259 if ( head_check( cheader, 0 ) )
260 {
261 decode_header( &hframe, cheader );
262 if ( hframe.framesize == 0 )
263 {
264 post( "mp3amp~: weird header ( frame size = 0 ) .... ignored" );
265 x->x_offset++;
266 continue;
267 }
268 x->x_packetsize = hframe.framesize;
269 // print_header_compact( &hframe );
270 // when the bitrate change, reinit decoder
271 if ( x->x_bitrateindex != hframe.bitrate_index )
272 {
273 post( "mp3amp~: bitrate has changed, reinitialize decoder" );
274 ExitMP3(&mps[x->x_instance]);
275 InitMP3(&mps[x->x_instance]);
276 x->x_bitrateindex = hframe.bitrate_index;
277 }
278 break;
279 }
280 x->x_offset++;
281 }
282
283 if ( x->x_inframes > 0 )
284 {
285
286 ret = decodeMP3(&mps[x->x_instance], (unsigned char*)(x->x_inbuffer+x->x_offset),
287 hframe.framesize+sizeof( unsigned long), (char *) p, sizeof(x->x_out), &pbytes);
288
289 switch (ret)
290 {
291 case MP3_OK:
292 switch (mps[x->x_instance].fr.stereo)
293 {
294 case 1:
295 case 2:
296 alength = ((mps[x->x_instance].fr.stereo==1)?pbytes >> 1 : pbytes >> 2);
297 // post( "mp3amp~: stereo : %d", mps[x->x_instance].fr.stereo );
298 // update outbuffer contents
299 for ( i=0; i<alength; i++ )
300 {
301 if ( x->x_outunread >= x->x_outbuffersize-2 )
302 {
303 // post( "mp3amp~: decode : too much input ... ignored" );
304 continue;
305 }
306 *(x->x_outbuffer+x->x_outwriteposition) = ((t_float)(*p++))/32767.0;
307 x->x_outwriteposition = (x->x_outwriteposition + 1)%x->x_outbuffersize;
308 *(x->x_outbuffer+x->x_outwriteposition) =
309 ((mps[x->x_instance].fr.stereo==2)?((t_float)(*p++))/32767.0 : 0.0);
310 x->x_outwriteposition = (x->x_outwriteposition + 1)%x->x_outbuffersize;
311 x->x_outunread+=2;
312
313 if ( x->x_outunread >= MIN_AUDIO_INPUT && !x->x_stream )
314 {
315 post("mp3amp~: stream connected" );
316 x->x_resample = x->x_samplerate / freqs[hframe.sampling_frequency];
317 if ( x->x_resample == 0 ) x->x_resample=1;
318 post("mp3amp~: resampling stream from %d to %d Hz (r=%d)",
319 freqs[hframe.sampling_frequency], x->x_samplerate, x->x_resample );
320 x->x_stream = 1;
321 }
322 }
323 break;
324 default:
325 alength = -1;
326 break;
327 }
328 // roll buffer
329 if ( x->x_inwriteposition > hframe.framesize+ (int) sizeof( unsigned long ) + x->x_offset )
330 // ^----- maybe the frame is not complete
331 {
332 x->x_inwriteposition -= hframe.framesize+sizeof( unsigned long )+x->x_offset;
333 memcpy( (void *)(x->x_inbuffer),
334 (void *)(x->x_inbuffer+x->x_offset+hframe.framesize+sizeof( unsigned long )),
335 x->x_inwriteposition);
336 x->x_offset = 0;
337 // post ( "mp3amp~: decoded frame %d", x->x_inframes );
338 x->x_inframes--;
339 pframes++;
340 }
341 else // sorry, it will be ignored
342 {
•343 // pd_error(x, "mp3amp~: incomplete frame...ignored");
344 // x->x_offset = 0;
345 // x->x_inwriteposition = 0;
346 // x->x_inframes = 0;
347 }
348
349 totlength += alength;
350 break;
351
352 case MP3_NEED_MORE:
353 if ( mps[x->x_instance].framesize == 0 && mps[x->x_instance].fsizeold != 0 )
354 {
355 post( "mp3amp~: decoding done (totlength=%d).", totlength );
356 }
357 else
358 {
359 post( "mp3amp~: retry lame decoding (more data needed)." );
360 return -1;
361 }
362 break;
363
364 case MP3_ERR:
365 post( "mp3amp~: lame decoding failed." );
366 return ret;
367 break;
368
369 }
370
371 }
372
373 if ( x->x_graphic && glist_isvisible( x->x_canvas ) )
374 {
375 /* update graphical read status */
376 if ( x->x_inframes != x->x_dframes )
377 {
378 char color[32];
379 t_int width;
380
381 width = rtext_width( glist_findrtext( (t_glist*)x->x_canvas, (t_text *)x ) );
382 SYS_VGUI3(".x%lx.c delete rectangle %xSTATUS\n", x->x_canvas, x );
383 if ( x->x_inframes < (MIN_AUDIO_INPUT/LAME_AUDIO_CHUNK_SIZE) )
384 {
385 strcpy( color, "red" );
386 }
387 else
388 {
389 strcpy( color, "lightgreen" );
390 }
391 SYS_VGUI8(".x%lx.c create rectangle %d %d %d %d -fill %s -tags %xSTATUS\n",
392 x->x_canvas, x->x_obj.te_xpix, x->x_obj.te_ypix-BARHEIGHT-1,
393 x->x_obj.te_xpix+(x->x_inwriteposition*width)/INPUT_BUFFER_SIZE,
394 x->x_obj.te_ypix - 1, color, x );
395 x->x_dframes = x->x_inframes;
396 }
397 }
398 return totlength;
399 }
400
401 static void mp3amp_recv(t_mp3amp *x)
402 {
403 int ret, i;
404 float resample = 0;
405 struct frame hframe;
406 unsigned int a,b,c,d;
407 unsigned long cheader;
408
409 #ifdef _WIN32
410 if(( ret = recv(x->x_fd, (char*)x->x_inbuffer + x->x_inwriteposition,
411 (x->x_inbuffersize-x->x_inwriteposition), 0)) < 0)
412 #else
413 if ( ( ret = recv(x->x_fd, (void*) (x->x_inbuffer + x->x_inwriteposition),
414 (size_t)((x->x_inbuffersize-x->x_inwriteposition)),
415 MSG_NOSIGNAL) ) < 0 )
416 #endif
417 {
418 post( "mp3amp~: receive error" );
419 #ifndef _MSC_VER
420 perror( "recv" );
421 #endif
422 mp3amp_disconnect(x);
423 return;
424 }
425 else
426 {
427
428 // post( "mp3amp~: received %d bytes at %d on %d ( up to %d)",
429 // ret, x->x_inwriteposition, x->x_fd,
430 // x->x_inbuffersize-x->x_inwriteposition );
431
432 if ( ret == 0 && ( x->x_inbuffersize-x->x_inwriteposition != 0 ) )
433 {
•434 pd_error(x, "mp3amp~: stream lost...");
435 mp3amp_disconnect(x);
436 }
437 else
438 {
439 // check if we should decode those packets
440 if ( x->x_standby )
441 {
442 return;
443 }
444 // check we don't overflow input buffer
445 if ( ( x->x_inwriteposition + ret ) > x->x_inbuffersize*0.9 )
446 {
447 post( "mp3streamin~ : too much input...resetting" );
448 x->x_inwriteposition=0;
449 x->x_offset = 0;
450 x->x_inframes = 0;
451 return;
452 }
453 x->x_inwriteposition += ret;
454 x->x_offset = 0;
455 // check some parameters in the stream
456 while ( x->x_offset < x->x_inwriteposition )
457 {
458 /* decode first 4 bytes as the header */
459 a = *((unsigned char*)x->x_inbuffer+x->x_offset);
460 b = *((unsigned char*)x->x_inbuffer+x->x_offset+1);
461 c = *((unsigned char*)x->x_inbuffer+x->x_offset+2);
462 d = *((unsigned char*)x->x_inbuffer+x->x_offset+3);
463
464 cheader = 0;
465 cheader = a;
466 cheader <<= 8;
467 cheader |= b;
468 cheader <<= 8;
469 cheader |= c;
470 cheader <<= 8;
471 cheader |= d;
472 if ( head_check( cheader, 0 ) )
473 {
474 decode_header( &hframe, cheader );
475 // print_header_compact( &hframe );
476 x->x_packetsize = hframe.framesize;
477 if ( hframe.framesize == 0 )
478 {
479 post( "mp3amp~: weird header ( frame size = 0 ) .... ignored" );
480 x->x_inwriteposition -= ret;
481 return;
482 }
483 x->x_inframes += ret/x->x_packetsize;
484 // post( "mp3amp~: nb frames %d", x->x_inframes );
485 break;
486 }
487 x->x_offset++;
488 }
489 }
490 }
491 }
492
493 static t_int *mp3amp_perform(t_int *w)
494 {
495 t_mp3amp *x = (t_mp3amp*) (w[1]);
496 t_float *out1 = (t_float *)(w[2]);
497 t_float *out2 = (t_float *)(w[3]);
498 int n = (int)(w[4]);
499 int ret;
500 int i = 0;
501
502 x->x_blocksize = n;
503 x->x_nbwaitloops = LAME_AUDIO_CHUNK_SIZE/x->x_blocksize;
504 // post( "mp3mp3amp~ : will wait %d loops", x->x_nbwaitloops );
505 x->x_dsp++;
506
507 while( n-- )
508 {
509 if(x->x_stream && !x->x_standby ) // check that the stream provides enough data
510 {
511 if(x->x_resample == 1) /* don't need to resample */
512 {
513 *out1++=*(x->x_outbuffer+x->x_outreadposition);
514 x->x_outreadposition = (x->x_outreadposition + 1)%x->x_outbuffersize;
515 *out2++=*(x->x_outbuffer+x->x_outreadposition);
516 x->x_outreadposition = (x->x_outreadposition + 1)%x->x_outbuffersize;
517 x->x_outunread-=2;
518 }
519 else
520 {
521 /* we just use the same sample x->x_resample times */
522 *out1++=*(x->x_outbuffer+x->x_outreadposition);
523 *out2++=*(x->x_outbuffer+((x->x_outreadposition + 1)%x->x_outbuffersize));
524 if((n%x->x_resample)== 0)
525 {
526 x->x_outreadposition = (x->x_outreadposition + 2)%x->x_outbuffersize;
527 x->x_outunread-=2;
528 }
529 }
530 if ( n == 1 ) x->x_pblocks++;
531 }
532 else
533 {
534 *out1++=0.0;
535 *out2++=0.0;
536 }
537 }
538
539 if ( x->x_pblocks == LAME_AUDIO_CHUNK_SIZE/x->x_blocksize )
540 {
541 x->x_pblocks = 0;
542 }
543
544 /* check for readability, then fill the input buffer */
545 if(( x->x_fd > 0 )&&(x->x_dsp >= 16)) /* determine how often we try to read */
546 {
547 fd_set readset;
548 fd_set exceptset;
549
550 FD_ZERO(&readset);
551 FD_ZERO(&exceptset);
552 FD_SET(x->x_fd, &readset );
553 FD_SET(x->x_fd, &exceptset );
554
555 x->x_dsp = 0;
556
557 if ( select( x->x_fd+1, &readset, NULL, &exceptset, &ztout ) >0 )
558 {
559 if ( FD_ISSET( x->x_fd, &readset) || FD_ISSET( x->x_fd, &exceptset ) )
560 {
561 /* receive data or error */
562 mp3amp_recv(x);
563 }
564 }
565 }
566
567 // check new incoming data
568 if ( x->x_fd > 0 && ( x->x_nbloops == 0 ) && ( x->x_inframes > 0 ) && ( !x->x_standby ) )
569 {
570 mp3amp_decode_input(x);
571 }
572 if ( x->x_nbwaitloops != 0 )
573 {
574 x->x_nbloops = (x->x_nbloops+1 ) % x->x_nbwaitloops;
575 }
576 return (w+5);
577 }
578
579 static void mp3amp_dsp(t_mp3amp *x, t_signal **sp)
580 {
581 dsp_add(mp3amp_perform, 4, x, sp[1]->s_vec, sp[2]->s_vec, sp[1]->s_n);
582 }
583
584
585 /* freeze decoding */
586 static void mp3amp_standby(t_mp3amp *x, t_floatarg fstandby )
587 {
588 if ( fstandby == 0. )
589 {
590 x->x_standby = 0;
591 }
592 else
593 {
594 x->x_standby = 1;
595 }
596 }
597
598 /* connection main procedure executed by a thread */
599 static void *mp3amp_do_connect(void *tdata )
600 {
601 t_mp3amp *x = (t_mp3amp*) tdata;
602 struct sockaddr_in server;
603 struct hostent *hp;
604 t_int portno = x->x_port; /* get port from message box */
605
606 /* variables used for communication with server */
607 char *sptr = NULL;
608 char request[STRBUF_SIZE]; /* string to be send to server */
609 char *url; /* used for relocation */
610 fd_set fdset;
611 struct timeval tv;
612 t_int sockfd; /* socket to server */
613 t_int relocate, numrelocs = 0;
614 t_int i, ret, rest, nanswers=0;
615 char *cpoint = NULL;
616 t_int offset = 0, endofheaders = 0;
617
618 if (x->x_fd >= 0)
619 {
•620 pd_error(x, "mp3amp~: already connected");
621 return NULL;
622 }
623
624 sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
625 if (sockfd < 0)
626 {
•627 pd_error(x, "mp3amp~: internal error while attempting to open socket");
628 return NULL;
629 }
630
631 /* connect socket using hostname provided in command line */
632 server.sin_family = AF_INET;
633 hp = gethostbyname(x->x_hostname);
634 if (hp == 0)
635 {
636 post("mp3amp~: bad host?");
637 sys_closesocket(sockfd);
638 return NULL;
639 }
640 memcpy((char *)&server.sin_addr, (char *)hp->h_addr, hp->h_length);
641
642 /* assign client port number */
643 server.sin_port = htons((unsigned short)portno);
644
645 /* try to connect. */
646 post("mp3amp~: connecting to http:/%s:%d/%s", x->x_hostname, x->x_port, x->x_mountpoint );
647 if (connect(sockfd, (struct sockaddr *) &server, sizeof (server)) < 0)
648 {
•649 pd_error(x, "mp3amp~: connection failed!\n");
650 sys_closesocket(sockfd);
651 return NULL;
652 }
653 post("mp3amp~: connected : socket opened" );
654
655 /* sheck if we can read/write from/to the socket */
656 FD_ZERO( &fdset);
657 FD_SET( sockfd, &fdset);
658 tv.tv_sec = 0; /* seconds */
659 tv.tv_usec = 500; /* microseconds */
660
661 ret = select(sockfd + 1, &fdset, NULL, NULL, &tv);
662 if(ret != 0)
663 {
•664 pd_error(x, "mp3amp~: can not read from socket");
665 sys_closesocket(sockfd);
666 return NULL;
667 }
668 post("mp3amp~: select done" );
669
670 /* check mountpoint */
671 if( strstr(x->x_mountpoint, "listen.pls") )
672 {
673 /* SHOUTcast playlist -> get / */
674 x->x_mountpoint = "";
675 }
676
677 /* build up stuff we need to send to server */
678 sprintf(request, "GET /%s HTTP/1.0 \r\nHost: %s\r\nUser-Agent: mp3amp~ 0.11\r\nAccept: */*\r\n\r\n",
679 x->x_mountpoint, x->x_hostname);
680
681 if ( send(sockfd, request, strlen(request), 0) < 0 ) /* say hello to server */
682 {
683 post( "mp3amp~: could not contact server... " );
684 #ifndef _MSC_VER
685 perror( "send" );
686 #endif
687 return NULL;
688 }
689 post("mp3amp~: send done" );
690
691 relocate = FALSE;
692 memset( request, 0x00, STRBUF_SIZE );
693
694 // read all the answer
695 endofheaders=0;
696 while ( !endofheaders )
697 {
698 if( ( ret = recv(sockfd, request+offset, STRBUF_SIZE, MSG_NOSIGNAL) ) <0)
699 {
•700 pd_error(x, "mp3amp~: no response from server");
701 #ifndef _MSC_VER
702 perror( "recv" );
703 #endif
704 return NULL;
705 }
706 post ( "mp3amp~ : received %d bytes at %d", ret, offset );
707 for ( i=offset; i<offset+ret-1; i++ )
708 {
709 if ( ( request[i] == '\n' && request[i+1] == '\n' ) ||
710 ( request[i] == 10 && request[i+1] == 13 ) )
711 {
712 endofheaders=1;
713 }
714 }
715 offset+=ret;
716 }
717
718 // time to parse content of the response...
719 if ( strstr(request, "audio/x-scpls") ) /* SHOUTcast playlist */
720 {
721 /* playlist playing not supported */
722 post("mp3amp~: SHOUTcast server returned a playlist, quitting");
723 sys_closesocket(sockfd);
724 return NULL;
725 }
726 if ( strstr(request, "HTTP") ) /* seems to be IceCast server */
727 {
728 strip_ice_header(request, STRBUF_SIZE);
729 if(sptr = strstr(request, "302"))
730 {
731 cpoint = NULL;
732 cpoint = strstr(request, "Location:");
733 if ( cpoint == NULL )
734 {
735 post( "mp3amp~ : stream has moved but couldn't find new location out of this :" );
736 post("mp3amp~: %s", request );
737 return NULL;
738 }
739 url = strdup(cpoint + 10);
740 post("mp3amp~: relocating to %s", url);
741 sys_closesocket(sockfd);
742 x->x_nooutput = 1;
743 mp3amp_connect_url(x, gensym(url));
744 x->x_nooutput = 0;
745 return NULL;
746 // relocate = TRUE;
747 }
748 if( !(sptr = strstr(request, "200")) && !relocate )
749 {
•750 pd_error(x, "mp3amp~: cannot connect to the (default) stream");
751 return NULL;
752 }
753
754 post("mp3amp~: IceCast server detected");
755
756 // post("mp3amp~: server's header : %s", request );
757
758 // check what we got
759 if( cpoint = strstr(request, "x-audiocast-mount:"))
760 {
761 x->x_mountpoint = strdup(cpoint + 18);
762 for ( i=0; i<(int)strlen(x->x_mountpoint); i++ )
763 {
764 if ( x->x_mountpoint[i] == '\n' )
765 {
766 x->x_mountpoint[i] = '\0';
767 break;
768 }
769 }
770 post(" mountpoint: %s", x->x_mountpoint);
771 }
772 if( cpoint = strstr(request, "x-audiocast-server-url:"))
773 {
774 sptr = strdup( cpoint + 24);
775 for ( i=0; i<(int)strlen(sptr); i++ )
776 {
777 if ( sptr[i] == '\n' )
778 {
779 sptr[i] = '\0';
780 break;
781 }
782 }
783 post(" server-url: %s", sptr);
784 }
785 if( cpoint = strstr(request, "x-audiocast-location:"))
786 {
787 sptr = strdup( cpoint + 22);
788 for ( i=0; i<(int)strlen(sptr); i++ )
789 {
790 if ( sptr[i] == '\n' )
791 {
792 sptr[i] = '\0';
793 break;
794 }
795 }
796 post(" location: %s", sptr);
797 }
798 if( cpoint = strstr(request, "x-audiocast-admin:"))
799 {
800 sptr = strdup( cpoint + 19);
801 for ( i=0; i<(int)strlen(sptr); i++ )
802 {
803 if ( sptr[i] == '\n' )
804 {
805 sptr[i] = '\0';
806 break;
807 }
808 }
809 post(" admin: %s", sptr);
810 }
811 if( cpoint = strstr(request, "x-audiocast-name:"))
812 {
813 x->x_bcname = strdup( cpoint + 17);
814 for ( i=0; i<(int)strlen(x->x_bcname); i++ )
815 {
816 if ( x->x_bcname[i] == '\n' )
817 {
818 x->x_bcname[i] = '\0';
819 break;
820 }
821 }
822 post(" name: %s", x->x_bcname);
823 }
824 if( cpoint = strstr(request, "x-audiocast-genre:"))
825 {
826 x->x_bcgenre = strdup( cpoint + 18);
827 for ( i=0; i<(int)strlen(x->x_bcgenre); i++ )
828 {
829 if ( x->x_bcgenre[i] == '\n' )
830 {
831 x->x_bcgenre[i] = '\0';
832 break;
833 }
834 }
835 post(" genre: %s", x->x_bcgenre);
836 }
837 if( cpoint = strstr(request, "x-audiocast-url:"))
838 {
839 x->x_bcurl = strdup( cpoint + 16);
840 for ( i=0; i<(int)strlen(x->x_bcurl); i++ )
841 {
842 if ( x->x_bcurl[i] == '\n' )
843 {
844 x->x_bcurl[i] = '\0';
845 break;
846 }
847 }
848 post(" url: %s", x->x_bcurl);
849 }
850 if( cpoint = strstr(request, "x-audiocast-public:1"))
851 {
852 post(" broadcast is public");
853 }
854 else if( cpoint = strstr(request, "x-audiocast-public:0"))
855 {
856 post(" broadcast is NOT public");
857 }
858 if( cpoint = strstr(request, "x-audiocast-bitrate:"))
859 {
860 sptr = strdup( cpoint + 20);
861 for ( i=0; i<(int)strlen(sptr); i++ )
862 {
863 if ( sptr[i] == '\n' )
864 {
865 sptr[i] = '\0';
866 break;
867 }
868 }
869 if(!strncmp(sptr, "320", 3))x->x_bitrate = 320;
870 else if(!strncmp(sptr, "256", 3))x->x_bitrate = 256;
871 else if(!strncmp(sptr, "224", 3))x->x_bitrate = 224;
872 else if(!strncmp(sptr, "192", 3))x->x_bitrate = 192;
873 else if(!strncmp(sptr, "160", 3))x->x_bitrate = 160;
874 else if(!strncmp(sptr, "144", 3))x->x_bitrate = 144;
875 else if(!strncmp(sptr, "128", 3))x->x_bitrate = 128;
876 else if(!strncmp(sptr, "112", 3))x->x_bitrate = 112;
877 else if(!strncmp(sptr, "96", 2))x->x_bitrate = 96;
878 else if(!strncmp(sptr, "80", 2))x->x_bitrate = 80;
879 else if(!strncmp(sptr, "64", 2))x->x_bitrate = 64;
880 else if(!strncmp(sptr, "56", 2))x->x_bitrate = 56;
881 else if(!strncmp(sptr, "48", 2))x->x_bitrate = 48;
882 else if(!strncmp(sptr, "40", 2))x->x_bitrate = 40;
883 else if(!strncmp(sptr, "32", 2))x->x_bitrate = 32;
884 else if(!strncmp(sptr, "24", 2))x->x_bitrate = 24;
885 else if(!strncmp(sptr, "16", 2))x->x_bitrate = 16;
886 else if(!strncmp(sptr, "8", 1))x->x_bitrate = 8;
887 else
888 {
889 post("mp3amp~: unsupported bitrate! : %s", sptr);
890 return NULL;
891 }
892 post(" bitrate: %d", x->x_bitrate);
893 }
894 if( cpoint = strstr(request, "x-audiocast-udpport:"))
895 {
896 post("mp3amp~: sorry, server wants UDP connection!");
897 return NULL;
898 }
899 }
900 else /* it is a SHOUTcast server */
901 {
902 strip_shout_header (request, STRBUF_SIZE);
903 post("mp3amp~: SHOUTcast server detected");
904 if(strstr(request, "ICY 401") != 0)
905 {
906 post("mp3amp~: ICY 401 Service Unavailable");
907 return NULL;
908 }
909 if (strstr(request, "ICY 200 OK"))
910 {
911 /* recv and decode info about broadcast line by line */
912 post("mp3amp~: connecting to stream...");
913 i = ret;
914 /* check what we got */
915
916 if( cpoint = strstr(request, "icy-name:"))
917 {
918 x->x_bcname = strdup( cpoint + 10);
919 for ( i=0; i<(int)strlen(x->x_bcname); i++ )
920 {
921 if ( x->x_bcname[i] == '\n' )
922 {
923 x->x_bcname[i] = '\0';
924 break;
925 }
926 }
927 post(" name: %s", x->x_bcname);
928 }
929 if( cpoint = strstr(request, "x-audiocast-name:"))
930 {
931 x->x_bcname = strdup( cpoint + 18);
932 for ( i=0; i<(int)strlen(x->x_bcname); i++ )
933 {
934 if ( x->x_bcname[i] == '\n' )
935 {
936 x->x_bcname[i] = '\0';
937 break;
938 }
939 }
940 post(" name: %s", x->x_bcname);
941 }
942 if( cpoint = strstr(request, "icy-genre:"))
943 {
944 x->x_bcgenre = strdup( cpoint + 10);
945 for ( i=0; i<(int)strlen(x->x_bcgenre); i++ )
946 {
947 if ( x->x_bcgenre[i] == '\n' )
948 {
949 x->x_bcgenre[i] = '\0';
950 break;
951 }
952 }
953 post(" name: %s", x->x_bcname);
954 }
955 if( cpoint = strstr(request, "icy-aim:"))
956 {
957 x->x_bcaim = strdup( cpoint + 8);
958 for ( i=0; i<(int)strlen(x->x_bcaim); i++ )
959 {
960 if ( x->x_bcaim[i] == '\n' )
961 {
962 x->x_bcaim[i] = '\0';
963 break;
964 }
965 }
966 post(" name: %s", x->x_bcname);
967 }
968 if( cpoint = strstr(request, "icy-url:"))
969 {
970 x->x_bcurl = strdup( cpoint + 8);
971 for ( i=0; i<(int)strlen(x->x_bcurl); i++ )
972 {
973 if ( x->x_bcurl[i] == '\n' )
974 {
975 x->x_bcurl[i] = '\0';
976 break;
977 }
978 }
979 post(" name: %s", x->x_bcname);
980 }
981 if(strstr(request, "icy-pub:1"))
982 {
983 post(" broadcast is public");
984 }
985 else if(strstr(request, "icy-pub:0"))
986 {
987 post(" broadcast is NOT public");
988 }
989 if( cpoint = strstr(request, "icy-br:"))
990 {
991 sptr = strdup( cpoint + 7);
992 if(!strncmp(sptr, "320", 3))x->x_bitrate = 320;
993 else if(!strncmp(sptr, "256", 3))x->x_bitrate = 256;
994 else if(!strncmp(sptr, "224", 3))x->x_bitrate = 224;
995 else if(!strncmp(sptr, "192", 3))x->x_bitrate = 192;
996 else if(!strncmp(sptr, "160", 3))x->x_bitrate = 160;
997 else if(!strncmp(sptr, "144", 3))x->x_bitrate = 144;
998 else if(!strncmp(sptr, "128", 3))x->x_bitrate = 128;
999 else if(!strncmp(sptr, "112", 3))x->x_bitrate = 112;
1000 else if(!strncmp(sptr, "96", 2))x->x_bitrate = 96;
1001 else if(!strncmp(sptr, "80", 2))x->x_bitrate = 80;
1002 else if(!strncmp(sptr, "64", 2))x->x_bitrate = 64;
1003 else if(!strncmp(sptr, "56", 2))x->x_bitrate = 56;
1004 else if(!strncmp(sptr, "48", 2))x->x_bitrate = 48;
1005 else if(!strncmp(sptr, "40", 2))x->x_bitrate = 40;
1006 else if(!strncmp(sptr, "32", 2))x->x_bitrate = 32;
1007 else if(!strncmp(sptr, "24", 2))x->x_bitrate = 24;
1008 else if(!strncmp(sptr, "16", 2))x->x_bitrate = 16;
1009 else if(!strncmp(sptr, "8", 2))x->x_bitrate = 8;
1010 else
1011 {
1012 post("mp3amp~: unsupported bitrate! (%s)", sptr);
1013 return NULL;
1014 }
1015 post(" bitrate: %d", x->x_bitrate);
1016 }
1017 if(strstr(request, "x-audiocast-udpport:"))
1018 {
1019 post("mp3amp~: sorry, server wants UDP connection!");
1020 return NULL;
1021 }
1022 }
1023 else
1024 {
1025 post("mp3amp~: unknown response from server");
1026 return NULL;
1027 }
1028 relocate = FALSE;
1029 }
1030 if (relocate)
1031 {
•1032 pd_error(x, "mp3amp~: too many HTTP relocations");
1033 return NULL;
1034 }
1035 post("mp3amp~: connected to http://%s:%d/%s", hp->h_name, portno, x->x_mountpoint);
1036 x->x_fd = sockfd;
1037 if ( x->x_graphic && glist_isvisible( x->x_canvas ) )
1038 {
1039 t_int width;
1040
1041 width = rtext_width( glist_findrtext( (t_glist*)x->x_canvas, (t_text *)x ) );
1042 SYS_VGUI3(".x%lx.c delete rectangle %xPBAR\n", x->x_canvas, x );
1043 SYS_VGUI7(".x%lx.c create rectangle %d %d %d %d -fill lightblue -tags %xPBAR\n",
1044 x->x_canvas, x->x_obj.te_xpix, x->x_obj.te_ypix-BARHEIGHT-1,
1045 x->x_obj.te_xpix + width, x->x_obj.te_ypix - 1, x );
1046 }
1047
1048 return NULL;
1049 }
1050
1051 /* launch the connection thread */
1052 static void mp3amp_connect(t_mp3amp *x, t_symbol *hostname, t_symbol *mountpoint, t_floatarg fportno )
1053 {
1054 pthread_attr_t update_child_attr;
1055 pthread_t connectchild;
1056
1057 // store data
1058 x->x_hostname = (char*) getbytes( strlen( hostname->s_name ) + 1 ); // there's a memory leak here
1059 strcpy( x->x_hostname, hostname->s_name );
1060
1061 x->x_mountpoint = (char*) getbytes( strlen( mountpoint->s_name ) + 1 ); // there's a memory leak here
1062 strcpy( x->x_mountpoint, mountpoint->s_name );
1063
1064 x->x_port = fportno;
1065
1066 // launch connection thread
1067 if ( pthread_attr_init( &update_child_attr ) < 0 )
1068 {
1069 post( "mp3amp~ : could not launch connection thread" );
1070 perror( "pthread_attr_init" );
1071 return;
1072 }
1073 if ( pthread_attr_setdetachstate( &update_child_attr, PTHREAD_CREATE_DETACHED ) < 0 )
1074 {
1075 post( "mp3amp~ : could not launch connection thread" );
1076 perror( "pthread_attr_setdetachstate" );
1077 return;
1078 }
1079 if ( pthread_create( &connectchild, &update_child_attr, mp3amp_do_connect, x ) < 0 )
1080 {
1081 post( "mp3amp~ : could not launch connection thread" );
1082 perror( "pthread_create" );
1083 return;
1084 }
1085 else
1086 {
1087 // post( "cooled~ : drawing thread %d launched", (int)x->x_updatechild );
1088 }
1089
1090 if ( !x->x_nooutput ) outlet_float(x->x_connection, 1);
1091 }
1092
1093 /* connect using url like "http://localhost:8000/mountpoint" */
1094 static void mp3amp_connect_url(t_mp3amp *x, t_symbol *url)
1095 {
1096 char *hostptr = NULL, *p, *endhost = NULL, *hostname = NULL;
1097 char *pathptr = NULL;
1098 t_int portno = 8000;
1099
1100 post( "mp3amp~ : connect url : %s", url->s_name );
1101
1102 /* strip http:// or ftp:// */
1103 p = url->s_name;
1104 if (strncmp(p, "http://", 7) == 0)
1105 p += 7;
1106
1107 if (strncmp(p, "ftp://", 6) == 0)
1108 p += 6;
1109
1110 hostptr = p;
1111 while (*p && *p != '/' && *p != ':') /* look for end of hostname: */
1112 p++;
1113
1114 endhost = p;
1115 switch ( *p )
1116 {
1117 case ':' :
1118 portno = atoi( p+1 );
1119 while (*p && *p != '/') p++;
1120 pathptr = p+1;
1121 break;
1122 case '/' :
1123 portno = 8000;
1124 pathptr = p+1;
1125 break;
1126 default :
1127 if ( ( p - url->s_name ) != (int)strlen( url->s_name ) )
1128 {
1129 post( "mp3amp~ : wrong url : %s", hostptr );
1130 return;
1131 }
1132 pathptr = "";
1133 break;
1134 }
1135
1136 hostname=(char*)getbytes( (int)(endhost - hostptr) + 1);
1137 strncpy( hostname, hostptr, (int)(endhost - hostptr) );
1138 hostname[ endhost - hostptr ] = '\0';
1139
1140 post ("mp3amp~ : connecting to host=%s port=%d path=%s", hostname, portno, pathptr );
1141
1142 /* call the 'normal' connection routine */
1143 mp3amp_connect(x, gensym(hostname), gensym(pathptr), portno);
1144 }
1145
1146 /* close connection to SHOUTcast server */
1147 static void mp3amp_disconnect(t_mp3amp *x)
1148 {
1149 x->x_stream = 0;
1150 x->x_inframes = 0;
1151 x->x_dframes = 0;
1152 x->x_inwriteposition = 0;
1153 x->x_offset = 0;
1154 if(x->x_fd >= 0) /* close socket */
1155 {
1156 sys_closesocket(x->x_fd);
1157 x->x_fd = -1;
1158 }
1159 ExitMP3(&mps[x->x_instance]);
1160 InitMP3(&mps[x->x_instance]);
1161 if ( x->x_graphic )
1162 {
1163 SYS_VGUI3(".x%lx.c delete rectangle %xPBAR\n", x->x_canvas, x );
1164 SYS_VGUI3(".x%lx.c delete rectangle %xSTATUS\n", x->x_canvas, x );
1165 }
1166 post("mp3amp~: connection closed");
1167 outlet_float(x->x_connection, 0);
1168 }
1169
1170 static void mp3amp_free(t_mp3amp *x)
1171 {
1172 if (x->x_fd > 0)
1173 {
1174 post( "mp3amp~: closing socket" );
1175 sys_closesocket(x->x_fd);
1176 x->x_fd = -1;
1177 }
1178 freebytes(x->x_inbuffer, INPUT_BUFFER_SIZE);
1179 freebytes(x->x_outbuffer, OUTPUT_BUFFER_SIZE*sizeof(t_float));
1180 }
1181
1182 static void *mp3amp_new(t_floatarg fdographics)
1183 {
1184 t_mp3amp *x = NULL;
1185
1186 if ( ((int)fdographics != 0) && ((int)fdographics != 1.) )
1187 {
1188 post( "mp3amp~: error : constructor : mp3amp~ [graphic flag = 0 | 1 ] ( got = %f)", fdographics );
1189 return NULL;
1190 }
1191
1192 x = (t_mp3amp *)pd_new(mp3amp_class);
1193 outlet_new(&x->x_obj, gensym("signal"));
1194 outlet_new(&x->x_obj, gensym("signal"));
1195 x->x_connection = outlet_new(&x->x_obj, gensym("float"));
1196
1197 if ( nbinstances < MAX_DECODERS )
1198 {
1199 x->x_instance = nbinstances++;
1200 }
1201 else
1202 {
1203 post( "mp3amp~: cannot create more decoders (memory issues), sorry" );
1204 return NULL;
1205 }
1206
1207 x->x_fd = -1;
1208 x->x_stream = 0;
1209 x->x_inframes = 0;
1210 x->x_samplerate = sys_getsr();
1211 x->x_nbwaitloops = 1;
1212 x->x_nbloops = 0;
1213 x->x_dsp = 0;
1214
1215 x->x_inbuffersize = INPUT_BUFFER_SIZE;
1216 x->x_outbuffersize = OUTPUT_BUFFER_SIZE;
1217 x->x_inbuffer = (unsigned char*) getbytes(INPUT_BUFFER_SIZE);
1218 x->x_offset = 0;
1219 x->x_outbuffer = (t_float*) getbytes(OUTPUT_BUFFER_SIZE*sizeof(t_float));
1220
1221 if ( !x->x_inbuffer || !x->x_outbuffer )
1222 {
1223 post( "mp3amp~: could not allocate buffers" );
1224 return NULL;
1225 }
1226 memset( x->x_inbuffer, 0x0, INPUT_BUFFER_SIZE );
1227 memset( x->x_outbuffer, 0x0, OUTPUT_BUFFER_SIZE );
1228
1229 x->x_inwriteposition = 0;
1230 x->x_outreadposition = 0;
1231 x->x_outwriteposition = 0;
1232 x->x_outunread = 0;
1233 x->x_standby = 0;
1234 x->x_resample = -1;
1235 x->x_nooutput = 0;
1236
1237 ztout.tv_sec = 0;
1238 ztout.tv_usec = 0;
1239
1240 x->x_graphic = (int)fdographics;
1241 post( "mp3amp~: getting canvas" );
1242 x->x_canvas = canvas_getcurrent();
1243
1244 post( "mp3amp~: initializing decoder..." );
1245 /* init mpg123 decoder */
1246 mp3amp_tilde_mpglib_init(x);
1247
•1248 logpost(NULL, 4, "%s", mp3amp_version);
1249
1250 return (x);
1251 }
1252
1253
1254 void mp3amp_tilde_setup(void)
1255 {
1256 mp3amp_class = class_new(gensym("mp3amp~"),
1257 (t_newmethod) mp3amp_new, (t_method) mp3amp_free,
1258 sizeof(t_mp3amp), 0, A_DEFFLOAT, A_NULL);
1259
1260 class_addmethod(mp3amp_class, nullfn, gensym("signal"), 0);
1261 class_addmethod(mp3amp_class, (t_method)mp3amp_dsp, gensym("dsp"), 0);
1262 class_addmethod(mp3amp_class, (t_method)mp3amp_connect, gensym("connect"), A_SYMBOL, A_SYMBOL, A_FLOAT, 0);
1263 class_addmethod(mp3amp_class, (t_method)mp3amp_connect_url, gensym("connecturl"), A_SYMBOL, 0);
1264 class_addmethod(mp3amp_class, (t_method)mp3amp_standby, gensym("standby"), A_DEFFLOAT, 0);
1265 class_addmethod(mp3amp_class, (t_method)mp3amp_disconnect, gensym("disconnect"), 0);
1266 }