Make sure we don't drop any data on the client side
[profile/ivi/pulseaudio.git] / src / utils / pacat.c
1 /***
2   This file is part of PulseAudio.
3
4   Copyright 2004-2006 Lennart Poettering
5   Copyright 2006 Pierre Ossman <ossman@cendio.se> for Cendio AB
6
7   PulseAudio is free software; you can redistribute it and/or modify
8   it under the terms of the GNU Lesser General Public License as published
9   by the Free Software Foundation; either version 2 of the License,
10   or (at your option) any later version.
11
12   PulseAudio is distributed in the hope that it will be useful, but
13   WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15   General Public License for more details.
16
17   You should have received a copy of the GNU Lesser General Public License
18   along with PulseAudio; if not, write to the Free Software
19   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
20   USA.
21 ***/
22
23 #ifdef HAVE_CONFIG_H
24 #include <config.h>
25 #endif
26
27 #include <signal.h>
28 #include <string.h>
29 #include <errno.h>
30 #include <unistd.h>
31 #include <assert.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <getopt.h>
35 #include <fcntl.h>
36 #include <locale.h>
37
38 #include <pulse/i18n.h>
39 #include <pulse/pulseaudio.h>
40
41 #define TIME_EVENT_USEC 50000
42
43 #define CLEAR_LINE "\x1B[K"
44
45 static enum { RECORD, PLAYBACK } mode = PLAYBACK;
46
47 static pa_context *context = NULL;
48 static pa_stream *stream = NULL;
49 static pa_mainloop_api *mainloop_api = NULL;
50
51 static void *buffer = NULL;
52 static size_t buffer_length = 0, buffer_index = 0;
53
54 static pa_io_event* stdio_event = NULL;
55
56 static char *stream_name = NULL, *client_name = NULL, *device = NULL;
57
58 static int verbose = 0;
59 static pa_volume_t volume = PA_VOLUME_NORM;
60 static int volume_is_set = 0;
61
62 static pa_sample_spec sample_spec = {
63     .format = PA_SAMPLE_S16LE,
64     .rate = 44100,
65     .channels = 2
66 };
67
68 static pa_channel_map channel_map;
69 static int channel_map_set = 0;
70
71 static pa_stream_flags_t flags = 0;
72
73 static size_t latency = 0, process_time=0;
74
75 /* A shortcut for terminating the application */
76 static void quit(int ret) {
77     assert(mainloop_api);
78     mainloop_api->quit(mainloop_api, ret);
79 }
80
81 /* Write some data to the stream */
82 static void do_stream_write(size_t length) {
83     size_t l;
84     assert(length);
85
86     if (!buffer || !buffer_length)
87         return;
88
89     l = length;
90     if (l > buffer_length)
91         l = buffer_length;
92
93     if (pa_stream_write(stream, (uint8_t*) buffer + buffer_index, l, NULL, 0, PA_SEEK_RELATIVE) < 0) {
94         fprintf(stderr, _("pa_stream_write() failed: %s\n"), pa_strerror(pa_context_errno(context)));
95         quit(1);
96         return;
97     }
98
99     buffer_length -= l;
100     buffer_index += l;
101
102     if (!buffer_length) {
103         pa_xfree(buffer);
104         buffer = NULL;
105         buffer_index = buffer_length = 0;
106     }
107 }
108
109 /* This is called whenever new data may be written to the stream */
110 static void stream_write_callback(pa_stream *s, size_t length, void *userdata) {
111     assert(s);
112     assert(length > 0);
113
114     if (stdio_event)
115         mainloop_api->io_enable(stdio_event, PA_IO_EVENT_INPUT);
116
117     if (!buffer)
118         return;
119
120     do_stream_write(length);
121 }
122
123 /* This is called whenever new data may is available */
124 static void stream_read_callback(pa_stream *s, size_t length, void *userdata) {
125     const void *data;
126     assert(s);
127     assert(length > 0);
128
129     if (stdio_event)
130         mainloop_api->io_enable(stdio_event, PA_IO_EVENT_OUTPUT);
131
132     if (pa_stream_peek(s, &data, &length) < 0) {
133         fprintf(stderr, _("pa_stream_peek() failed: %s\n"), pa_strerror(pa_context_errno(context)));
134         quit(1);
135         return;
136     }
137
138     assert(data);
139     assert(length > 0);
140
141     if (buffer) {
142         buffer = pa_xrealloc(buffer, buffer_length + length);
143         memcpy((uint8_t*) buffer + buffer_length, data, length);
144         buffer_length += length;
145     } else {
146         buffer = pa_xmalloc(length);
147         memcpy(buffer, data, length);
148         buffer_length = length;
149         buffer_index = 0;
150     }
151
152     pa_stream_drop(s);
153 }
154
155 /* This routine is called whenever the stream state changes */
156 static void stream_state_callback(pa_stream *s, void *userdata) {
157     assert(s);
158
159     switch (pa_stream_get_state(s)) {
160         case PA_STREAM_CREATING:
161         case PA_STREAM_TERMINATED:
162             break;
163
164         case PA_STREAM_READY:
165             if (verbose) {
166                 const pa_buffer_attr *a;
167                 char cmt[PA_CHANNEL_MAP_SNPRINT_MAX], sst[PA_SAMPLE_SPEC_SNPRINT_MAX];
168
169                 fprintf(stderr, _("Stream successfully created.\n"));
170
171                 if (!(a = pa_stream_get_buffer_attr(s)))
172                     fprintf(stderr, _("pa_stream_get_buffer_attr() failed: %s\n"), pa_strerror(pa_context_errno(pa_stream_get_context(s))));
173                 else {
174
175                     if (mode == PLAYBACK)
176                         fprintf(stderr, _("Buffer metrics: maxlength=%u, tlength=%u, prebuf=%u, minreq=%u\n"), a->maxlength, a->tlength, a->prebuf, a->minreq);
177                     else {
178                         assert(mode == RECORD);
179                         fprintf(stderr, _("Buffer metrics: maxlength=%u, fragsize=%u\n"), a->maxlength, a->fragsize);
180                     }
181                 }
182
183                 fprintf(stderr, _("Using sample spec '%s', channel map '%s'.\n"),
184                         pa_sample_spec_snprint(sst, sizeof(sst), pa_stream_get_sample_spec(s)),
185                         pa_channel_map_snprint(cmt, sizeof(cmt), pa_stream_get_channel_map(s)));
186
187                 fprintf(stderr, _("Connected to device %s (%u, %ssuspended).\n"),
188                         pa_stream_get_device_name(s),
189                         pa_stream_get_device_index(s),
190                         pa_stream_is_suspended(s) ? "" : "not ");
191             }
192
193             break;
194
195         case PA_STREAM_FAILED:
196         default:
197             fprintf(stderr, _("Stream error: %s\n"), pa_strerror(pa_context_errno(pa_stream_get_context(s))));
198             quit(1);
199     }
200 }
201
202 static void stream_suspended_callback(pa_stream *s, void *userdata) {
203     assert(s);
204
205     if (verbose) {
206         if (pa_stream_is_suspended(s))
207             fprintf(stderr, _("Stream device suspended.%s \n"), CLEAR_LINE);
208         else
209             fprintf(stderr, _("Stream device resumed.%s \n"), CLEAR_LINE);
210     }
211 }
212
213 static void stream_underflow_callback(pa_stream *s, void *userdata) {
214     assert(s);
215
216     if (verbose)
217         fprintf(stderr, _("Stream underrun.%s \n"),  CLEAR_LINE);
218 }
219
220 static void stream_overflow_callback(pa_stream *s, void *userdata) {
221     assert(s);
222
223     if (verbose)
224         fprintf(stderr, _("Stream overrun.%s \n"), CLEAR_LINE);
225 }
226
227 static void stream_started_callback(pa_stream *s, void *userdata) {
228     assert(s);
229
230     if (verbose)
231         fprintf(stderr, _("Stream started.%s \n"), CLEAR_LINE);
232 }
233
234 static void stream_moved_callback(pa_stream *s, void *userdata) {
235     assert(s);
236
237     if (verbose)
238         fprintf(stderr, _("Stream moved to device %s (%u, %ssuspended).%s \n"), pa_stream_get_device_name(s), pa_stream_get_device_index(s), pa_stream_is_suspended(s) ? "" : _("not "),  CLEAR_LINE);
239 }
240
241 /* This is called whenever the context status changes */
242 static void context_state_callback(pa_context *c, void *userdata) {
243     assert(c);
244
245     switch (pa_context_get_state(c)) {
246         case PA_CONTEXT_CONNECTING:
247         case PA_CONTEXT_AUTHORIZING:
248         case PA_CONTEXT_SETTING_NAME:
249             break;
250
251         case PA_CONTEXT_READY: {
252             int r;
253             pa_buffer_attr buffer_attr;
254
255             assert(c);
256             assert(!stream);
257
258             if (verbose)
259                 fprintf(stderr, _("Connection established.%s \n"), CLEAR_LINE);
260
261             if (!(stream = pa_stream_new(c, stream_name, &sample_spec, channel_map_set ? &channel_map : NULL))) {
262                 fprintf(stderr, _("pa_stream_new() failed: %s\n"), pa_strerror(pa_context_errno(c)));
263                 goto fail;
264             }
265
266             pa_stream_set_state_callback(stream, stream_state_callback, NULL);
267             pa_stream_set_write_callback(stream, stream_write_callback, NULL);
268             pa_stream_set_read_callback(stream, stream_read_callback, NULL);
269             pa_stream_set_suspended_callback(stream, stream_suspended_callback, NULL);
270             pa_stream_set_moved_callback(stream, stream_moved_callback, NULL);
271             pa_stream_set_underflow_callback(stream, stream_underflow_callback, NULL);
272             pa_stream_set_overflow_callback(stream, stream_overflow_callback, NULL);
273             pa_stream_set_started_callback(stream, stream_started_callback, NULL);
274
275             if (latency > 0) {
276                 memset(&buffer_attr, 0, sizeof(buffer_attr));
277                 buffer_attr.tlength = (uint32_t) latency;
278                 buffer_attr.minreq = (uint32_t) process_time;
279                 buffer_attr.maxlength = (uint32_t) -1;
280                 buffer_attr.prebuf = (uint32_t) -1;
281                 flags |= PA_STREAM_ADJUST_LATENCY;
282             }
283
284             if (mode == PLAYBACK) {
285                 pa_cvolume cv;
286                 if ((r = pa_stream_connect_playback(stream, device, latency > 0 ? &buffer_attr : NULL, flags, volume_is_set ? pa_cvolume_set(&cv, sample_spec.channels, volume) : NULL, NULL)) < 0) {
287                     fprintf(stderr, _("pa_stream_connect_playback() failed: %s\n"), pa_strerror(pa_context_errno(c)));
288                     goto fail;
289                 }
290
291             } else {
292                 if ((r = pa_stream_connect_record(stream, device, latency > 0 ? &buffer_attr : NULL, flags)) < 0) {
293                     fprintf(stderr, _("pa_stream_connect_record() failed: %s\n"), pa_strerror(pa_context_errno(c)));
294                     goto fail;
295                 }
296             }
297
298             break;
299         }
300
301         case PA_CONTEXT_TERMINATED:
302             quit(0);
303             break;
304
305         case PA_CONTEXT_FAILED:
306         default:
307             fprintf(stderr, _("Connection failure: %s\n"), pa_strerror(pa_context_errno(c)));
308             goto fail;
309     }
310
311     return;
312
313 fail:
314     quit(1);
315
316 }
317
318 /* Connection draining complete */
319 static void context_drain_complete(pa_context*c, void *userdata) {
320     pa_context_disconnect(c);
321 }
322
323 /* Stream draining complete */
324 static void stream_drain_complete(pa_stream*s, int success, void *userdata) {
325     pa_operation *o;
326
327     if (!success) {
328         fprintf(stderr, _("Failed to drain stream: %s\n"), pa_strerror(pa_context_errno(context)));
329         quit(1);
330     }
331
332     if (verbose)
333         fprintf(stderr, _("Playback stream drained.\n"));
334
335     pa_stream_disconnect(stream);
336     pa_stream_unref(stream);
337     stream = NULL;
338
339     if (!(o = pa_context_drain(context, context_drain_complete, NULL)))
340         pa_context_disconnect(context);
341     else {
342         if (verbose)
343             fprintf(stderr, _("Draining connection to server.\n"));
344     }
345 }
346
347 /* New data on STDIN **/
348 static void stdin_callback(pa_mainloop_api*a, pa_io_event *e, int fd, pa_io_event_flags_t f, void *userdata) {
349     size_t l, w = 0;
350     ssize_t r;
351
352     assert(a == mainloop_api);
353     assert(e);
354     assert(stdio_event == e);
355
356     if (buffer) {
357         mainloop_api->io_enable(stdio_event, PA_IO_EVENT_NULL);
358         return;
359     }
360
361     if (!stream || pa_stream_get_state(stream) != PA_STREAM_READY || !(l = w = pa_stream_writable_size(stream)))
362         l = 4096;
363
364     buffer = pa_xmalloc(l);
365
366     if ((r = read(fd, buffer, l)) <= 0) {
367         if (r == 0) {
368             if (verbose)
369                 fprintf(stderr, _("Got EOF.\n"));
370
371             if (stream) {
372                 pa_operation *o;
373
374                 if (!(o = pa_stream_drain(stream, stream_drain_complete, NULL))) {
375                     fprintf(stderr, _("pa_stream_drain(): %s\n"), pa_strerror(pa_context_errno(context)));
376                     quit(1);
377                     return;
378                 }
379
380                 pa_operation_unref(o);
381             } else
382                 quit(0);
383
384         } else {
385             fprintf(stderr, _("read() failed: %s\n"), strerror(errno));
386             quit(1);
387         }
388
389         mainloop_api->io_free(stdio_event);
390         stdio_event = NULL;
391         return;
392     }
393
394     buffer_length = (uint32_t) r;
395     buffer_index = 0;
396
397     if (w)
398         do_stream_write(w);
399 }
400
401 /* Some data may be written to STDOUT */
402 static void stdout_callback(pa_mainloop_api*a, pa_io_event *e, int fd, pa_io_event_flags_t f, void *userdata) {
403     ssize_t r;
404
405     assert(a == mainloop_api);
406     assert(e);
407     assert(stdio_event == e);
408
409     if (!buffer) {
410         mainloop_api->io_enable(stdio_event, PA_IO_EVENT_NULL);
411         return;
412     }
413
414     assert(buffer_length);
415
416     if ((r = write(fd, (uint8_t*) buffer+buffer_index, buffer_length)) <= 0) {
417         fprintf(stderr, _("write() failed: %s\n"), strerror(errno));
418         quit(1);
419
420         mainloop_api->io_free(stdio_event);
421         stdio_event = NULL;
422         return;
423     }
424
425     buffer_length -= (uint32_t) r;
426     buffer_index += (uint32_t) r;
427
428     if (!buffer_length) {
429         pa_xfree(buffer);
430         buffer = NULL;
431         buffer_length = buffer_index = 0;
432     }
433 }
434
435 /* UNIX signal to quit recieved */
436 static void exit_signal_callback(pa_mainloop_api*m, pa_signal_event *e, int sig, void *userdata) {
437     if (verbose)
438         fprintf(stderr, _("Got signal, exiting.\n"));
439     quit(0);
440 }
441
442 /* Show the current latency */
443 static void stream_update_timing_callback(pa_stream *s, int success, void *userdata) {
444     pa_usec_t l, usec;
445     int negative = 0;
446
447     assert(s);
448
449     if (!success ||
450         pa_stream_get_time(s, &usec) < 0 ||
451         pa_stream_get_latency(s, &l, &negative) < 0) {
452         fprintf(stderr, _("Failed to get latency: %s\n"), pa_strerror(pa_context_errno(context)));
453         quit(1);
454         return;
455     }
456
457     fprintf(stderr, _("Time: %0.3f sec; Latency: %0.0f usec.  \r"),
458             (float) usec / 1000000,
459             (float) l * (negative?-1.0f:1.0f));
460 }
461
462 /* Someone requested that the latency is shown */
463 static void sigusr1_signal_callback(pa_mainloop_api*m, pa_signal_event *e, int sig, void *userdata) {
464
465     if (!stream)
466         return;
467
468     pa_operation_unref(pa_stream_update_timing_info(stream, stream_update_timing_callback, NULL));
469 }
470
471 static void time_event_callback(pa_mainloop_api*m, pa_time_event *e, const struct timeval *tv, void *userdata) {
472     struct timeval next;
473
474     if (stream && pa_stream_get_state(stream) == PA_STREAM_READY) {
475         pa_operation *o;
476         if (!(o = pa_stream_update_timing_info(stream, stream_update_timing_callback, NULL)))
477             fprintf(stderr, _("pa_stream_update_timing_info() failed: %s\n"), pa_strerror(pa_context_errno(context)));
478         else
479             pa_operation_unref(o);
480     }
481
482     pa_gettimeofday(&next);
483     pa_timeval_add(&next, TIME_EVENT_USEC);
484
485     m->time_restart(e, &next);
486 }
487
488 static void help(const char *argv0) {
489
490     printf(_("%s [options]\n\n"
491            "  -h, --help                            Show this help\n"
492            "      --version                         Show version\n\n"
493            "  -r, --record                          Create a connection for recording\n"
494            "  -p, --playback                        Create a connection for playback\n\n"
495            "  -v, --verbose                         Enable verbose operations\n\n"
496            "  -s, --server=SERVER                   The name of the server to connect to\n"
497            "  -d, --device=DEVICE                   The name of the sink/source to connect to\n"
498            "  -n, --client-name=NAME                How to call this client on the server\n"
499            "      --stream-name=NAME                How to call this stream on the server\n"
500            "      --volume=VOLUME                   Specify the initial (linear) volume in range 0...65536\n"
501            "      --rate=SAMPLERATE                 The sample rate in Hz (defaults to 44100)\n"
502            "      --format=SAMPLEFORMAT             The sample type, one of s16le, s16be, u8, float32le,\n"
503            "                                        float32be, ulaw, alaw, s32le, s32be (defaults to s16ne)\n"
504            "      --channels=CHANNELS               The number of channels, 1 for mono, 2 for stereo\n"
505            "                                        (defaults to 2)\n"
506            "      --channel-map=CHANNELMAP          Channel map to use instead of the default\n"
507            "      --fix-format                      Take the sample format from the sink the stream is\n"
508            "                                        being connected to.\n"
509            "      --fix-rate                        Take the sampling rate from the sink the stream is\n"
510            "                                        being connected to.\n"
511            "      --fix-channels                    Take the number of channels and the channel map\n"
512            "                                        from the sink the stream is being connected to.\n"
513            "      --no-remix                        Don't upmix or downmix channels.\n"
514            "      --no-remap                        Map channels by index instead of name.\n"
515            "      --latency=BYTES                   Request the specified latency in bytes.\n"
516            "      --process-time=BYTES              Request the specified process time per request in bytes.\n")
517            ,
518            argv0);
519 }
520
521 enum {
522     ARG_VERSION = 256,
523     ARG_STREAM_NAME,
524     ARG_VOLUME,
525     ARG_SAMPLERATE,
526     ARG_SAMPLEFORMAT,
527     ARG_CHANNELS,
528     ARG_CHANNELMAP,
529     ARG_FIX_FORMAT,
530     ARG_FIX_RATE,
531     ARG_FIX_CHANNELS,
532     ARG_NO_REMAP,
533     ARG_NO_REMIX,
534     ARG_LATENCY,
535     ARG_PROCESS_TIME
536 };
537
538 int main(int argc, char *argv[]) {
539     pa_mainloop* m = NULL;
540     int ret = 1, r, c;
541     char *bn, *server = NULL;
542     pa_time_event *time_event = NULL;
543
544     static const struct option long_options[] = {
545         {"record",       0, NULL, 'r'},
546         {"playback",     0, NULL, 'p'},
547         {"device",       1, NULL, 'd'},
548         {"server",       1, NULL, 's'},
549         {"client-name",  1, NULL, 'n'},
550         {"stream-name",  1, NULL, ARG_STREAM_NAME},
551         {"version",      0, NULL, ARG_VERSION},
552         {"help",         0, NULL, 'h'},
553         {"verbose",      0, NULL, 'v'},
554         {"volume",       1, NULL, ARG_VOLUME},
555         {"rate",         1, NULL, ARG_SAMPLERATE},
556         {"format",       1, NULL, ARG_SAMPLEFORMAT},
557         {"channels",     1, NULL, ARG_CHANNELS},
558         {"channel-map",  1, NULL, ARG_CHANNELMAP},
559         {"fix-format",   0, NULL, ARG_FIX_FORMAT},
560         {"fix-rate",     0, NULL, ARG_FIX_RATE},
561         {"fix-channels", 0, NULL, ARG_FIX_CHANNELS},
562         {"no-remap",     0, NULL, ARG_NO_REMAP},
563         {"no-remix",     0, NULL, ARG_NO_REMIX},
564         {"latency",      1, NULL, ARG_LATENCY},
565         {"process-time", 1, NULL, ARG_PROCESS_TIME},
566         {NULL,           0, NULL, 0}
567     };
568
569     setlocale(LC_ALL, "");
570     bindtextdomain(GETTEXT_PACKAGE, PULSE_LOCALEDIR);
571
572     if (!(bn = strrchr(argv[0], '/')))
573         bn = argv[0];
574     else
575         bn++;
576
577     if (strstr(bn, "rec") || strstr(bn, "mon"))
578         mode = RECORD;
579     else if (strstr(bn, "cat") || strstr(bn, "play"))
580         mode = PLAYBACK;
581
582     while ((c = getopt_long(argc, argv, "rpd:s:n:hv", long_options, NULL)) != -1) {
583
584         switch (c) {
585             case 'h' :
586                 help(bn);
587                 ret = 0;
588                 goto quit;
589
590             case ARG_VERSION:
591                 printf(_("pacat %s\nCompiled with libpulse %s\nLinked with libpulse %s\n"), PACKAGE_VERSION, pa_get_headers_version(), pa_get_library_version());
592                 ret = 0;
593                 goto quit;
594
595             case 'r':
596                 mode = RECORD;
597                 break;
598
599             case 'p':
600                 mode = PLAYBACK;
601                 break;
602
603             case 'd':
604                 pa_xfree(device);
605                 device = pa_xstrdup(optarg);
606                 break;
607
608             case 's':
609                 pa_xfree(server);
610                 server = pa_xstrdup(optarg);
611                 break;
612
613             case 'n':
614                 pa_xfree(client_name);
615                 client_name = pa_xstrdup(optarg);
616                 break;
617
618             case ARG_STREAM_NAME:
619                 pa_xfree(stream_name);
620                 stream_name = pa_xstrdup(optarg);
621                 break;
622
623             case 'v':
624                 verbose = 1;
625                 break;
626
627             case ARG_VOLUME: {
628                 int v = atoi(optarg);
629                 volume = v < 0 ? 0U : (pa_volume_t) v;
630                 volume_is_set = 1;
631                 break;
632             }
633
634             case ARG_CHANNELS:
635                 sample_spec.channels = (uint8_t) atoi(optarg);
636                 break;
637
638             case ARG_SAMPLEFORMAT:
639                 sample_spec.format = pa_parse_sample_format(optarg);
640                 break;
641
642             case ARG_SAMPLERATE:
643                 sample_spec.rate = (uint32_t) atoi(optarg);
644                 break;
645
646             case ARG_CHANNELMAP:
647                 if (!pa_channel_map_parse(&channel_map, optarg)) {
648                     fprintf(stderr, _("Invalid channel map '%s'\n"), optarg);
649                     goto quit;
650                 }
651
652                 channel_map_set = 1;
653                 break;
654
655             case ARG_FIX_CHANNELS:
656                 flags |= PA_STREAM_FIX_CHANNELS;
657                 break;
658
659             case ARG_FIX_RATE:
660                 flags |= PA_STREAM_FIX_RATE;
661                 break;
662
663             case ARG_FIX_FORMAT:
664                 flags |= PA_STREAM_FIX_FORMAT;
665                 break;
666
667             case ARG_NO_REMIX:
668                 flags |= PA_STREAM_NO_REMIX_CHANNELS;
669                 break;
670
671             case ARG_NO_REMAP:
672                 flags |= PA_STREAM_NO_REMAP_CHANNELS;
673                 break;
674
675             case ARG_LATENCY:
676                 if (((latency = (size_t) atoi(optarg))) <= 0) {
677                     fprintf(stderr, _("Invalid latency specification '%s'\n"), optarg);
678                     goto quit;
679                 }
680                 break;
681
682             case ARG_PROCESS_TIME:
683                 if (((process_time = (size_t) atoi(optarg))) <= 0) {
684                     fprintf(stderr, _("Invalid process time specification '%s'\n"), optarg);
685                     goto quit;
686                 }
687                 break;
688
689             default:
690                 goto quit;
691         }
692     }
693
694     if (!pa_sample_spec_valid(&sample_spec)) {
695         fprintf(stderr, _("Invalid sample specification\n"));
696         goto quit;
697     }
698
699     if (channel_map_set && pa_channel_map_compatible(&channel_map, &sample_spec)) {
700         fprintf(stderr, _("Channel map doesn't match sample specification\n"));
701         goto quit;
702     }
703
704     if (verbose) {
705         char t[PA_SAMPLE_SPEC_SNPRINT_MAX];
706         pa_sample_spec_snprint(t, sizeof(t), &sample_spec);
707         fprintf(stderr, _("Opening a %s stream with sample specification '%s'.\n"), mode == RECORD ? _("recording") : _("playback"), t);
708     }
709
710     if (!(optind >= argc)) {
711         if (optind+1 == argc) {
712             int fd;
713
714             if ((fd = open(argv[optind], mode == PLAYBACK ? O_RDONLY : O_WRONLY|O_TRUNC|O_CREAT, 0666)) < 0) {
715                 fprintf(stderr, _("open(): %s\n"), strerror(errno));
716                 goto quit;
717             }
718
719             if (dup2(fd, mode == PLAYBACK ? 0 : 1) < 0) {
720                 fprintf(stderr, _("dup2(): %s\n"), strerror(errno));
721                 goto quit;
722             }
723
724             close(fd);
725
726             if (!stream_name)
727                 stream_name = pa_xstrdup(argv[optind]);
728
729         } else {
730             fprintf(stderr, _("Too many arguments.\n"));
731             goto quit;
732         }
733     }
734
735     if (!client_name)
736         client_name = pa_xstrdup(bn);
737
738     if (!stream_name)
739         stream_name = pa_xstrdup(client_name);
740
741     /* Set up a new main loop */
742     if (!(m = pa_mainloop_new())) {
743         fprintf(stderr, _("pa_mainloop_new() failed.\n"));
744         goto quit;
745     }
746
747     mainloop_api = pa_mainloop_get_api(m);
748
749     r = pa_signal_init(mainloop_api);
750     assert(r == 0);
751     pa_signal_new(SIGINT, exit_signal_callback, NULL);
752     pa_signal_new(SIGTERM, exit_signal_callback, NULL);
753 #ifdef SIGUSR1
754     pa_signal_new(SIGUSR1, sigusr1_signal_callback, NULL);
755 #endif
756 #ifdef SIGPIPE
757     signal(SIGPIPE, SIG_IGN);
758 #endif
759
760     if (!(stdio_event = mainloop_api->io_new(mainloop_api,
761                                              mode == PLAYBACK ? STDIN_FILENO : STDOUT_FILENO,
762                                              mode == PLAYBACK ? PA_IO_EVENT_INPUT : PA_IO_EVENT_OUTPUT,
763                                              mode == PLAYBACK ? stdin_callback : stdout_callback, NULL))) {
764         fprintf(stderr, _("io_new() failed.\n"));
765         goto quit;
766     }
767
768     /* Create a new connection context */
769     if (!(context = pa_context_new(mainloop_api, client_name))) {
770         fprintf(stderr, _("pa_context_new() failed.\n"));
771         goto quit;
772     }
773
774     pa_context_set_state_callback(context, context_state_callback, NULL);
775
776     /* Connect the context */
777     if (pa_context_connect(context, server, 0, NULL) < 0) {
778         fprintf(stderr, _("pa_context_connect() failed: %s"), pa_strerror(pa_context_errno(context)));
779         goto quit;
780     }
781
782     if (verbose) {
783         struct timeval tv;
784
785         pa_gettimeofday(&tv);
786         pa_timeval_add(&tv, TIME_EVENT_USEC);
787
788         if (!(time_event = mainloop_api->time_new(mainloop_api, &tv, time_event_callback, NULL))) {
789             fprintf(stderr, _("time_new() failed.\n"));
790             goto quit;
791         }
792     }
793
794     /* Run the main loop */
795     if (pa_mainloop_run(m, &ret) < 0) {
796         fprintf(stderr, _("pa_mainloop_run() failed.\n"));
797         goto quit;
798     }
799
800 quit:
801     if (stream)
802         pa_stream_unref(stream);
803
804     if (context)
805         pa_context_unref(context);
806
807     if (stdio_event) {
808         assert(mainloop_api);
809         mainloop_api->io_free(stdio_event);
810     }
811
812     if (time_event) {
813         assert(mainloop_api);
814         mainloop_api->time_free(time_event);
815     }
816
817     if (m) {
818         pa_signal_done();
819         pa_mainloop_free(m);
820     }
821
822     pa_xfree(buffer);
823
824     pa_xfree(server);
825     pa_xfree(device);
826     pa_xfree(client_name);
827     pa_xfree(stream_name);
828
829     return ret;
830 }