when using record mode, allow file to save data to to be passed on the command line
[profile/ivi/pulseaudio.git] / src / utils / pacat.c
1 /* $Id$ */
2
3 /***
4   This file is part of polypaudio.
5  
6   polypaudio is free software; you can redistribute it and/or modify
7   it under the terms of the GNU Lesser General Public License as published
8   by the Free Software Foundation; either version 2 of the License,
9   or (at your option) any later version.
10  
11   polypaudio is distributed in the hope that it will be useful, but
12   WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14   General Public License for more details.
15  
16   You should have received a copy of the GNU Lesser General Public License
17   along with polypaudio; if not, write to the Free Software
18   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19   USA.
20 ***/
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <signal.h>
27 #include <string.h>
28 #include <errno.h>
29 #include <unistd.h>
30 #include <assert.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <getopt.h>
34 #include <fcntl.h>
35
36 #include <polyp/polypaudio.h>
37 #include <polyp/mainloop.h>
38 #include <polyp/mainloop-signal.h>
39
40 #if PA_API_VERSION != 8
41 #error Invalid Polypaudio API version
42 #endif
43
44 static enum { RECORD, PLAYBACK } mode = PLAYBACK;
45
46 static pa_context *context = NULL;
47 static pa_stream *stream = NULL;
48 static pa_mainloop_api *mainloop_api = NULL;
49
50 static void *buffer = NULL;
51 static size_t buffer_length = 0, buffer_index = 0;
52
53 static pa_io_event* stdio_event = NULL;
54
55 static char *stream_name = NULL, *client_name = NULL, *device = NULL;
56
57 static int verbose = 0;
58 static pa_volume_t volume = PA_VOLUME_NORM;
59
60 static pa_sample_spec sample_spec = {
61     .format = PA_SAMPLE_S16LE,
62     .rate = 44100,
63     .channels = 2
64 };
65
66 /* A shortcut for terminating the application */
67 static void quit(int ret) {
68     assert(mainloop_api);
69     mainloop_api->quit(mainloop_api, ret);
70 }
71
72 /* Write some data to the stream */
73 static void do_stream_write(size_t length) {
74     size_t l;
75     assert(length);
76
77     if (!buffer || !buffer_length)
78         return;
79     
80     l = length;
81     if (l > buffer_length)
82         l = buffer_length;
83     
84     if (pa_stream_write(stream, (uint8_t*) buffer + buffer_index, l, NULL, 0, PA_SEEK_RELATIVE) < 0) {
85         fprintf(stderr, "pa_stream_write() failed: %s\n", pa_strerror(pa_context_errno(context)));
86         quit(1);
87         return;
88     }
89     
90     buffer_length -= l;
91     buffer_index += l;
92     
93     if (!buffer_length) {
94         free(buffer);
95         buffer = NULL;
96         buffer_index = buffer_length = 0;
97     }
98 }
99
100 /* This is called whenever new data may be written to the stream */
101 static void stream_write_callback(pa_stream *s, size_t length, void *userdata) {
102     assert(s && length);
103
104     if (stdio_event)
105         mainloop_api->io_enable(stdio_event, PA_IO_EVENT_INPUT);
106
107     if (!buffer)
108         return;
109
110     do_stream_write(length);
111 }
112
113 /* This is called whenever new data may is available */
114 static void stream_read_callback(pa_stream *s, size_t length, void *userdata) {
115     const void *data;
116     assert(s && length);
117
118     if (stdio_event)
119         mainloop_api->io_enable(stdio_event, PA_IO_EVENT_OUTPUT);
120
121     if (pa_stream_peek(s, &data, &length) < 0) {
122         fprintf(stderr, "pa_stream_peek() failed: %s\n", pa_strerror(pa_context_errno(context)));
123         quit(1);
124         return;
125     }
126     
127     assert(data && length);
128
129     if (buffer) {
130         fprintf(stderr, "Buffer overrun, dropping incoming data\n");
131         if (pa_stream_drop(s) < 0) {
132             fprintf(stderr, "pa_stream_drop() failed: %s\n", pa_strerror(pa_context_errno(context)));
133             quit(1);
134         }
135         return;
136     }
137
138     buffer = malloc(buffer_length = length);
139     assert(buffer);
140     memcpy(buffer, data, length);
141     buffer_index = 0;
142     pa_stream_drop(s);
143 }
144
145 /* This routine is called whenever the stream state changes */
146 static void stream_state_callback(pa_stream *s, void *userdata) {
147     assert(s);
148
149     switch (pa_stream_get_state(s)) {
150         case PA_STREAM_CREATING:
151         case PA_STREAM_TERMINATED:
152             break;
153
154         case PA_STREAM_READY:
155             if (verbose)
156                 fprintf(stderr, "Stream successfully created\n");
157             break;
158             
159         case PA_STREAM_FAILED:
160         default:
161             fprintf(stderr, "Stream error: %s\n", pa_strerror(pa_context_errno(pa_stream_get_context(s))));
162             quit(1);
163     }
164 }
165
166 /* This is called whenever the context status changes */
167 static void context_state_callback(pa_context *c, void *userdata) {
168     assert(c);
169
170     switch (pa_context_get_state(c)) {
171         case PA_CONTEXT_CONNECTING:
172         case PA_CONTEXT_AUTHORIZING:
173         case PA_CONTEXT_SETTING_NAME:
174             break;
175         
176         case PA_CONTEXT_READY: {
177             int r;
178             
179             assert(c && !stream);
180
181             if (verbose)
182                 fprintf(stderr, "Connection established.\n");
183
184             if (!(stream = pa_stream_new(c, stream_name, &sample_spec, NULL))) {
185                 fprintf(stderr, "pa_stream_new() failed: %s\n", pa_strerror(pa_context_errno(c)));
186                 goto fail;
187             }
188
189             pa_stream_set_state_callback(stream, stream_state_callback, NULL);
190             pa_stream_set_write_callback(stream, stream_write_callback, NULL);
191             pa_stream_set_read_callback(stream, stream_read_callback, NULL);
192
193             if (mode == PLAYBACK) {
194                 pa_cvolume cv;
195                 if ((r = pa_stream_connect_playback(stream, device, NULL, 0, pa_cvolume_set(&cv, sample_spec.channels, volume), NULL)) < 0) {
196                     fprintf(stderr, "pa_stream_connect_playback() failed: %s\n", pa_strerror(pa_context_errno(c)));
197                     goto fail;
198                 }
199                     
200             } else {
201                 if ((r = pa_stream_connect_record(stream, device, NULL, 0)) < 0) {
202                     fprintf(stderr, "pa_stream_connect_record() failed: %s\n", pa_strerror(pa_context_errno(c)));
203                     goto fail;
204                 }
205             }
206                 
207             break;
208         }
209             
210         case PA_CONTEXT_TERMINATED:
211             quit(0);
212             break;
213
214         case PA_CONTEXT_FAILED:
215         default:
216             fprintf(stderr, "Connection failure: %s\n", pa_strerror(pa_context_errno(c)));
217             goto fail;
218     }
219
220     return;
221     
222 fail:
223     quit(1);
224     
225 }
226
227 /* Connection draining complete */
228 static void context_drain_complete(pa_context*c, void *userdata) {
229     pa_context_disconnect(c);
230 }
231
232 /* Stream draining complete */
233 static void stream_drain_complete(pa_stream*s, int success, void *userdata) {
234     pa_operation *o;
235
236     if (!success) {
237         fprintf(stderr, "Failed to drain stream: %s\n", pa_strerror(pa_context_errno(context)));
238         quit(1);
239     }
240     
241     if (verbose)    
242         fprintf(stderr, "Playback stream drained.\n");
243
244     pa_stream_disconnect(stream);
245     pa_stream_unref(stream);
246     stream = NULL;
247     
248     if (!(o = pa_context_drain(context, context_drain_complete, NULL)))
249         pa_context_disconnect(context);
250     else {
251         if (verbose)
252             fprintf(stderr, "Draining connection to server.\n");
253     }
254 }
255
256 /* New data on STDIN **/
257 static void stdin_callback(pa_mainloop_api*a, pa_io_event *e, int fd, pa_io_event_flags_t f, void *userdata) {
258     size_t l, w = 0;
259     ssize_t r;
260     assert(a == mainloop_api && e && stdio_event == e);
261
262     if (buffer) {
263         mainloop_api->io_enable(stdio_event, PA_IO_EVENT_NULL);
264         return;
265     }
266
267     if (!stream || pa_stream_get_state(stream) != PA_STREAM_READY || !(l = w = pa_stream_writable_size(stream)))
268         l = 4096;
269     
270     buffer = malloc(l);
271     assert(buffer);
272     if ((r = read(fd, buffer, l)) <= 0) {
273         if (r == 0) {
274             pa_operation *o;
275             
276             if (verbose)
277                 fprintf(stderr, "Got EOF.\n");
278             
279             if (!(o = pa_stream_drain(stream, stream_drain_complete, NULL))) {
280                 fprintf(stderr, "pa_stream_drain(): %s\n", pa_strerror(pa_context_errno(context)));
281                 quit(1);
282                 return;
283             }
284
285             pa_operation_unref(o);
286         } else {
287             fprintf(stderr, "read() failed: %s\n", strerror(errno));
288             quit(1);
289         }
290
291         mainloop_api->io_free(stdio_event);
292         stdio_event = NULL;
293         return;
294     }
295
296     buffer_length = r;
297     buffer_index = 0;
298
299     if (w)
300         do_stream_write(w);
301 }
302
303 /* Some data may be written to STDOUT */
304 static void stdout_callback(pa_mainloop_api*a, pa_io_event *e, int fd, pa_io_event_flags_t f, void *userdata) {
305     ssize_t r;
306     assert(a == mainloop_api && e && stdio_event == e);
307
308     if (!buffer) {
309         mainloop_api->io_enable(stdio_event, PA_IO_EVENT_NULL);
310         return;
311     }
312
313     assert(buffer_length);
314     
315     if ((r = write(fd, (uint8_t*) buffer+buffer_index, buffer_length)) <= 0) {
316         fprintf(stderr, "write() failed: %s\n", strerror(errno));
317         quit(1);
318
319         mainloop_api->io_free(stdio_event);
320         stdio_event = NULL;
321         return;
322     }
323
324     buffer_length -= r;
325     buffer_index += r;
326
327     if (!buffer_length) {
328         free(buffer);
329         buffer = NULL;
330         buffer_length = buffer_index = 0;
331     }
332 }
333
334 /* UNIX signal to quit recieved */
335 static void exit_signal_callback(pa_mainloop_api*m, pa_signal_event *e, int sig, void *userdata) {
336     if (verbose)
337         fprintf(stderr, "Got signal, exiting.\n");
338     quit(0);
339     
340 }
341
342 /* Show the current latency */
343 static void stream_update_timing_callback(pa_stream *s, int success, void *userdata) {
344     pa_usec_t total;
345     int negative = 0;
346     const pa_timing_info *i;
347     
348     assert(s);
349
350     if (!success ||
351         !(i = pa_stream_get_timing_info(s)) ||
352         pa_stream_get_latency(s, &total, &negative) < 0) {
353         fprintf(stderr, "Failed to get latency: %s\n", pa_strerror(pa_context_errno(context)));
354         quit(1);
355         return;
356     }
357
358     fprintf(stderr, "Latency: buffer: %0.0f usec; sink: %0.0f usec; source: %0.0f usec; transport: %0.0f usec; total: %0.0f usec; synchronized clocks: %s.\n",
359             (float) i->buffer_usec,
360             (float) i->sink_usec,
361             (float) i->source_usec,
362             (float) i->transport_usec,
363             (float) total * (negative?-1:1),
364             i->synchronized_clocks ? "yes" : "no");
365 }
366
367 /* Someone requested that the latency is shown */
368 static void sigusr1_signal_callback(pa_mainloop_api*m, pa_signal_event *e, int sig, void *userdata) {
369     pa_operation_unref(pa_stream_update_timing_info(stream, stream_update_timing_callback, NULL));
370 }
371
372
373 static void help(const char *argv0) {
374
375     printf("%s [options]\n\n"
376            "  -h, --help                            Show this help\n"
377            "      --version                         Show version\n\n"
378            "  -r, --record                          Create a connection for recording\n"
379            "  -p, --playback                        Create a connection for playback\n\n"
380            "  -v, --verbose                         Enable verbose operations\n\n"
381            "  -s, --server=SERVER                   The name of the server to connect to\n"
382            "  -d, --device=DEVICE                   The name of the sink/source to connect to\n"
383            "  -n, --client-name=NAME                How to call this client on the server\n"
384            "      --stream-name=NAME                How to call this stream on the server\n"
385            "      --volume=VOLUME                   Specify the initial (linear) volume in range 0...256\n"
386            "      --rate=SAMPLERATE                 The sample rate in Hz (defaults to 44100)\n"
387            "      --format=SAMPLEFORMAT             The sample type, one of s16le, s16be, u8, float32le,\n"
388            "                                        float32be, ulaw, alaw (defaults to s16ne)\n"
389            "      --channels=CHANNELS               The number of channels, 1 for mono, 2 for stereo\n"
390            "                                        (defaults to 2)\n",
391            argv0);
392 }
393
394 enum {
395     ARG_VERSION = 256,
396     ARG_STREAM_NAME,
397     ARG_VOLUME,
398     ARG_SAMPLERATE,
399     ARG_SAMPLEFORMAT,
400     ARG_CHANNELS
401 };
402
403 int main(int argc, char *argv[]) {
404     pa_mainloop* m = NULL;
405     int ret = 1, r, c;
406     char *bn, *server = NULL;
407
408     static const struct option long_options[] = {
409         {"record",      0, NULL, 'r'},
410         {"playback",    0, NULL, 'p'},
411         {"device",      1, NULL, 'd'},
412         {"server",      1, NULL, 's'},
413         {"client-name", 1, NULL, 'n'},
414         {"stream-name", 1, NULL, ARG_STREAM_NAME},
415         {"version",     0, NULL, ARG_VERSION},
416         {"help",        0, NULL, 'h'},
417         {"verbose",     0, NULL, 'v'},
418         {"volume",      1, NULL, ARG_VOLUME},
419         {"rate",        1, NULL, ARG_SAMPLERATE},
420         {"format",      1, NULL, ARG_SAMPLEFORMAT},
421         {"channels",    1, NULL, ARG_CHANNELS},
422         {NULL,          0, NULL, 0}
423     };
424
425     if (!(bn = strrchr(argv[0], '/')))
426         bn = argv[0];
427     else
428         bn++;
429
430     if (strstr(bn, "rec") || strstr(bn, "mon"))
431         mode = RECORD;
432     else if (strstr(bn, "cat") || strstr(bn, "play"))
433         mode = PLAYBACK;
434
435     while ((c = getopt_long(argc, argv, "rpd:s:n:hv", long_options, NULL)) != -1) {
436
437         switch (c) {
438             case 'h' :
439                 help(bn);
440                 ret = 0;
441                 goto quit;
442                 
443             case ARG_VERSION:
444                 printf("pacat "PACKAGE_VERSION"\nCompiled with libpolyp %s\nLinked with libpolyp %s\n", pa_get_headers_version(), pa_get_library_version());
445                 ret = 0;
446                 goto quit;
447
448             case 'r':
449                 mode = RECORD;
450                 break;
451
452             case 'p':
453                 mode = PLAYBACK;
454                 break;
455
456             case 'd':
457                 free(device);
458                 device = strdup(optarg);
459                 break;
460
461             case 's':
462                 free(server);
463                 server = strdup(optarg);
464                 break;
465
466             case 'n':
467                 free(client_name);
468                 client_name = strdup(optarg);
469                 break;
470
471             case ARG_STREAM_NAME:
472                 free(stream_name);
473                 stream_name = strdup(optarg);
474                 break;
475
476             case 'v':
477                 verbose = 1;
478                 break;
479
480             case ARG_VOLUME: {
481                 int v = atoi(optarg);
482                 volume = v < 0 ? 0 : v;
483                 break;
484             }
485
486             case ARG_CHANNELS: 
487                 sample_spec.channels = atoi(optarg);
488                 break;
489
490             case ARG_SAMPLEFORMAT:
491                 sample_spec.format = pa_parse_sample_format(optarg);
492                 break;
493
494             case ARG_SAMPLERATE:
495                 sample_spec.rate = atoi(optarg);
496                 break;
497
498             default:
499                 goto quit;
500         }
501     }
502
503     if (!client_name)
504         client_name = strdup(bn);
505
506     if (!stream_name)
507         stream_name = strdup(client_name);
508
509     if (!pa_sample_spec_valid(&sample_spec)) {
510         fprintf(stderr, "Invalid sample specification\n");
511         goto quit;
512     }
513     
514     if (verbose) {
515         char t[PA_SAMPLE_SPEC_SNPRINT_MAX];
516         pa_sample_spec_snprint(t, sizeof(t), &sample_spec);
517         fprintf(stderr, "Opening a %s stream with sample specification '%s'.\n", mode == RECORD ? "recording" : "playback", t);
518     }
519
520     if (!(optind >= argc)) {
521         if (optind+1 == argc) {
522             int fd;
523             
524             if ((fd = open(argv[optind], mode == PLAYBACK ? O_RDONLY : O_WRONLY|O_TRUNC|O_CREAT)) < 0) {
525                 fprintf(stderr, "open(): %s\n", strerror(errno));
526                 goto quit;
527             }
528             
529             if (dup2(fd, mode == PLAYBACK ? 0 : 1) < 0) {
530                 fprintf(stderr, "dup2(): %s\n", strerror(errno));
531                 goto quit;
532             }
533             
534             close(fd);
535         } else {
536             fprintf(stderr, "Too many arguments.\n");
537             goto quit;
538         }
539     }
540     
541     /* Set up a new main loop */
542     if (!(m = pa_mainloop_new())) {
543         fprintf(stderr, "pa_mainloop_new() failed.\n");
544         goto quit;
545     }
546
547     mainloop_api = pa_mainloop_get_api(m);
548
549     r = pa_signal_init(mainloop_api);
550     assert(r == 0);
551     pa_signal_new(SIGINT, exit_signal_callback, NULL);
552     pa_signal_new(SIGTERM, exit_signal_callback, NULL);
553 #ifdef SIGUSR1
554     pa_signal_new(SIGUSR1, sigusr1_signal_callback, NULL);
555 #endif
556 #ifdef SIGPIPE
557     signal(SIGPIPE, SIG_IGN);
558 #endif
559     
560     if (!(stdio_event = mainloop_api->io_new(mainloop_api,
561                                              mode == PLAYBACK ? STDIN_FILENO : STDOUT_FILENO,
562                                              mode == PLAYBACK ? PA_IO_EVENT_INPUT : PA_IO_EVENT_OUTPUT,
563                                              mode == PLAYBACK ? stdin_callback : stdout_callback, NULL))) {
564         fprintf(stderr, "source_io() failed.\n");
565         goto quit;
566     }
567
568     /* Create a new connection context */
569     if (!(context = pa_context_new(mainloop_api, client_name))) {
570         fprintf(stderr, "pa_context_new() failed.\n");
571         goto quit;
572     }
573
574     pa_context_set_state_callback(context, context_state_callback, NULL);
575
576     /* Connect the context */
577     pa_context_connect(context, server, 0, NULL);
578
579     /* Run the main loop */
580     if (pa_mainloop_run(m, &ret) < 0) {
581         fprintf(stderr, "pa_mainloop_run() failed.\n");
582         goto quit;
583     }
584     
585 quit:
586     if (stream)
587         pa_stream_unref(stream);
588
589     if (context)
590         pa_context_unref(context);
591
592     if (stdio_event) {
593         assert(mainloop_api);
594         mainloop_api->io_free(stdio_event);
595     }
596     
597     if (m) {
598         pa_signal_done();
599         pa_mainloop_free(m);
600     }
601
602     free(buffer);
603
604     free(server);
605     free(device);
606     free(client_name);
607     free(stream_name);
608     
609     return ret;
610 }