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