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