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