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