]> git.tuebingen.mpg.de Git - paraslash.git/blob - play.c
Convert receivers to lopsub.
[paraslash.git] / play.c
1 /*
2  * Copyright (C) 2012 Andre Noll <maan@tuebingen.mpg.de>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file play.c Paraslash's standalone player. */
8
9 #include <regex.h>
10 #include <signal.h>
11 #include <inttypes.h>
12 #include <lopsub.h>
13
14 #include "recv_cmd.lsg.h"
15 #include "para.h"
16 #include "list.h"
17 #include "play.cmdline.h"
18 #include "play_cmd.lsg.h"
19 #include "error.h"
20 #include "ggo.h"
21 #include "buffer_tree.h"
22 #include "version.h"
23 #include "string.h"
24 #include "sched.h"
25 #include "filter.h"
26 #include "afh.h"
27 #include "recv.h"
28 #include "write.h"
29 #include "write_common.h"
30 #include "fd.h"
31
32 /**
33  * Besides playback tasks which correspond to the receiver/filter/writer nodes,
34  * para_play creates two further tasks: The play task and the i9e task. It is
35  * important whether a function can be called in the context of para_play or
36  * i9e or both. As a rule, all command handlers are called only in i9e context via
37  * the line handler (input mode) or the key handler (command mode) below.
38  *
39  * Playlist handling is done exclusively in play context.
40  */
41
42 /** Array of error strings. */
43 DEFINE_PARA_ERRLIST;
44
45 /**
46  * Describes a request to change the state of para_play.
47  *
48  * There is only one variable of this type: \a rq of the global play task
49  * structure. Command handlers only set this variable and the post_select()
50  * function of the play task investigates its value during each iteration of
51  * the scheduler run and performs the actual work.
52  */
53 enum state_change_request_type {
54         /** Everybody is happy. */
55         CRT_NONE,
56         /** Stream must be repositioned (com_jmp(), com_ff()). */
57         CRT_REPOS,
58         /** New file should be loaded (com_next()). */
59         CRT_FILE_CHANGE,
60         /** Someone wants us for dead (com_quit()). */
61         CRT_TERM_RQ
62 };
63
64 struct play_task {
65         struct task *task;
66         /* A bit array of invalid files (those will be skipped). */
67         bool *invalid;
68         /* The file which is currently open. */
69         unsigned current_file;
70         /* When to update the status again. */
71         struct timeval next_update;
72
73         /* Root of the buffer tree for command and status output. */
74         struct btr_node *btrn;
75
76         /* The decoding machinery.  */
77         struct receiver_node rn;
78         struct filter_node fn;
79         struct writer_node wn;
80
81         /* See comment to enum state_change_request_type above */
82         enum state_change_request_type rq;
83         /* only relevant if rq == CRT_FILE_CHANGE */
84         unsigned next_file;
85         /*
86                 bg: read lines at prompt, fg: display status and wait
87                 for keystroke.
88         */
89         bool background;
90
91         /* We have the *intention* to play. Set by com_play(). */
92         bool playing;
93
94         /* as returned by afh_recv->open() */
95         int audio_format_num;
96
97         /* retrieved via the btr exec mechanism */
98         long unsigned start_chunk;
99         long unsigned seconds;
100         long unsigned num_chunks;
101         char *afhi_txt;
102 };
103
104 typedef int (*play_cmd_handler_t)(struct play_task *pt,
105                 struct lls_parse_result *lpr);
106 struct play_command_info {
107         play_cmd_handler_t handler;
108 };
109 #define EXPORT_PLAY_CMD_HANDLER(_cmd) \
110         const struct play_command_info lsg_play_cmd_com_ ## _cmd ## _user_data = { \
111                 .handler = com_ ## _cmd \
112         };
113
114 static int loglevel = LL_WARNING;
115
116 /** The log function which writes log messages to stderr. */
117 INIT_STDERR_LOGGING(loglevel);
118
119 char *stat_item_values[NUM_STAT_ITEMS] = {NULL};
120
121 /** Iterate over all files in the playlist. */
122 #define FOR_EACH_PLAYLIST_FILE(i) for (i = 0; i < conf.inputs_num; i++)
123 static struct play_args_info conf;
124
125 static struct sched sched = {.max_fileno = 0};
126 static struct play_task play_task;
127
128 #define AFH_RECV_CMD (lls_cmd(LSG_RECV_CMD_CMD_AFH, recv_cmd_suite))
129 #define AFH_RECV ((struct receiver *)lls_user_data(AFH_RECV_CMD))
130
131 __noreturn static void print_help_and_die(void)
132 {
133         struct ggo_help help = DEFINE_GGO_HELP(play);
134         unsigned flags = conf.detailed_help_given?
135                 GPH_STANDARD_FLAGS_DETAILED : GPH_STANDARD_FLAGS;
136
137         ggo_print_help(&help, flags);
138         printf("supported audio formats: %s\n", AUDIO_FORMAT_HANDLERS);
139         exit(0);
140 }
141
142 static void parse_config_or_die(int argc, char *argv[])
143 {
144         int i, ret;
145         char *config_file;
146         struct play_cmdline_parser_params params = {
147                 .override = 0,
148                 .initialize = 1,
149                 .check_required = 0,
150                 .check_ambiguity = 0,
151                 .print_errors = 1
152         };
153
154         play_cmdline_parser_ext(argc, argv, &conf, &params);
155         loglevel = get_loglevel_by_name(conf.loglevel_arg);
156         version_handle_flag("play", conf.version_given);
157         if (conf.help_given || conf.detailed_help_given)
158                 print_help_and_die();
159         if (conf.config_file_given)
160                 config_file = para_strdup(conf.config_file_arg);
161         else {
162                 char *home = para_homedir();
163                 config_file = make_message("%s/.paraslash/play.conf", home);
164                 free(home);
165         }
166         ret = file_exists(config_file);
167         if (conf.config_file_given && !ret) {
168                 PARA_EMERG_LOG("can not read config file %s\n", config_file);
169                 goto err;
170         }
171         if (ret) {
172                 params.initialize = 0;
173                 params.check_required = 1;
174                 play_cmdline_parser_config_file(config_file, &conf, &params);
175                 loglevel = get_loglevel_by_name(conf.loglevel_arg);
176         }
177         for (i = 0; i < conf.key_map_given; i++) {
178                 char *kma = conf.key_map_arg[i];
179                 if (*kma && strchr(kma + 1, ':'))
180                         continue;
181                 PARA_EMERG_LOG("invalid key map arg: %s\n", kma);
182                 goto err;
183         }
184         free(config_file);
185         return;
186 err:
187         free(config_file);
188         exit(EXIT_FAILURE);
189 }
190
191 static char get_playback_state(struct play_task *pt)
192 {
193         switch (pt->rq) {
194         case CRT_NONE: return pt->playing? 'P' : 'U';
195         case CRT_REPOS: return 'R';
196         case CRT_FILE_CHANGE: return 'F';
197         case CRT_TERM_RQ: return 'X';
198         }
199         assert(false);
200 };
201
202 static long unsigned get_play_time(struct play_task *pt)
203 {
204         char state = get_playback_state(pt);
205         long unsigned result;
206
207         if (state != 'P' && state != 'U')
208                 return 0;
209         if (pt->num_chunks == 0 || pt->seconds == 0)
210                 return 0;
211         /* where the stream started (in seconds) */
212         result = pt->start_chunk * pt->seconds / pt->num_chunks;
213         if (pt->wn.btrn) { /* Add the uptime of the writer node */
214                 struct timeval diff = {.tv_sec = 0}, wstime;
215                 btr_get_node_start(pt->wn.btrn, &wstime);
216                 if (wstime.tv_sec > 0)
217                         tv_diff(now, &wstime, &diff);
218                 result += diff.tv_sec;
219         }
220         result = PARA_MIN(result, pt->seconds);
221         result = PARA_MAX(result, 0UL);
222         return result;
223 }
224
225
226 static void wipe_receiver_node(struct play_task *pt)
227 {
228         PARA_NOTICE_LOG("cleaning up receiver node\n");
229         btr_remove_node(&pt->rn.btrn);
230         AFH_RECV->close(&pt->rn);
231         lls_free_parse_result(pt->rn.lpr, AFH_RECV_CMD);
232         memset(&pt->rn, 0, sizeof(struct receiver_node));
233 }
234
235 /* returns: 0 not eof, 1: eof, < 0: fatal error.  */
236 static int get_playback_error(struct play_task *pt)
237 {
238         int err;
239
240         if (!pt->wn.task)
241                 return 0;
242         err = task_status(pt->wn.task);
243         if (err >= 0)
244                 return 0;
245         if (task_status(pt->fn.task) >= 0)
246                 return 0;
247         if (task_status(pt->rn.task) >= 0)
248                 return 0;
249         if (err == -E_BTR_EOF || err == -E_RECV_EOF || err == -E_EOF
250                         || err == -E_WRITE_COMMON_EOF)
251                 return 1;
252         return err;
253 }
254
255 static int eof_cleanup(struct play_task *pt)
256 {
257         struct writer *w = writers + DEFAULT_WRITER;
258         const struct filter *decoder = filter_get(pt->fn.filter_num);
259         int ret;
260
261         ret = get_playback_error(pt);
262         if (ret == 0)
263                 return ret;
264         PARA_NOTICE_LOG("cleaning up wn/fn nodes\n");
265         task_reap(&pt->wn.task);
266         w->close(&pt->wn);
267         btr_remove_node(&pt->wn.btrn);
268         w->free_config(pt->wn.conf);
269         memset(&pt->wn, 0, sizeof(struct writer_node));
270
271         task_reap(&pt->fn.task);
272         if (decoder->close)
273                 decoder->close(&pt->fn);
274         btr_remove_node(&pt->fn.btrn);
275         free(pt->fn.conf);
276         memset(&pt->fn, 0, sizeof(struct filter_node));
277
278         task_reap(&pt->rn.task);
279         btr_remove_node(&pt->rn.btrn);
280         /*
281          * On eof (ret > 0), we do not wipe the receiver node struct until a
282          * new file is loaded because we still need it for jumping around when
283          * paused.
284          */
285         if (ret < 0)
286                 wipe_receiver_node(pt);
287         return ret;
288 }
289
290 static int shuffle_compare(__a_unused const void *a, __a_unused const void *b)
291 {
292         return para_random(100) - 50;
293 }
294
295 static void shuffle(char **base, size_t num)
296 {
297         srandom(time(NULL));
298         qsort(base, num, sizeof(char *), shuffle_compare);
299 }
300
301 static struct btr_node *new_recv_btrn(struct receiver_node *rn)
302 {
303         return btr_new_node(&(struct btr_node_description)
304                 EMBRACE(.name = lls_command_name(AFH_RECV_CMD), .context = rn,
305                         .handler = AFH_RECV->execute));
306 }
307
308 static int open_new_file(struct play_task *pt)
309 {
310         int ret;
311         char *tmp, *path = conf.inputs[pt->next_file], *errctx = NULL,
312                 *argv[] = {"play", "-f", path, "-b", "0", NULL};
313
314         PARA_NOTICE_LOG("next file: %s\n", path);
315         wipe_receiver_node(pt);
316         pt->start_chunk = 0;
317         pt->rn.btrn = new_recv_btrn(&pt->rn);
318         ret = lls(lls_parse(ARRAY_SIZE(argv) - 1, argv, AFH_RECV_CMD,
319                 &pt->rn.lpr, &errctx));
320         free(tmp);
321         assert(ret >= 0);
322         pt->rn.receiver = AFH_RECV;
323         ret = AFH_RECV->open(&pt->rn);
324         if (ret < 0) {
325                 PARA_ERROR_LOG("could not open %s\n", path);
326                 goto fail;
327         }
328         pt->audio_format_num = ret;
329         free(pt->afhi_txt);
330         ret = btr_exec_up(pt->rn.btrn, "afhi", &pt->afhi_txt);
331         if (ret < 0)
332                 pt->afhi_txt = make_message("[afhi command failed]\n");
333         ret = btr_exec_up(pt->rn.btrn, "seconds_total", &tmp);
334         if (ret < 0)
335                 pt->seconds = 1;
336         else {
337                 int32_t x;
338                 ret = para_atoi32(tmp, &x);
339                 pt->seconds = ret < 0? 1 : x;
340                 free(tmp);
341                 tmp = NULL;
342         }
343         ret = btr_exec_up(pt->rn.btrn, "chunks_total", &tmp);
344         if (ret < 0)
345                 pt->num_chunks = 1;
346         else {
347                 int32_t x;
348                 ret = para_atoi32(tmp, &x);
349                 pt->num_chunks = ret < 0? 1 : x;
350                 free(tmp);
351                 tmp = NULL;
352         }
353         return 1;
354 fail:
355         wipe_receiver_node(pt);
356         return ret;
357 }
358
359 static int load_file(struct play_task *pt)
360 {
361         const char *af;
362         char *tmp, buf[20];
363         int ret;
364         const struct filter *decoder;
365
366         btr_remove_node(&pt->rn.btrn);
367         if (!pt->rn.receiver || pt->next_file != pt->current_file) {
368                 ret = open_new_file(pt);
369                 if (ret < 0)
370                         return ret;
371         } else {
372                 pt->rn.btrn = new_recv_btrn(&pt->rn);
373                 sprintf(buf, "repos %lu", pt->start_chunk);
374                 ret = btr_exec_up(pt->rn.btrn, buf, &tmp);
375                 if (ret < 0)
376                         PARA_CRIT_LOG("repos failed: %s\n", para_strerror(-ret));
377                 freep(&tmp);
378         }
379         if (!pt->playing)
380                 return 0;
381         /* set up decoding filter */
382         af = audio_format_name(pt->audio_format_num);
383         tmp = make_message("%sdec", af);
384         PARA_INFO_LOG("decoder: %s\n", tmp);
385         ret = check_filter_arg(tmp, &pt->fn.conf);
386         freep(&tmp);
387         if (ret < 0)
388                 goto fail;
389         pt->fn.filter_num = ret;
390         decoder = filter_get(ret);
391         pt->fn.btrn = btr_new_node(&(struct btr_node_description)
392                 EMBRACE(.name = decoder->name, .parent = pt->rn.btrn,
393                         .handler = decoder->execute, .context = &pt->fn));
394         if (decoder->open)
395                 decoder->open(&pt->fn);
396         PARA_INFO_LOG("buffer tree:\n");
397         btr_log_tree(pt->rn.btrn, LL_INFO);
398
399         /* setup default writer */
400         pt->wn.conf = check_writer_arg_or_die(NULL, &pt->wn.writer_num);
401
402         /* success, register tasks */
403         pt->rn.task = task_register(
404                 &(struct task_info) {
405                         .name = lls_command_name(AFH_RECV_CMD),
406                         .pre_select = AFH_RECV->pre_select,
407                         .post_select = AFH_RECV->post_select,
408                         .context = &pt->rn
409                 }, &sched);
410         sprintf(buf, "%s decoder", af);
411         pt->fn.task = task_register(
412                 &(struct task_info) {
413                         .name = buf,
414                         .pre_select = decoder->pre_select,
415                         .post_select = decoder->post_select,
416                         .context = &pt->fn
417                 }, &sched);
418         register_writer_node(&pt->wn, pt->fn.btrn, &sched);
419         return 1;
420 fail:
421         wipe_receiver_node(pt);
422         return ret;
423 }
424
425 static int next_valid_file(struct play_task *pt)
426 {
427         int i, j = pt->current_file;
428
429         FOR_EACH_PLAYLIST_FILE(i) {
430                 j = (j + 1) % conf.inputs_num;
431                 if (!pt->invalid[j])
432                         return j;
433         }
434         return -E_NO_VALID_FILES;
435 }
436
437 static int load_next_file(struct play_task *pt)
438 {
439         int ret;
440
441 again:
442         if (pt->rq == CRT_NONE) {
443                 pt->start_chunk = 0;
444                 ret = next_valid_file(pt);
445                 if (ret < 0)
446                         return ret;
447                 pt->next_file = ret;
448         } else if (pt->rq == CRT_REPOS)
449                 pt->next_file = pt->current_file;
450         ret = load_file(pt);
451         if (ret < 0) {
452                 PARA_ERROR_LOG("%s: marking file as invalid\n",
453                         para_strerror(-ret));
454                 pt->invalid[pt->next_file] = true;
455                 pt->rq = CRT_NONE;
456                 goto again;
457         }
458         pt->current_file = pt->next_file;
459         pt->rq = CRT_NONE;
460         return ret;
461 }
462
463 static void kill_stream(struct play_task *pt)
464 {
465         if (pt->wn.task)
466                 task_notify(pt->wn.task, E_EOF);
467 }
468
469 #ifdef HAVE_READLINE
470
471 /* only called from com_prev(), nec. only if we have readline */
472 static int previous_valid_file(struct play_task *pt)
473 {
474         int i, j = pt->current_file;
475
476         FOR_EACH_PLAYLIST_FILE(i) {
477                 j--;
478                 if (j < 0)
479                         j = conf.inputs_num - 1;
480                 if (!pt->invalid[j])
481                         return j;
482         }
483         return -E_NO_VALID_FILES;
484 }
485
486 #include "interactive.h"
487
488 /*
489  * Define the default (internal) key mappings and helper functions to get the
490  * key sequence or the command from a key id, which is what we obtain from
491  * i9e/readline when the key is pressed.
492  *
493  * In some of these helper functions we could return pointers to the constant
494  * arrays defined below. However, for others we can not, so let's better be
495  * consistent and allocate all returned strings on the heap.
496  */
497
498 #define INTERNAL_KEYMAP_ENTRIES \
499         KEYMAP_ENTRY("^", "jmp 0"), \
500         KEYMAP_ENTRY("1", "jmp 10"), \
501         KEYMAP_ENTRY("2", "jmp 21"), \
502         KEYMAP_ENTRY("3", "jmp 32"), \
503         KEYMAP_ENTRY("4", "jmp 43"), \
504         KEYMAP_ENTRY("5", "jmp 54"), \
505         KEYMAP_ENTRY("6", "jmp 65"), \
506         KEYMAP_ENTRY("7", "jmp 76"), \
507         KEYMAP_ENTRY("8", "jmp 87"), \
508         KEYMAP_ENTRY("9", "jmp 98"), \
509         KEYMAP_ENTRY("+", "next"), \
510         KEYMAP_ENTRY("-", "prev"), \
511         KEYMAP_ENTRY(":", "bg"), \
512         KEYMAP_ENTRY("i", "info"), \
513         KEYMAP_ENTRY("l", "ls"), \
514         KEYMAP_ENTRY("s", "play"), \
515         KEYMAP_ENTRY("p", "pause"), \
516         KEYMAP_ENTRY("q", "quit"), \
517         KEYMAP_ENTRY("?", "help"), \
518         KEYMAP_ENTRY("\033[D", "ff -10"), \
519         KEYMAP_ENTRY("\033[C", "ff 10"), \
520         KEYMAP_ENTRY("\033[A", "ff 60"), \
521         KEYMAP_ENTRY("\033[B", "ff -60"), \
522
523 #define KEYMAP_ENTRY(a, b) a
524 static const char *default_keyseqs[] = {INTERNAL_KEYMAP_ENTRIES};
525 #undef KEYMAP_ENTRY
526 #define KEYMAP_ENTRY(a, b) b
527 static const char *default_commands[] = {INTERNAL_KEYMAP_ENTRIES};
528 #undef KEYMAP_ENTRY
529 #define NUM_INTERNALLY_MAPPED_KEYS ARRAY_SIZE(default_commands)
530 #define NUM_MAPPED_KEYS (NUM_INTERNALLY_MAPPED_KEYS + conf.key_map_given)
531 #define FOR_EACH_MAPPED_KEY(i) for (i = 0; i < NUM_MAPPED_KEYS; i++)
532
533 static inline bool is_internal_key(int key)
534 {
535         return key < NUM_INTERNALLY_MAPPED_KEYS;
536 }
537
538 /* for internal keys, the key id is just the array index. */
539 static inline int get_internal_key_map_idx(int key)
540 {
541         assert(is_internal_key(key));
542         return key;
543 }
544
545 /*
546  * For user-defined keys, we have to subtract NUM_INTERNALLY_MAPPED_KEYS. The
547  * difference is the index to the array of user defined key maps.
548  */
549 static inline int get_user_key_map_idx(int key)
550 {
551         assert(!is_internal_key(key));
552         return key - NUM_INTERNALLY_MAPPED_KEYS;
553 }
554
555 static inline int get_key_map_idx(int key)
556 {
557         return is_internal_key(key)?
558                 get_internal_key_map_idx(key) : get_user_key_map_idx(key);
559 }
560
561 static inline char *get_user_key_map_arg(int key)
562 {
563         return conf.key_map_arg[get_user_key_map_idx(key)];
564 }
565
566 static inline char *get_internal_key_map_seq(int key)
567 {
568         return para_strdup(default_keyseqs[get_internal_key_map_idx(key)]);
569 }
570
571 static char *get_user_key_map_seq(int key)
572 {
573         const char *kma = get_user_key_map_arg(key);
574         const char *p = strchr(kma + 1, ':');
575         char *result;
576         int len;
577
578         if (!p)
579                 return NULL;
580         len = p - kma;
581         result = para_malloc(len + 1);
582         memcpy(result, kma, len);
583         result[len] = '\0';
584         return result;
585 }
586
587 static char *get_key_map_seq(int key)
588 {
589         return is_internal_key(key)?
590                 get_internal_key_map_seq(key) : get_user_key_map_seq(key);
591 }
592
593 static char *get_key_map_seq_safe(int key)
594 {
595         const char hex[] = "0123456789abcdef";
596         char *seq = get_key_map_seq(key), *sseq;
597         size_t n, len = strlen(seq);
598
599         if (len == 1 && isprint(*seq))
600                 return seq;
601         sseq = para_malloc(2 + 2 * len + 1);
602         sseq[0] = '0';
603         sseq[1] = 'x';
604         for (n = 0; n < len; n++) {
605                 uint8_t val = (seq[n] & 0xf0) >> 4;
606                 sseq[2 + 2 * n] = hex[val];
607                 val = seq[n] & 0xf;
608                 sseq[2 + 2 * n + 1] = hex[val];
609         }
610         free(seq);
611         sseq[2 + 2 * n] = '\0';
612         return sseq;
613 }
614
615 static inline char *get_internal_key_map_cmd(int key)
616 {
617         return para_strdup(default_commands[get_internal_key_map_idx(key)]);
618 }
619
620 static char *get_user_key_map_cmd(int key)
621 {
622         const char *kma = get_user_key_map_arg(key);
623         const char *p = strchr(kma + 1, ':');
624
625         if (!p)
626                 return NULL;
627         return para_strdup(p + 1);
628 }
629
630 static char *get_key_map_cmd(int key)
631 {
632         return is_internal_key(key)?
633                 get_internal_key_map_cmd(key) : get_user_key_map_cmd(key);
634 }
635
636 static char **get_mapped_keyseqs(void)
637 {
638         char **result;
639         int i;
640
641         result = para_malloc((NUM_MAPPED_KEYS + 1) * sizeof(char *));
642         FOR_EACH_MAPPED_KEY(i) {
643                 char *seq = get_key_map_seq(i);
644                 result[i] = seq;
645         }
646         result[i] = NULL;
647         return result;
648 }
649
650 static struct i9e_completer pp_completers[];
651
652 I9E_DUMMY_COMPLETER(jmp);
653 I9E_DUMMY_COMPLETER(next);
654 I9E_DUMMY_COMPLETER(prev);
655 I9E_DUMMY_COMPLETER(fg);
656 I9E_DUMMY_COMPLETER(bg);
657 I9E_DUMMY_COMPLETER(ls);
658 I9E_DUMMY_COMPLETER(info);
659 I9E_DUMMY_COMPLETER(play);
660 I9E_DUMMY_COMPLETER(pause);
661 I9E_DUMMY_COMPLETER(stop);
662 I9E_DUMMY_COMPLETER(tasks);
663 I9E_DUMMY_COMPLETER(quit);
664 I9E_DUMMY_COMPLETER(ff);
665
666 static void help_completer(struct i9e_completion_info *ci,
667                 struct i9e_completion_result *result)
668 {
669         result->matches = i9e_complete_commands(ci->word, pp_completers);
670 }
671
672 I9E_DUMMY_COMPLETER(SUPERCOMMAND_UNAVAILABLE);
673 static struct i9e_completer pp_completers[] = {
674 #define LSG_PLAY_CMD_CMD(_name) {.name = #_name, \
675         .completer = _name ## _completer}
676         LSG_PLAY_CMD_SUBCOMMANDS
677 #undef LSG_PLAY_CMD_CMD
678         {.name = NULL}
679 };
680
681 static void attach_stdout(struct play_task *pt, const char *name)
682 {
683         if (pt->btrn)
684                 return;
685         pt->btrn = btr_new_node(&(struct btr_node_description)
686                 EMBRACE(.name = name));
687         i9e_attach_to_stdout(pt->btrn);
688 }
689
690 static void detach_stdout(struct play_task *pt)
691 {
692         btr_remove_node(&pt->btrn);
693 }
694
695 static int com_quit(struct play_task *pt,
696                 __a_unused struct lls_parse_result *lpr)
697 {
698         pt->rq = CRT_TERM_RQ;
699         return 0;
700 }
701 EXPORT_PLAY_CMD_HANDLER(quit);
702
703 static int com_help(struct play_task *pt, struct lls_parse_result *lpr)
704 {
705         int i, ret;
706         char *buf, *errctx;
707         size_t sz;
708         const struct lls_command *cmd;
709
710         ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
711         if (ret < 0) {
712                 if (errctx)
713                         PARA_ERROR_LOG("%s\n", errctx);
714                 free(errctx);
715                 return ret;
716         }
717         if (lls_num_inputs(lpr) == 0) {
718                 if (pt->background) {
719                         for (i = 1; (cmd = lls_cmd(i, play_cmd_suite)); i++) {
720                                 sz = xasprintf(&buf, "%s\t%s\n",
721                                         lls_command_name(cmd), lls_purpose(cmd));
722                                 btr_add_output(buf, sz, pt->btrn);
723                         }
724                         return 0;
725                 }
726                 FOR_EACH_MAPPED_KEY(i) {
727                         bool internal = is_internal_key(i);
728                         int idx = get_key_map_idx(i);
729                         char *seq = get_key_map_seq_safe(i);
730                         char *kmc = get_key_map_cmd(i);
731                         sz = xasprintf(&buf, "%s key #%d: %s -> %s\n",
732                                 internal? "internal" : "user-defined",
733                                 idx, seq, kmc);
734                         btr_add_output(buf, sz, pt->btrn);
735                         free(seq);
736                         free(kmc);
737                 }
738                 return 0;
739         }
740         ret = lls(lls_lookup_subcmd(lls_input(0, lpr), play_cmd_suite,
741                 &errctx));
742         if (ret < 0) {
743                 if (errctx)
744                         PARA_ERROR_LOG("%s\n", errctx);
745                 free(errctx);
746                 return ret;
747         }
748         cmd = lls_cmd(ret, play_cmd_suite);
749         buf = lls_long_help(cmd);
750         assert(buf);
751         btr_add_output(buf, strlen(buf), pt->btrn);
752         return 0;
753 }
754 EXPORT_PLAY_CMD_HANDLER(help);
755
756 static int com_info(struct play_task *pt,
757                 __a_unused struct lls_parse_result *lpr)
758 {
759         char *buf;
760         size_t sz;
761         static char dflt[] = "[no information available]";
762
763         sz = xasprintf(&buf, "playlist_pos: %u\npath: %s\n",
764                 pt->current_file, conf.inputs[pt->current_file]);
765         btr_add_output(buf, sz, pt->btrn);
766         buf = pt->afhi_txt? pt->afhi_txt : dflt;
767         btr_add_output_dont_free(buf, strlen(buf), pt->btrn);
768         return 0;
769 }
770 EXPORT_PLAY_CMD_HANDLER(info);
771
772 static void list_file(struct play_task *pt, int num)
773 {
774         char *buf;
775         size_t sz;
776
777         sz = xasprintf(&buf, "%s %4d %s\n", num == pt->current_file?
778                 "*" : " ", num, conf.inputs[num]);
779         btr_add_output(buf, sz, pt->btrn);
780 }
781
782 static int com_tasks(struct play_task *pt,
783                 __a_unused struct lls_parse_result *lpr)
784 {
785         static char state;
786         char *buf;
787         size_t sz;
788
789         buf = get_task_list(&sched);
790         btr_add_output(buf, strlen(buf), pt->btrn);
791         state = get_playback_state(pt);
792         sz = xasprintf(&buf, "state: %c\n", state);
793         btr_add_output(buf, sz, pt->btrn);
794         return 0;
795 }
796 EXPORT_PLAY_CMD_HANDLER(tasks);
797
798 static int com_ls(struct play_task *pt,
799         __a_unused struct lls_parse_result *lpr)
800 {
801         int i;
802
803         FOR_EACH_PLAYLIST_FILE(i)
804                 list_file(pt, i);
805         return 0;
806 }
807 EXPORT_PLAY_CMD_HANDLER(ls);
808
809 static int com_play(struct play_task *pt, struct lls_parse_result *lpr)
810 {
811         int32_t x;
812         int ret;
813         char state, *errctx;
814
815         ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
816         if (ret < 0) {
817                 if (errctx)
818                         PARA_ERROR_LOG("%s\n", errctx);
819                 free(errctx);
820                 return ret;
821         }
822         state = get_playback_state(pt);
823         if (lls_num_inputs(lpr) == 0) {
824                 if (state == 'P')
825                         return 0;
826                 pt->next_file = pt->current_file;
827                 pt->rq = CRT_REPOS;
828                 pt->playing = true;
829                 return 0;
830         }
831         ret = para_atoi32(lls_input(0, lpr), &x);
832         if (ret < 0)
833                 return ret;
834         if (x < 0 || x >= conf.inputs_num)
835                 return -ERRNO_TO_PARA_ERROR(EINVAL);
836         kill_stream(pt);
837         pt->next_file = x;
838         pt->rq = CRT_FILE_CHANGE;
839         return 0;
840 }
841 EXPORT_PLAY_CMD_HANDLER(play);
842
843 static int com_pause(struct play_task *pt,
844                 __a_unused struct lls_parse_result *lpr)
845 {
846         char state;
847         long unsigned seconds, ss;
848
849         state = get_playback_state(pt);
850         pt->playing = false;
851         if (state != 'P')
852                 return 0;
853         seconds = get_play_time(pt);
854         pt->playing = false;
855         ss = 0;
856         if (pt->seconds > 0)
857                 ss = seconds * pt->num_chunks / pt->seconds + 1;
858         ss = PARA_MAX(ss, 0UL);
859         ss = PARA_MIN(ss, pt->num_chunks);
860         pt->start_chunk = ss;
861         kill_stream(pt);
862         return 0;
863 }
864 EXPORT_PLAY_CMD_HANDLER(pause);
865
866 static int com_prev(struct play_task *pt,
867         __a_unused struct lls_parse_result *lpr)
868 {
869         int ret;
870
871         ret = previous_valid_file(pt);
872         if (ret < 0)
873                 return ret;
874         kill_stream(pt);
875         pt->next_file = ret;
876         pt->rq = CRT_FILE_CHANGE;
877         pt->start_chunk = 0;
878         return 0;
879 }
880 EXPORT_PLAY_CMD_HANDLER(prev);
881
882 static int com_next(struct play_task *pt,
883                 __a_unused struct lls_parse_result *lpr)
884 {
885         int ret;
886
887         ret = next_valid_file(pt);
888         if (ret < 0)
889                 return ret;
890         kill_stream(pt);
891         pt->next_file = ret;
892         pt->rq = CRT_FILE_CHANGE;
893         pt->start_chunk = 0;
894         return 0;
895 }
896 EXPORT_PLAY_CMD_HANDLER(next);
897
898 static int com_fg(struct play_task *pt,
899                 __a_unused struct lls_parse_result *lpr)
900 {
901         pt->background = false;
902         return 0;
903 }
904 EXPORT_PLAY_CMD_HANDLER(fg);
905
906 static int com_bg(struct play_task *pt,
907         __a_unused struct lls_parse_result *lpr)
908 {
909         pt->background = true;
910         return 0;
911 }
912 EXPORT_PLAY_CMD_HANDLER(bg);
913
914 static int com_jmp(struct play_task *pt, struct lls_parse_result *lpr)
915 {
916         int32_t percent;
917         int ret;
918         char *errctx;
919
920         ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
921         if (ret < 0) {
922                 if (errctx)
923                         PARA_ERROR_LOG("%s\n", errctx);
924                 free(errctx);
925                 return ret;
926         }
927         ret = para_atoi32(lls_input(0, lpr), &percent);
928         if (ret < 0)
929                 return ret;
930         if (percent < 0 || percent > 100)
931                 return -ERRNO_TO_PARA_ERROR(EINVAL);
932         if (percent == 100)
933                 return com_next(pt, NULL);
934         if (pt->playing && !pt->fn.btrn)
935                 return 0;
936         pt->start_chunk = percent * pt->num_chunks / 100;
937         if (!pt->playing)
938                 return 0;
939         pt->rq = CRT_REPOS;
940         kill_stream(pt);
941         return 0;
942 }
943 EXPORT_PLAY_CMD_HANDLER(jmp);
944
945 static int com_ff(struct play_task *pt, struct lls_parse_result *lpr)
946 {
947         int32_t seconds;
948         char *errctx;
949         int ret;
950
951         ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
952         if (ret < 0) {
953                 if (errctx)
954                         PARA_ERROR_LOG("%s\n", errctx);
955                 free(errctx);
956                 return ret;
957         }
958         ret = para_atoi32(lls_input(0, lpr), &seconds);
959         if (ret < 0)
960                 return ret;
961         if (pt->playing && !pt->fn.btrn)
962                 return 0;
963         seconds += get_play_time(pt);
964         seconds = PARA_MIN(seconds, (typeof(seconds))pt->seconds - 4);
965         seconds = PARA_MAX(seconds, 0);
966         pt->start_chunk = pt->num_chunks * seconds / pt->seconds;
967         pt->start_chunk = PARA_MIN(pt->start_chunk, pt->num_chunks - 1);
968         pt->start_chunk = PARA_MAX(pt->start_chunk, 0UL);
969         if (!pt->playing)
970                 return 0;
971         pt->rq = CRT_REPOS;
972         kill_stream(pt);
973         return 0;
974 }
975 EXPORT_PLAY_CMD_HANDLER(ff);
976
977 static int run_command(char *line, struct play_task *pt)
978 {
979         int ret, argc;
980         char **argv = NULL;
981         char *errctx = NULL;
982         const struct play_command_info *pci;
983         struct lls_parse_result *lpr;
984         const struct lls_command *cmd;
985
986         attach_stdout(pt, __FUNCTION__);
987         ret = create_argv(line, " ", &argv);
988         if (ret < 0)
989                 goto out;
990         if (ret == 0)
991                 goto out;
992         argc = ret;
993         ret = lls(lls_lookup_subcmd(argv[0], play_cmd_suite, &errctx));
994         if (ret < 0)
995                 goto out;
996         cmd = lls_cmd(ret, play_cmd_suite);
997         ret = lls(lls_parse(argc, argv, cmd, &lpr, &errctx));
998         if (ret < 0)
999                 goto out;
1000         pci = lls_user_data(cmd);
1001         ret = pci->handler(pt, lpr);
1002         lls_free_parse_result(lpr, cmd);
1003 out:
1004         if (errctx)
1005                 PARA_ERROR_LOG("%s\n", errctx);
1006         free(errctx);
1007         free_argv(argv);
1008         return ret;
1009 }
1010
1011 static int play_i9e_line_handler(char *line)
1012 {
1013         return run_command(line, &play_task);
1014 }
1015
1016 static int play_i9e_key_handler(int key)
1017 {
1018         struct play_task *pt = &play_task;
1019         int idx = get_key_map_idx(key);
1020         char *seq = get_key_map_seq(key);
1021         char *cmd = get_key_map_cmd(key);
1022         bool internal = is_internal_key(key);
1023
1024         PARA_NOTICE_LOG("pressed %d: %s key #%d (%s -> %s)\n",
1025                 key, internal? "internal" : "user-defined",
1026                 idx, seq, cmd);
1027         run_command(cmd, pt);
1028         free(seq);
1029         free(cmd);
1030         pt->next_update = *now;
1031         return 0;
1032 }
1033
1034 static struct i9e_client_info ici = {
1035         .fds = {0, 1, 2},
1036         .prompt = "para_play> ",
1037         .line_handler = play_i9e_line_handler,
1038         .key_handler = play_i9e_key_handler,
1039         .completers = pp_completers,
1040 };
1041
1042 static void sigint_handler(int sig)
1043 {
1044         play_task.background = true;
1045         i9e_signal_dispatch(sig);
1046 }
1047
1048 /*
1049  * We start with para_log() set to the standard log function which writes to
1050  * stderr. Once the i9e subsystem has been initialized, we switch to the i9e
1051  * log facility.
1052  */
1053 static void session_open(struct play_task *pt)
1054 {
1055         int ret;
1056         char *history_file;
1057         struct sigaction act;
1058
1059         PARA_NOTICE_LOG("\n%s\n", version_text("play"));
1060         if (conf.history_file_given)
1061                 history_file = para_strdup(conf.history_file_arg);
1062         else {
1063                 char *home = para_homedir();
1064                 history_file = make_message("%s/.paraslash/play.history",
1065                         home);
1066                 free(home);
1067         }
1068         ici.history_file = history_file;
1069         ici.loglevel = loglevel;
1070
1071         act.sa_handler = sigint_handler;
1072         sigemptyset(&act.sa_mask);
1073         act.sa_flags = 0;
1074         sigaction(SIGINT, &act, NULL);
1075         act.sa_handler = i9e_signal_dispatch;
1076         sigemptyset(&act.sa_mask);
1077         act.sa_flags = 0;
1078         sigaction(SIGWINCH, &act, NULL);
1079         sched.select_function = i9e_select;
1080
1081         ici.bound_keyseqs = get_mapped_keyseqs();
1082         pt->btrn = ici.producer = btr_new_node(&(struct btr_node_description)
1083                 EMBRACE(.name = __FUNCTION__));
1084         ret = i9e_open(&ici, &sched);
1085         if (ret < 0)
1086                 goto out;
1087         para_log = i9e_log;
1088         return;
1089 out:
1090         free(history_file);
1091         if (ret >= 0)
1092                 return;
1093         PARA_EMERG_LOG("fatal: %s\n", para_strerror(-ret));
1094         exit(EXIT_FAILURE);
1095 }
1096
1097 static void session_update_time_string(struct play_task *pt, char *str, unsigned len)
1098 {
1099         if (pt->background)
1100                 return;
1101         if (pt->btrn) {
1102                 if (btr_get_output_queue_size(pt->btrn) > 0)
1103                         return;
1104                 if (btr_get_input_queue_size(pt->btrn) > 0)
1105                         return;
1106         }
1107         ie9_print_status_bar(str, len);
1108 }
1109
1110 /*
1111  * If we are about to die we must call i9e_close() to reset the terminal.
1112  * However, i9e_close() must be called in *this* context, i.e. from
1113  * play_task.post_select() rather than from i9e_post_select(), because
1114  * otherwise i9e would access freed memory upon return. So the play task must
1115  * stay alive until the i9e task terminates.
1116  *
1117  * We achieve this by sending a fake SIGTERM signal via i9e_signal_dispatch()
1118  * and reschedule. In the next iteration, i9e->post_select returns an error and
1119  * terminates. Subsequent calls to i9e_get_error() then return negative and we
1120  * are allowed to call i9e_close() and terminate as well.
1121  */
1122 static int session_post_select(__a_unused struct sched *s, struct play_task *pt)
1123 {
1124         int ret;
1125
1126         if (pt->background)
1127                 detach_stdout(pt);
1128         else
1129                 attach_stdout(pt, __FUNCTION__);
1130         ret = i9e_get_error();
1131         if (ret < 0) {
1132                 kill_stream(pt);
1133                 i9e_close();
1134                 para_log = stderr_log;
1135                 free(ici.history_file);
1136                 return ret;
1137         }
1138         if (get_playback_state(pt) == 'X')
1139                 i9e_signal_dispatch(SIGTERM);
1140         return 0;
1141 }
1142
1143 #else /* HAVE_READLINE */
1144
1145 static int session_post_select(struct sched *s, struct play_task *pt)
1146 {
1147         char c;
1148
1149         if (!FD_ISSET(STDIN_FILENO, &s->rfds))
1150                 return 0;
1151         if (read(STDIN_FILENO, &c, 1))
1152                 do_nothing;
1153         kill_stream(pt);
1154         return 1;
1155 }
1156
1157 static void session_open(__a_unused struct play_task *pt)
1158 {
1159 }
1160
1161 static void session_update_time_string(__a_unused struct play_task *pt,
1162                 char *str, __a_unused unsigned len)
1163 {
1164         printf("\r%s     ", str);
1165         fflush(stdout);
1166 }
1167 #endif /* HAVE_READLINE */
1168
1169 static void play_pre_select(struct sched *s, void *context)
1170 {
1171         struct play_task *pt = context;
1172         char state;
1173
1174         para_fd_set(STDIN_FILENO, &s->rfds, &s->max_fileno);
1175         state = get_playback_state(pt);
1176         if (state == 'R' || state == 'F' || state == 'X')
1177                 return sched_min_delay(s);
1178         sched_request_barrier_or_min_delay(&pt->next_update, s);
1179 }
1180
1181 static unsigned get_time_string(struct play_task *pt, char **result)
1182 {
1183         int seconds, length;
1184         char state = get_playback_state(pt);
1185
1186         /* do not return anything if things are about to change */
1187         if (state != 'P' && state != 'U') {
1188                 *result = NULL;
1189                 return 0;
1190         }
1191         length = pt->seconds;
1192         if (length == 0)
1193                 return xasprintf(result, "0:00 [0:00] (0%%/0:00)");
1194         seconds = get_play_time(pt);
1195         return xasprintf(result, "#%u: %d:%02d [%d:%02d] (%d%%/%d:%02d) %s",
1196                 pt->current_file,
1197                 seconds / 60,
1198                 seconds % 60,
1199                 (length - seconds) / 60,
1200                 (length - seconds) % 60,
1201                 length? (seconds * 100 + length / 2) / length : 0,
1202                 length / 60,
1203                 length % 60,
1204                 conf.inputs[pt->current_file]
1205         );
1206 }
1207
1208 static int play_post_select(struct sched *s, void *context)
1209 {
1210         struct play_task *pt = context;
1211         int ret;
1212
1213         ret = eof_cleanup(pt);
1214         if (ret < 0) {
1215                 pt->rq = CRT_TERM_RQ;
1216                 return 0;
1217         }
1218         ret = session_post_select(s, pt);
1219         if (ret < 0)
1220                 goto out;
1221         if (!pt->wn.btrn && !pt->fn.btrn) {
1222                 char state = get_playback_state(pt);
1223                 if (state == 'P' || state == 'R' || state == 'F') {
1224                         PARA_NOTICE_LOG("state: %c\n", state);
1225                         ret = load_next_file(pt);
1226                         if (ret < 0) {
1227                                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1228                                 pt->rq = CRT_TERM_RQ;
1229                                 ret = 1;
1230                                 goto out;
1231                         }
1232                         pt->next_update = *now;
1233                 }
1234         }
1235         if (tv_diff(now, &pt->next_update, NULL) >= 0) {
1236                 char *str;
1237                 unsigned len = get_time_string(pt, &str);
1238                 struct timeval delay = {.tv_sec = 0, .tv_usec = 100 * 1000};
1239                 if (str && len > 0)
1240                         session_update_time_string(pt, str, len);
1241                 free(str);
1242                 tv_add(now, &delay, &pt->next_update);
1243         }
1244         ret = 1;
1245 out:
1246         return ret;
1247 }
1248
1249 /**
1250  * The main function of para_play.
1251  *
1252  * \param argc Standard.
1253  * \param argv Standard.
1254  *
1255  * \return \p EXIT_FAILURE or \p EXIT_SUCCESS.
1256  */
1257 int main(int argc, char *argv[])
1258 {
1259         int ret;
1260         struct play_task *pt = &play_task;
1261
1262         /* needed this early to make help work */
1263         recv_init();
1264         filter_init();
1265         writer_init();
1266
1267         sched.default_timeout.tv_sec = 5;
1268
1269         parse_config_or_die(argc, argv);
1270         if (conf.inputs_num == 0)
1271                 print_help_and_die();
1272         AFH_RECV->init();
1273         session_open(pt);
1274         if (conf.randomize_given)
1275                 shuffle(conf.inputs, conf.inputs_num);
1276         pt->invalid = para_calloc(sizeof(*pt->invalid) * conf.inputs_num);
1277         pt->rq = CRT_FILE_CHANGE;
1278         pt->current_file = conf.inputs_num - 1;
1279         pt->playing = true;
1280         pt->task = task_register(&(struct task_info){
1281                 .name = "play",
1282                 .pre_select = play_pre_select,
1283                 .post_select = play_post_select,
1284                 .context = pt,
1285         }, &sched);
1286         ret = schedule(&sched);
1287         sched_shutdown(&sched);
1288         if (ret < 0)
1289                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1290         return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;
1291 }