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