Debian Codegraph @

mp3write~.c

raw symbols ◀ ▶ SCIP
3 Debian patches touch this file
1 /* ------------------------ mp3write~ ----------------------------------------- */
2 /* */
3 /* Tilde object to record audio in mp3 format */
4 /* Note that it is, in no way, related to mp3play~ */
5 /* Written by Yves Degoyon ([email protected]). */
6 /* Tarballs and updates at http://ydegoyon.free.fr */
7 /* */
8 /* This program is free software; you can redistribute it and/or */
9 /* modify it under the terms of the GNU General Public License */
10 /* as published by the Free Software Foundation; either version 2 */
11 /* of the License, or (at your option) any later version. */
12 /* */
13 /* See file LICENSE for further informations on licensing terms. */
14 /* */
15 /* This program is distributed in the hope that it will be useful, */
16 /* but WITHOUT ANY WARRANTY; without even the implied warranty of */
17 /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
18 /* GNU General Public License for more details. */
19 /* */
20 /* You should have received a copy of the GNU General Public License */
21 /* along with this program; if not, write to the Free Software */
22 /* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
23 /* */
24 /* Based on PureData by Miller Puckette and others. */
25 /* Uses the LAME MPEG 1 Layer 3 version 3.92 */
26 /* Get it via http://www.freshmeat.net */
27 /* */
28 /* "All this talk of blood and iron is the cause of all my kicking" */
29 /* Gang Of Four - "Guns Before Butter" */
30 /* ---------------------------------------------------------------------------- */
31
32 #include <string.h>
33 #include <stdio.h>
34 #include <errno.h>
35 #include <stdlib.h>
36 #include <fcntl.h>
37 #include <sys/stat.h>
38 #ifndef __APPLE__
39 #include <malloc.h>
40 #endif
41 #include <ctype.h>
42 #ifdef _WIN32
43 #include <io.h>
44 #include <windows.h>
45 #include <winsock.h>
46 #include <windef.h>
47 #else
48 #include <sys/types.h>
49 #include <unistd.h>
50 #include <sys/socket.h>
51 #include <netinet/in.h>
52 #include <netdb.h>
53 #include <time.h>
54 #define SOCKET_ERROR -1
55 #endif /* _WIN32 */
56 #include <sys/time.h>
57 #include <lame/lame.h> /* lame encoder stuff */
58 #include "m_pd.h" /* standard pd stuff */
59
60 /* support older Pd versions without sys_fopen(), sys_fclose(), and, sys_close() */
61 #if PD_MAJOR_VERSION == 0 && PD_MINOR_VERSION < 44
62 #define sys_fopen fopen
63 #define sys_fclose fclose
64 #define sys_close close
65 #endif
66
67 #define MY_MP3_MALLOC_IN_SIZE 65536
68 /* max size taken from lame readme */
69 #define MY_MP3_MALLOC_OUT_SIZE 1.25*MY_MP3_MALLOC_IN_SIZE+7200
70
71 #define MAXDATARATE 320 /* maximum mp3 data rate is 320kbit/s */
72 #define STRBUF_SIZE 32
73
74 static char *mp3write_version = "mp3write~: mp3 file recorder version 0.4, written by Yves Degoyon";
75 static int sockfd;
76
77 static t_class *mp3write_class;
78
79 typedef struct _mp3write
80 {
81 t_object x_obj;
82
83 /* LAME stuff */
84 int x_lame; /* info about encoder status */
85 int x_lamechunk; /* chunk size for LAME encoder */
86
87 /* buffer stuff */
88 unsigned short x_inp; /* in position for buffer */
89 unsigned short x_outp; /* out position for buffer*/
90 short *x_mp3inbuf; /* data to be sent to LAME */
91 char *x_mp3outbuf; /* data returned by LAME -> our mp3 stream */
92 int x_mp3size; /* number of returned mp3 samples */
93 short *x_buffer; /* data to be buffered */
94 int x_bytesbuffered; /* number of unprocessed bytes in buffer */
95 int x_start;
96
97 /* mp3 format stuff */
98 int x_samplerate;
99 int x_bitrate; /* bitrate of mp3 stream */
100 int x_mp3mode; /* mode (mono, joint stereo, stereo, dual mono) */
101 int x_mp3quality; /* quality of encoding */
102
103 /* recording stuff */
104 int x_fd; /* file descriptor of the mp3 output */
105 int x_file_open_mode; /* file opening mode */
106 int x_byteswritten; /* number of bytes written */
107 int x_recflag; /* recording flag toggled by messages "start" and "stop" */
108
109 t_float x_f; /* float needed for signal input */
110 char *x_title; /* title of the mp3 */
111
112 lame_global_flags *lgfp; /* lame encoder configuration */
113 } t_mp3write;
114
115
116 /* encode PCM data to mp3 stream */
117 static void mp3write_encode(t_mp3write *x)
118 {
119 unsigned short i, wp;
120 int err = -1;
121 int n = x->x_lamechunk;
122
123 #ifdef _WIN32
124 if(x->x_lamechunk < sizeof(x->x_mp3inbuf))
125 #else
126 if(x->x_lamechunk < (int)sizeof(x->x_mp3inbuf))
127 #endif
128 {
•129 pd_error(x, "not enough memory!");
130 return;
131 }
132
133 /* on start/reconnect set outpoint so that it won't interfere with inpoint */
134 if(x->x_start == -1)
135 {
•136 post("mp3write~: resetting buffer positions");
137 /* we try to keep 2.5 times the data the encoder needs in the buffer */
138 if(x->x_inp > (2 * x->x_lamechunk))
139 {
140 x->x_outp = (short) x->x_inp - (2.5 * x->x_lamechunk);
141 }
142 else if(x->x_inp < (2 * x->x_lamechunk))
143 {
144 x->x_outp = (short) MY_MP3_MALLOC_IN_SIZE - (2.5 * x->x_lamechunk);
145 }
146 x->x_start = 1;
147 }
•148 if((unsigned short)(x->x_outp - x->x_inp) < x->x_lamechunk)pd_error(x, "mp3write~: buffers overlap!");
149
150 i = MY_MP3_MALLOC_IN_SIZE - x->x_outp;
151
152 /* read from buffer */
153 if(x->x_lamechunk <= i)
154 {
155 /* enough data until end of buffer */
156 for(n = 0; n < x->x_lamechunk; n++) /* fill encode buffer */
157 {
158 x->x_mp3inbuf[n] = x->x_buffer[n + x->x_outp];
159 }
160 x->x_outp += x->x_lamechunk;
161 }
162 else /* split data */
163 {
164 for(wp = 0; wp < i; wp++) /* data at end of buffer */
165 {
166 x->x_mp3inbuf[wp] = x->x_buffer[wp + x->x_outp];
167 }
168
169 for(wp = i; wp < x->x_lamechunk; wp++) /* write rest of data at beginning of buffer */
170 {
171 x->x_mp3inbuf[wp] = x->x_buffer[wp - i];
172 }
173 x->x_outp = x->x_lamechunk - i;
174 }
175
176 /* encode mp3 data */
177
178 x->x_mp3size = lame_encode_buffer_interleaved(x->lgfp, x->x_mp3inbuf,
179 x->x_lamechunk/lame_get_num_channels(x->lgfp),
180 x->x_mp3outbuf, MY_MP3_MALLOC_OUT_SIZE);
181 // post( "mp3write~ : encoding returned %d frames", x->x_mp3size );
182
183 /* check result */
184 if(x->x_mp3size<0)
185 {
186 lame_close( x->lgfp );
•187 pd_error(x, "mp3write~: lame_encode_buffer_interleaved failed (%d)", x->x_mp3size);
188 x->x_lame = -1;
189 }
190 }
191
192 /* store mp3 frames in the file */
193 static void mp3write_writeframes(t_mp3write *x)
194 {
195 int err = -1; /* error return code */
196
197 if ( x->x_fd < 0 )
198 {
199 post( "mp3write~ : error : trying to write frames but no valid file is opened" );
200 return;
201 }
202
203 #ifdef _WIN32
204 err = _write(x->x_fd, x->x_mp3outbuf, x->x_mp3size);
205 #else
206 err = write(x->x_fd, x->x_mp3outbuf, x->x_mp3size);
207 #endif
208
209 if(err < 0)
210 {
•211 pd_error(x, "mp3write~: could not write encoded data to file (%d)", err);
212 lame_close( x->lgfp );
213 x->x_lame = -1;
214 #ifdef _WIN32
•215 pd_error(x, "mp3write~: writing data");
216 _close(x->x_fd);
217 #else
218 perror("mp3write~: writing data");
219 close(x->x_fd);
220 #endif
221 x->x_fd = -1;
222 }
223 else
224 {
225 x->x_byteswritten += err;
226 outlet_float( x->x_obj.ob_outlet, x->x_byteswritten );
227 }
•228 if((err > 0)&&(err != x->x_mp3size))pd_error(x, "mp3write~: %d bytes skipped", x->x_mp3size - err);
229 }
230
231
232 /* buffer data as channel interleaved PCM */
233 static t_int *mp3write_perform(t_int *w)
234 {
235 t_float *in1 = (t_float *)(w[1]); /* left audio inlet */
236 t_float *in2 = (t_float *)(w[2]); /* right audio inlet */
237 t_mp3write *x = (t_mp3write *)(w[3]);
238 int n = (int)(w[4]); /* number of samples */
239 unsigned short i,wp;
240 float in;
241
242 /* copy the data into the buffer */
243 i = MY_MP3_MALLOC_IN_SIZE - x->x_inp; /* space left at the end of buffer */
244
245 n *= 2; /* two channels go into one buffer */
246
247 if( n <= i )
248 {
249 /* the place between inp and MY_MP3_MALLOC_IN_SIZE */
250 /* is big enough to hold the data */
251
252 for(wp = 0; wp < n; wp++)
253 {
254 if(wp%2)
255 {
256 in = *(in2++); /* right channel / inlet */
257 }
258 else
259 {
260 in = *(in1++); /* left channel / inlet */
261 }
262 if (in > 1.0)
263 {
264 in = 1.0;
265 }
266 if (in < -1.0)
267 {
268 in = -1.0;
269 }
270 x->x_buffer[wp + x->x_inp] = (short) (32767.0 * in);
271 }
272 x->x_inp += n; /* n more samples written to buffer */
273 }
274 else
275 {
276 /* the place between inp and MY_MP3_MALLOC_IN_SIZE is not */
277 /* big enough to hold the data */
278 /* writing will take place in two turns, one from */
279 /* x->x_inp -> MY_MP3_MALLOC_IN_SIZE, then from 0 on */
280
281 for(wp = 0; wp < i; wp++) /* fill up to end of buffer */
282 {
283 if(wp%2)
284 {
285 in = *(in2++);
286 }
287 else
288 {
289 in = *(in1++);
290 }
291 if (in > 1.0)
292 {
293 in = 1.0;
294 }
295 if (in < -1.0)
296 {
297 in = -1.0;
298 }
299 x->x_buffer[wp + x->x_inp] = (short) (32767.0 * in);
300 }
301 for(wp = i; wp < n; wp++) /* write rest at start of buffer */
302 {
303 if(wp%2)
304 {
305 in = *(in2++);
306 }
307 else
308 {
309 in = *(in1++);
310 }
311 if (in > 1.0)
312 {
313 in = 1.0;
314 }
315 if (in < -1.0)
316 {
317 in = -1.0;
318 }
319 x->x_buffer[wp - i] = (short) (32767.0 * in);
320 }
321 x->x_inp = n - i; /* new writeposition in buffer */
322 }
323
324 if((x->x_fd >= 0)&&(x->x_lame >= 0)&&(x->x_recflag))
325 {
326 /* count buffered samples when things are running */
327 x->x_bytesbuffered += n;
328
329 /* encode and send to server */
330 if(x->x_bytesbuffered > x->x_lamechunk)
331 {
332 mp3write_encode(x); /* encode to mp3 */
333 mp3write_writeframes(x); /* write mp3 to file */
334 x->x_bytesbuffered -= x->x_lamechunk;
335 }
336 }
337 else
338 {
339 x->x_start = -1;
340 }
341 return (w+5);
342 }
343
344 static void mp3write_dsp(t_mp3write *x, t_signal **sp)
345 {
346 dsp_add(mp3write_perform, 4, sp[0]->s_vec, sp[1]->s_vec, x, sp[0]->s_n);
347 }
348
349 /* initialize the lame library */
350 static int mp3write_tilde_lame_init(t_mp3write *x)
351 {
352 time_t now;
353
354 int ret;
355 x->lgfp = lame_init(); /* set default parameters for now */
356
357 #ifdef _WIN32
358 /* load lame_enc.dll library */
359 HINSTANCE dll;
360 dll=LoadLibrary("lame_enc.dll");
361 if(dll==NULL)
362 {
•363 pd_error(x, "mp3write~: error loading lame_enc.dll");
364 closesocket(x->x_fd);
365 x->x_fd = -1;
366 post("mp3write~: connection closed");
367 return -1;
368 }
369 #endif
370 {
371 const char *lameVersion = get_lame_version();
•372 logpost(NULL, 4, "%s", "mp3write~ : using lame version : %s", lameVersion );
373 }
374
375 /* setting lame parameters */
376 lame_set_num_channels( x->lgfp, 2);
377 lame_set_in_samplerate( x->lgfp, sys_getsr() );
378 lame_set_out_samplerate( x->lgfp, x->x_samplerate );
379 lame_set_brate( x->lgfp, x->x_bitrate );
380 lame_set_mode( x->lgfp, x->x_mp3mode );
381 lame_set_quality( x->lgfp, x->x_mp3quality );
382 lame_set_emphasis( x->lgfp, 1 );
383 lame_set_original( x->lgfp, 1 );
384 lame_set_copyright( x->lgfp, 1 ); /* viva free music societies !!! */
385 lame_set_disable_reservoir( x->lgfp, 0 );
386 //lame_set_padding_type( x->lgfp, PAD_NO ); /* deprecated in LAME */
387 ret = lame_init_params( x->lgfp );
388 if ( ret<0 )
389 {
390 post( "mp3write~ : error : lame params initialization returned : %d", ret );
391 return -1;
392 }
393 else
394 {
395 x->x_lame=1;
396 /* magic formula copied from windows dll for MPEG-I */
397 x->x_lamechunk = 2*1152;
398
399 post( "mp3write~ : lame initialization done. (%d)", x->x_lame );
400 }
401 lame_init_bitstream( x->lgfp );
402
403 /* setting tag information */
404 id3tag_init(x->lgfp);
405 id3tag_v1_only(x->lgfp);
406 id3tag_space_v1(x->lgfp);
407 id3tag_set_artist(x->lgfp, "Pd Session");
408 now=time(NULL);
409 sprintf( x->x_title, "Started at %s", ctime(&now) );
410 id3tag_set_title(x->lgfp, x->x_title );
411
412 return 0;
413
414 }
415
416 /* open file and initialize lame */
417 static void mp3write_open(t_mp3write *x, t_symbol *sfile)
418 {
419 if ( mp3write_tilde_lame_init(x) < 0 )
420 {
•421 pd_error(x, "mp3write~ : lame initialization failed ... check parameters.");
422 return;
423 }
424
425 /* closing previous file descriptor */
426 if ( x->x_fd > 0 )
427 {
428 if(sys_close(x->x_fd) < 0)
429 {
430 perror( "mp3write~ : closing file" );
431 }
432 }
433
434 if ( x->x_recflag )
435 {
436 x->x_recflag = 0;
437 }
438
439
440 #ifdef _WIN32
441 int mode = _S_IREAD|_S_IWRITE;
442 #else
443 int mode = S_IRWXU|S_IRWXG|S_IRWXO;
444 #endif
445 if ( ( x->x_fd = sys_open( sfile->s_name, x->x_file_open_mode, mode) ) < 0 )
446 {
•447 pd_error(x, "mp3write~ : cannot open >%s<", sfile->s_name);
448 x->x_fd=-1;
449 return;
450 }
451 x->x_byteswritten = 0;
452 post( "mp3write~ : opened >%s< fd=%d", sfile->s_name, x->x_fd);
453 }
454
455 /* setting file write mode to append */
456 static void mp3write_append(t_mp3write *x)
457 {
458 #ifdef _WIN32
459 x->x_file_open_mode = _O_CREAT|_O_WRONLY|_O_APPEND|_O_BINARY;
460 #else
461 x->x_file_open_mode = O_CREAT|O_WRONLY|O_APPEND|O_NONBLOCK;
462 #endif
463 if(x->x_fd>=0)post("mp3write~ : mode set to append : open a new file to make changes take effect! ");
464 }
465
466 /* setting file write mode to truncate */
467 static void mp3write_truncate(t_mp3write *x)
468 {
469 #ifdef _WIN32
470 x->x_file_open_mode = _O_CREAT|_O_WRONLY|_O_TRUNC|_O_BINARY;
471 #else
472 x->x_file_open_mode = O_CREAT|O_WRONLY|O_TRUNC|O_NONBLOCK;
473 #endif
474 if(x->x_fd>=0)post("mp3write~ : mode set to truncate : open a new file to make changes take effect! ");
475 }
476
477 /* settings for mp3 encoding */
478 static void mp3write_mpeg(t_mp3write *x, t_floatarg fsamplerate, t_floatarg fbitrate,
479 t_floatarg fmode, t_floatarg fquality)
480 {
481 x->x_samplerate = fsamplerate;
482 if(fbitrate > MAXDATARATE)
483 {
484 fbitrate = MAXDATARATE;
485 }
486 x->x_bitrate = fbitrate;
487 x->x_mp3mode = fmode;
488 x->x_mp3quality = fquality;
489 post("mp3write~: setting mp3 stream to %dHz, %dkbit/s, mode %d, quality %d",
490 x->x_samplerate, x->x_bitrate, x->x_mp3mode, x->x_mp3quality);
491 if(x->x_fd>=0)post("mp3write~ : restart recording to make changes take effect! ");
492 }
493
494 /* print settings */
495 static void mp3write_print(t_mp3write *x)
496 {
497 const char * buf = 0;
•498 logpost(NULL, 4, "%s", mp3write_version);
499 post(" LAME mp3 settings:\n"
500 " output sample rate: %d Hz\n"
501 " bitrate: %d kbit/s", x->x_samplerate, x->x_bitrate);
502 switch(x->x_mp3mode)
503 {
504 case 0 :
505 buf = "stereo";
506 break;
507 case 1 :
508 buf = "joint stereo";
509 break;
510 case 2 :
511 buf = "dual channel";
512 break;
513 case 3 :
514 buf = "mono";
515 break;
516 }
517 post(" mode: %s\n"
518 " quality: %d", buf, x->x_mp3quality);
519 #ifdef _WIN32
520 if(x->x_lamechunk!=0)post(" calculated mp3 chunk size: %d", x->x_lamechunk);
521 #else
522 post(" mp3 chunk size: %d", x->x_lamechunk);
523 #endif
524 if(x->x_samplerate!=sys_getsr())
525 {
526 post(" resampling from %d to %d Hz!", (int)sys_getsr(), x->x_samplerate);
527 }
528 }
529
530 /* start recording */
531 static void mp3write_start(t_mp3write *x)
532 {
533 if ( x->x_fd < 0 )
534 {
535 post("mp3write~: start received but no file has been set ... ignored.");
536 return;
537 }
538
539 if ( x->x_recflag == 1 )
540 {
541 post("mp3write~: start received but recording is started ... ignored.");
542 return;
543 }
544
545 x->x_recflag = 1;
546 post("mp3write~: start recording");
547 }
548
549 /* stop recording */
550 static void mp3write_stop(t_mp3write *x)
551 {
552 int err = -1;
553
554 if ( x->x_fd < 0 )
555 {
556 post("mp3write~: stop received but no file has been set ... ignored.");
557 return;
558 }
559
560 if ( x->x_recflag == 0 )
561 {
562 post("mp3write~: stop received but recording is stopped ... ignored.");
563 return;
564 }
565 /* first stop recording / buffering and so on, than do the rest */
566 x->x_recflag = 0;
567
568 /* flushing remaining frames and tag */
569 x->x_mp3size = lame_encode_flush( x->lgfp, x->x_mp3outbuf, MY_MP3_MALLOC_OUT_SIZE );
570
571 mp3write_writeframes(x); /* write mp3 to file */
572
573 x->x_recflag = 0;
574 post("mp3write~: stop recording, flushed %d bytes", x->x_mp3size);
575 }
576
577 /* clean up */
578 static void mp3write_free(t_mp3write *x)
579 {
580 if(x->x_lame >= 0)
581 lame_close( x->lgfp );
582 if(x->x_fd >= 0)
583 #ifdef _WIN32
584 _close(x->x_fd);
585 #else
586 close(x->x_fd);
587 #endif
588 freebytes(x->x_mp3inbuf, MY_MP3_MALLOC_IN_SIZE*sizeof(short));
589 freebytes(x->x_mp3outbuf, MY_MP3_MALLOC_OUT_SIZE);
590 freebytes(x->x_buffer, MY_MP3_MALLOC_IN_SIZE*sizeof(short));
591 freebytes( x->x_title, 255 );
592 }
593
594 static void *mp3write_new(void)
595 {
596 t_mp3write *x = (t_mp3write *)pd_new(mp3write_class);
597 inlet_new (&x->x_obj, &x->x_obj.ob_pd, gensym ("signal"), gensym ("signal"));
598 outlet_new (&x->x_obj, &s_float);
599 x->x_fd = -1;
600 #ifdef _WIN32
601 x->x_file_open_mode = _O_CREAT|_O_WRONLY|_O_APPEND|_O_BINARY;
602 #else
603 x->x_file_open_mode = O_CREAT|O_WRONLY|O_APPEND|O_NONBLOCK;
604 #endif
605 x->x_lame = -1;
606 x->x_samplerate = sys_getsr();
607 x->x_bitrate = 128;
608 x->x_byteswritten = 0;
609 x->x_mp3mode = 1;
610 x->lgfp = NULL;
611 x->x_title = getbytes( 255 );
612 x->x_mp3quality = 5;
613 x->x_mp3inbuf = getbytes(MY_MP3_MALLOC_IN_SIZE*sizeof(short)); /* buffer for encoder input */
614 x->x_mp3outbuf = getbytes(MY_MP3_MALLOC_OUT_SIZE*sizeof(char)); /* our mp3 stream */
615 x->x_buffer = getbytes(MY_MP3_MALLOC_IN_SIZE*sizeof(short)); /* what we get from pd, converted to PCM */
616 if ((!x->x_buffer)||(!x->x_mp3inbuf)||(!x->x_mp3outbuf)) /* check buffers... */
617 {
•618 pd_error(x, "mp3write~ : cannot allocate internal buffers");
619 return NULL;
620 }
621 x->x_bytesbuffered = 0;
622 x->x_inp = 0;
623 x->x_outp = 0;
624 x->x_start = -1;
625 return(x);
626 }
627
628 void mp3write_tilde_setup(void)
629 {
•630 logpost(NULL, 4, "%s", mp3write_version);
631 mp3write_class = class_new(gensym("mp3write~"), (t_newmethod)mp3write_new, (t_method)mp3write_free,
632 sizeof(t_mp3write), 0, 0);
633 CLASS_MAINSIGNALIN(mp3write_class, t_mp3write, x_f );
634 class_addmethod(mp3write_class, (t_method)mp3write_dsp, gensym("dsp"), 0);
635 class_addmethod(mp3write_class, (t_method)mp3write_open, gensym("open"), A_SYMBOL, 0);
636 class_addmethod(mp3write_class, (t_method)mp3write_mpeg, gensym("mpeg"), A_FLOAT, A_FLOAT, A_FLOAT, A_FLOAT, 0);
637 class_addmethod(mp3write_class, (t_method)mp3write_start, gensym("start"), 0);
638 class_addmethod(mp3write_class, (t_method)mp3write_stop, gensym("stop"), 0);
639 class_addmethod(mp3write_class, (t_method)mp3write_print, gensym("print"), 0);
640 class_addmethod(mp3write_class, (t_method)mp3write_append, gensym("append"), 0);
641 class_addmethod(mp3write_class, (t_method)mp3write_truncate, gensym("truncate"), 0);
642 }