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