add new latency argument
[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_moved_callback(pa_stream *s, void *userdata) {
216     assert(s);
217
218     if (verbose)
219         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 ");
220 }
221
222 /* This is called whenever the context status changes */
223 static void context_state_callback(pa_context *c, void *userdata) {
224     assert(c);
225
226     switch (pa_context_get_state(c)) {
227         case PA_CONTEXT_CONNECTING:
228         case PA_CONTEXT_AUTHORIZING:
229         case PA_CONTEXT_SETTING_NAME:
230             break;
231
232         case PA_CONTEXT_READY: {
233             int r;
234             pa_buffer_attr buffer_attr;
235
236             assert(c);
237             assert(!stream);
238
239             if (verbose)
240                 fprintf(stderr, "Connection established.\n");
241
242             if (!(stream = pa_stream_new(c, stream_name, &sample_spec, channel_map_set ? &channel_map : NULL))) {
243                 fprintf(stderr, "pa_stream_new() failed: %s\n", pa_strerror(pa_context_errno(c)));
244                 goto fail;
245             }
246
247             pa_stream_set_state_callback(stream, stream_state_callback, NULL);
248             pa_stream_set_write_callback(stream, stream_write_callback, NULL);
249             pa_stream_set_read_callback(stream, stream_read_callback, NULL);
250             pa_stream_set_suspended_callback(stream, stream_suspended_callback, NULL);
251             pa_stream_set_moved_callback(stream, stream_moved_callback, NULL);
252
253             if (latency > 0) {
254                 memset(&buffer_attr, 0, sizeof(buffer_attr));
255                 buffer_attr.tlength = latency;
256                 flags |= PA_STREAM_ADJUST_LATENCY;
257             }
258
259             if (mode == PLAYBACK) {
260                 pa_cvolume cv;
261                 if ((r = pa_stream_connect_playback(stream, device, latency > 0 ? &buffer_attr : NULL, flags, pa_cvolume_set(&cv, sample_spec.channels, volume), NULL)) < 0) {
262                     fprintf(stderr, "pa_stream_connect_playback() failed: %s\n", pa_strerror(pa_context_errno(c)));
263                     goto fail;
264                 }
265
266             } else {
267                 if ((r = pa_stream_connect_record(stream, device, latency > 0 ? &buffer_attr : NULL, flags)) < 0) {
268                     fprintf(stderr, "pa_stream_connect_record() failed: %s\n", pa_strerror(pa_context_errno(c)));
269                     goto fail;
270                 }
271             }
272
273             break;
274         }
275
276         case PA_CONTEXT_TERMINATED:
277             quit(0);
278             break;
279
280         case PA_CONTEXT_FAILED:
281         default:
282             fprintf(stderr, "Connection failure: %s\n", pa_strerror(pa_context_errno(c)));
283             goto fail;
284     }
285
286     return;
287
288 fail:
289     quit(1);
290
291 }
292
293 /* Connection draining complete */
294 static void context_drain_complete(pa_context*c, void *userdata) {
295     pa_context_disconnect(c);
296 }
297
298 /* Stream draining complete */
299 static void stream_drain_complete(pa_stream*s, int success, void *userdata) {
300     pa_operation *o;
301
302     if (!success) {
303         fprintf(stderr, "Failed to drain stream: %s\n", pa_strerror(pa_context_errno(context)));
304         quit(1);
305     }
306
307     if (verbose)
308         fprintf(stderr, "Playback stream drained.\n");
309
310     pa_stream_disconnect(stream);
311     pa_stream_unref(stream);
312     stream = NULL;
313
314     if (!(o = pa_context_drain(context, context_drain_complete, NULL)))
315         pa_context_disconnect(context);
316     else {
317         if (verbose)
318             fprintf(stderr, "Draining connection to server.\n");
319     }
320 }
321
322 /* New data on STDIN **/
323 static void stdin_callback(pa_mainloop_api*a, pa_io_event *e, int fd, pa_io_event_flags_t f, void *userdata) {
324     size_t l, w = 0;
325     ssize_t r;
326
327     assert(a == mainloop_api);
328     assert(e);
329     assert(stdio_event == e);
330
331     if (buffer) {
332         mainloop_api->io_enable(stdio_event, PA_IO_EVENT_NULL);
333         return;
334     }
335
336     if (!stream || pa_stream_get_state(stream) != PA_STREAM_READY || !(l = w = pa_stream_writable_size(stream)))
337         l = 4096;
338
339     buffer = pa_xmalloc(l);
340
341     if ((r = read(fd, buffer, l)) <= 0) {
342         if (r == 0) {
343             if (verbose)
344                 fprintf(stderr, "Got EOF.\n");
345
346             if (stream) {
347                 pa_operation *o;
348
349                 if (!(o = pa_stream_drain(stream, stream_drain_complete, NULL))) {
350                     fprintf(stderr, "pa_stream_drain(): %s\n", pa_strerror(pa_context_errno(context)));
351                     quit(1);
352                     return;
353                 }
354
355                 pa_operation_unref(o);
356             } else
357                 quit(0);
358
359         } else {
360             fprintf(stderr, "read() failed: %s\n", strerror(errno));
361             quit(1);
362         }
363
364         mainloop_api->io_free(stdio_event);
365         stdio_event = NULL;
366         return;
367     }
368
369     buffer_length = r;
370     buffer_index = 0;
371
372     if (w)
373         do_stream_write(w);
374 }
375
376 /* Some data may be written to STDOUT */
377 static void stdout_callback(pa_mainloop_api*a, pa_io_event *e, int fd, pa_io_event_flags_t f, void *userdata) {
378     ssize_t r;
379
380     assert(a == mainloop_api);
381     assert(e);
382     assert(stdio_event == e);
383
384     if (!buffer) {
385         mainloop_api->io_enable(stdio_event, PA_IO_EVENT_NULL);
386         return;
387     }
388
389     assert(buffer_length);
390
391     if ((r = write(fd, (uint8_t*) buffer+buffer_index, buffer_length)) <= 0) {
392         fprintf(stderr, "write() failed: %s\n", strerror(errno));
393         quit(1);
394
395         mainloop_api->io_free(stdio_event);
396         stdio_event = NULL;
397         return;
398     }
399
400     buffer_length -= r;
401     buffer_index += r;
402
403     if (!buffer_length) {
404         pa_xfree(buffer);
405         buffer = NULL;
406         buffer_length = buffer_index = 0;
407     }
408 }
409
410 /* UNIX signal to quit recieved */
411 static void exit_signal_callback(pa_mainloop_api*m, pa_signal_event *e, int sig, void *userdata) {
412     if (verbose)
413         fprintf(stderr, "Got signal, exiting.\n");
414     quit(0);
415 }
416
417 /* Show the current latency */
418 static void stream_update_timing_callback(pa_stream *s, int success, void *userdata) {
419     pa_usec_t latency, usec;
420     int negative = 0;
421
422     assert(s);
423
424     if (!success ||
425         pa_stream_get_time(s, &usec) < 0 ||
426         pa_stream_get_latency(s, &latency, &negative) < 0) {
427         fprintf(stderr, "Failed to get latency: %s\n", pa_strerror(pa_context_errno(context)));
428         quit(1);
429         return;
430     }
431
432     fprintf(stderr, "Time: %0.3f sec; Latency: %0.0f usec.  \r",
433             (float) usec / 1000000,
434             (float) latency * (negative?-1:1));
435 }
436
437 /* Someone requested that the latency is shown */
438 static void sigusr1_signal_callback(pa_mainloop_api*m, pa_signal_event *e, int sig, void *userdata) {
439
440     if (!stream)
441         return;
442
443     pa_operation_unref(pa_stream_update_timing_info(stream, stream_update_timing_callback, NULL));
444 }
445
446 static void time_event_callback(pa_mainloop_api*m, pa_time_event *e, const struct timeval *tv, void *userdata) {
447     struct timeval next;
448
449     if (stream && pa_stream_get_state(stream) == PA_STREAM_READY) {
450         pa_operation *o;
451         if (!(o = pa_stream_update_timing_info(stream, stream_update_timing_callback, NULL)))
452             fprintf(stderr, "pa_stream_update_timing_info() failed: %s\n", pa_strerror(pa_context_errno(context)));
453         else
454             pa_operation_unref(o);
455     }
456
457     pa_gettimeofday(&next);
458     pa_timeval_add(&next, TIME_EVENT_USEC);
459
460     m->time_restart(e, &next);
461 }
462
463 static void help(const char *argv0) {
464
465     printf("%s [options]\n\n"
466            "  -h, --help                            Show this help\n"
467            "      --version                         Show version\n\n"
468            "  -r, --record                          Create a connection for recording\n"
469            "  -p, --playback                        Create a connection for playback\n\n"
470            "  -v, --verbose                         Enable verbose operations\n\n"
471            "  -s, --server=SERVER                   The name of the server to connect to\n"
472            "  -d, --device=DEVICE                   The name of the sink/source to connect to\n"
473            "  -n, --client-name=NAME                How to call this client on the server\n"
474            "      --stream-name=NAME                How to call this stream on the server\n"
475            "      --volume=VOLUME                   Specify the initial (linear) volume in range 0...65536\n"
476            "      --rate=SAMPLERATE                 The sample rate in Hz (defaults to 44100)\n"
477            "      --format=SAMPLEFORMAT             The sample type, one of s16le, s16be, u8, float32le,\n"
478            "                                        float32be, ulaw, alaw (defaults to s16ne)\n"
479            "      --channels=CHANNELS               The number of channels, 1 for mono, 2 for stereo\n"
480            "                                        (defaults to 2)\n"
481            "      --channel-map=CHANNELMAP          Channel map to use instead of the default\n"
482            "      --fix-format                      Take the sample format from the sink the stream is\n"
483            "                                        being connected to.\n"
484            "      --fix-rate                        Take the sampling rate from the sink the stream is\n"
485            "                                        being connected to.\n"
486            "      --fix-channels                    Take the number of channels and the channel map\n"
487            "                                        from the sink the stream is being connected to.\n"
488            "      --no-remix                        Don't upmix or downmix channels.\n"
489            "      --no-remap                        Map channels by index instead of name.\n"
490            "      --latency=BYTES                   Request the specified latency in bytes.\n"
491            ,
492            argv0);
493 }
494
495 enum {
496     ARG_VERSION = 256,
497     ARG_STREAM_NAME,
498     ARG_VOLUME,
499     ARG_SAMPLERATE,
500     ARG_SAMPLEFORMAT,
501     ARG_CHANNELS,
502     ARG_CHANNELMAP,
503     ARG_FIX_FORMAT,
504     ARG_FIX_RATE,
505     ARG_FIX_CHANNELS,
506     ARG_NO_REMAP,
507     ARG_NO_REMIX,
508     ARG_LATENCY
509 };
510
511 int main(int argc, char *argv[]) {
512     pa_mainloop* m = NULL;
513     int ret = 1, r, c;
514     char *bn, *server = NULL;
515     pa_time_event *time_event = NULL;
516
517     static const struct option long_options[] = {
518         {"record",      0, NULL, 'r'},
519         {"playback",    0, NULL, 'p'},
520         {"device",      1, NULL, 'd'},
521         {"server",      1, NULL, 's'},
522         {"client-name", 1, NULL, 'n'},
523         {"stream-name", 1, NULL, ARG_STREAM_NAME},
524         {"version",     0, NULL, ARG_VERSION},
525         {"help",        0, NULL, 'h'},
526         {"verbose",     0, NULL, 'v'},
527         {"volume",      1, NULL, ARG_VOLUME},
528         {"rate",        1, NULL, ARG_SAMPLERATE},
529         {"format",      1, NULL, ARG_SAMPLEFORMAT},
530         {"channels",    1, NULL, ARG_CHANNELS},
531         {"channel-map", 1, NULL, ARG_CHANNELMAP},
532         {"fix-format",  0, NULL, ARG_FIX_FORMAT},
533         {"fix-rate",    0, NULL, ARG_FIX_RATE},
534         {"fix-channels",0, NULL, ARG_FIX_CHANNELS},
535         {"no-remap",    0, NULL, ARG_NO_REMAP},
536         {"no-remix",    0, NULL, ARG_NO_REMIX},
537         {"latency",     0, NULL, ARG_LATENCY},
538         {NULL,          0, NULL, 0}
539     };
540
541     if (!(bn = strrchr(argv[0], '/')))
542         bn = argv[0];
543     else
544         bn++;
545
546     if (strstr(bn, "rec") || strstr(bn, "mon"))
547         mode = RECORD;
548     else if (strstr(bn, "cat") || strstr(bn, "play"))
549         mode = PLAYBACK;
550
551     while ((c = getopt_long(argc, argv, "rpd:s:n:hv", long_options, NULL)) != -1) {
552
553         switch (c) {
554             case 'h' :
555                 help(bn);
556                 ret = 0;
557                 goto quit;
558
559             case ARG_VERSION:
560                 printf("pacat "PACKAGE_VERSION"\nCompiled with libpulse %s\nLinked with libpulse %s\n", pa_get_headers_version(), pa_get_library_version());
561                 ret = 0;
562                 goto quit;
563
564             case 'r':
565                 mode = RECORD;
566                 break;
567
568             case 'p':
569                 mode = PLAYBACK;
570                 break;
571
572             case 'd':
573                 pa_xfree(device);
574                 device = pa_xstrdup(optarg);
575                 break;
576
577             case 's':
578                 pa_xfree(server);
579                 server = pa_xstrdup(optarg);
580                 break;
581
582             case 'n':
583                 pa_xfree(client_name);
584                 client_name = pa_xstrdup(optarg);
585                 break;
586
587             case ARG_STREAM_NAME:
588                 pa_xfree(stream_name);
589                 stream_name = pa_xstrdup(optarg);
590                 break;
591
592             case 'v':
593                 verbose = 1;
594                 break;
595
596             case ARG_VOLUME: {
597                 int v = atoi(optarg);
598                 volume = v < 0 ? 0 : v;
599                 break;
600             }
601
602             case ARG_CHANNELS:
603                 sample_spec.channels = atoi(optarg);
604                 break;
605
606             case ARG_SAMPLEFORMAT:
607                 sample_spec.format = pa_parse_sample_format(optarg);
608                 break;
609
610             case ARG_SAMPLERATE:
611                 sample_spec.rate = atoi(optarg);
612                 break;
613
614             case ARG_CHANNELMAP:
615                 if (!pa_channel_map_parse(&channel_map, optarg)) {
616                     fprintf(stderr, "Invalid channel map '%s'\n", optarg);
617                     goto quit;
618                 }
619
620                 channel_map_set = 1;
621                 break;
622
623             case ARG_FIX_CHANNELS:
624                 flags |= PA_STREAM_FIX_CHANNELS;
625                 break;
626
627             case ARG_FIX_RATE:
628                 flags |= PA_STREAM_FIX_RATE;
629                 break;
630
631             case ARG_FIX_FORMAT:
632                 flags |= PA_STREAM_FIX_FORMAT;
633                 break;
634
635             case ARG_NO_REMIX:
636                 flags |= PA_STREAM_NO_REMIX_CHANNELS;
637                 break;
638
639             case ARG_NO_REMAP:
640                 flags |= PA_STREAM_NO_REMAP_CHANNELS;
641                 break;
642
643             case ARG_LATENCY:
644                 if (((latency = atoi(optarg))) <= 0) {
645                     fprintf(stderr, "Invallid latency specification '%s'\n", optarg);
646                     goto quit;
647                 }
648                 break;
649
650             default:
651                 goto quit;
652         }
653     }
654
655     if (!pa_sample_spec_valid(&sample_spec)) {
656         fprintf(stderr, "Invalid sample specification\n");
657         goto quit;
658     }
659
660     if (channel_map_set && channel_map.channels != sample_spec.channels) {
661         fprintf(stderr, "Channel map doesn't match sample specification\n");
662         goto quit;
663     }
664
665     if (verbose) {
666         char t[PA_SAMPLE_SPEC_SNPRINT_MAX];
667         pa_sample_spec_snprint(t, sizeof(t), &sample_spec);
668         fprintf(stderr, "Opening a %s stream with sample specification '%s'.\n", mode == RECORD ? "recording" : "playback", t);
669     }
670
671     if (!(optind >= argc)) {
672         if (optind+1 == argc) {
673             int fd;
674
675             if ((fd = open(argv[optind], mode == PLAYBACK ? O_RDONLY : O_WRONLY|O_TRUNC|O_CREAT, 0666)) < 0) {
676                 fprintf(stderr, "open(): %s\n", strerror(errno));
677                 goto quit;
678             }
679
680             if (dup2(fd, mode == PLAYBACK ? 0 : 1) < 0) {
681                 fprintf(stderr, "dup2(): %s\n", strerror(errno));
682                 goto quit;
683             }
684
685             close(fd);
686
687             if (!stream_name)
688                 stream_name = pa_xstrdup(argv[optind]);
689
690         } else {
691             fprintf(stderr, "Too many arguments.\n");
692             goto quit;
693         }
694     }
695
696     if (!client_name)
697         client_name = pa_xstrdup(bn);
698
699     if (!stream_name)
700         stream_name = pa_xstrdup(client_name);
701
702     /* Set up a new main loop */
703     if (!(m = pa_mainloop_new())) {
704         fprintf(stderr, "pa_mainloop_new() failed.\n");
705         goto quit;
706     }
707
708     mainloop_api = pa_mainloop_get_api(m);
709
710     r = pa_signal_init(mainloop_api);
711     assert(r == 0);
712     pa_signal_new(SIGINT, exit_signal_callback, NULL);
713     pa_signal_new(SIGTERM, exit_signal_callback, NULL);
714 #ifdef SIGUSR1
715     pa_signal_new(SIGUSR1, sigusr1_signal_callback, NULL);
716 #endif
717 #ifdef SIGPIPE
718     signal(SIGPIPE, SIG_IGN);
719 #endif
720
721     if (!(stdio_event = mainloop_api->io_new(mainloop_api,
722                                              mode == PLAYBACK ? STDIN_FILENO : STDOUT_FILENO,
723                                              mode == PLAYBACK ? PA_IO_EVENT_INPUT : PA_IO_EVENT_OUTPUT,
724                                              mode == PLAYBACK ? stdin_callback : stdout_callback, NULL))) {
725         fprintf(stderr, "io_new() failed.\n");
726         goto quit;
727     }
728
729     /* Create a new connection context */
730     if (!(context = pa_context_new(mainloop_api, client_name))) {
731         fprintf(stderr, "pa_context_new() failed.\n");
732         goto quit;
733     }
734
735     pa_context_set_state_callback(context, context_state_callback, NULL);
736
737     /* Connect the context */
738     pa_context_connect(context, server, 0, NULL);
739
740     if (verbose) {
741         struct timeval tv;
742
743         pa_gettimeofday(&tv);
744         pa_timeval_add(&tv, TIME_EVENT_USEC);
745
746         if (!(time_event = mainloop_api->time_new(mainloop_api, &tv, time_event_callback, NULL))) {
747             fprintf(stderr, "time_new() failed.\n");
748             goto quit;
749         }
750     }
751
752     /* Run the main loop */
753     if (pa_mainloop_run(m, &ret) < 0) {
754         fprintf(stderr, "pa_mainloop_run() failed.\n");
755         goto quit;
756     }
757
758 quit:
759     if (stream)
760         pa_stream_unref(stream);
761
762     if (context)
763         pa_context_unref(context);
764
765     if (stdio_event) {
766         assert(mainloop_api);
767         mainloop_api->io_free(stdio_event);
768     }
769
770     if (time_event) {
771         assert(mainloop_api);
772         mainloop_api->time_free(time_event);
773     }
774
775     if (m) {
776         pa_signal_done();
777         pa_mainloop_free(m);
778     }
779
780     pa_xfree(buffer);
781
782     pa_xfree(server);
783     pa_xfree(device);
784     pa_xfree(client_name);
785     pa_xfree(stream_name);
786
787     return ret;
788 }