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