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