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