Debian Codegraph @

src/playlist.c

raw
1 /*
2 playlist: playlist logic
3
4 copyright 1995-2023 by the mpg123 project - free software under the terms of the LGPL 2.1
5 see COPYING and AUTHORS files in distribution or http://mpg123.org
6 initially written by Michael Hipp, outsourced/reorganized by Thomas Orgis
7
8 If we officially support Windows again, we should have this reworked to really cope with Windows paths, too.
9 */
10
11 /* Need random(). */
12 #define _DEFAULT_SOURCE
13 #define _BSD_SOURCE
14
15 #include "mpg123app.h"
16 #include "sysutil.h"
17 #include "getlopt.h" /* for loptind */
18 #include "term.h" /* for term_restore */
19 #include "playlist.h"
20 #include "httpget.h"
21 #include "streamdump.h"
22 #include "local.h"
23 #include "metaprint.h"
24 #include <time.h> /* For srand(). */
25 #include "common/debug.h"
26
27 #ifdef HAVE_RANDOM
28 #define RAND random
29 #define SRAND srandom
30 #else
31 #define RAND rand
32 #define SRAND srand
33 #endif
34
35 enum playlist_type { UNKNOWN = 0, M3U, PLS, NO_LIST };
36
37 enum playflag
38 {
39 PL_IS_UTF8 = 1 // if we really know the contents are UTF-8-encooded
40 , PL_HIT_END = 2
41 , PL_STDIN_USED = 4 // If the playlist itself or an input file was '-' (stdin not usable for terminal.).
42 , PL_NO_RANDOM = 8
43 };
44
45 typedef struct listitem
46 {
47 char* url; /* the filename */
48 char freeit; /* if it was allocated and should be free()d here */
49 size_t playcount; /* has been played as ...th track in overall counting */
50 } listitem;
51
52 typedef struct playlist_struct
53 {
54 struct stream *file; /* the current playlist stream */
55 size_t entry; /* entry in the playlist file */
56 size_t playcount; /* overall track counter for playback */
57 long loop; /* repeat a track n times */
58 size_t size;
59 size_t fill;
60 size_t pos; /* (next) position, internal use */
61 size_t num; /* current track number */
62 size_t alloc_step;
63 struct listitem* list;
64 mpg123_string linebuf;
65 mpg123_string dir;
66 enum playlist_type type;
67 unsigned int flags;
68 } playlist_struct;
69
70 /* one global instance... add a pointer to this to every function definition and you have OO-style... */
71 static playlist_struct pl;
72
73 static int add_next_file (int argc, char *argv[], int args_utf8);
74 static void shuffle_playlist(void);
75 static void init_playlist(void);
76 static int add_copy_to_playlist(char* new_entry);
77 static int add_to_playlist(char* new_entry, char freeit);
78
79 /* used to be init_input */
80 void prepare_playlist(int argc, char** argv, int args_utf8, int *is_utf8)
81 {
82 /*
83 fetch all playlist entries ... I don't consider playlists to be an endless stream.
84 If you want to intentionally hang mpg123 on some other prog that may take infinite time to produce the full list (perhaps load tracks on demand), then just use the remote control and let that program print "load filename" instead of "filename".
85 We may even provide a simple wrapper script that emulates the old playlist reading behaviour (for files and stdin, http playlists are actually a strong point on reading the list in _before_ starting playback since http connections don't last forever).
86 */
87 init_playlist();
88 while (add_next_file(argc, argv, args_utf8)) {}
89 if(pl.file)
90 {
91 stream_close(pl.file);
92 pl.file = NULL;
93 }
94 if(param.verbose > 1)
95 {
96 fprintf(stderr, "\nplaylist in normal order:\n");
97 print_playlist(stderr, 0);
98 fprintf(stderr, "\n");
99 }
100 if(param.shuffle == 1) shuffle_playlist();
101 /* Don't need these anymore, we have copies! */
102 mpg123_free_string(&pl.linebuf);
103 mpg123_free_string(&pl.dir);
104 if(is_utf8)
105 *is_utf8 = (pl.flags & PL_IS_UTF8) != 0;
106 }
107
108 /* Return a random number >= 0 and < n */
109 static size_t rando(size_t n)
110 {
111 long ran;
112 long limit = RAND_MAX - (RAND_MAX % (long)n);
113 if(n<2) return 0; /* Better settle that here than in an endless loop... */
114 do{ ran = RAND(); }while( ran >= limit );
115 return (size_t)(ran%n);
116 }
117
118 char *get_next_file(void)
119 {
120 struct listitem *newitem = NULL;
121
122 /* Zero looping is nothing, as is nothing at all. */
123 if(pl.fill == 0 || param.loop == 0)
124 return NULL;
125
126 ++pl.playcount;
127
128 /* normal order, just pick next thing */
129 if(param.shuffle < 2)
130 {
131 do
132 {
133 if(pl.pos < pl.fill)
134 {
135 newitem = &pl.list[pl.pos];
136 pl.num = pl.pos+1;
137 }
138 else newitem = NULL;
139 /* if we have rounds left, decrease loop, else reinit loop because it's a new track */
140 if(pl.loop > 0) --pl.loop; /* loop for current track... */
141 if(pl.loop == 0)
142 {
143 pl.loop = param.loop;
144 ++pl.pos;
145 }
146 } while(pl.loop == 0 && newitem != NULL);
147 }
148 else
149 {
150 // Handle looping first, but only if there is a random track selection
151 // Also applies to continue mode.
152 if(!(pl.num && ((pl.loop > 0 && --pl.loop) || pl.loop < 0)) && !(pl.flags & PL_NO_RANDOM))
153 {
154 /* Randomly select the next track. */
155 do /* limiting randomness: don't repeat too early */
156 {
157 pl.pos = rando(pl.fill);
158 } while( pl.list[pl.pos].playcount
159 && (pl.playcount - pl.list[pl.pos].playcount) <= pl.fill/2 );
160 pl.loop = param.loop;
161 }
162
163 newitem = &pl.list[pl.pos];
164 pl.num = pl.pos+1;
165 pl.flags &= ~PL_NO_RANDOM; // The random blocking works only once.
166 }
167
168 /* "-" is STDIN, "" is dumb, NULL is nothing */
169 if(newitem != NULL)
170 {
171 /* Remember the playback position of the track. */
172 newitem->playcount = pl.playcount;
173 return newitem->url;
174 }
175 else
176 {
177 pl.flags |= PL_HIT_END;
178 return NULL;
179 }
180 }
181
182 size_t playlist_pos(size_t *total, long *loop)
183 {
184 if(total)
185 *total = pl.fill;
186 if(loop)
187 *loop = pl.loop;
188 return pl.flags & PL_HIT_END ? pl.fill+1 : pl.num;
189 }
190
191 void playlist_jump(mpg123_ssize_t incr)
192 {
193 size_t off = incr < 0 ? -incr : incr;
194
195 pl.loop = 0; /* This loop is done, always. */
196 /* Straight or shuffled lists can be jumped around in. */
197 if(pl.fill && param.shuffle < 2)
198 {
199 debug3("jump %zu (%ld) + %" PRIiMAX, pl.pos, pl.loop, (intmax_t)incr);
200 if(pl.pos)
201 --pl.pos;
202 /* Now we're at the _current_ position. */
203 if(incr < 0)
204 pl.pos -= off > pl.pos ? pl.pos : off;
205 else
206 {
207 if(off >= pl.fill - pl.pos)
208 pl.pos = pl.fill; /* Any value >= pl.fill would actually be OK. */
209 else
210 pl.pos += off;
211 }
212 debug2("jumped %zu (%ld)", pl.pos, pl.loop);
213 }
214 }
215
216 /* Directory jumping based on comparing the directory part of the playlist
217 URLs. */
218 static int cmp_dir(const char* patha, const char* pathb)
219 {
220 size_t dirlen[2];
221 dirlen[0] = dir_length(patha);
222 dirlen[1] = dir_length(pathb);
223 return (dirlen[0] < dirlen[1])
224 ? -1
225 : ( dirlen[0] > dirlen[1]
226 ? 1
227 : memcmp(patha, pathb, dirlen[0])
228 );
229 }
230
231 void playlist_next_dir(void)
232 {
233 if(pl.fill && param.shuffle < 2)
234 {
235 size_t npos = pl.pos ? pl.pos-1 : 0;
236 do ++npos;
237 while(npos < pl.fill && !cmp_dir(pl.list[npos-1].url, pl.list[npos].url));
238 pl.pos = npos;
239 }
240 pl.loop = 0;
241 }
242
243 void playlist_prev_dir(void)
244 {
245 if(pl.fill && param.shuffle < 2)
246 {
247 size_t npos = pl.pos ? pl.pos-1 : 0;
248 /* 1. Find end of previous directory. */
249 if(npos && npos < pl.fill)
250 do --npos;
251 while(npos && !cmp_dir(pl.list[npos+1].url, pl.list[npos].url));
252 /* npos == the last track of previous directory */
253 /* 2. Find the first track of this directory */
254 if(npos < pl.fill)
255 while(npos && !cmp_dir(pl.list[npos-1].url, pl.list[npos].url))
256 --npos;
257 pl.pos = npos;
258 }
259 pl.loop = 0;
260 }
261
262 /* It doesn't really matter on program exit, but anyway...
263 Make sure you don't free() an item of argv! */
264 void free_playlist(void)
265 {
266 if(pl.list != NULL)
267 {
268 debug("going to free() the playlist");
269 while(pl.fill)
270 {
271 --pl.fill;
272 debug1("free()ing entry %lu", (unsigned long)pl.fill);
273 if(pl.list[pl.fill].freeit) free(pl.list[pl.fill].url);
274 }
275 free(pl.list);
276 pl.list = NULL;
277 pl.size = 0;
278 debug("free()d the playlist");
279 }
280 mpg123_free_string(&pl.linebuf);
281 mpg123_free_string(&pl.dir);
282 }
283
284 /* the constructor... */
285 static void init_playlist(void)
286 {
287 SRAND(time(NULL));
288 pl.file = NULL;
289 pl.entry = 0;
290 pl.playcount = 0;
291 pl.size = 0;
292 pl.fill = 0;
293 pl.pos = 0;
294 pl.num = 0;
295 pl.list = NULL;
296 pl.alloc_step = 10;
297 mpg123_init_string(&pl.dir);
298 mpg123_init_string(&pl.linebuf);
299 pl.type = UNKNOWN;
300 pl.flags = 0;
301 pl.loop = param.loop;
302 if(APPFLAG(MPG123APP_CONTINUE) && param.listentry > 0)
303 {
304 pl.pos = param.listentry - 1;
305 pl.flags |= PL_NO_RANDOM; // Skip random selection for first track.
306 }
307 }
308
309 int playlist_stdin(void)
310 {
311 return (pl.flags & PL_STDIN_USED) != 0;
312 }
313
314 /*
315 slightly modified find_next_file from mpg123.c
316 now doesn't return the next entry but adds it to playlist struct
317 returns 1 if it found something, 0 on end
318 */
319 static int add_next_file (int argc, char *argv[], int args_utf8)
320 {
321 int firstline = 0;
322
323 if(args_utf8)
324 pl.flags |= PL_IS_UTF8;
325 else
326 pl.flags &= ~PL_IS_UTF8;
327
328 /* hack for url that has been detected as track, not playlist */
329 if(pl.type == NO_LIST) return 0;
330
331 /* Get playlist dirname to append it to the files in playlist */
332 if (param.listname)
333 {
334 char* slashpos;
335 /* Oh, right... that doesn't look good for Windows... */
336 if ((slashpos=strrchr(param.listname, '/')))
337 {
338 /* up to and including /, with space for \0 */
339 if(mpg123_resize_string(&pl.dir, 2 + slashpos - param.listname))
340 {
341 memcpy(pl.dir.p, param.listname, pl.dir.size-1);
342 pl.dir.p[pl.dir.size-1] = 0;
343 }
344 else
345 {
346 error("cannot allocate memory for list directory!");
347 pl.dir.size = 0;
348 }
349 }
350 }
351
352 if (param.listname || pl.file)
353 {
354 size_t line_offset = 0;
355 pl.flags &= ~PL_IS_UTF8; // Playlist files in env encoding (HTTP lists should be ASCII-clean).
356 if(!pl.file)
357 {
358 pl.file = stream_open(param.listname);
359 if(pl.file)
360 {
361 firstline = 1; /* just opened */
362 if(pl.file->fd == STDIN_FILENO)
363 {
364 pl.flags |= PL_STDIN_USED;
365 param.listname = NULL;
366 }
367 }
368 pl.entry = 0;
369 #ifdef NET123
370 if(pl.file && pl.file->nh)
371 {
372 debug1("htd.content_type.p: %p", (void*) pl.file->htd.content_type.p);
373 if(!APPFLAG(MPG123APP_IGNORE_MIME) && pl.file->htd.content_type.p != NULL)
374 {
375 int mimi;
376 debug1("htd.content_type.p value: %s", pl.file->htd.content_type.p);
377 mimi = debunk_mime(pl.file->htd.content_type.p);
378
379 if(mimi & IS_M3U)
380 pl.type = M3U;
381 else if(mimi & IS_PLS)
382 pl.type = PLS;
383 else
384 {
385 if(mimi & IS_FILE)
386 {
387 stream_close(pl.file);
388 pl.file = NULL;
389 pl.type = NO_LIST;
390 if(param.listentry < 0)
391 {
392 printf("#note you gave me a file url, no playlist, so...\n#entry 1\n");
393 print_outstr(stdout, param.listname, args_utf8, stdout_is_term);
394 printf("\n");
395 return 0;
396 }
397 else
398 {
399 fprintf(stderr, "Note: MIME type indicates that this is no playlist but an mpeg audio file... reopening as such.\n");
400 add_to_playlist(param.listname, 0);
401 return 1;
402 }
403 }
404 char *ptmp = NULL;
405 outstr(&ptmp, pl.file->htd.content_type.p, 1, stderr_is_term);
406 error1( "Unknown playlist MIME type %s; maybe "PACKAGE_NAME
407 " can support it in future if you report this to the maintainer."
408 , PSTR(ptmp) );
409 free(ptmp);
410 stream_close(pl.file);
411 pl.file = NULL;
412 }
413 }
414 }
415 #endif
416 if(!pl.file)
417 {
418 param.listname = NULL; // why?
419 error("failed to open playlist file");
420 return 0;
421 } else if(param.verbose)
422 {
423 fprintf(stderr, "Using playlist from ");
424 print_outstr( stderr, param.listname ? param.listname : "standard input"
425 , args_utf8, stderr_is_term );
426 fprintf(stderr, " ...\n");
427 }
428 }
429 /* reading the file line by line */
430 while(pl.file && stream_getline(pl.file, &pl.linebuf) > 0)
431 {
432 /* a bit of fuzzyness */
433 if(firstline)
434 {
435 if(pl.type == UNKNOWN)
436 {
437 if(!strcmp("[playlist]", pl.linebuf.p))
438 {
439 if(param.verbose)
440 fprintf(stderr, "Note: detected Shoutcast/Winamp PLS playlist\n");
441 pl.type = PLS;
442 continue;
443 }
444 else if
445 (
446 (!strncasecmp("#M3U", pl.linebuf.p ,4))
447 ||
448 (!strncasecmp("#EXTM3U", pl.linebuf.p ,7))
449 ||
450 (param.listname != NULL && (strrchr(param.listname, '.')) != NULL && !strcasecmp(".m3u", strrchr(param.listname, '.')))
451 )
452 {
453 if(param.verbose) fprintf(stderr, "Note: detected M3U playlist type\n");
454 pl.type = M3U;
455 }
456 else
457 {
458 if(param.verbose) fprintf(stderr, "Note: guessed M3U playlist type\n");
459 pl.type = M3U;
460 }
461 }
462 else
463 {
464 if(param.verbose)
465 {
466 fprintf(stderr, "Note: Interpreting as ");
467 switch(pl.type)
468 {
469 case M3U: fprintf(stderr, "M3U"); break;
470 case PLS: fprintf(stderr, "PLS (Winamp/Shoutcast)"); break;
471 default: fprintf(stderr, "???");
472 }
473 fprintf(stderr, " playlist\n");
474 }
475 }
476 firstline = 0;
477 }
478 #if !defined(WIN32)
479 {
480 size_t i;
481 /* convert \ to / (from MS-like directory format) */
482 for (i=0;pl.linebuf.p[i]!='\0';i++)
483 {
484 if (pl.linebuf.p[i] == '\\') pl.linebuf.p[i] = '/';
485 }
486 }
487 #endif
488 if (pl.linebuf.p[0]=='\0')
489 continue; // skip empty lines...
490 if (((pl.type == M3U) && (pl.linebuf.p[0]=='#')))
491 {
492 /* a comment line in m3u file */
493 if(param.listentry < 0)
494 {
495 print_outstr(stdout, pl.linebuf.p, 0, stdout_is_term);
496 printf("\n");
497 }
498 continue;
499 }
500
501 /* real filename may start at an offset */
502 line_offset = 0;
503 /* extract path out of PLS */
504 if(pl.type == PLS)
505 {
506 if(!strncasecmp("File", pl.linebuf.p, 4))
507 {
508 /* too lazy to really check for file number... would have to change logic to support unordered file entries anyway */
509 char* in_line;
510 if((in_line = strchr(pl.linebuf.p+4, '=')) != NULL)
511 {
512 /* FileN=? */
513 if(in_line[1] != 0)
514 {
515 ++in_line;
516 line_offset = (size_t) (in_line-pl.linebuf.p);
517 }
518 else
519 {
520 fprintf(stderr, "Warning: Invalid PLS line (empty filename) - corrupt playlist file?\n");
521 continue;
522 }
523 }
524 else
525 {
526 fprintf(stderr, "Warning: Invalid PLS line (no '=' after 'File') - corrupt playlist file?\n");
527 continue;
528 }
529 }
530 else
531 {
532 if(param.listentry < 0)
533 {
534 printf("#metainfo ");
535 print_outstr(stdout, pl.linebuf.p, 0, stdout_is_term);
536 printf("\n");
537 }
538 continue;
539 }
540 }
541
542 /* make paths absolute */
543 /* Windows knows absolute paths with c: in front... should handle this if really supporting win32 again */
544 if
545 (
546 (pl.dir.p != NULL)
547 && (pl.linebuf.p[line_offset]!='/')
548 && (pl.linebuf.p[line_offset]!='\\')
549 && strncmp(pl.linebuf.p+line_offset, "http://", 7)
550 && strncmp(pl.linebuf.p+line_offset, "https://", 8)
551 && strncmp(pl.linebuf.p+line_offset, "file://", 7)
552 )
553 {
554 size_t need;
555 need = pl.dir.size + strlen(pl.linebuf.p+line_offset);
556 if(pl.linebuf.size < need)
557 {
558 if(!mpg123_resize_string(&pl.linebuf, need))
559 {
560 error("unable to enlarge linebuf for appending path! skipping");
561 continue;
562 }
563 }
564 /* move to have the space at beginning */
565 memmove(pl.linebuf.p+pl.dir.size-1, pl.linebuf.p+line_offset, strlen(pl.linebuf.p+line_offset)+1);
566 /* prepend path */
567 memcpy(pl.linebuf.p, pl.dir.p, pl.dir.size-1);
568 line_offset = 0;
569 }
570 ++pl.entry;
571 if(param.listentry < 0)
572 {
573 printf("#entry %zu\n", pl.entry);
574 print_outstr(stdout, pl.linebuf.p+line_offset, 0, stdout_is_term);
575 printf("\n");
576 }
577 else if((param.listentry == 0) || (param.listentry == pl.entry) || APPFLAG(MPG123APP_CONTINUE))
578 {
579 add_copy_to_playlist(pl.linebuf.p+line_offset);
580 return 1;
581 }
582 }
583 }
584 if(loptind < argc)
585 {
586 add_to_playlist(argv[loptind++], 0);
587 return 1;
588 }
589 return 0;
590 }
591
592 static void shuffle_playlist(void)
593 {
594 size_t loop;
595 size_t rannum;
596 if(pl.fill >= 2)
597 {
598 /* Refer to bug 1777621 for discussion on that.
599 It's Durstenfeld... */
600 for (loop = 0; loop < pl.fill; loop++)
601 {
602 struct listitem tmp;
603 rannum = loop + rando(pl.fill-loop);
604 /*
605 Small test on your binary operation skills (^ is XOR):
606 a = b^(a^b)
607 b = (a^b)^(b^(a^b))
608 And, understood? ;-)
609
610 pl.list[loop] ^= pl.list[rannum];
611 pl.list[rannum] ^= pl.list[loop];
612 pl.list[loop] ^= pl.list[rannum];
613
614 But since this is not allowed with pointers and any speed gain questionable (well, saving _some_ memory...), doing it the lame way:
615 */
616 tmp = pl.list[rannum];
617 pl.list[rannum] = pl.list[loop];
618 pl.list[loop] = tmp;
619 }
620 }
621
622 if(param.verbose > 1)
623 {
624 /* print them */
625 fprintf(stderr, "\nshuffled playlist:\n");
626 print_playlist(stderr, 0);
627 fprintf(stderr, "\n");
628 }
629 }
630
631 void print_playlist(FILE* out, int showpos)
632 {
633 size_t loop;
634 int is_term = term_width(fileno(out)) >= 0;
635 for (loop = 0; loop < pl.fill; loop++)
636 {
637 char *pre = "";
638 if(showpos)
639 pre = (loop+1==pl.num) ? "> " : " ";
640
641 fprintf(out, "%s", pre);
642 print_outstr(out, pl.list[loop].url, 0, is_term);
643 fprintf(out, "\n");
644 }
645 }
646
647
648 static int add_copy_to_playlist(char* new_entry)
649 {
650 char* cop;
651 if((cop = (char*) malloc(strlen(new_entry)+1)) != NULL)
652 {
653 strcpy(cop, new_entry);
654 return add_to_playlist(cop, 1);
655 }
656 else return 0;
657 }
658
659 /* add new entry to playlist - no string copy, just the pointer! */
660 static int add_to_playlist(char* new_entry, char freeit)
661 {
662 if(pl.fill == pl.size)
663 {
664 struct listitem* tmp = NULL;
665 /* enlarge the list */
666 tmp = (struct listitem*) INT123_safe_realloc(pl.list, (pl.size + pl.alloc_step) * sizeof(struct listitem));
667 if(!tmp)
668 {
669 error("unable to allocate more memory for playlist");
670 perror("");
671 return 0;
672 }
673 else
674 {
675 pl.list = tmp;
676 pl.size += pl.alloc_step;
677 }
678 }
679 /* paranoid */
680 if(pl.fill < pl.size)
681 {
682 if(!strcmp(new_entry, "-") || !strcmp(new_entry, "/dev/stdin"))
683 pl.flags |= PL_STDIN_USED;
684 pl.list[pl.fill].freeit = freeit;
685 pl.list[pl.fill].url = new_entry;
686 pl.list[pl.fill].playcount = 0;
687 ++pl.fill;
688 }
689 else
690 {
691 error("playlist memory still too small?!");
692 return 0;
693 }
694 return 1;
695 }
696