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