replace a few remaining uppercase "Polypaudio" occurences with "PulseAudio"
[profile/ivi/pulseaudio.git] / src / utils / pacat.c
1 /* $Id$ */
2
3 /***
4   This file is part of PulseAudio.
5  
6   PulseAudio 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   PulseAudio 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 PulseAudio; 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 <pulse/pulseaudio.h>
37
38 #define TIME_EVENT_USEC 50000
39
40 #if PA_API_VERSION != 9
41 #error Invalid PulseAudio 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 static pa_channel_map channel_map;
67 static int channel_map_set = 0;
68
69 /* A shortcut for terminating the application */
70 static void quit(int ret) {
71     assert(mainloop_api);
72     mainloop_api->quit(mainloop_api, ret);
73 }
74
75 /* Write some data to the stream */
76 static void do_stream_write(size_t length) {
77     size_t l;
78     assert(length);
79
80     if (!buffer || !buffer_length)
81         return;
82     
83     l = length;
84     if (l > buffer_length)
85         l = buffer_length;
86     
87     if (pa_stream_write(stream, (uint8_t*) buffer + buffer_index, l, NULL, 0, PA_SEEK_RELATIVE) < 0) {
88         fprintf(stderr, "pa_stream_write() failed: %s\n", pa_strerror(pa_context_errno(context)));
89         quit(1);
90         return;
91     }
92     
93     buffer_length -= l;
94     buffer_index += l;
95     
96     if (!buffer_length) {
97         pa_xfree(buffer);
98         buffer = NULL;
99         buffer_index = buffer_length = 0;
100     }
101 }
102
103 /* This is called whenever new data may be written to the stream */
104 static void stream_write_callback(pa_stream *s, size_t length, void *userdata) {
105     assert(s && length);
106
107     if (stdio_event)
108         mainloop_api->io_enable(stdio_event, PA_IO_EVENT_INPUT);
109
110     if (!buffer)
111         return;
112
113     do_stream_write(length);
114 }
115
116 /* This is called whenever new data may is available */
117 static void stream_read_callback(pa_stream *s, size_t length, void *userdata) {
118     const void *data;
119     assert(s && length);
120
121     if (stdio_event)
122         mainloop_api->io_enable(stdio_event, PA_IO_EVENT_OUTPUT);
123
124     if (pa_stream_peek(s, &data, &length) < 0) {
125         fprintf(stderr, "pa_stream_peek() failed: %s\n", pa_strerror(pa_context_errno(context)));
126         quit(1);
127         return;
128     }
129     
130     assert(data && length);
131
132     if (buffer) {
133         fprintf(stderr, "Buffer overrun, dropping incoming data\n");
134         if (pa_stream_drop(s) < 0) {
135             fprintf(stderr, "pa_stream_drop() failed: %s\n", pa_strerror(pa_context_errno(context)));
136             quit(1);
137         }
138         return;
139     }
140
141     buffer = pa_xmalloc(buffer_length = length);
142     memcpy(buffer, data, length);
143     buffer_index = 0;
144     pa_stream_drop(s);
145 }
146
147 /* This routine is called whenever the stream state changes */
148 static void stream_state_callback(pa_stream *s, void *userdata) {
149     assert(s);
150
151     switch (pa_stream_get_state(s)) {
152         case PA_STREAM_CREATING:
153         case PA_STREAM_TERMINATED:
154             break;
155
156         case PA_STREAM_READY:
157             if (verbose) {
158                 const pa_buffer_attr *a;
159                 
160                 fprintf(stderr, "Stream successfully created.\n");
161
162                 if (!(a = pa_stream_get_buffer_attr(s)))
163                     fprintf(stderr, "pa_stream_get_buffer_attr() failed: %s\n", pa_strerror(pa_context_errno(pa_stream_get_context(s))));
164                 else {
165
166                     if (mode == PLAYBACK)
167                         fprintf(stderr, "Buffer metrics: maxlength=%u, tlength=%u, prebuf=%u, minreq=%u\n", a->maxlength, a->tlength, a->prebuf, a->minreq);
168                     else {
169                         assert(mode == RECORD);
170                         fprintf(stderr, "Buffer metrics: maxlength=%u, fragsize=%u\n", a->maxlength, a->fragsize);
171                     }
172                     
173                 }
174
175             }
176             
177             break;
178             
179         case PA_STREAM_FAILED:
180         default:
181             fprintf(stderr, "Stream error: %s\n", pa_strerror(pa_context_errno(pa_stream_get_context(s))));
182             quit(1);
183     }
184 }
185
186 /* This is called whenever the context status changes */
187 static void context_state_callback(pa_context *c, void *userdata) {
188     assert(c);
189
190     switch (pa_context_get_state(c)) {
191         case PA_CONTEXT_CONNECTING:
192         case PA_CONTEXT_AUTHORIZING:
193         case PA_CONTEXT_SETTING_NAME:
194             break;
195         
196         case PA_CONTEXT_READY: {
197             int r;
198             
199             assert(c && !stream);
200
201             if (verbose)
202                 fprintf(stderr, "Connection established.\n");
203
204             if (!(stream = pa_stream_new(c, stream_name, &sample_spec, channel_map_set ? &channel_map : NULL))) {
205                 fprintf(stderr, "pa_stream_new() failed: %s\n", pa_strerror(pa_context_errno(c)));
206                 goto fail;
207             }
208
209             pa_stream_set_state_callback(stream, stream_state_callback, NULL);
210             pa_stream_set_write_callback(stream, stream_write_callback, NULL);
211             pa_stream_set_read_callback(stream, stream_read_callback, NULL);
212
213             if (mode == PLAYBACK) {
214                 pa_cvolume cv;
215                 if ((r = pa_stream_connect_playback(stream, device, NULL, 0, pa_cvolume_set(&cv, sample_spec.channels, volume), NULL)) < 0) {
216                     fprintf(stderr, "pa_stream_connect_playback() failed: %s\n", pa_strerror(pa_context_errno(c)));
217                     goto fail;
218                 }
219                     
220             } else {
221                 if ((r = pa_stream_connect_record(stream, device, NULL, 0)) < 0) {
222                     fprintf(stderr, "pa_stream_connect_record() failed: %s\n", pa_strerror(pa_context_errno(c)));
223                     goto fail;
224                 }
225             }
226                 
227             break;
228         }
229             
230         case PA_CONTEXT_TERMINATED:
231             quit(0);
232             break;
233
234         case PA_CONTEXT_FAILED:
235         default:
236             fprintf(stderr, "Connection failure: %s\n", pa_strerror(pa_context_errno(c)));
237             goto fail;
238     }
239
240     return;
241     
242 fail:
243     quit(1);
244     
245 }
246
247 /* Connection draining complete */
248 static void context_drain_complete(pa_context*c, void *userdata) {
249     pa_context_disconnect(c);
250 }
251
252 /* Stream draining complete */
253 static void stream_drain_complete(pa_stream*s, int success, void *userdata) {
254     pa_operation *o;
255
256     if (!success) {
257         fprintf(stderr, "Failed to drain stream: %s\n", pa_strerror(pa_context_errno(context)));
258         quit(1);
259     }
260     
261     if (verbose)    
262         fprintf(stderr, "Playback stream drained.\n");
263
264     pa_stream_disconnect(stream);
265     pa_stream_unref(stream);
266     stream = NULL;
267     
268     if (!(o = pa_context_drain(context, context_drain_complete, NULL)))
269         pa_context_disconnect(context);
270     else {
271         if (verbose)
272             fprintf(stderr, "Draining connection to server.\n");
273     }
274 }
275
276 /* New data on STDIN **/
277 static void stdin_callback(pa_mainloop_api*a, pa_io_event *e, int fd, pa_io_event_flags_t f, void *userdata) {
278     size_t l, w = 0;
279     ssize_t r;
280     assert(a == mainloop_api && e && stdio_event == e);
281
282     if (buffer) {
283         mainloop_api->io_enable(stdio_event, PA_IO_EVENT_NULL);
284         return;
285     }
286
287     if (!stream || pa_stream_get_state(stream) != PA_STREAM_READY || !(l = w = pa_stream_writable_size(stream)))
288         l = 4096;
289     
290     buffer = pa_xmalloc(l);
291
292     if ((r = read(fd, buffer, l)) <= 0) {
293         if (r == 0) {
294             pa_operation *o;
295             
296             if (verbose)
297                 fprintf(stderr, "Got EOF.\n");
298             
299             if (!(o = pa_stream_drain(stream, stream_drain_complete, NULL))) {
300                 fprintf(stderr, "pa_stream_drain(): %s\n", pa_strerror(pa_context_errno(context)));
301                 quit(1);
302                 return;
303             }
304
305             pa_operation_unref(o);
306         } else {
307             fprintf(stderr, "read() failed: %s\n", strerror(errno));
308             quit(1);
309         }
310
311         mainloop_api->io_free(stdio_event);
312         stdio_event = NULL;
313         return;
314     }
315
316     buffer_length = r;
317     buffer_index = 0;
318
319     if (w)
320         do_stream_write(w);
321 }
322
323 /* Some data may be written to STDOUT */
324 static void stdout_callback(pa_mainloop_api*a, pa_io_event *e, int fd, pa_io_event_flags_t f, void *userdata) {
325     ssize_t r;
326     assert(a == mainloop_api && e && stdio_event == e);
327
328     if (!buffer) {
329         mainloop_api->io_enable(stdio_event, PA_IO_EVENT_NULL);
330         return;
331     }
332
333     assert(buffer_length);
334     
335     if ((r = write(fd, (uint8_t*) buffer+buffer_index, buffer_length)) <= 0) {
336         fprintf(stderr, "write() failed: %s\n", strerror(errno));
337         quit(1);
338
339         mainloop_api->io_free(stdio_event);
340         stdio_event = NULL;
341         return;
342     }
343
344     buffer_length -= r;
345     buffer_index += r;
346
347     if (!buffer_length) {
348         pa_xfree(buffer);
349         buffer = NULL;
350         buffer_length = buffer_index = 0;
351     }
352 }
353
354 /* UNIX signal to quit recieved */
355 static void exit_signal_callback(pa_mainloop_api*m, pa_signal_event *e, int sig, void *userdata) {
356     if (verbose)
357         fprintf(stderr, "Got signal, exiting.\n");
358     quit(0);
359 }
360
361 /* Show the current latency */
362 static void stream_update_timing_callback(pa_stream *s, int success, void *userdata) {
363     pa_usec_t latency, usec;
364     int negative = 0;
365     
366     assert(s);
367
368     if (!success ||
369         pa_stream_get_time(s, &usec) < 0 ||
370         pa_stream_get_latency(s, &latency, &negative) < 0) {
371         fprintf(stderr, "Failed to get latency: %s\n", pa_strerror(pa_context_errno(context)));
372         quit(1);
373         return;
374     }
375
376     fprintf(stderr, "Time: %0.3f sec; Latency: %0.0f usec.  \r",
377             (float) usec / 1000000,
378             (float) latency * (negative?-1:1));
379 }
380
381 /* Someone requested that the latency is shown */
382 static void sigusr1_signal_callback(pa_mainloop_api*m, pa_signal_event *e, int sig, void *userdata) {
383
384     if (!stream)
385         return;
386     
387     pa_operation_unref(pa_stream_update_timing_info(stream, stream_update_timing_callback, NULL));
388 }
389
390 static void time_event_callback(pa_mainloop_api*m, pa_time_event *e, const struct timeval *tv, void *userdata) {
391     struct timeval next;
392     
393     if (stream && pa_stream_get_state(stream) == PA_STREAM_READY) {
394         pa_operation *o;
395         if (!(o = pa_stream_update_timing_info(stream, stream_update_timing_callback, NULL)))
396             fprintf(stderr, "pa_stream_update_timing_info() failed: %s\n", pa_strerror(pa_context_errno(context)));
397         else
398             pa_operation_unref(o);
399     }
400
401     pa_gettimeofday(&next);
402     pa_timeval_add(&next, TIME_EVENT_USEC);
403
404     m->time_restart(e, &next);
405 }
406
407 static void help(const char *argv0) {
408
409     printf("%s [options]\n\n"
410            "  -h, --help                            Show this help\n"
411            "      --version                         Show version\n\n"
412            "  -r, --record                          Create a connection for recording\n"
413            "  -p, --playback                        Create a connection for playback\n\n"
414            "  -v, --verbose                         Enable verbose operations\n\n"
415            "  -s, --server=SERVER                   The name of the server to connect to\n"
416            "  -d, --device=DEVICE                   The name of the sink/source to connect to\n"
417            "  -n, --client-name=NAME                How to call this client on the server\n"
418            "      --stream-name=NAME                How to call this stream on the server\n"
419            "      --volume=VOLUME                   Specify the initial (linear) volume in range 0...65536\n"
420            "      --rate=SAMPLERATE                 The sample rate in Hz (defaults to 44100)\n"
421            "      --format=SAMPLEFORMAT             The sample type, one of s16le, s16be, u8, float32le,\n"
422            "                                        float32be, ulaw, alaw (defaults to s16ne)\n"
423            "      --channels=CHANNELS               The number of channels, 1 for mono, 2 for stereo\n"
424            "                                        (defaults to 2)\n"
425            "      --channel-map=CHANNELMAP          Channel map to use instead of the default\n",
426            argv0);
427 }
428
429 enum {
430     ARG_VERSION = 256,
431     ARG_STREAM_NAME,
432     ARG_VOLUME,
433     ARG_SAMPLERATE,
434     ARG_SAMPLEFORMAT,
435     ARG_CHANNELS,
436     ARG_CHANNELMAP,
437 };
438
439 int main(int argc, char *argv[]) {
440     pa_mainloop* m = NULL;
441     int ret = 1, r, c;
442     char *bn, *server = NULL;
443     pa_time_event *time_event = NULL;
444
445     static const struct option long_options[] = {
446         {"record",      0, NULL, 'r'},
447         {"playback",    0, NULL, 'p'},
448         {"device",      1, NULL, 'd'},
449         {"server",      1, NULL, 's'},
450         {"client-name", 1, NULL, 'n'},
451         {"stream-name", 1, NULL, ARG_STREAM_NAME},
452         {"version",     0, NULL, ARG_VERSION},
453         {"help",        0, NULL, 'h'},
454         {"verbose",     0, NULL, 'v'},
455         {"volume",      1, NULL, ARG_VOLUME},
456         {"rate",        1, NULL, ARG_SAMPLERATE},
457         {"format",      1, NULL, ARG_SAMPLEFORMAT},
458         {"channels",    1, NULL, ARG_CHANNELS},
459         {"channel-map", 1, NULL, ARG_CHANNELMAP},
460         {NULL,          0, NULL, 0}
461     };
462
463     if (!(bn = strrchr(argv[0], '/')))
464         bn = argv[0];
465     else
466         bn++;
467
468     if (strstr(bn, "rec") || strstr(bn, "mon"))
469         mode = RECORD;
470     else if (strstr(bn, "cat") || strstr(bn, "play"))
471         mode = PLAYBACK;
472
473     while ((c = getopt_long(argc, argv, "rpd:s:n:hv", long_options, NULL)) != -1) {
474
475         switch (c) {
476             case 'h' :
477                 help(bn);
478                 ret = 0;
479                 goto quit;
480                 
481             case ARG_VERSION:
482                 printf("pacat "PACKAGE_VERSION"\nCompiled with libpulse %s\nLinked with libpulse %s\n", pa_get_headers_version(), pa_get_library_version());
483                 ret = 0;
484                 goto quit;
485
486             case 'r':
487                 mode = RECORD;
488                 break;
489
490             case 'p':
491                 mode = PLAYBACK;
492                 break;
493
494             case 'd':
495                 pa_xfree(device);
496                 device = pa_xstrdup(optarg);
497                 break;
498
499             case 's':
500                 pa_xfree(server);
501                 server = pa_xstrdup(optarg);
502                 break;
503
504             case 'n':
505                 pa_xfree(client_name);
506                 client_name = pa_xstrdup(optarg);
507                 break;
508
509             case ARG_STREAM_NAME:
510                 pa_xfree(stream_name);
511                 stream_name = pa_xstrdup(optarg);
512                 break;
513
514             case 'v':
515                 verbose = 1;
516                 break;
517
518             case ARG_VOLUME: {
519                 int v = atoi(optarg);
520                 volume = v < 0 ? 0 : v;
521                 break;
522             }
523
524             case ARG_CHANNELS: 
525                 sample_spec.channels = atoi(optarg);
526                 break;
527
528             case ARG_SAMPLEFORMAT:
529                 sample_spec.format = pa_parse_sample_format(optarg);
530                 break;
531
532             case ARG_SAMPLERATE:
533                 sample_spec.rate = atoi(optarg);
534                 break;
535
536             case ARG_CHANNELMAP:
537                 if (!pa_channel_map_parse(&channel_map, optarg)) {
538                     fprintf(stderr, "Invalid channel map\n");
539                     goto quit;
540                 }
541
542                 channel_map_set = 1;
543                 break;
544                 
545             default:
546                 goto quit;
547         }
548     }
549
550     if (!pa_sample_spec_valid(&sample_spec)) {
551         fprintf(stderr, "Invalid sample specification\n");
552         goto quit;
553     }
554
555     if (channel_map_set && channel_map.channels != sample_spec.channels) {
556         fprintf(stderr, "Channel map doesn't match sample specification\n");
557         goto quit;
558     }
559     
560     if (verbose) {
561         char t[PA_SAMPLE_SPEC_SNPRINT_MAX];
562         pa_sample_spec_snprint(t, sizeof(t), &sample_spec);
563         fprintf(stderr, "Opening a %s stream with sample specification '%s'.\n", mode == RECORD ? "recording" : "playback", t);
564     }
565
566     if (!(optind >= argc)) {
567         if (optind+1 == argc) {
568             int fd;
569             
570             if ((fd = open(argv[optind], mode == PLAYBACK ? O_RDONLY : O_WRONLY|O_TRUNC|O_CREAT, 0666)) < 0) {
571                 fprintf(stderr, "open(): %s\n", strerror(errno));
572                 goto quit;
573             }
574             
575             if (dup2(fd, mode == PLAYBACK ? 0 : 1) < 0) {
576                 fprintf(stderr, "dup2(): %s\n", strerror(errno));
577                 goto quit;
578             }
579             
580             close(fd);
581
582             if (!stream_name)
583                 stream_name = pa_xstrdup(argv[optind]);
584             
585         } else {
586             fprintf(stderr, "Too many arguments.\n");
587             goto quit;
588         }
589     }
590
591     if (!client_name)
592         client_name = pa_xstrdup(bn);
593
594     if (!stream_name)
595         stream_name = pa_xstrdup(client_name);
596
597     /* Set up a new main loop */
598     if (!(m = pa_mainloop_new())) {
599         fprintf(stderr, "pa_mainloop_new() failed.\n");
600         goto quit;
601     }
602
603     mainloop_api = pa_mainloop_get_api(m);
604
605     r = pa_signal_init(mainloop_api);
606     assert(r == 0);
607     pa_signal_new(SIGINT, exit_signal_callback, NULL);
608     pa_signal_new(SIGTERM, exit_signal_callback, NULL);
609 #ifdef SIGUSR1
610     pa_signal_new(SIGUSR1, sigusr1_signal_callback, NULL);
611 #endif
612 #ifdef SIGPIPE
613     signal(SIGPIPE, SIG_IGN);
614 #endif
615     
616     if (!(stdio_event = mainloop_api->io_new(mainloop_api,
617                                              mode == PLAYBACK ? STDIN_FILENO : STDOUT_FILENO,
618                                              mode == PLAYBACK ? PA_IO_EVENT_INPUT : PA_IO_EVENT_OUTPUT,
619                                              mode == PLAYBACK ? stdin_callback : stdout_callback, NULL))) {
620         fprintf(stderr, "io_new() failed.\n");
621         goto quit;
622     }
623
624     /* Create a new connection context */
625     if (!(context = pa_context_new(mainloop_api, client_name))) {
626         fprintf(stderr, "pa_context_new() failed.\n");
627         goto quit;
628     }
629
630     pa_context_set_state_callback(context, context_state_callback, NULL);
631
632     /* Connect the context */
633     pa_context_connect(context, server, 0, NULL);
634
635     if (verbose) {
636         struct timeval tv;
637
638         pa_gettimeofday(&tv);
639         pa_timeval_add(&tv, TIME_EVENT_USEC);
640         
641         if (!(time_event = mainloop_api->time_new(mainloop_api, &tv, time_event_callback, NULL))) {
642             fprintf(stderr, "time_new() failed.\n");
643             goto quit;
644         }
645     }
646
647     /* Run the main loop */
648     if (pa_mainloop_run(m, &ret) < 0) {
649         fprintf(stderr, "pa_mainloop_run() failed.\n");
650         goto quit;
651     }
652     
653 quit:
654     if (stream)
655         pa_stream_unref(stream);
656
657     if (context)
658         pa_context_unref(context);
659
660     if (stdio_event) {
661         assert(mainloop_api);
662         mainloop_api->io_free(stdio_event);
663     }
664
665     if (time_event) {
666         assert(mainloop_api);
667         mainloop_api->time_free(time_event);
668     }
669     
670     if (m) {
671         pa_signal_done();
672         pa_mainloop_free(m);
673     }
674
675     pa_xfree(buffer);
676
677     pa_xfree(server);
678     pa_xfree(device);
679     pa_xfree(client_name);
680     pa_xfree(stream_name);
681     
682     return ret;
683 }