2 * Copyright (C) 2007 Andre Noll <maan@systemlinux.org>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file aft.c Audio file table functions. */
19 static struct osl_table *audio_file_table;
21 /** The different sorting methods of the ls command. */
22 enum ls_sorting_method {
28 LS_SORT_BY_LAST_PLAYED,
30 LS_SORT_BY_NUM_PLAYED,
44 LS_SORT_BY_AUDIO_FORMAT,
49 /** The different listing modes of the ls command. */
50 enum ls_listing_mode {
51 /** Default listing mode. */
61 /** The flags accepted by the ls command. */
64 LS_FLAG_FULL_PATH = 1,
66 LS_FLAG_ADMISSIBLE_ONLY = 2,
72 * The size of the individual output fields of the ls command.
74 * These depend on the actual content being listed. If, for instance only files
75 * with duration less than an hour are being listed, then the duration with is
76 * made smaller because then the duration is listed as mm:ss rather than
80 /** size of the score field. */
81 unsigned short score_width;
82 /** size of the image id field. */
83 unsigned short image_id_width;
84 /** size of the lyrics id field. */
85 unsigned short lyrics_id_width;
86 /** size of the bitrate field. */
87 unsigned short bitrate_width;
88 /** size of the frequency field. */
89 unsigned short frequency_width;
90 /** size of the duration field. */
91 unsigned short duration_width;
92 /** size of the num played field. */
93 unsigned short num_played_width;
96 /** Data passed to the different compare functions (called by qsort()). */
98 /** Usual audio format handler information. */
99 struct audio_format_info afhi;
100 /** Audio file selector information. */
101 struct afs_info afsi;
102 /** The full path of the audio file. */
104 /** The score value (if -a was given). */
106 /** The sha1 hash of audio file. */
112 enum ls_sorting_method sorting;
113 enum ls_listing_mode mode;
116 struct ls_widths widths;
118 uint32_t num_matching_paths;
119 struct ls_data *data;
120 struct ls_data **data_ptr;
124 * Describes the layout of the mmapped-afs info struct.
126 * \sa struct afs_info.
129 /** Where .last_played is stored. */
130 AFSI_LAST_PLAYED_OFFSET = 0,
131 /** Storage position of the attributes bitmap. */
132 AFSI_ATTRIBUTES_OFFSET = 8,
133 /** Storage position of the .num_played field. */
134 AFSI_NUM_PLAYED_OFFSET = 16,
135 /** Storage position of the .image_id field. */
136 AFSI_IMAGE_ID_OFFSET = 20,
137 /** Storage position of the .lyrics_id field. */
138 AFSI_LYRICS_ID_OFFSET = 24,
139 /** Storage position of the .audio_format_id field. */
140 AFSI_AUDIO_FORMAT_ID_OFFSET = 28,
141 /** 3 bytes reserved space for future usage. */
142 AFSI_AUDIO_FORMAT_UNUSED_OFFSET = 29,
143 /** On-disk storage space needed. */
148 * Convert a struct afs_info to an osl object.
150 * \param afsi Pointer to the audio file info to be converted.
151 * \param obj Result pointer.
155 void save_afsi(struct afs_info *afsi, struct osl_object *obj)
157 char *buf = obj->data;
159 write_u64(buf + AFSI_LAST_PLAYED_OFFSET, afsi->last_played);
160 write_u64(buf + AFSI_ATTRIBUTES_OFFSET, afsi->attributes);
161 write_u32(buf + AFSI_NUM_PLAYED_OFFSET, afsi->num_played);
162 write_u32(buf + AFSI_IMAGE_ID_OFFSET, afsi->image_id);
163 write_u32(buf + AFSI_LYRICS_ID_OFFSET, afsi->lyrics_id);
164 write_u8(buf + AFSI_AUDIO_FORMAT_ID_OFFSET,
165 afsi->audio_format_id);
166 memset(buf + AFSI_AUDIO_FORMAT_UNUSED_OFFSET, 0, 3);
170 * Get the audio file selector info struct stored in an osl object.
172 * \param afsi Points to the audio_file info structure to be filled in.
173 * \param obj The osl object holding the data.
175 * \return Positive on success, negative on errors. Possible errors: \p E_BAD_AFS.
179 int load_afsi(struct afs_info *afsi, struct osl_object *obj)
181 char *buf = obj->data;
182 if (obj->size < AFSI_SIZE)
184 afsi->last_played = read_u64(buf + AFSI_LAST_PLAYED_OFFSET);
185 afsi->attributes = read_u64(buf + AFSI_ATTRIBUTES_OFFSET);
186 afsi->num_played = read_u32(buf + AFSI_NUM_PLAYED_OFFSET);
187 afsi->image_id = read_u32(buf + AFSI_IMAGE_ID_OFFSET);
188 afsi->lyrics_id = read_u32(buf + AFSI_LYRICS_ID_OFFSET);
189 afsi->audio_format_id = read_u8(buf +
190 AFSI_AUDIO_FORMAT_ID_OFFSET);
194 /** The columns of the audio file table. */
195 enum audio_file_table_columns {
196 /** The hash on the content of the audio file. */
198 /** The full path in the filesystem. */
200 /** The audio file selector info. */
202 /** The audio format handler info. */
204 /** The chunk table info and the chunk table of the audio file. */
206 /** The number of columns of this table. */
210 static struct osl_column_description aft_cols[] = {
212 .storage_type = OSL_MAPPED_STORAGE,
213 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE | OSL_UNIQUE,
215 .compare_function = osl_hash_compare,
216 .data_size = HASH_SIZE
219 .storage_type = OSL_MAPPED_STORAGE,
220 .storage_flags = OSL_RBTREE | OSL_UNIQUE,
222 .compare_function = string_compare,
225 .storage_type = OSL_MAPPED_STORAGE,
226 .storage_flags = OSL_FIXED_SIZE,
228 .data_size = AFSI_SIZE
231 .storage_type = OSL_MAPPED_STORAGE,
235 .storage_type = OSL_DISK_STORAGE,
240 static struct osl_table_description audio_file_table_desc = {
241 .name = "audio_files",
242 .num_columns = NUM_AFT_COLUMNS,
243 .flags = OSL_LARGE_TABLE,
244 .column_descriptions = aft_cols
247 /* We don't want * dot or dot-dot anywhere. */
248 static int verify_dotfile(const char *rest)
251 * The first character was '.', but that has already been discarded, we
255 case '\0': case '/': /* /foo/. and /foo/./bar are not ok */
257 case '.': /* path start with /foo/.. */
258 if (rest[1] == '\0' || rest[1] == '/')
259 return -1; /* /foo/.. or /foo/../bar are not ok */
260 /* /foo/..bar is ok */
266 * We fundamentally don't like some paths: We don't want double slashes or
267 * slashes at the end that can make pathnames ambiguous.
269 static int verify_path(const char *orig_path, char **resolved_path)
275 if (*orig_path != '/') /* we only accept absolute paths */
277 len = strlen(orig_path);
278 *resolved_path = para_strdup(orig_path);
279 path = *resolved_path;
280 while (len > 1 && path[--len] == '/')
281 path[len] = '\0'; /* remove slash at the end */
287 case '/': /* double slash */
290 if (verify_dotfile(path) < 0)
300 free(*resolved_path);
304 /** The on-disk layout of a afhi struct. */
306 /** Where the number of seconds is stored. */
307 AFHI_SECONDS_TOTAL_OFFSET = 0,
308 /** Position of the bitrate. */
309 AFHI_BITRATE_OFFSET = 4,
310 /** Position of the frequency. */
311 AFHI_FREQUENCY_OFFSET = 8,
312 /** Number of channels is stored here. */
313 AFHI_CHANNELS_OFFSET = 12,
314 /** The tag info position. */
315 AFHI_INFO_STRING_OFFSET = 13,
316 /** Minimal on-disk size of a valid afhi struct. */
320 static unsigned sizeof_afhi_buf(const struct audio_format_info *afhi)
324 return strlen(afhi->info_string) + MIN_AFHI_SIZE;
327 static void save_afhi(struct audio_format_info *afhi, char *buf)
331 write_u32(buf + AFHI_SECONDS_TOTAL_OFFSET,
332 afhi->seconds_total);
333 write_u32(buf + AFHI_BITRATE_OFFSET, afhi->bitrate);
334 write_u32(buf + AFHI_FREQUENCY_OFFSET, afhi->frequency);
335 write_u8(buf + AFHI_CHANNELS_OFFSET, afhi->channels);
336 strcpy(buf + AFHI_INFO_STRING_OFFSET, afhi->info_string); /* OK */
337 PARA_DEBUG_LOG("last byte written: %p\n", buf + AFHI_INFO_STRING_OFFSET + strlen(afhi->info_string));
340 static void load_afhi(const char *buf, struct audio_format_info *afhi)
342 afhi->seconds_total = read_u32(buf + AFHI_SECONDS_TOTAL_OFFSET);
343 afhi->bitrate = read_u32(buf + AFHI_BITRATE_OFFSET);
344 afhi->frequency = read_u32(buf + AFHI_FREQUENCY_OFFSET);
345 afhi->channels = read_u8(buf + AFHI_CHANNELS_OFFSET);
346 strcpy(afhi->info_string, buf + AFHI_INFO_STRING_OFFSET);
349 static unsigned sizeof_chunk_info_buf(struct audio_format_info *afhi)
353 return 4 * afhi->chunks_total + 20;
357 /** The offsets of the data contained in the AFTCOL_CHUNKS column. */
358 enum chunk_info_offsets{
359 /** The total number of chunks (4 bytes). */
360 CHUNKS_TOTAL_OFFSET = 0,
361 /** The length of the audio file header (4 bytes). */
362 HEADER_LEN_OFFSET = 4,
363 /** The start of the audio file header (4 bytes). */
364 HEADER_OFFSET_OFFSET = 8,
365 /** The seconds part of the chunk time (4 bytes). */
366 CHUNK_TV_TV_SEC_OFFSET = 12,
367 /** The microseconds part of the chunk time (4 bytes). */
368 CHUNK_TV_TV_USEC = 16,
369 /** Chunk table entries start here. */
370 CHUNK_TABLE_OFFSET = 20,
373 /* TODO: audio format handlers could just produce this */
374 static void save_chunk_info(struct audio_format_info *afhi, char *buf)
380 write_u32(buf + CHUNKS_TOTAL_OFFSET, afhi->chunks_total);
381 write_u32(buf + HEADER_LEN_OFFSET, afhi->header_len);
382 write_u32(buf + HEADER_OFFSET_OFFSET, afhi->header_offset);
383 write_u32(buf + CHUNK_TV_TV_SEC_OFFSET, afhi->chunk_tv.tv_sec);
384 write_u32(buf + CHUNK_TV_TV_USEC, afhi->chunk_tv.tv_usec);
385 for (i = 0; i < afhi->chunks_total; i++)
386 write_u32(buf + CHUNK_TABLE_OFFSET + 4 * i, afhi->chunk_table[i]);
389 static int load_chunk_info(struct osl_object *obj, struct audio_format_info *afhi)
391 char *buf = obj->data;
394 if (obj->size < CHUNK_TABLE_OFFSET)
395 return -E_BAD_DATA_SIZE;
397 afhi->chunks_total = read_u32(buf + CHUNKS_TOTAL_OFFSET);
398 afhi->header_len = read_u32(buf + HEADER_LEN_OFFSET);
399 afhi->header_offset = read_u32(buf + HEADER_OFFSET_OFFSET);
400 afhi->chunk_tv.tv_sec = read_u32(buf + CHUNK_TV_TV_SEC_OFFSET);
401 afhi->chunk_tv.tv_usec = read_u32(buf + CHUNK_TV_TV_USEC);
403 if (afhi->chunks_total * 4 + CHUNK_TABLE_OFFSET > obj->size)
404 return -E_BAD_DATA_SIZE;
405 afhi->chunk_table = para_malloc(afhi->chunks_total * sizeof(size_t));
406 for (i = 0; i < afhi->chunks_total; i++)
407 afhi->chunk_table[i] = read_u32(buf + CHUNK_TABLE_OFFSET + 4 * i);
412 * Get the row of the audio file table corresponding to the given path.
414 * \param path The full path of the audio file.
415 * \param row Result pointer.
417 * \return The return value of the underlying call to osl_get_row().
419 int aft_get_row_of_path(const char *path, struct osl_row **row)
421 struct osl_object obj = {.data = (char *)path, .size = strlen(path) + 1};
423 return osl_get_row(audio_file_table, AFTCOL_PATH, &obj, row);
427 * Get the row of the audio file table corresponding to the given hash value.
429 * \param hash The hash value of the desired audio file.
430 * \param row resul pointer.
432 * \return The return value of the underlying call to osl_get_row().
434 int aft_get_row_of_hash(HASH_TYPE *hash, struct osl_row **row)
436 const struct osl_object obj = {.data = hash, .size = HASH_SIZE};
437 return osl_get_row(audio_file_table, AFTCOL_HASH, &obj, row);
441 * Get the osl object holding the audio file selector info of a row.
443 * \param row Pointer to a row in the audio file table.
444 * \param obj Result pointer.
446 * \return The return value of the underlying call to osl_get_object().
448 int get_afsi_object_of_row(const struct osl_row *row, struct osl_object *obj)
450 return osl_get_object(audio_file_table, row, AFTCOL_AFSI, obj);
454 * Get the osl object holding the audio file selector info, given a path.
457 * \param path The full path of the audio file.
458 * \param obj Result pointer.
460 * \return Positive on success, negative on errors.
462 int get_afsi_object_of_path(const char *path, struct osl_object *obj)
465 int ret = aft_get_row_of_path(path, &row);
468 return get_afsi_object_of_row(row, obj);
472 * Get the audio file selector info, given a row of the audio file table.
474 * \param row Pointer to a row in the audio file table.
475 * \param afsi Result pointer.
477 * \return Positive on success, negative on errors.
479 int get_afsi_of_row(const struct osl_row *row, struct afs_info *afsi)
481 struct osl_object obj;
482 int ret = get_afsi_object_of_row(row, &obj);
485 return load_afsi(afsi, &obj);
489 * Get the audio file selector info, given the path of an audio table.
491 * \param path The full path of the audio file.
492 * \param afsi Result pointer.
494 * \return Positive on success, negative on errors.
496 int get_afsi_of_path(const char *path, struct afs_info *afsi)
498 struct osl_object obj;
499 int ret = get_afsi_object_of_path(path, &obj);
502 return load_afsi(afsi, &obj);
506 * Get the path of an audio file, given a row of the audio file table.
508 * \param row Pointer to a row in the audio file table.
509 * \param path Result pointer.
511 * \return Positive on success, negative on errors.
513 int get_audio_file_path_of_row(const struct osl_row *row, char **path)
515 struct osl_object path_obj;
516 int ret = osl_get_object(audio_file_table, row, AFTCOL_PATH,
520 *path = path_obj.data;
525 * Get the object containing the hash value of an audio file, given a row.
527 * \param row Pointer to a row of the audio file table.
528 * \param obj Result pointer.
530 * \return The return value of the underlying call to osl_get_object().
532 * \sa get_hash_of_row().
534 static int get_hash_object_of_aft_row(const struct osl_row *row, struct osl_object *obj)
536 return osl_get_object(audio_file_table, row, AFTCOL_HASH, obj);
540 * Get the hash value of an audio file, given a row of the audio file table.
542 * \param row Pointer to a row of the audio file table.
543 * \param hash Result pointer.
545 * \a hash points to mapped data and must not be freed by the caller.
547 * \return The return value of the underlying call to
548 * get_hash_object_of_aft_row().
550 static int get_hash_of_row(const struct osl_row *row, HASH_TYPE **hash)
552 struct osl_object obj;
553 int ret = get_hash_object_of_aft_row(row, &obj);
562 * Get the audio format handler info, given a row of the audio file table.
564 * \param row Pointer to a row of the audio file table.
565 * \param afhi Result pointer.
567 * \return The return value of the underlying call to osl_get_object().
569 * \sa get_chunk_table_of_row().
571 int get_afhi_of_row(const struct osl_row *row, struct audio_format_info *afhi)
573 struct osl_object obj;
574 int ret = osl_get_object(audio_file_table, row, AFTCOL_AFHI,
578 load_afhi(obj.data, afhi);
583 * Get the chunk table of an audio file, given a row of the audio file table.
585 * \param row Pointer to a row of the audio file table.
586 * \param afhi Result pointer.
588 * \return The return value of the underlying call to osl_open_disk_object().
590 * \sa get_afhi_of_row().
592 static int get_chunk_table_of_row(const struct osl_row *row, struct audio_format_info *afhi)
594 struct osl_object obj;
595 int ret = osl_open_disk_object(audio_file_table, row, AFTCOL_CHUNKS,
599 ret = load_chunk_info(&obj, afhi);
600 osl_close_disk_object(&obj);
605 * Mmap the given audio file and update statistics.
607 * \param aft_row Determines the audio file to be opened and updated.
608 * \param afd Result pointer.
610 * On success, the numplayed field of the audio file selector info is increased
611 * and the lastplayed time is set to the current time. Finally, the score of
612 * the audio file is updated.
614 * \return Positive on success, negative on errors.
616 int open_and_update_audio_file(struct osl_row *aft_row, struct audio_file_data *afd)
618 HASH_TYPE *aft_hash, file_hash[HASH_SIZE];
619 struct osl_object afsi_obj;
620 struct afs_info new_afsi;
621 int ret = get_hash_of_row(aft_row, &aft_hash);
622 struct afsi_change_event_data aced;
626 ret = get_audio_file_path_of_row(aft_row, &afd->path);
629 ret = get_afsi_object_of_row(aft_row, &afsi_obj);
632 ret = load_afsi(&afd->afsi, &afsi_obj);
635 ret = get_afhi_of_row(aft_row, &afd->afhi);
638 ret = get_chunk_table_of_row(aft_row, &afd->afhi);
641 ret = mmap_full_file(afd->path, O_RDONLY, &afd->map);
644 hash_function(afd->map.data, afd->map.size, file_hash);
645 ret = -E_HASH_MISMATCH;
646 if (hash_compare(file_hash, aft_hash))
648 new_afsi = afd->afsi;
649 new_afsi.num_played++;
650 new_afsi.last_played = time(NULL);
651 save_afsi(&new_afsi, &afsi_obj); /* in-place update */
653 aced.aft_row = aft_row;
654 aced.old_afsi = &afd->afsi;
655 afs_event(AFSI_CHANGE, NULL, &aced);
659 free(afd->afhi.chunk_table);
663 static int get_local_time(uint64_t *seconds, char *buf, size_t size,
664 time_t current_time, enum ls_listing_mode lm)
668 if (!localtime_r((time_t *)seconds, &t))
670 if (lm == LS_MODE_MBOX) {
671 if (!strftime(buf, size, "%c", &t))
675 if (*seconds + 6 * 30 * 24 * 3600 > current_time) {
676 if (!strftime(buf, size, "%b %e %k:%M", &t))
680 if (!strftime(buf, size, "%b %e %Y", &t))
685 /** Compute the number of (decimal) digits of a number. */
686 #define GET_NUM_DIGITS(x, num) { \
687 typeof((x)) _tmp = PARA_ABS(x); \
690 while ((_tmp) > 9) { \
696 static short unsigned get_duration_width(int seconds)
698 short unsigned width;
699 unsigned hours = seconds / 3600, mins = (seconds % 3600) / 60;
701 if (!hours) /* less than one hour => m:ss or mm:ss => 4 or 5 digits */
702 return 4 + (mins > 9);
703 /* more than one hour => h:mm:ss, hh:mm:ss, hhh:mm:ss, ... */
704 GET_NUM_DIGITS(hours, &width);
708 static void get_duration_buf(int seconds, char *buf, short unsigned max_width)
710 unsigned hours = seconds / 3600, mins = (seconds % 3600) / 60;
712 if (!hours) /* m:ss or mm:ss */
713 sprintf(buf, "%*u:%02u", max_width - 3, mins, seconds % 60);
714 else /* more than one hour => h:mm:ss, hh:mm:ss, hhh:mm:ss, ... */
715 sprintf(buf, "%*u:%02u:%02u", max_width - 6, hours, mins,
719 static char *make_attribute_line(const char *att_bitmap, struct afs_info *afsi)
721 char *att_text, *att_line;
723 get_attribute_text(&afsi->attributes, " ", &att_text);
725 return para_strdup(att_bitmap);
726 att_line = make_message("%s (%s)", att_bitmap, att_text);
731 static char *make_lyrics_line(struct afs_info *afsi)
735 lyr_get_name_by_id(afsi->lyrics_id, &lyrics_name);
737 return make_message("%u", afsi->lyrics_id);
738 return make_message("%u (%s)", afsi->lyrics_id, lyrics_name);
741 static char *make_image_line(struct afs_info *afsi)
744 img_get_name_by_id(afsi->image_id, &image_name);
746 return make_message("%u", afsi->image_id);
747 return make_message("%u (%s)", afsi->image_id, image_name);
750 static int print_list_item(struct ls_data *d, struct ls_options *opts,
751 struct para_buffer *b, time_t current_time)
755 char last_played_time[30];
756 char duration_buf[30]; /* nobody has an audio file long enough to overflow this */
757 char score_buf[30] = "";
758 struct afs_info *afsi = &d->afsi;
759 struct audio_format_info *afhi = &d->afhi;
760 struct ls_widths *w = &opts->widths;
761 int have_score = opts->flags & LS_FLAG_ADMISSIBLE_ONLY;
762 char asc_hash[2 * HASH_SIZE + 1];
763 char *att_line, *lyrics_line, *image_line;
765 if (opts->mode == LS_MODE_SHORT) {
766 para_printf(b, "%s\n", d->path);
769 get_attribute_bitmap(&afsi->attributes, att_buf);
770 ret = get_local_time(&afsi->last_played, last_played_time,
771 sizeof(last_played_time), current_time, opts->mode);
774 get_duration_buf(afhi->seconds_total, duration_buf, w->duration_width);
776 if (opts->mode == LS_MODE_LONG)
777 sprintf(score_buf, "%*li ", w->score_width, d->score);
779 sprintf(score_buf, "%li ", d->score);
782 if (opts->mode == LS_MODE_LONG) {
785 "%s " /* attributes */
786 "%*d " /* image_id */
787 "%*d " /* lyrics_id */
789 "%s " /* audio format */
790 "%*d " /* frequency */
793 "%*d " /* num_played */
794 "%s " /* last_played */
798 w->image_id_width, afsi->image_id,
799 w->lyrics_id_width, afsi->lyrics_id,
800 w->bitrate_width, afhi->bitrate,
801 audio_format_name(afsi->audio_format_id),
802 w->frequency_width, afhi->frequency,
805 w->num_played_width, afsi->num_played,
811 hash_to_asc(d->hash, asc_hash);
812 att_line = make_attribute_line(att_buf, afsi);
813 lyrics_line = make_lyrics_line(afsi);
814 image_line = make_image_line(afsi);
815 if (opts->mode == LS_MODE_VERBOSE) {
818 "%s: %s\n" /* path */
824 "bitrate: %dkbit/s\n"
832 (opts->flags & LS_FLAG_FULL_PATH)?
833 "path" : "file", d->path,
834 have_score? "score: " : "", score_buf,
835 have_score? "\n" : "",
841 audio_format_name(afsi->audio_format_id),
849 } else { /* mbox mode */
850 struct osl_object lyrics_def;
851 lyr_get_def_by_id(afsi->lyrics_id, &lyrics_def);
853 "From foo@localhost %s\n"
854 "Received: from\nTo: bar\nFrom: a\n"
855 "Subject: %s\n\n" /* path */
861 "bitrate: %dkbit/s\n"
871 have_score? "score: " : "", score_buf,
872 have_score? "\n" : "",
878 audio_format_name(afsi->audio_format_id),
884 lyrics_def.data? "Lyrics:\n~~~~~~~\n" : "",
885 lyrics_def.data? (char *)lyrics_def.data : ""
888 osl_close_disk_object(lyrics_def.data);
896 static int ls_audio_format_compare(const void *a, const void *b)
898 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
899 return NUM_COMPARE(d1->afsi.audio_format_id, d2->afsi.audio_format_id);
902 static int ls_duration_compare(const void *a, const void *b)
904 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
905 return NUM_COMPARE(d1->afhi.seconds_total, d2->afhi.seconds_total);
908 static int ls_bitrate_compare(const void *a, const void *b)
910 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
911 return NUM_COMPARE(d1->afhi.bitrate, d2->afhi.bitrate);
914 static int ls_lyrics_id_compare(const void *a, const void *b)
916 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
917 return NUM_COMPARE(d1->afsi.lyrics_id, d2->afsi.lyrics_id);
920 static int ls_image_id_compare(const void *a, const void *b)
922 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
923 return NUM_COMPARE(d1->afsi.image_id, d2->afsi.image_id);
926 static int ls_channels_compare(const void *a, const void *b)
928 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
929 return NUM_COMPARE(d1->afhi.channels, d2->afhi.channels);
932 static int ls_frequency_compare(const void *a, const void *b)
934 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
935 return NUM_COMPARE(d1->afhi.frequency, d2->afhi.frequency);
938 static int ls_num_played_compare(const void *a, const void *b)
940 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
941 return NUM_COMPARE(d1->afsi.num_played, d2->afsi.num_played);
944 static int ls_last_played_compare(const void *a, const void *b)
946 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
947 return NUM_COMPARE(d1->afsi.last_played, d2->afsi.last_played);
950 static int ls_score_compare(const void *a, const void *b)
952 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
953 return NUM_COMPARE(d1->score, d2->score);
956 static int ls_path_compare(const void *a, const void *b)
958 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
959 return strcmp(d1->path, d2->path);
962 static int sort_matching_paths(struct ls_options *options)
964 size_t nmemb = options->num_matching_paths;
965 size_t size = sizeof(*options->data_ptr);
966 int (*compar)(const void *, const void *);
969 options->data_ptr = para_malloc(nmemb * sizeof(*options->data_ptr));
970 for (i = 0; i < nmemb; i++)
971 options->data_ptr[i] = options->data + i;
973 /* In these cases the array is already sorted */
974 if (options->sorting == LS_SORT_BY_PATH
975 && !(options->flags & LS_FLAG_ADMISSIBLE_ONLY)
976 && (options->flags & LS_FLAG_FULL_PATH))
978 if (options->sorting == LS_SORT_BY_SCORE &&
979 options->flags & LS_FLAG_ADMISSIBLE_ONLY)
982 switch (options->sorting) {
983 case LS_SORT_BY_PATH:
984 compar = ls_path_compare; break;
985 case LS_SORT_BY_SCORE:
986 compar = ls_score_compare; break;
987 case LS_SORT_BY_LAST_PLAYED:
988 compar = ls_last_played_compare; break;
989 case LS_SORT_BY_NUM_PLAYED:
990 compar = ls_num_played_compare; break;
991 case LS_SORT_BY_FREQUENCY:
992 compar = ls_frequency_compare; break;
993 case LS_SORT_BY_CHANNELS:
994 compar = ls_channels_compare; break;
995 case LS_SORT_BY_IMAGE_ID:
996 compar = ls_image_id_compare; break;
997 case LS_SORT_BY_LYRICS_ID:
998 compar = ls_lyrics_id_compare; break;
999 case LS_SORT_BY_BITRATE:
1000 compar = ls_bitrate_compare; break;
1001 case LS_SORT_BY_DURATION:
1002 compar = ls_duration_compare; break;
1003 case LS_SORT_BY_AUDIO_FORMAT:
1004 compar = ls_audio_format_compare; break;
1008 qsort(options->data_ptr, nmemb, size, compar);
1012 /* row is either an aft_row or a row of the score table */
1013 /* TODO: Only compute widths if we need them */
1014 static int prepare_ls_row(struct osl_row *row, void *ls_opts)
1017 struct ls_options *options = ls_opts;
1019 struct ls_widths *w;
1020 unsigned short num_digits;
1022 struct osl_row *aft_row;
1026 if (options->flags & LS_FLAG_ADMISSIBLE_ONLY) {
1027 ret = get_score_and_aft_row(row, &score, &aft_row);
1032 ret = get_audio_file_path_of_row(aft_row, &path);
1035 if (!(options->flags & LS_FLAG_FULL_PATH)) {
1036 char *p = strrchr(path, '/');
1040 if (options->num_patterns) {
1041 for (i = 0; i < options->num_patterns; i++) {
1042 ret = fnmatch(options->patterns[i], path, 0);
1045 if (ret == FNM_NOMATCH)
1049 if (i >= options->num_patterns) /* no match */
1052 tmp = options->num_matching_paths++;
1053 if (options->num_matching_paths > options->array_size) {
1054 options->array_size++;
1055 options->array_size *= 2;
1056 options->data = para_realloc(options->data, options->array_size
1057 * sizeof(*options->data));
1059 d = options->data + tmp;
1060 ret = get_afsi_of_row(aft_row, &d->afsi);
1063 ret = get_afhi_of_row(aft_row, &d->afhi);
1067 ret = get_hash_of_row(aft_row, &d->hash);
1070 w = &options->widths;
1071 GET_NUM_DIGITS(d->afsi.image_id, &num_digits);
1072 w->image_id_width = PARA_MAX(w->image_id_width, num_digits);
1073 GET_NUM_DIGITS(d->afsi.lyrics_id, &num_digits);
1074 w->lyrics_id_width = PARA_MAX(w->lyrics_id_width, num_digits);
1075 GET_NUM_DIGITS(d->afhi.bitrate, &num_digits);
1076 w->bitrate_width = PARA_MAX(w->bitrate_width, num_digits);
1077 GET_NUM_DIGITS(d->afhi.frequency, &num_digits);
1078 w->frequency_width = PARA_MAX(w->frequency_width, num_digits);
1079 GET_NUM_DIGITS(d->afsi.num_played, &num_digits);
1080 w->num_played_width = PARA_MAX(w->num_played_width, num_digits);
1081 /* get the number of chars to print this amount of time */
1082 tmp = get_duration_width(d->afhi.seconds_total);
1083 w->duration_width = PARA_MAX(w->duration_width, tmp);
1084 if (options->flags & LS_FLAG_ADMISSIBLE_ONLY) {
1085 GET_NUM_DIGITS(score, &num_digits);
1086 num_digits++; /* add one for the sign (space or "-") */
1087 w->score_width = PARA_MAX(w->score_width, num_digits);
1093 static int com_ls_callback(const struct osl_object *query,
1094 struct osl_object *ls_output)
1096 struct ls_options *opts = query->data;
1097 char *p, *pattern_start = (char *)query->data + sizeof(*opts);
1098 struct para_buffer b = {.buf = NULL, .size = 0};
1100 time_t current_time;
1103 if (opts->num_patterns) {
1104 opts->patterns = para_malloc(opts->num_patterns * sizeof(char *));
1105 for (i = 0, p = pattern_start; i < opts->num_patterns; i++) {
1106 opts->patterns[i] = p;
1110 opts->patterns = NULL;
1111 if (opts->flags & LS_FLAG_ADMISSIBLE_ONLY)
1112 ret = admissible_file_loop(opts, prepare_ls_row);
1114 ret = osl_rbtree_loop(audio_file_table, AFTCOL_PATH, opts,
1118 ret = opts->num_patterns? -E_NO_MATCH : 0;
1119 if (!opts->num_matching_paths)
1121 ret = sort_matching_paths(opts);
1124 time(¤t_time);
1125 if (opts->flags & LS_FLAG_REVERSE)
1126 for (i = opts->num_matching_paths - 1; i >= 0; i--) {
1127 ret = print_list_item(opts->data_ptr[i], opts, &b, current_time);
1132 for (i = 0; i < opts->num_matching_paths; i++) {
1133 ret = print_list_item(opts->data_ptr[i], opts, &b, current_time);
1139 ls_output->data = b.buf;
1140 ls_output->size = b.size;
1142 free(opts->data_ptr);
1143 free(opts->patterns);
1148 * TODO: flags -h (sort by hash) -lm (list in mbox format)
1150 * long list: list hash, attributes as (xx--x-x-), file size, lastplayed
1151 * full list: list everything, including afsi, afhi, atts as clear text
1154 int com_afs_ls(int fd, int argc, char * const * const argv)
1158 enum ls_sorting_method sort = LS_SORT_BY_PATH;
1159 enum ls_listing_mode mode = LS_MODE_SHORT;
1160 struct ls_options opts = {.patterns = NULL};
1161 struct osl_object query = {.data = &opts, .size = sizeof(opts)},
1164 for (i = 1; i < argc; i++) {
1165 const char *arg = argv[i];
1168 if (!strcmp(arg, "--")) {
1172 if (!strncmp(arg, "-l", 2)) {
1174 mode = LS_MODE_LONG;
1178 return -E_AFT_SYNTAX;
1179 switch(*(arg + 2)) {
1181 mode = LS_MODE_SHORT;
1184 mode = LS_MODE_LONG;
1187 mode = LS_MODE_VERBOSE;
1190 mode = LS_MODE_MBOX;
1193 return -E_AFT_SYNTAX;
1196 if (!strcmp(arg, "-p")) {
1197 flags |= LS_FLAG_FULL_PATH;
1200 if (!strcmp(arg, "-a")) {
1201 flags |= LS_FLAG_ADMISSIBLE_ONLY;
1204 if (!strcmp(arg, "-r")) {
1205 flags |= LS_FLAG_REVERSE;
1208 if (!strncmp(arg, "-s", 2)) {
1209 if (!*(arg + 2) || *(arg + 3))
1210 return -E_AFT_SYNTAX;
1211 switch(*(arg + 2)) {
1213 sort = LS_SORT_BY_PATH;
1215 case 's': /* -ss implies -a */
1216 sort = LS_SORT_BY_SCORE;
1217 flags |= LS_FLAG_ADMISSIBLE_ONLY;
1220 sort = LS_SORT_BY_LAST_PLAYED;
1223 sort = LS_SORT_BY_NUM_PLAYED;
1226 sort = LS_SORT_BY_FREQUENCY;
1229 sort = LS_SORT_BY_CHANNELS;
1232 sort = LS_SORT_BY_IMAGE_ID;
1235 sort = LS_SORT_BY_LYRICS_ID;
1238 sort = LS_SORT_BY_BITRATE;
1241 sort = LS_SORT_BY_DURATION;
1244 sort = LS_SORT_BY_AUDIO_FORMAT;
1247 return -E_AFT_SYNTAX;
1250 return -E_AFT_SYNTAX;
1253 opts.sorting = sort;
1255 opts.num_patterns = argc - i;
1256 ret = send_option_arg_callback_request(&query, opts.num_patterns,
1257 argv + i, com_ls_callback, &ls_output);
1259 ret = send_buffer(fd, (char *)ls_output.data);
1260 free(ls_output.data);
1266 * Call the given function for each file in the audio file table.
1268 * \param private_data An arbitrary data pointer, passed to \a func.
1269 * \param func The custom function to be called.
1271 * \return The return value of the underlying call to osl_rbtree_loop().
1273 int audio_file_loop(void *private_data, osl_rbtree_loop_func *func)
1275 return osl_rbtree_loop(audio_file_table, AFTCOL_HASH, private_data,
1279 static struct osl_row *find_hash_sister(HASH_TYPE *hash)
1281 const struct osl_object obj = {.data = hash, .size = HASH_SIZE};
1282 struct osl_row *row;
1284 osl_get_row(audio_file_table, AFTCOL_HASH, &obj, &row);
1288 enum aft_row_offsets {
1289 AFTROW_AFHI_OFFSET_POS = 0,
1290 AFTROW_CHUNKS_OFFSET_POS = 2,
1291 AFTROW_AUDIO_FORMAT_OFFSET = 4,
1292 AFTROW_FLAGS_OFFSET = 5,
1293 AFTROW_HASH_OFFSET = 9,
1294 AFTROW_PATH_OFFSET = (AFTROW_HASH_OFFSET + HASH_SIZE),
1297 /* never save the afsi, as the server knows it too. Note that afhi might be NULL.
1298 * In this case, afhi won't be stored in the buffer */
1299 static void save_audio_file_info(HASH_TYPE *hash, const char *path,
1300 struct audio_format_info *afhi, uint32_t flags,
1301 uint8_t audio_format_num, struct osl_object *obj)
1303 size_t path_len = strlen(path) + 1;
1304 size_t afhi_size = sizeof_afhi_buf(afhi);
1305 size_t size = AFTROW_PATH_OFFSET + path_len + afhi_size
1306 + sizeof_chunk_info_buf(afhi);
1307 char *buf = para_malloc(size);
1310 write_u8(buf + AFTROW_AUDIO_FORMAT_OFFSET, audio_format_num);
1311 write_u32(buf + AFTROW_FLAGS_OFFSET, flags);
1313 memcpy(buf + AFTROW_HASH_OFFSET, hash, HASH_SIZE);
1314 strcpy(buf + AFTROW_PATH_OFFSET, path);
1316 pos = AFTROW_PATH_OFFSET + path_len;
1317 PARA_DEBUG_LOG("size: %zu, afhi starts at %d\n", size, pos);
1318 PARA_DEBUG_LOG("last afhi byte: %p, pos %zu\n", buf + pos + afhi_size - 1,
1319 pos + afhi_size - 1);
1320 write_u16(buf + AFTROW_AFHI_OFFSET_POS, pos);
1321 save_afhi(afhi, buf + pos);
1324 PARA_DEBUG_LOG("size: %zu, chunks start at %d\n", size, pos);
1325 write_u16(buf + AFTROW_CHUNKS_OFFSET_POS, pos);
1326 save_chunk_info(afhi, buf + pos);
1327 PARA_DEBUG_LOG("last byte in buf: %p\n", buf + size - 1);
1341 AFHI: whether afhi and chunk table are computed and sent
1342 ACTION: table modifications to be performed
1344 +---+----+-----+------+---------------------------------------------------+
1345 | HS | PB | F | AFHI | ACTION
1346 +---+----+-----+------+---------------------------------------------------+
1347 | Y | Y | Y | Y | if HS != PB: remove PB. HS: force afhi update,
1348 | | update path, keep afsi
1349 +---+----+-----+------+---------------------------------------------------+
1350 | Y | Y | N | N | if HS == PB: do not send callback request at all.
1351 | | otherwise: remove PB, HS: update path, keep afhi,
1353 +---+----+-----+------+---------------------------------------------------+
1354 | Y | N | Y | Y | (rename) force afhi update of HS, update path of
1356 +---+----+-----+------+---------------------------------------------------+
1357 | Y | N | N | N | (file rename) update path of HS, keep afsi, afhi
1358 +---+----+-----+------+---------------------------------------------------+
1359 | N | Y | Y | Y | (file change) update afhi, hash, of PB, keep afsi
1360 | | (force has no effect)
1361 +---+----+-----+------+---------------------------------------------------+
1362 | N | Y | N | Y | (file change) update afhi, hash of PB, keep afsi
1363 +---+----+-----+------+---------------------------------------------------+
1364 | N | N | Y | Y | (new file) create new entry (force has no effect)
1365 +---+----+-----+------+---------------------------------------------------+
1366 | N | N | N | Y | (new file) create new entry
1367 +---+----+-----+------+---------------------------------------------------+
1369 afhi <=> force or no HS
1373 /** Flags passed to the add command. */
1374 enum com_add_flags {
1375 /** Skip paths that exist already. */
1377 /** Force adding. */
1379 /** Print what is being done. */
1380 ADD_FLAG_VERBOSE = 4,
1381 /** Try to add files with unknown suffixes. */
1385 static int com_add_callback(const struct osl_object *query,
1386 struct osl_object *result)
1388 char *buf = query->data, *path;
1389 struct osl_row *pb, *aft_row;
1391 struct osl_object objs[NUM_AFT_COLUMNS];
1393 char asc[2 * HASH_SIZE + 1];
1395 char afsi_buf[AFSI_SIZE];
1396 uint32_t flags = read_u32(buf + AFTROW_FLAGS_OFFSET);
1397 struct afs_info default_afsi = {.last_played = 0};
1398 struct para_buffer msg = {.buf = NULL};
1400 hash = (HASH_TYPE *)buf + AFTROW_HASH_OFFSET;
1401 hash_to_asc(hash, asc);;
1402 objs[AFTCOL_HASH].data = buf + AFTROW_HASH_OFFSET;
1403 objs[AFTCOL_HASH].size = HASH_SIZE;
1405 path = buf + AFTROW_PATH_OFFSET;
1406 objs[AFTCOL_PATH].data = path;
1407 objs[AFTCOL_PATH].size = strlen(path) + 1;
1409 PARA_INFO_LOG("request to add %s\n", path);
1410 hs = find_hash_sister(hash);
1411 ret = aft_get_row_of_path(path, &pb);
1412 if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
1414 if (hs && pb && hs == pb && !(flags & ADD_FLAG_FORCE)) {
1415 if (flags & ADD_FLAG_VERBOSE)
1416 para_printf(&msg, "ignoring duplicate\n");
1420 if (hs && hs != pb) {
1421 struct osl_object obj;
1422 if (pb) { /* hs trumps pb, remove pb */
1423 if (flags & ADD_FLAG_VERBOSE)
1424 para_printf(&msg, "removing path brother\n");
1425 ret = osl_del_row(audio_file_table, pb);
1430 /* file rename, update hs' path */
1431 if (flags & ADD_FLAG_VERBOSE) {
1432 ret = osl_get_object(audio_file_table, hs,
1436 para_printf(&msg, "renamed from %s\n", (char *)obj.data);
1438 ret = osl_update_object(audio_file_table, hs, AFTCOL_PATH,
1439 &objs[AFTCOL_PATH]);
1442 afs_event(AUDIO_FILE_RENAME, &msg, hs);
1443 if (!(flags & ADD_FLAG_FORCE))
1446 /* no hs or force mode, child must have sent afhi */
1447 uint16_t afhi_offset = read_u16(buf + AFTROW_AFHI_OFFSET_POS);
1448 uint16_t chunks_offset = read_u16(buf + AFTROW_CHUNKS_OFFSET_POS);
1450 objs[AFTCOL_AFHI].data = buf + afhi_offset;
1451 objs[AFTCOL_AFHI].size = chunks_offset - afhi_offset;
1453 if (!objs[AFTCOL_AFHI].size) /* "impossible" */
1455 objs[AFTCOL_CHUNKS].data = buf + chunks_offset;
1456 objs[AFTCOL_CHUNKS].size = query->size - chunks_offset;
1457 if (pb && !hs) { /* update pb's hash */
1458 char old_asc[2 * HASH_SIZE + 1];
1459 HASH_TYPE *old_hash;
1460 ret = get_hash_of_row(pb, &old_hash);
1463 hash_to_asc(old_hash, old_asc);
1464 if (flags & ADD_FLAG_VERBOSE)
1465 para_printf(&msg, "file change: %s -> %s\n",
1467 ret = osl_update_object(audio_file_table, pb, AFTCOL_HASH,
1468 &objs[AFTCOL_HASH]);
1472 if (hs || pb) { /* (hs != NULL and pb != NULL) implies hs == pb */
1473 struct osl_row *row = pb? pb : hs;
1474 /* update afhi and chunk_table */
1475 if (flags & ADD_FLAG_VERBOSE)
1476 para_printf(&msg, "updating afhi and chunk table\n");
1477 ret = osl_update_object(audio_file_table, row, AFTCOL_AFHI,
1478 &objs[AFTCOL_AFHI]);
1481 ret = osl_update_object(audio_file_table, row, AFTCOL_CHUNKS,
1482 &objs[AFTCOL_CHUNKS]);
1485 afs_event(AFHI_CHANGE, &msg, row);
1488 /* new entry, use default afsi */
1489 if (flags & ADD_FLAG_VERBOSE)
1490 para_printf(&msg, "new file\n");
1491 default_afsi.last_played = time(NULL) - 365 * 24 * 60 * 60;
1492 default_afsi.audio_format_id = read_u8(buf + AFTROW_AUDIO_FORMAT_OFFSET);
1494 objs[AFTCOL_AFSI].data = &afsi_buf;
1495 objs[AFTCOL_AFSI].size = AFSI_SIZE;
1496 save_afsi(&default_afsi, &objs[AFTCOL_AFSI]);
1497 ret = osl_add_and_get_row(audio_file_table, objs, &aft_row);
1500 para_printf(&msg, "%s\n", PARA_STRERROR(-ret));
1503 result->data = msg.buf;
1504 result->size = msg.size;
1505 afs_event(AUDIO_FILE_ADD, &msg, aft_row);
1509 struct private_add_data {
1514 static int path_brother_callback(const struct osl_object *query,
1515 struct osl_object *result)
1517 char *path = query->data;
1518 struct osl_row *path_brother;
1519 int ret = aft_get_row_of_path(path, &path_brother);
1522 result->data = para_malloc(sizeof(path_brother));
1523 result->size = sizeof(path_brother);
1524 *(struct osl_row **)(result->data) = path_brother;
1528 static int hash_sister_callback(const struct osl_object *query,
1529 struct osl_object *result)
1531 HASH_TYPE *hash = query->data;
1532 struct osl_row *hash_sister;
1534 hash_sister = find_hash_sister(hash);
1536 return -E_RB_KEY_NOT_FOUND;
1537 result->data = para_malloc(sizeof(hash_sister));
1538 result->size = sizeof(hash_sister);
1539 *(struct osl_row **)(result->data) = hash_sister;
1543 static int add_one_audio_file(const char *path, const void *private_data)
1546 uint8_t format_num = -1;
1547 const struct private_add_data *pad = private_data;
1548 struct audio_format_info afhi, *afhi_ptr = NULL;
1549 struct osl_row *pb = NULL, *hs = NULL; /* path brother/hash sister */
1550 struct osl_object map, obj = {.data = NULL}, query, result;
1551 HASH_TYPE hash[HASH_SIZE];
1553 afhi.header_offset = 0;
1554 afhi.header_len = 0;
1555 ret = guess_audio_format(path);
1556 if (ret < 0 && !(pad->flags & ADD_FLAG_ALL))
1558 query.data = (char *)path;
1559 query.size = strlen(path) + 1;
1560 ret = send_callback_request(path_brother_callback, &query, &result);
1561 if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
1564 pb = *(struct osl_row **)result.data;
1568 if (pb && (pad->flags & ADD_FLAG_LAZY)) { /* lazy is really cheap */
1569 if (pad->flags & ADD_FLAG_VERBOSE)
1570 ret = send_va_buffer(pad->fd, "lazy-ignore: %s\n", path);
1573 /* We still want to add this file. Compute its hash. */
1574 ret = mmap_full_file(path, O_RDONLY, &map);
1577 hash_function(map.data, map.size, hash);
1579 /* Check whether database contains file with the same hash. */
1581 query.size = HASH_SIZE;
1582 ret = send_callback_request(hash_sister_callback, &query, &result);
1583 if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
1586 hs = *(struct osl_row **)result.data;
1589 /* Return success if we already know this file. */
1591 if (pb && hs && hs == pb && (!(pad->flags & ADD_FLAG_FORCE))) {
1592 if (pad->flags & ADD_FLAG_VERBOSE)
1593 ret = send_va_buffer(pad->fd,
1594 "%s exists, not forcing update\n", path);
1598 * we won't recalculate the audio format info and the chunk table if
1599 * there is a hash sister unless in FORCE mode.
1601 if (!hs || (pad->flags & ADD_FLAG_FORCE)) {
1602 ret = compute_afhi(path, map.data, map.size, &afhi);
1608 if (pad->flags & ADD_FLAG_VERBOSE) {
1609 ret = send_va_buffer(pad->fd, "adding %s\n", path);
1613 munmap(map.data, map.size);
1614 save_audio_file_info(hash, path, afhi_ptr, pad->flags, format_num, &obj);
1615 /* Ask afs to consider this entry for adding. */
1616 ret = send_callback_request(com_add_callback, &obj, &result);
1617 if (result.data && result.size) {
1618 ret2 = send_va_buffer(pad->fd, "%s", (char *)result.data);
1620 if (ret >= 0 && ret2 < 0)
1626 munmap(map.data, map.size);
1628 if (ret < 0 && ret != -E_SEND)
1629 send_va_buffer(pad->fd, "failed to add %s (%s)\n", path,
1630 PARA_STRERROR(-ret));
1633 free(afhi_ptr->chunk_table);
1634 /* it's not an error if not all files could be added */
1635 return ret == -E_SEND? ret : 1;
1638 int com_add(int fd, int argc, char * const * const argv)
1641 struct private_add_data pad = {.fd = fd, .flags = 0};
1642 struct stat statbuf;
1644 for (i = 1; i < argc; i++) {
1645 const char *arg = argv[i];
1648 if (!strcmp(arg, "--")) {
1652 if (!strcmp(arg, "-a")) {
1653 pad.flags |= ADD_FLAG_ALL;
1656 if (!strcmp(arg, "-l")) {
1657 pad.flags |= ADD_FLAG_LAZY;
1660 if (!strcmp(arg, "-f")) {
1661 pad.flags |= ADD_FLAG_FORCE;
1664 if (!strcmp(arg, "-v")) {
1665 pad.flags |= ADD_FLAG_VERBOSE;
1670 return -E_AFT_SYNTAX;
1671 for (; i < argc; i++) {
1673 ret = verify_path(argv[i], &path);
1675 ret = send_va_buffer(fd, "%s: %s\n", argv[i], PARA_STRERROR(-ret));
1680 ret = stat(path, &statbuf);
1682 ret = send_va_buffer(fd, "failed to stat %s (%s)\n", path,
1689 if (S_ISDIR(statbuf.st_mode))
1690 ret = for_each_file_in_dir(path, add_one_audio_file,
1693 ret = add_one_audio_file(path, &pad);
1695 send_va_buffer(fd, "%s: %s\n", path, PARA_STRERROR(-ret));
1706 * Flags used by the touch command.
1711 /** Whether the \p FNM_PATHNAME flag should be passed to fnmatch(). */
1712 TOUCH_FLAG_FNM_PATHNAME = 1,
1713 /** Activates verbose mode. */
1714 TOUCH_FLAG_VERBOSE = 2
1717 struct com_touch_options {
1719 int64_t last_played;
1725 struct touch_action_data {
1726 struct com_touch_options *cto;
1727 struct para_buffer pb;
1730 static int touch_audio_file(__a_unused struct osl_table *table,
1731 struct osl_row *row, const char *name, void *data)
1733 struct touch_action_data *tad = data;
1734 struct osl_object obj;
1735 struct afs_info old_afsi, new_afsi;
1736 int ret, no_options = tad->cto->num_played < 0 && tad->cto->last_played < 0 &&
1737 tad->cto->lyrics_id < 0 && tad->cto->image_id < 0;
1738 struct afsi_change_event_data aced;
1740 ret = get_afsi_object_of_row(row, &obj);
1742 para_printf(&tad->pb, "%s: %s\n", name, PARA_STRERROR(-ret));
1745 ret = load_afsi(&old_afsi, &obj);
1747 para_printf(&tad->pb, "%s: %s\n", name, PARA_STRERROR(-ret));
1750 new_afsi = old_afsi;
1752 new_afsi.num_played++;
1753 new_afsi.last_played = time(NULL);
1754 if (tad->cto->flags & TOUCH_FLAG_VERBOSE)
1755 para_printf(&tad->pb, "%s: num_played = %u, "
1756 "last_played = now()\n", name,
1757 new_afsi.num_played);
1759 if (tad->cto->flags & TOUCH_FLAG_VERBOSE)
1760 para_printf(&tad->pb, "touching %s\n", name);
1761 if (tad->cto->lyrics_id >= 0)
1762 new_afsi.lyrics_id = tad->cto->lyrics_id;
1763 if (tad->cto->image_id >= 0)
1764 new_afsi.image_id = tad->cto->image_id;
1765 if (tad->cto->num_played >= 0)
1766 new_afsi.num_played = tad->cto->num_played;
1767 if (tad->cto->last_played >= 0)
1768 new_afsi.last_played = tad->cto->last_played;
1770 save_afsi(&new_afsi, &obj); /* in-place update */
1772 aced.old_afsi = &old_afsi;
1773 afs_event(AFSI_CHANGE, &tad->pb, &aced);
1777 static int com_touch_callback(const struct osl_object *query,
1778 struct osl_object *result)
1780 struct touch_action_data tad = {.cto = query->data};
1782 struct pattern_match_data pmd = {
1783 .table = audio_file_table,
1784 .loop_col_num = AFTCOL_HASH,
1785 .match_col_num = AFTCOL_PATH,
1786 .patterns = {.data = (char *)query->data + sizeof(*tad.cto),
1787 .size = query->size - sizeof(*tad.cto)},
1789 .action = touch_audio_file
1791 if (tad.cto->flags & TOUCH_FLAG_FNM_PATHNAME)
1792 pmd.fnmatch_flags |= FNM_PATHNAME;
1793 ret = for_each_matching_row(&pmd);
1795 para_printf(&tad.pb, "%s\n", PARA_STRERROR(-ret));
1797 result->data = tad.pb.buf;
1798 result->size = tad.pb.size;
1801 return ret < 0? ret : 0;
1804 int com_touch(int fd, int argc, char * const * const argv)
1806 struct com_touch_options cto = {
1812 struct osl_object query = {.data = &cto, .size = sizeof(cto)},
1817 for (i = 1; i < argc; i++) {
1818 const char *arg = argv[i];
1821 if (!strcmp(arg, "--")) {
1825 if (!strncmp(arg, "-n", 2)) {
1826 ret = para_atoi32(arg + 2, &cto.num_played);
1831 if (!strncmp(arg, "-l", 2)) {
1832 ret = para_atoi64(arg + 2, &cto.last_played);
1837 if (!strncmp(arg, "-y", 2)) {
1838 ret = para_atoi32(arg + 2, &cto.lyrics_id);
1843 if (!strncmp(arg, "-i", 2)) {
1844 ret = para_atoi32(arg + 2, &cto.image_id);
1849 if (!strcmp(arg, "-p")) {
1850 cto.flags |= TOUCH_FLAG_FNM_PATHNAME;
1853 if (!strcmp(arg, "-v")) {
1854 cto.flags |= TOUCH_FLAG_VERBOSE;
1857 break; /* non-option starting with dash */
1860 return -E_AFT_SYNTAX;
1861 ret = send_option_arg_callback_request(&query, argc - i,
1862 argv + i, com_touch_callback, &result);
1864 send_buffer(fd, (char *)result.data);
1867 send_va_buffer(fd, "%s\n", PARA_STRERROR(-ret));
1872 RM_FLAG_VERBOSE = 1,
1874 RM_FLAG_FNM_PATHNAME = 4
1877 struct com_rm_data {
1879 struct para_buffer pb;
1880 unsigned num_removed;
1883 static int remove_audio_file(__a_unused struct osl_table *table,
1884 struct osl_row *row, const char *name, void *data)
1886 struct com_rm_data *crd = data;
1889 if (crd->flags & RM_FLAG_VERBOSE)
1890 para_printf(&crd->pb, "removing %s\n", name);
1891 afs_event(AUDIO_FILE_REMOVE, &crd->pb, row);
1892 ret = osl_del_row(audio_file_table, row);
1894 para_printf(&crd->pb, "%s: %s\n", name, PARA_STRERROR(-ret));
1900 static int com_rm_callback(const struct osl_object *query,
1901 __a_unused struct osl_object *result)
1903 struct com_rm_data crd = {.flags = *(uint32_t *)query->data};
1905 struct pattern_match_data pmd = {
1906 .table = audio_file_table,
1907 .loop_col_num = AFTCOL_HASH,
1908 .match_col_num = AFTCOL_PATH,
1909 .patterns = {.data = (char *)query->data + sizeof(uint32_t),
1910 .size = query->size - sizeof(uint32_t)},
1912 .action = remove_audio_file
1914 if (crd.flags & RM_FLAG_FNM_PATHNAME)
1915 pmd.fnmatch_flags |= FNM_PATHNAME;
1916 ret = for_each_matching_row(&pmd);
1918 para_printf(&crd.pb, "%s\n", PARA_STRERROR(-ret));
1919 if (!crd.num_removed && !(crd.flags & RM_FLAG_FORCE))
1920 para_printf(&crd.pb, "no matches -- nothing removed\n");
1922 if (crd.flags & RM_FLAG_VERBOSE)
1923 para_printf(&crd.pb, "removed %u files\n", crd.num_removed);
1926 result->data = crd.pb.buf;
1927 result->size = crd.pb.size;
1930 return ret < 0? ret : 0;
1933 /* TODO options: -r (recursive) */
1934 int com_afs_rm(int fd, int argc, char * const * const argv)
1937 struct osl_object query = {.data = &flags, .size = sizeof(flags)},
1941 for (i = 1; i < argc; i++) {
1942 const char *arg = argv[i];
1945 if (!strcmp(arg, "--")) {
1949 if (!strcmp(arg, "-f")) {
1950 flags |= RM_FLAG_FORCE;
1953 if (!strcmp(arg, "-p")) {
1954 flags |= RM_FLAG_FNM_PATHNAME;
1957 if (!strcmp(arg, "-v")) {
1958 flags |= RM_FLAG_VERBOSE;
1964 return -E_AFT_SYNTAX;
1965 ret = send_option_arg_callback_request(&query, argc - i, argv + i,
1966 com_rm_callback, &result);
1968 send_buffer(fd, (char *)result.data);
1971 send_va_buffer(fd, "%s\n", PARA_STRERROR(-ret));
1976 * Flags used by the cpsi command.
1981 /** Whether the lyrics id should be copied. */
1982 CPSI_FLAG_COPY_LYRICS_ID = 1,
1983 /** Whether the image id should be copied. */
1984 CPSI_FLAG_COPY_IMAGE_ID = 2,
1985 /** Whether the lastplayed time should be copied. */
1986 CPSI_FLAG_COPY_LASTPLAYED = 4,
1987 /** Whether the numplayed count should be copied. */
1988 CPSI_FLAG_COPY_NUMPLAYED = 8,
1989 /** Whether the attributes should be copied. */
1990 CPSI_FLAG_COPY_ATTRIBUTES = 16,
1991 /** Activates verbose mode. */
1992 CPSI_FLAG_VERBOSE = 32,
1995 struct cpsi_action_data {
1997 unsigned num_copied;
1998 struct para_buffer pb;
1999 struct afs_info source_afsi;
2002 static int copy_selector_info(__a_unused struct osl_table *table,
2003 struct osl_row *row, const char *name, void *data)
2005 struct cpsi_action_data *cad = data;
2006 struct osl_object target_afsi_obj;
2008 struct afs_info old_afsi, target_afsi;
2009 struct afsi_change_event_data aced;
2011 ret = get_afsi_object_of_row(row, &target_afsi_obj);
2014 load_afsi(&target_afsi, &target_afsi_obj);
2015 old_afsi = target_afsi;
2016 if (cad->flags & CPSI_FLAG_COPY_LYRICS_ID)
2017 target_afsi.lyrics_id = cad->source_afsi.lyrics_id;
2018 if (cad->flags & CPSI_FLAG_COPY_IMAGE_ID)
2019 target_afsi.image_id = cad->source_afsi.image_id;
2020 if (cad->flags & CPSI_FLAG_COPY_LASTPLAYED)
2021 target_afsi.last_played = cad->source_afsi.last_played;
2022 if (cad->flags & CPSI_FLAG_COPY_NUMPLAYED)
2023 target_afsi.num_played = cad->source_afsi.num_played;
2024 if (cad->flags & CPSI_FLAG_COPY_ATTRIBUTES)
2025 target_afsi.attributes = cad->source_afsi.attributes;
2026 save_afsi(&target_afsi, &target_afsi_obj); /* in-place update */
2028 if (cad->flags & CPSI_FLAG_VERBOSE)
2029 para_printf(&cad->pb, "copied afsi to %s\n", name);
2031 aced.old_afsi = &old_afsi;
2032 afs_event(AFSI_CHANGE, &cad->pb, &aced);
2036 static int com_cpsi_callback(const struct osl_object *query,
2037 struct osl_object *result)
2039 struct cpsi_action_data cad = {.flags = *(unsigned *)query->data};
2041 char *source_path = (char *)query->data + sizeof(cad.flags);
2043 ret = get_afsi_of_path(source_path, &cad.source_afsi);
2046 struct pattern_match_data pmd = {
2047 .table = audio_file_table,
2048 .loop_col_num = AFTCOL_HASH,
2049 .match_col_num = AFTCOL_PATH,
2050 .patterns = {.data = source_path + strlen(source_path) + 1,
2051 .size = query->size - sizeof(cad.flags)
2052 - strlen(source_path) - 1},
2054 .action = copy_selector_info
2056 ret = for_each_matching_row(&pmd);
2059 para_printf(&cad.pb, "%s\n", PARA_STRERROR(-ret));
2060 if (cad.flags & CPSI_FLAG_VERBOSE) {
2062 para_printf(&cad.pb, "copied requested afsi from %s "
2064 source_path, cad.num_copied);
2066 para_printf(&cad.pb, "nothing copied\n");
2069 result->data = cad.pb.buf;
2070 result->size = cad.pb.size;
2073 return ret < 0? ret : 0;
2076 int com_cpsi(int fd, int argc, char * const * const argv)
2080 struct osl_object options = {.data = &flags, .size = sizeof(flags)},
2083 for (i = 1; i < argc; i++) {
2084 const char *arg = argv[i];
2087 if (!strcmp(arg, "--")) {
2091 if (!strcmp(arg, "-y")) {
2092 flags |= CPSI_FLAG_COPY_LYRICS_ID;
2095 if (!strcmp(arg, "-i")) {
2096 flags |= CPSI_FLAG_COPY_IMAGE_ID;
2099 if (!strcmp(arg, "-l")) {
2100 flags |= CPSI_FLAG_COPY_LASTPLAYED;
2103 if (!strcmp(arg, "-n")) {
2104 flags |= CPSI_FLAG_COPY_NUMPLAYED;
2107 if (!strcmp(arg, "-a")) {
2108 flags |= CPSI_FLAG_COPY_ATTRIBUTES;
2111 if (!strcmp(arg, "-v")) {
2112 flags |= CPSI_FLAG_VERBOSE;
2117 if (i + 1 >= argc) /* need at least souce file and pattern */
2118 return -E_AFT_SYNTAX;
2119 if (!(flags & ~CPSI_FLAG_VERBOSE)) /* no copy flags given */
2120 flags = ~(unsigned)CPSI_FLAG_VERBOSE | flags;
2121 ret = send_option_arg_callback_request(&options, argc - i, argv + i,
2122 com_cpsi_callback, &result);
2124 send_buffer(fd, (char *)result.data);
2127 send_va_buffer(fd, "%s\n", PARA_STRERROR(-ret));
2131 /* TODO: optionally fix problems by removing offending rows */
2132 static int check_audio_file(struct osl_row *row, void *data)
2135 struct para_buffer *pb = data;
2136 struct stat statbuf;
2137 int ret = get_audio_file_path_of_row(row, &path);
2138 struct afs_info afsi;
2142 para_printf(pb, "%s\n", PARA_STRERROR(-ret));
2145 if (stat(path, &statbuf) < 0)
2146 para_printf(pb, "%s: stat error (%s)\n", path, strerror(errno));
2148 if (!S_ISREG(statbuf.st_mode))
2149 para_printf(pb, "%s: not a regular file\n", path);
2151 ret = get_afsi_of_row(row, &afsi);
2153 para_printf(pb, "%s: %s\n", path, PARA_STRERROR(-ret));
2156 ret = lyr_get_name_by_id(afsi.lyrics_id, &blob_name);
2158 para_printf(pb, "%s lyrics id %u: %s\n", path, afsi.lyrics_id,
2159 PARA_STRERROR(-ret));
2160 ret = img_get_name_by_id(afsi.image_id, &blob_name);
2162 para_printf(pb, "%s image id %u: %s\n", path, afsi.image_id,
2163 PARA_STRERROR(-ret));
2168 * Check the audio file table for inconsistencies.
2170 * \param query Unused.
2171 * \param result Contains message string upon return.
2173 * This function always succeeds.
2177 int aft_check_callback(__a_unused const struct osl_object *query, struct osl_object *result)
2179 struct para_buffer pb = {.buf = NULL};
2181 para_printf(&pb, "checking audio file table...\n");
2182 audio_file_loop(&pb, check_audio_file);
2183 result->data = pb.buf;
2184 result->size = pb.size;
2190 * Close the audio file table.
2192 * \param flags Ususal flags that are passed to osl_close_table().
2194 * \sa osl_close_table().
2196 static void aft_close(void)
2198 osl_close_table(audio_file_table, OSL_MARK_CLEAN);
2199 audio_file_table = NULL;
2203 * Open the audio file table.
2205 * \param dir The database directory.
2209 * \sa osl_open_table().
2211 static int aft_open(const char *dir)
2215 audio_file_table_desc.dir = dir;
2216 ret = osl_open_table(&audio_file_table_desc, &audio_file_table);
2219 osl_get_num_rows(audio_file_table, &num);
2220 PARA_INFO_LOG("audio file table contains %d files\n", num);
2223 PARA_INFO_LOG("failed to open audio file table\n");
2224 audio_file_table = NULL;
2225 if (ret >= 0 || is_errno(-ret, ENOENT))
2230 static int aft_create(const char *dir)
2232 audio_file_table_desc.dir = dir;
2233 return osl_create_table(&audio_file_table_desc);
2236 static int clear_attribute(struct osl_row *row, void *data)
2238 struct rmatt_event_data *red = data;
2239 struct afs_info afsi;
2240 struct osl_object obj;
2241 int ret = get_afsi_object_of_row(row, &obj);
2242 uint64_t mask = ~(1ULL << red->bitnum);
2246 ret = load_afsi(&afsi, &obj);
2249 afsi.attributes &= mask;
2250 save_afsi(&afsi, &obj);
2254 static int aft_event_handler(enum afs_events event, struct para_buffer *pb,
2258 case ATTRIBUTE_REMOVE: {
2259 const struct rmatt_event_data *red = data;
2260 para_printf(pb, "clearing attribute %s (bit %u) from all "
2261 "entries in the audio file table\n", red->name,
2263 return audio_file_loop(data, clear_attribute);
2270 void aft_init(struct afs_table *t)
2272 t->name = audio_file_table_desc.name;
2274 t->close = aft_close;
2275 t->create = aft_create;
2276 t->event_handler = aft_event_handler;