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 /** On-disk storage space needed. */
146 * Convert a struct afs_info to an osl object.
148 * \param afsi Pointer to the audio file info to be converted.
149 * \param obj Result pointer.
153 void save_afsi(struct afs_info *afsi, struct osl_object *obj)
155 char *buf = obj->data;
157 write_u64(buf + AFSI_LAST_PLAYED_OFFSET, afsi->last_played);
158 write_u64(buf + AFSI_ATTRIBUTES_OFFSET, afsi->attributes);
159 write_u32(buf + AFSI_NUM_PLAYED_OFFSET, afsi->num_played);
160 write_u32(buf + AFSI_IMAGE_ID_OFFSET, afsi->image_id);
161 write_u32(buf + AFSI_LYRICS_ID_OFFSET, afsi->lyrics_id);
162 write_u8(buf + AFSI_AUDIO_FORMAT_ID_OFFSET,
163 afsi->audio_format_id);
167 * Get the audio file selector info struct stored in an osl object.
169 * \param afsi Points to the audio_file info structure to be filled in.
170 * \param obj The osl object holding the data.
172 * \return Positive on success, negative on errors. Possible errors: \p E_BAD_AFS.
176 int load_afsi(struct afs_info *afsi, struct osl_object *obj)
178 char *buf = obj->data;
179 if (obj->size < AFSI_SIZE)
181 afsi->last_played = read_u64(buf + AFSI_LAST_PLAYED_OFFSET);
182 afsi->attributes = read_u64(buf + AFSI_ATTRIBUTES_OFFSET);
183 afsi->num_played = read_u32(buf + AFSI_NUM_PLAYED_OFFSET);
184 afsi->image_id = read_u32(buf + AFSI_IMAGE_ID_OFFSET);
185 afsi->lyrics_id = read_u32(buf + AFSI_LYRICS_ID_OFFSET);
186 afsi->audio_format_id = read_u8(buf +
187 AFSI_AUDIO_FORMAT_ID_OFFSET);
191 /** The columns of the audio file table. */
192 enum audio_file_table_columns {
193 /** The hash on the content of the audio file. */
195 /** The full path in the filesystem. */
197 /** The audio file selector info. */
199 /** The audio format handler info. */
201 /** The chunk table info and the chunk table of the audio file. */
203 /** The number of columns of this table. */
207 static struct osl_column_description aft_cols[] = {
209 .storage_type = OSL_MAPPED_STORAGE,
210 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE | OSL_UNIQUE,
212 .compare_function = osl_hash_compare,
213 .data_size = HASH_SIZE
216 .storage_type = OSL_MAPPED_STORAGE,
217 .storage_flags = OSL_RBTREE | OSL_UNIQUE,
219 .compare_function = string_compare,
222 .storage_type = OSL_MAPPED_STORAGE,
223 .storage_flags = OSL_FIXED_SIZE,
225 .data_size = AFSI_SIZE
228 .storage_type = OSL_MAPPED_STORAGE,
232 .storage_type = OSL_DISK_STORAGE,
237 static struct osl_table_description audio_file_table_desc = {
238 .name = "audio_files",
239 .num_columns = NUM_AFT_COLUMNS,
240 .flags = OSL_LARGE_TABLE,
241 .column_descriptions = aft_cols
244 /* We don't want * dot or dot-dot anywhere. */
245 static int verify_dotfile(const char *rest)
248 * The first character was '.', but that has already been discarded, we
252 case '\0': case '/': /* /foo/. and /foo/./bar are not ok */
254 case '.': /* path start with /foo/.. */
255 if (rest[1] == '\0' || rest[1] == '/')
256 return -1; /* /foo/.. or /foo/../bar are not ok */
257 /* /foo/..bar is ok */
263 * We fundamentally don't like some paths: We don't want double slashes or
264 * slashes at the end that can make pathnames ambiguous.
266 static int verify_path(const char *orig_path, char **resolved_path)
272 if (*orig_path != '/') /* we only accept absolute paths */
274 len = strlen(orig_path);
275 *resolved_path = para_strdup(orig_path);
276 path = *resolved_path;
277 while (len > 1 && path[--len] == '/')
278 path[len] = '\0'; /* remove slash at the end */
284 case '/': /* double slash */
287 if (verify_dotfile(path) < 0)
297 free(*resolved_path);
301 /** The on-disk layout of a afhi struct. */
303 /** Where the number of seconds is stored. */
304 AFHI_SECONDS_TOTAL_OFFSET = 0,
305 /** Position of the bitrate. */
306 AFHI_BITRATE_OFFSET = 4,
307 /** Position of the frequency. */
308 AFHI_FREQUENCY_OFFSET = 8,
309 /** Number of channels is stored here. */
310 AFHI_CHANNELS_OFFSET = 12,
311 /** The tag info position. */
312 AFHI_INFO_STRING_OFFSET = 13,
313 /** Minimal on-disk size of a valid afhi struct. */
317 static unsigned sizeof_afhi_buf(const struct audio_format_info *afhi)
321 return strlen(afhi->info_string) + MIN_AFHI_SIZE;
324 static void save_afhi(struct audio_format_info *afhi, char *buf)
328 write_u32(buf + AFHI_SECONDS_TOTAL_OFFSET,
329 afhi->seconds_total);
330 write_u32(buf + AFHI_BITRATE_OFFSET, afhi->bitrate);
331 write_u32(buf + AFHI_FREQUENCY_OFFSET, afhi->frequency);
332 write_u8(buf + AFHI_CHANNELS_OFFSET, afhi->channels);
333 strcpy(buf + AFHI_INFO_STRING_OFFSET, afhi->info_string); /* OK */
334 PARA_DEBUG_LOG("last byte written: %p\n", buf + AFHI_INFO_STRING_OFFSET + strlen(afhi->info_string));
337 static void load_afhi(const char *buf, struct audio_format_info *afhi)
339 afhi->seconds_total = read_u32(buf + AFHI_SECONDS_TOTAL_OFFSET);
340 afhi->bitrate = read_u32(buf + AFHI_BITRATE_OFFSET);
341 afhi->frequency = read_u32(buf + AFHI_FREQUENCY_OFFSET);
342 afhi->channels = read_u8(buf + AFHI_CHANNELS_OFFSET);
343 strcpy(afhi->info_string, buf + AFHI_INFO_STRING_OFFSET);
346 static unsigned sizeof_chunk_info_buf(struct audio_format_info *afhi)
350 return 4 * afhi->chunks_total + 20;
354 /** The offsets of the data contained in the AFTCOL_CHUNKS column. */
355 enum chunk_info_offsets{
356 /** The total number of chunks (4 bytes). */
357 CHUNKS_TOTAL_OFFSET = 0,
358 /** The length of the audio file header (4 bytes). */
359 HEADER_LEN_OFFSET = 4,
360 /** The start of the audio file header (4 bytes). */
361 HEADER_OFFSET_OFFSET = 8,
362 /** The seconds part of the chunk time (4 bytes). */
363 CHUNK_TV_TV_SEC_OFFSET = 12,
364 /** The microseconds part of the chunk time (4 bytes). */
365 CHUNK_TV_TV_USEC = 16,
366 /** Chunk table entries start here. */
367 CHUNK_TABLE_OFFSET = 20,
370 /* TODO: audio format handlers could just produce this */
371 static void save_chunk_info(struct audio_format_info *afhi, char *buf)
377 write_u32(buf + CHUNKS_TOTAL_OFFSET, afhi->chunks_total);
378 write_u32(buf + HEADER_LEN_OFFSET, afhi->header_len);
379 write_u32(buf + HEADER_OFFSET_OFFSET, afhi->header_offset);
380 write_u32(buf + CHUNK_TV_TV_SEC_OFFSET, afhi->chunk_tv.tv_sec);
381 write_u32(buf + CHUNK_TV_TV_USEC, afhi->chunk_tv.tv_usec);
382 for (i = 0; i < afhi->chunks_total; i++)
383 write_u32(buf + CHUNK_TABLE_OFFSET + 4 * i, afhi->chunk_table[i]);
386 static int load_chunk_info(struct osl_object *obj, struct audio_format_info *afhi)
388 char *buf = obj->data;
391 if (obj->size < CHUNK_TABLE_OFFSET)
392 return -E_BAD_DATA_SIZE;
394 afhi->chunks_total = read_u32(buf + CHUNKS_TOTAL_OFFSET);
395 afhi->header_len = read_u32(buf + HEADER_LEN_OFFSET);
396 afhi->header_offset = read_u32(buf + HEADER_OFFSET_OFFSET);
397 afhi->chunk_tv.tv_sec = read_u32(buf + CHUNK_TV_TV_SEC_OFFSET);
398 afhi->chunk_tv.tv_usec = read_u32(buf + CHUNK_TV_TV_USEC);
400 if (afhi->chunks_total * 4 + CHUNK_TABLE_OFFSET > obj->size)
401 return -E_BAD_DATA_SIZE;
402 afhi->chunk_table = para_malloc(afhi->chunks_total * sizeof(size_t));
403 for (i = 0; i < afhi->chunks_total; i++)
404 afhi->chunk_table[i] = read_u32(buf + CHUNK_TABLE_OFFSET + 4 * i);
409 * Get the row of the audio file table corresponding to the given path.
411 * \param path The full path of the audio file.
412 * \param row Result pointer.
414 * \return The return value of the underlying call to osl_get_row().
416 int aft_get_row_of_path(const char *path, struct osl_row **row)
418 struct osl_object obj = {.data = (char *)path, .size = strlen(path) + 1};
420 return osl_get_row(audio_file_table, AFTCOL_PATH, &obj, row);
424 * Get the row of the audio file table corresponding to the given hash value.
426 * \param hash The hash value of the desired audio file.
427 * \param row resul pointer.
429 * \return The return value of the underlying call to osl_get_row().
431 int aft_get_row_of_hash(HASH_TYPE *hash, struct osl_row **row)
433 const struct osl_object obj = {.data = hash, .size = HASH_SIZE};
434 return osl_get_row(audio_file_table, AFTCOL_HASH, &obj, row);
438 * Get the osl object holding the audio file selector info of a row.
440 * \param row Pointer to a row in the audio file table.
441 * \param obj Result pointer.
443 * \return The return value of the underlying call to osl_get_object().
445 int get_afsi_object_of_row(const struct osl_row *row, struct osl_object *obj)
447 return osl_get_object(audio_file_table, row, AFTCOL_AFSI, obj);
451 * Get the osl object holding the audio file selector info, given a path.
454 * \param path The full path of the audio file.
455 * \param obj Result pointer.
457 * \return Positive on success, negative on errors.
459 int get_afsi_object_of_path(const char *path, struct osl_object *obj)
462 int ret = aft_get_row_of_path(path, &row);
465 return get_afsi_object_of_row(row, obj);
469 * Get the audio file selector info, given a row of the audio file table.
471 * \param row Pointer to a row in the audio file table.
472 * \param afsi Result pointer.
474 * \return Positive on success, negative on errors.
476 int get_afsi_of_row(const struct osl_row *row, struct afs_info *afsi)
478 struct osl_object obj;
479 int ret = get_afsi_object_of_row(row, &obj);
482 return load_afsi(afsi, &obj);
486 * Get the audio file selector info, given the path of an audio table.
488 * \param path The full path of the audio file.
489 * \param afsi Result pointer.
491 * \return Positive on success, negative on errors.
493 int get_afsi_of_path(const char *path, struct afs_info *afsi)
495 struct osl_object obj;
496 int ret = get_afsi_object_of_path(path, &obj);
499 return load_afsi(afsi, &obj);
503 * Get the path of an audio file, given a row of the audio file table.
505 * \param row Pointer to a row in the audio file table.
506 * \param path Result pointer.
508 * \return Positive on success, negative on errors.
510 int get_audio_file_path_of_row(const struct osl_row *row, char **path)
512 struct osl_object path_obj;
513 int ret = osl_get_object(audio_file_table, row, AFTCOL_PATH,
517 *path = path_obj.data;
522 * Get the object containing the hash value of an audio file, given a row.
524 * \param row Pointer to a row of the audio file table.
525 * \param obj Result pointer.
527 * \return The return value of the underlying call to osl_get_object().
529 * \sa get_hash_of_row().
531 static int get_hash_object_of_aft_row(const struct osl_row *row, struct osl_object *obj)
533 return osl_get_object(audio_file_table, row, AFTCOL_HASH, obj);
537 * Get the hash value of an audio file, given a row of the audio file table.
539 * \param row Pointer to a row of the audio file table.
540 * \param hash Result pointer.
542 * \a hash points to mapped data and must not be freed by the caller.
544 * \return The return value of the underlying call to
545 * get_hash_object_of_aft_row().
547 static int get_hash_of_row(const struct osl_row *row, HASH_TYPE **hash)
549 struct osl_object obj;
550 int ret = get_hash_object_of_aft_row(row, &obj);
559 * Get the audio format handler info, given a row of the audio file table.
561 * \param row Pointer to a row of the audio file table.
562 * \param afhi Result pointer.
564 * \return The return value of the underlying call to osl_get_object().
566 * \sa get_chunk_table_of_row().
568 int get_afhi_of_row(const struct osl_row *row, struct audio_format_info *afhi)
570 struct osl_object obj;
571 int ret = osl_get_object(audio_file_table, row, AFTCOL_AFHI,
575 load_afhi(obj.data, afhi);
580 * Get the chunk table of an audio file, given a row of the audio file table.
582 * \param row Pointer to a row of the audio file table.
583 * \param afhi Result pointer.
585 * \return The return value of the underlying call to osl_open_disk_object().
587 * \sa get_afhi_of_row().
589 static int get_chunk_table_of_row(const struct osl_row *row, struct audio_format_info *afhi)
591 struct osl_object obj;
592 int ret = osl_open_disk_object(audio_file_table, row, AFTCOL_CHUNKS,
596 ret = load_chunk_info(&obj, afhi);
597 osl_close_disk_object(&obj);
602 * Mmap the given audio file and update statistics.
604 * \param aft_row Determines the audio file to be opened and updated.
605 * \param afd Result pointer.
607 * On success, the numplayed field of the audio file selector info is increased
608 * and the lastplayed time is set to the current time. Finally, the score of
609 * the audio file is updated.
611 * \return Positive on success, negative on errors.
613 int open_and_update_audio_file(struct osl_row *aft_row, struct audio_file_data *afd)
615 HASH_TYPE *aft_hash, file_hash[HASH_SIZE];
616 struct osl_object afsi_obj;
617 struct afs_info new_afsi;
618 int ret = get_hash_of_row(aft_row, &aft_hash);
622 ret = get_audio_file_path_of_row(aft_row, &afd->path);
625 ret = get_afsi_object_of_row(aft_row, &afsi_obj);
628 ret = load_afsi(&afd->afsi, &afsi_obj);
631 ret = get_afhi_of_row(aft_row, &afd->afhi);
634 ret = get_chunk_table_of_row(aft_row, &afd->afhi);
637 ret = mmap_full_file(afd->path, O_RDONLY, &afd->map);
640 hash_function(afd->map.data, afd->map.size, file_hash);
641 ret = -E_HASH_MISMATCH;
642 if (hash_compare(file_hash, aft_hash))
644 new_afsi = afd->afsi;
645 new_afsi.num_played++;
646 new_afsi.last_played = time(NULL);
647 save_afsi(&new_afsi, &afsi_obj); /* in-place update */
648 if (afd->current_play_mode == PLAY_MODE_PLAYLIST)
649 ret = playlist_update_audio_file(aft_row);
651 struct afsi_change_event_data aced = {.aft_row = aft_row,
652 .old_afsi = &afd->afsi};
653 afs_event(AFSI_CHANGE, NULL, &aced);
657 free(afd->afhi.chunk_table);
661 static int get_local_time(uint64_t *seconds, char *buf, size_t size,
662 time_t current_time, enum ls_listing_mode lm)
666 if (!localtime_r((time_t *)seconds, &t))
668 if (lm == LS_MODE_MBOX) {
669 if (!strftime(buf, size, "%c", &t))
673 if (*seconds + 6 * 30 * 24 * 3600 > current_time) {
674 if (!strftime(buf, size, "%b %e %k:%M", &t))
678 if (!strftime(buf, size, "%b %e %Y", &t))
683 /** Compute the number of (decimal) digits of a number. */
684 #define GET_NUM_DIGITS(x, num) { \
685 typeof((x)) _tmp = PARA_ABS(x); \
688 while ((_tmp) > 9) { \
694 static short unsigned get_duration_width(int seconds)
696 short unsigned width;
697 unsigned hours = seconds / 3600, mins = (seconds % 3600) / 60;
699 if (!hours) /* less than one hour => m:ss or mm:ss => 4 or 5 digits */
700 return 4 + (mins > 9);
701 /* more than one hour => h:mm:ss, hh:mm:ss, hhh:mm:ss, ... */
702 GET_NUM_DIGITS(hours, &width);
706 static void get_duration_buf(int seconds, char *buf, short unsigned max_width)
708 unsigned hours = seconds / 3600, mins = (seconds % 3600) / 60;
710 if (!hours) /* m:ss or mm:ss */
711 sprintf(buf, "%*u:%02u", max_width - 3, mins, seconds % 60);
712 else /* more than one hour => h:mm:ss, hh:mm:ss, hhh:mm:ss, ... */
713 sprintf(buf, "%*u:%02u:%02u", max_width - 6, hours, mins,
717 static char *make_attribute_line(const char *att_bitmap, struct afs_info *afsi)
719 char *att_text, *att_line;
721 get_attribute_text(&afsi->attributes, " ", &att_text);
723 return para_strdup(att_bitmap);
724 att_line = make_message("%s (%s)", att_bitmap, att_text);
729 static char *make_lyrics_line(struct afs_info *afsi)
733 lyr_get_name_by_id(afsi->lyrics_id, &lyrics_name);
735 return make_message("%u", afsi->lyrics_id);
736 return make_message("%u (%s)", afsi->lyrics_id, lyrics_name);
739 static char *make_image_line(struct afs_info *afsi)
742 img_get_name_by_id(afsi->image_id, &image_name);
744 return make_message("%u", afsi->image_id);
745 return make_message("%u (%s)", afsi->image_id, image_name);
748 static int print_list_item(struct ls_data *d, struct ls_options *opts,
749 struct para_buffer *b, time_t current_time)
753 char last_played_time[30];
754 char duration_buf[30]; /* nobody has an audio file long enough to overflow this */
755 char score_buf[30] = "";
756 struct afs_info *afsi = &d->afsi;
757 struct audio_format_info *afhi = &d->afhi;
758 struct ls_widths *w = &opts->widths;
759 int have_score = opts->flags & LS_FLAG_ADMISSIBLE_ONLY;
760 char asc_hash[2 * HASH_SIZE + 1];
761 char *att_line, *lyrics_line, *image_line;
763 if (opts->mode == LS_MODE_SHORT) {
764 para_printf(b, "%s\n", d->path);
767 get_attribute_bitmap(&afsi->attributes, att_buf);
768 ret = get_local_time(&afsi->last_played, last_played_time,
769 sizeof(last_played_time), current_time, opts->mode);
772 get_duration_buf(afhi->seconds_total, duration_buf, w->duration_width);
774 if (opts->mode == LS_MODE_LONG)
775 sprintf(score_buf, "%*li ", w->score_width, d->score);
777 sprintf(score_buf, "%li ", d->score);
780 if (opts->mode == LS_MODE_LONG) {
783 "%s " /* attributes */
784 "%*d " /* image_id */
785 "%*d " /* lyrics_id */
787 "%s " /* audio format */
788 "%*d " /* frequency */
791 "%*d " /* num_played */
792 "%s " /* last_played */
796 w->image_id_width, afsi->image_id,
797 w->lyrics_id_width, afsi->lyrics_id,
798 w->bitrate_width, afhi->bitrate,
799 audio_format_name(afsi->audio_format_id),
800 w->frequency_width, afhi->frequency,
803 w->num_played_width, afsi->num_played,
809 hash_to_asc(d->hash, asc_hash);
810 att_line = make_attribute_line(att_buf, afsi);
811 lyrics_line = make_lyrics_line(afsi);
812 image_line = make_image_line(afsi);
813 if (opts->mode == LS_MODE_VERBOSE) {
816 "%s: %s\n" /* path */
822 "bitrate: %dkbit/s\n"
830 (opts->flags & LS_FLAG_FULL_PATH)?
831 "path" : "file", d->path,
832 have_score? "score: " : "", score_buf,
833 have_score? "\n" : "",
839 audio_format_name(afsi->audio_format_id),
847 } else { /* mbox mode */
848 struct osl_object lyrics_def;
849 lyr_get_def_by_id(afsi->lyrics_id, &lyrics_def);
851 "From foo@localhost %s\n"
852 "Received: from\nTo: bar\nFrom: a\n"
853 "Subject: %s\n\n" /* path */
859 "bitrate: %dkbit/s\n"
869 have_score? "score: " : "", score_buf,
870 have_score? "\n" : "",
876 audio_format_name(afsi->audio_format_id),
882 lyrics_def.data? "Lyrics:\n~~~~~~~\n" : "",
883 lyrics_def.data? (char *)lyrics_def.data : ""
886 osl_close_disk_object(lyrics_def.data);
894 static int ls_audio_format_compare(const void *a, const void *b)
896 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
897 return NUM_COMPARE(d1->afsi.audio_format_id, d2->afsi.audio_format_id);
900 static int ls_duration_compare(const void *a, const void *b)
902 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
903 return NUM_COMPARE(d1->afhi.seconds_total, d2->afhi.seconds_total);
906 static int ls_bitrate_compare(const void *a, const void *b)
908 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
909 return NUM_COMPARE(d1->afhi.bitrate, d2->afhi.bitrate);
912 static int ls_lyrics_id_compare(const void *a, const void *b)
914 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
915 return NUM_COMPARE(d1->afsi.lyrics_id, d2->afsi.lyrics_id);
918 static int ls_image_id_compare(const void *a, const void *b)
920 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
921 return NUM_COMPARE(d1->afsi.image_id, d2->afsi.image_id);
924 static int ls_channels_compare(const void *a, const void *b)
926 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
927 return NUM_COMPARE(d1->afhi.channels, d2->afhi.channels);
930 static int ls_frequency_compare(const void *a, const void *b)
932 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
933 return NUM_COMPARE(d1->afhi.frequency, d2->afhi.frequency);
936 static int ls_num_played_compare(const void *a, const void *b)
938 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
939 return NUM_COMPARE(d1->afsi.num_played, d2->afsi.num_played);
942 static int ls_last_played_compare(const void *a, const void *b)
944 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
945 return NUM_COMPARE(d1->afsi.last_played, d2->afsi.last_played);
948 static int ls_score_compare(const void *a, const void *b)
950 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
951 return NUM_COMPARE(d1->score, d2->score);
954 static int ls_path_compare(const void *a, const void *b)
956 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
957 return strcmp(d1->path, d2->path);
960 static int sort_matching_paths(struct ls_options *options)
962 size_t nmemb = options->num_matching_paths;
963 size_t size = sizeof(*options->data_ptr);
964 int (*compar)(const void *, const void *);
967 options->data_ptr = para_malloc(nmemb * sizeof(*options->data_ptr));
968 for (i = 0; i < nmemb; i++)
969 options->data_ptr[i] = options->data + i;
971 /* In these cases the array is already sorted */
972 if (options->sorting == LS_SORT_BY_PATH
973 && !(options->flags & LS_FLAG_ADMISSIBLE_ONLY)
974 && (options->flags & LS_FLAG_FULL_PATH))
976 if (options->sorting == LS_SORT_BY_SCORE &&
977 options->flags & LS_FLAG_ADMISSIBLE_ONLY)
980 switch (options->sorting) {
981 case LS_SORT_BY_PATH:
982 compar = ls_path_compare; break;
983 case LS_SORT_BY_SCORE:
984 compar = ls_score_compare; break;
985 case LS_SORT_BY_LAST_PLAYED:
986 compar = ls_last_played_compare; break;
987 case LS_SORT_BY_NUM_PLAYED:
988 compar = ls_num_played_compare; break;
989 case LS_SORT_BY_FREQUENCY:
990 compar = ls_frequency_compare; break;
991 case LS_SORT_BY_CHANNELS:
992 compar = ls_channels_compare; break;
993 case LS_SORT_BY_IMAGE_ID:
994 compar = ls_image_id_compare; break;
995 case LS_SORT_BY_LYRICS_ID:
996 compar = ls_lyrics_id_compare; break;
997 case LS_SORT_BY_BITRATE:
998 compar = ls_bitrate_compare; break;
999 case LS_SORT_BY_DURATION:
1000 compar = ls_duration_compare; break;
1001 case LS_SORT_BY_AUDIO_FORMAT:
1002 compar = ls_audio_format_compare; break;
1006 qsort(options->data_ptr, nmemb, size, compar);
1010 /* row is either an aft_row or a row of the score table */
1011 /* TODO: Only compute widths if we need them */
1012 static int prepare_ls_row(struct osl_row *row, void *ls_opts)
1015 struct ls_options *options = ls_opts;
1017 struct ls_widths *w;
1018 unsigned short num_digits;
1020 struct osl_row *aft_row;
1024 if (options->flags & LS_FLAG_ADMISSIBLE_ONLY) {
1025 ret = get_score_and_aft_row(row, &score, &aft_row);
1030 ret = get_audio_file_path_of_row(aft_row, &path);
1033 if (!(options->flags & LS_FLAG_FULL_PATH)) {
1034 char *p = strrchr(path, '/');
1038 if (options->num_patterns) {
1039 for (i = 0; i < options->num_patterns; i++) {
1040 ret = fnmatch(options->patterns[i], path, 0);
1043 if (ret == FNM_NOMATCH)
1047 if (i >= options->num_patterns) /* no match */
1050 tmp = options->num_matching_paths++;
1051 if (options->num_matching_paths > options->array_size) {
1052 options->array_size++;
1053 options->array_size *= 2;
1054 options->data = para_realloc(options->data, options->array_size
1055 * sizeof(*options->data));
1057 d = options->data + tmp;
1058 ret = get_afsi_of_row(aft_row, &d->afsi);
1061 ret = get_afhi_of_row(aft_row, &d->afhi);
1065 ret = get_hash_of_row(aft_row, &d->hash);
1068 w = &options->widths;
1069 GET_NUM_DIGITS(d->afsi.image_id, &num_digits);
1070 w->image_id_width = PARA_MAX(w->image_id_width, num_digits);
1071 GET_NUM_DIGITS(d->afsi.lyrics_id, &num_digits);
1072 w->lyrics_id_width = PARA_MAX(w->lyrics_id_width, num_digits);
1073 GET_NUM_DIGITS(d->afhi.bitrate, &num_digits);
1074 w->bitrate_width = PARA_MAX(w->bitrate_width, num_digits);
1075 GET_NUM_DIGITS(d->afhi.frequency, &num_digits);
1076 w->frequency_width = PARA_MAX(w->frequency_width, num_digits);
1077 GET_NUM_DIGITS(d->afsi.num_played, &num_digits);
1078 w->num_played_width = PARA_MAX(w->num_played_width, num_digits);
1079 /* get the number of chars to print this amount of time */
1080 tmp = get_duration_width(d->afhi.seconds_total);
1081 w->duration_width = PARA_MAX(w->duration_width, tmp);
1082 if (options->flags & LS_FLAG_ADMISSIBLE_ONLY) {
1083 GET_NUM_DIGITS(score, &num_digits);
1084 num_digits++; /* add one for the sign (space or "-") */
1085 w->score_width = PARA_MAX(w->score_width, num_digits);
1091 static int com_ls_callback(const struct osl_object *query,
1092 struct osl_object *ls_output)
1094 struct ls_options *opts = query->data;
1095 char *p, *pattern_start = (char *)query->data + sizeof(*opts);
1096 struct para_buffer b = {.buf = NULL, .size = 0};
1098 time_t current_time;
1101 if (opts->num_patterns) {
1102 opts->patterns = para_malloc(opts->num_patterns * sizeof(char *));
1103 for (i = 0, p = pattern_start; i < opts->num_patterns; i++) {
1104 opts->patterns[i] = p;
1108 opts->patterns = NULL;
1109 if (opts->flags & LS_FLAG_ADMISSIBLE_ONLY)
1110 ret = admissible_file_loop(opts, prepare_ls_row);
1112 ret = osl_rbtree_loop(audio_file_table, AFTCOL_PATH, opts,
1116 ret = opts->num_patterns? -E_NO_MATCH : 0;
1117 if (!opts->num_matching_paths)
1119 ret = sort_matching_paths(opts);
1122 time(¤t_time);
1123 if (opts->flags & LS_FLAG_REVERSE)
1124 for (i = opts->num_matching_paths - 1; i >= 0; i--) {
1125 ret = print_list_item(opts->data_ptr[i], opts, &b, current_time);
1130 for (i = 0; i < opts->num_matching_paths; i++) {
1131 ret = print_list_item(opts->data_ptr[i], opts, &b, current_time);
1137 ls_output->data = b.buf;
1138 ls_output->size = b.size;
1140 free(opts->data_ptr);
1141 free(opts->patterns);
1146 * TODO: flags -h (sort by hash) -lm (list in mbox format)
1148 * long list: list hash, attributes as (xx--x-x-), file size, lastplayed
1149 * full list: list everything, including afsi, afhi, atts as clear text
1152 int com_afs_ls(int fd, int argc, char * const * const argv)
1156 enum ls_sorting_method sort = LS_SORT_BY_PATH;
1157 enum ls_listing_mode mode = LS_MODE_SHORT;
1158 struct ls_options opts = {.patterns = NULL};
1159 struct osl_object query = {.data = &opts, .size = sizeof(opts)},
1162 for (i = 1; i < argc; i++) {
1163 const char *arg = argv[i];
1166 if (!strcmp(arg, "--")) {
1170 if (!strncmp(arg, "-l", 2)) {
1172 mode = LS_MODE_LONG;
1176 return -E_AFT_SYNTAX;
1177 switch(*(arg + 2)) {
1179 mode = LS_MODE_SHORT;
1182 mode = LS_MODE_LONG;
1185 mode = LS_MODE_VERBOSE;
1188 mode = LS_MODE_MBOX;
1191 return -E_AFT_SYNTAX;
1194 if (!strcmp(arg, "-p")) {
1195 flags |= LS_FLAG_FULL_PATH;
1198 if (!strcmp(arg, "-a")) {
1199 flags |= LS_FLAG_ADMISSIBLE_ONLY;
1202 if (!strcmp(arg, "-r")) {
1203 flags |= LS_FLAG_REVERSE;
1206 if (!strncmp(arg, "-s", 2)) {
1207 if (!*(arg + 2) || *(arg + 3))
1208 return -E_AFT_SYNTAX;
1209 switch(*(arg + 2)) {
1211 sort = LS_SORT_BY_PATH;
1213 case 's': /* -ss implies -a */
1214 sort = LS_SORT_BY_SCORE;
1215 flags |= LS_FLAG_ADMISSIBLE_ONLY;
1218 sort = LS_SORT_BY_LAST_PLAYED;
1221 sort = LS_SORT_BY_NUM_PLAYED;
1224 sort = LS_SORT_BY_FREQUENCY;
1227 sort = LS_SORT_BY_CHANNELS;
1230 sort = LS_SORT_BY_IMAGE_ID;
1233 sort = LS_SORT_BY_LYRICS_ID;
1236 sort = LS_SORT_BY_BITRATE;
1239 sort = LS_SORT_BY_DURATION;
1242 sort = LS_SORT_BY_AUDIO_FORMAT;
1245 return -E_AFT_SYNTAX;
1248 return -E_AFT_SYNTAX;
1251 opts.sorting = sort;
1253 opts.num_patterns = argc - i;
1254 ret = send_option_arg_callback_request(&query, opts.num_patterns,
1255 argv + i, com_ls_callback, &ls_output);
1257 ret = send_buffer(fd, (char *)ls_output.data);
1258 free(ls_output.data);
1264 * Call the given function for each file in the audio file table.
1266 * \param private_data An arbitrary data pointer, passed to \a func.
1267 * \param func The custom function to be called.
1269 * \return The return value of the underlying call to osl_rbtree_loop().
1271 int audio_file_loop(void *private_data, osl_rbtree_loop_func *func)
1273 return osl_rbtree_loop(audio_file_table, AFTCOL_HASH, private_data,
1277 static struct osl_row *find_hash_sister(HASH_TYPE *hash)
1279 const struct osl_object obj = {.data = hash, .size = HASH_SIZE};
1280 struct osl_row *row;
1282 osl_get_row(audio_file_table, AFTCOL_HASH, &obj, &row);
1286 enum aft_row_offsets {
1287 AFTROW_AFHI_OFFSET_POS = 0,
1288 AFTROW_CHUNKS_OFFSET_POS = 2,
1289 AFTROW_AUDIO_FORMAT_OFFSET = 4,
1290 AFTROW_FLAGS_OFFSET = 5,
1291 AFTROW_HASH_OFFSET = 9,
1292 AFTROW_PATH_OFFSET = (AFTROW_HASH_OFFSET + HASH_SIZE),
1295 /* never save the afsi, as the server knows it too. Note that afhi might be NULL.
1296 * In this case, afhi won't be stored in the buffer */
1297 static void save_audio_file_info(HASH_TYPE *hash, const char *path,
1298 struct audio_format_info *afhi, uint32_t flags,
1299 uint8_t audio_format_num, struct osl_object *obj)
1301 size_t path_len = strlen(path) + 1;
1302 size_t afhi_size = sizeof_afhi_buf(afhi);
1303 size_t size = AFTROW_PATH_OFFSET + path_len + afhi_size
1304 + sizeof_chunk_info_buf(afhi);
1305 char *buf = para_malloc(size);
1308 write_u8(buf + AFTROW_AUDIO_FORMAT_OFFSET, audio_format_num);
1309 write_u32(buf + AFTROW_FLAGS_OFFSET, flags);
1311 memcpy(buf + AFTROW_HASH_OFFSET, hash, HASH_SIZE);
1312 strcpy(buf + AFTROW_PATH_OFFSET, path);
1314 pos = AFTROW_PATH_OFFSET + path_len;
1315 PARA_DEBUG_LOG("size: %zu, afhi starts at %d\n", size, pos);
1316 PARA_DEBUG_LOG("last afhi byte: %p, pos %zu\n", buf + pos + afhi_size - 1,
1317 pos + afhi_size - 1);
1318 write_u16(buf + AFTROW_AFHI_OFFSET_POS, pos);
1319 save_afhi(afhi, buf + pos);
1322 PARA_DEBUG_LOG("size: %zu, chunks start at %d\n", size, pos);
1323 write_u16(buf + AFTROW_CHUNKS_OFFSET_POS, pos);
1324 save_chunk_info(afhi, buf + pos);
1325 PARA_DEBUG_LOG("last byte in buf: %p\n", buf + size - 1);
1339 AFHI: whether afhi and chunk table are computed and sent
1340 ACTION: table modifications to be performed
1342 +---+----+-----+------+---------------------------------------------------+
1343 | HS | PB | F | AFHI | ACTION
1344 +---+----+-----+------+---------------------------------------------------+
1345 | Y | Y | Y | Y | if HS != PB: remove PB. HS: force afhi update,
1346 | | update path, keep afsi
1347 +---+----+-----+------+---------------------------------------------------+
1348 | Y | Y | N | N | if HS == PB: do not send callback request at all.
1349 | | otherwise: remove PB, HS: update path, keep afhi,
1351 +---+----+-----+------+---------------------------------------------------+
1352 | Y | N | Y | Y | (rename) force afhi update of HS, update path of
1354 +---+----+-----+------+---------------------------------------------------+
1355 | Y | N | N | N | (file rename) update path of HS, keep afsi, afhi
1356 +---+----+-----+------+---------------------------------------------------+
1357 | N | Y | Y | Y | (file change) update afhi, hash, of PB, keep afsi
1358 | | (force has no effect)
1359 +---+----+-----+------+---------------------------------------------------+
1360 | N | Y | N | Y | (file change) update afhi, hash of PB, keep afsi
1361 +---+----+-----+------+---------------------------------------------------+
1362 | N | N | Y | Y | (new file) create new entry (force has no effect)
1363 +---+----+-----+------+---------------------------------------------------+
1364 | N | N | N | Y | (new file) create new entry
1365 +---+----+-----+------+---------------------------------------------------+
1367 afhi <=> force or no HS
1371 /** Flags passed to the add command. */
1372 enum com_add_flags {
1373 /** Skip paths that exist already. */
1375 /** Force adding. */
1377 /** Print what is being done. */
1378 ADD_FLAG_VERBOSE = 4,
1379 /** Try to add files with unknown suffixes. */
1383 static int com_add_callback(const struct osl_object *query,
1384 struct osl_object *result)
1386 char *buf = query->data, *path;
1387 struct osl_row *pb, *aft_row;
1389 struct osl_object objs[NUM_AFT_COLUMNS];
1391 char asc[2 * HASH_SIZE + 1];
1393 char afsi_buf[AFSI_SIZE];
1394 uint32_t flags = read_u32(buf + AFTROW_FLAGS_OFFSET);
1395 struct afs_info default_afsi = {.last_played = 0};
1396 struct para_buffer msg = {.buf = NULL};
1398 hash = (HASH_TYPE *)buf + AFTROW_HASH_OFFSET;
1399 hash_to_asc(hash, asc);;
1400 objs[AFTCOL_HASH].data = buf + AFTROW_HASH_OFFSET;
1401 objs[AFTCOL_HASH].size = HASH_SIZE;
1403 path = buf + AFTROW_PATH_OFFSET;
1404 objs[AFTCOL_PATH].data = path;
1405 objs[AFTCOL_PATH].size = strlen(path) + 1;
1407 PARA_INFO_LOG("request to add %s\n", path);
1408 hs = find_hash_sister(hash);
1409 ret = aft_get_row_of_path(path, &pb);
1410 if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
1412 if (hs && pb && hs == pb && !(flags & ADD_FLAG_FORCE)) {
1413 if (flags & ADD_FLAG_VERBOSE)
1414 para_printf(&msg, "ignoring duplicate\n");
1418 if (hs && hs != pb) {
1419 struct osl_object obj;
1420 if (pb) { /* hs trumps pb, remove pb */
1421 if (flags & ADD_FLAG_VERBOSE)
1422 para_printf(&msg, "removing path brother\n");
1423 ret = osl_del_row(audio_file_table, pb);
1428 /* file rename, update hs' path */
1429 if (flags & ADD_FLAG_VERBOSE) {
1430 ret = osl_get_object(audio_file_table, hs,
1434 para_printf(&msg, "renamed from %s\n", (char *)obj.data);
1436 ret = osl_update_object(audio_file_table, hs, AFTCOL_PATH,
1437 &objs[AFTCOL_PATH]);
1440 afs_event(AUDIO_FILE_RENAME, &msg, hs);
1441 if (!(flags & ADD_FLAG_FORCE))
1444 /* no hs or force mode, child must have sent afhi */
1445 uint16_t afhi_offset = read_u16(buf + AFTROW_AFHI_OFFSET_POS);
1446 uint16_t chunks_offset = read_u16(buf + AFTROW_CHUNKS_OFFSET_POS);
1448 objs[AFTCOL_AFHI].data = buf + afhi_offset;
1449 objs[AFTCOL_AFHI].size = chunks_offset - afhi_offset;
1451 if (!objs[AFTCOL_AFHI].size) /* "impossible" */
1453 objs[AFTCOL_CHUNKS].data = buf + chunks_offset;
1454 objs[AFTCOL_CHUNKS].size = query->size - chunks_offset;
1455 if (pb && !hs) { /* update pb's hash */
1456 char old_asc[2 * HASH_SIZE + 1];
1457 HASH_TYPE *old_hash;
1458 ret = get_hash_of_row(pb, &old_hash);
1461 hash_to_asc(old_hash, old_asc);
1462 if (flags & ADD_FLAG_VERBOSE)
1463 para_printf(&msg, "file change: %s -> %s\n",
1465 ret = osl_update_object(audio_file_table, pb, AFTCOL_HASH,
1466 &objs[AFTCOL_HASH]);
1470 if (hs || pb) { /* (hs != NULL and pb != NULL) implies hs == pb */
1471 struct osl_row *row = pb? pb : hs;
1472 /* update afhi and chunk_table */
1473 if (flags & ADD_FLAG_VERBOSE)
1474 para_printf(&msg, "updating afhi and chunk table\n");
1475 ret = osl_update_object(audio_file_table, row, AFTCOL_AFHI,
1476 &objs[AFTCOL_AFHI]);
1479 ret = osl_update_object(audio_file_table, row, AFTCOL_CHUNKS,
1480 &objs[AFTCOL_CHUNKS]);
1483 afs_event(AFHI_CHANGE, &msg, row);
1486 /* new entry, use default afsi */
1487 if (flags & ADD_FLAG_VERBOSE)
1488 para_printf(&msg, "new file\n");
1489 default_afsi.last_played = time(NULL) - 365 * 24 * 60 * 60;
1490 default_afsi.audio_format_id = read_u8(buf + AFTROW_AUDIO_FORMAT_OFFSET);
1492 objs[AFTCOL_AFSI].data = &afsi_buf;
1493 objs[AFTCOL_AFSI].size = AFSI_SIZE;
1494 save_afsi(&default_afsi, &objs[AFTCOL_AFSI]);
1495 ret = osl_add_and_get_row(audio_file_table, objs, &aft_row);
1498 para_printf(&msg, "%s\n", PARA_STRERROR(-ret));
1501 result->data = msg.buf;
1502 result->size = msg.size;
1503 afs_event(AUDIO_FILE_ADD, &msg, aft_row);
1507 struct private_add_data {
1512 static int path_brother_callback(const struct osl_object *query,
1513 struct osl_object *result)
1515 char *path = query->data;
1516 struct osl_row *path_brother;
1517 int ret = aft_get_row_of_path(path, &path_brother);
1520 result->data = para_malloc(sizeof(path_brother));
1521 result->size = sizeof(path_brother);
1522 *(struct osl_row **)(result->data) = path_brother;
1526 static int hash_sister_callback(const struct osl_object *query,
1527 struct osl_object *result)
1529 HASH_TYPE *hash = query->data;
1530 struct osl_row *hash_sister;
1532 hash_sister = find_hash_sister(hash);
1534 return -E_RB_KEY_NOT_FOUND;
1535 result->data = para_malloc(sizeof(hash_sister));
1536 result->size = sizeof(hash_sister);
1537 *(struct osl_row **)(result->data) = hash_sister;
1541 static int add_one_audio_file(const char *path, const void *private_data)
1544 uint8_t format_num = -1;
1545 const struct private_add_data *pad = private_data;
1546 struct audio_format_info afhi, *afhi_ptr = NULL;
1547 struct osl_row *pb = NULL, *hs = NULL; /* path brother/hash sister */
1548 struct osl_object map, obj = {.data = NULL}, query, result;
1549 HASH_TYPE hash[HASH_SIZE];
1551 afhi.header_offset = 0;
1552 afhi.header_len = 0;
1553 ret = guess_audio_format(path);
1554 if (ret < 0 && !(pad->flags & ADD_FLAG_ALL))
1556 query.data = (char *)path;
1557 query.size = strlen(path) + 1;
1558 ret = send_callback_request(path_brother_callback, &query, &result);
1559 if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
1562 pb = *(struct osl_row **)result.data;
1566 if (pb && (pad->flags & ADD_FLAG_LAZY)) { /* lazy is really cheap */
1567 if (pad->flags & ADD_FLAG_VERBOSE)
1568 ret = send_va_buffer(pad->fd, "lazy-ignore: %s\n", path);
1571 /* We still want to add this file. Compute its hash. */
1572 ret = mmap_full_file(path, O_RDONLY, &map);
1575 hash_function(map.data, map.size, hash);
1577 /* Check whether database contains file with the same hash. */
1579 query.size = HASH_SIZE;
1580 ret = send_callback_request(hash_sister_callback, &query, &result);
1581 if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
1584 hs = *(struct osl_row **)result.data;
1587 /* Return success if we already know this file. */
1589 if (pb && hs && hs == pb && (!(pad->flags & ADD_FLAG_FORCE))) {
1590 if (pad->flags & ADD_FLAG_VERBOSE)
1591 ret = send_va_buffer(pad->fd,
1592 "%s exists, not forcing update\n", path);
1596 * we won't recalculate the audio format info and the chunk table if
1597 * there is a hash sister unless in FORCE mode.
1599 if (!hs || (pad->flags & ADD_FLAG_FORCE)) {
1600 ret = compute_afhi(path, map.data, map.size, &afhi);
1606 if (pad->flags & ADD_FLAG_VERBOSE) {
1607 ret = send_va_buffer(pad->fd, "adding %s\n", path);
1611 munmap(map.data, map.size);
1612 save_audio_file_info(hash, path, afhi_ptr, pad->flags, format_num, &obj);
1613 /* Ask afs to consider this entry for adding. */
1614 ret = send_callback_request(com_add_callback, &obj, &result);
1615 if (result.data && result.size) {
1616 ret2 = send_va_buffer(pad->fd, "%s", (char *)result.data);
1618 if (ret >= 0 && ret2 < 0)
1624 munmap(map.data, map.size);
1626 if (ret < 0 && ret != -E_SEND)
1627 send_va_buffer(pad->fd, "failed to add %s (%s)\n", path,
1628 PARA_STRERROR(-ret));
1631 free(afhi_ptr->chunk_table);
1632 /* it's not an error if not all files could be added */
1633 return ret == -E_SEND? ret : 1;
1636 int com_add(int fd, int argc, char * const * const argv)
1639 struct private_add_data pad = {.fd = fd, .flags = 0};
1640 struct stat statbuf;
1642 for (i = 1; i < argc; i++) {
1643 const char *arg = argv[i];
1646 if (!strcmp(arg, "--")) {
1650 if (!strcmp(arg, "-a")) {
1651 pad.flags |= ADD_FLAG_ALL;
1654 if (!strcmp(arg, "-l")) {
1655 pad.flags |= ADD_FLAG_LAZY;
1658 if (!strcmp(arg, "-f")) {
1659 pad.flags |= ADD_FLAG_FORCE;
1662 if (!strcmp(arg, "-v")) {
1663 pad.flags |= ADD_FLAG_VERBOSE;
1668 return -E_AFT_SYNTAX;
1669 for (; i < argc; i++) {
1671 ret = verify_path(argv[i], &path);
1673 ret = send_va_buffer(fd, "%s: %s\n", argv[i], PARA_STRERROR(-ret));
1678 ret = stat(path, &statbuf);
1680 ret = send_va_buffer(fd, "failed to stat %s (%s)\n", path,
1687 if (S_ISDIR(statbuf.st_mode))
1688 ret = for_each_file_in_dir(path, add_one_audio_file,
1691 ret = add_one_audio_file(path, &pad);
1693 send_va_buffer(fd, "%s: %s\n", path, PARA_STRERROR(-ret));
1704 * Flags used by the touch command.
1709 /** Whether the \p FNM_PATHNAME flag should be passed to fnmatch(). */
1710 TOUCH_FLAG_FNM_PATHNAME = 1,
1711 /** Activates verbose mode. */
1712 TOUCH_FLAG_VERBOSE = 2
1715 struct com_touch_options {
1717 int64_t last_played;
1723 struct touch_action_data {
1724 struct com_touch_options *cto;
1725 struct para_buffer pb;
1728 static int touch_audio_file(__a_unused struct osl_table *table,
1729 struct osl_row *row, const char *name, void *data)
1731 struct touch_action_data *tad = data;
1732 struct osl_object obj;
1733 struct afs_info old_afsi, new_afsi;
1734 int ret, no_options = tad->cto->num_played < 0 && tad->cto->last_played < 0 &&
1735 tad->cto->lyrics_id < 0 && tad->cto->image_id < 0;
1736 struct afsi_change_event_data aced;
1738 ret = get_afsi_object_of_row(row, &obj);
1740 para_printf(&tad->pb, "%s: %s\n", name, PARA_STRERROR(-ret));
1743 ret = load_afsi(&old_afsi, &obj);
1745 para_printf(&tad->pb, "%s: %s\n", name, PARA_STRERROR(-ret));
1748 new_afsi = old_afsi;
1750 new_afsi.num_played++;
1751 new_afsi.last_played = time(NULL);
1752 if (tad->cto->flags & TOUCH_FLAG_VERBOSE)
1753 para_printf(&tad->pb, "%s: num_played = %u, "
1754 "last_played = now()\n", name,
1755 new_afsi.num_played);
1757 if (tad->cto->flags & TOUCH_FLAG_VERBOSE)
1758 para_printf(&tad->pb, "touching %s\n", name);
1759 if (tad->cto->lyrics_id >= 0)
1760 new_afsi.lyrics_id = tad->cto->lyrics_id;
1761 if (tad->cto->image_id >= 0)
1762 new_afsi.image_id = tad->cto->image_id;
1763 if (tad->cto->num_played >= 0)
1764 new_afsi.num_played = tad->cto->num_played;
1765 if (tad->cto->last_played >= 0)
1766 new_afsi.last_played = tad->cto->last_played;
1768 save_afsi(&new_afsi, &obj); /* in-place update */
1770 aced.old_afsi = &old_afsi;
1771 afs_event(AFSI_CHANGE, &tad->pb, &aced);
1775 static int com_touch_callback(const struct osl_object *query,
1776 struct osl_object *result)
1778 struct touch_action_data tad = {.cto = query->data};
1780 struct pattern_match_data pmd = {
1781 .table = audio_file_table,
1782 .loop_col_num = AFTCOL_HASH,
1783 .match_col_num = AFTCOL_PATH,
1784 .patterns = {.data = (char *)query->data + sizeof(*tad.cto),
1785 .size = query->size - sizeof(*tad.cto)},
1787 .action = touch_audio_file
1789 if (tad.cto->flags & TOUCH_FLAG_FNM_PATHNAME)
1790 pmd.fnmatch_flags |= FNM_PATHNAME;
1791 ret = for_each_matching_row(&pmd);
1793 para_printf(&tad.pb, "%s\n", PARA_STRERROR(-ret));
1795 result->data = tad.pb.buf;
1796 result->size = tad.pb.size;
1799 return ret < 0? ret : 0;
1802 int com_touch(int fd, int argc, char * const * const argv)
1804 struct com_touch_options cto = {
1810 struct osl_object query = {.data = &cto, .size = sizeof(cto)},
1815 for (i = 1; i < argc; i++) {
1816 const char *arg = argv[i];
1819 if (!strcmp(arg, "--")) {
1823 if (!strncmp(arg, "-n", 2)) {
1824 ret = para_atoi32(arg + 2, &cto.num_played);
1829 if (!strncmp(arg, "-l", 2)) {
1830 ret = para_atoi64(arg + 2, &cto.last_played);
1835 if (!strncmp(arg, "-y", 2)) {
1836 ret = para_atoi32(arg + 2, &cto.lyrics_id);
1841 if (!strncmp(arg, "-i", 2)) {
1842 ret = para_atoi32(arg + 2, &cto.image_id);
1847 if (!strcmp(arg, "-p")) {
1848 cto.flags |= TOUCH_FLAG_FNM_PATHNAME;
1851 if (!strcmp(arg, "-v")) {
1852 cto.flags |= TOUCH_FLAG_VERBOSE;
1855 break; /* non-option starting with dash */
1858 return -E_AFT_SYNTAX;
1859 ret = send_option_arg_callback_request(&query, argc - i,
1860 argv + i, com_touch_callback, &result);
1862 send_buffer(fd, (char *)result.data);
1865 send_va_buffer(fd, "%s\n", PARA_STRERROR(-ret));
1870 RM_FLAG_VERBOSE = 1,
1872 RM_FLAG_FNM_PATHNAME = 4
1875 struct com_rm_data {
1877 struct para_buffer pb;
1878 unsigned num_removed;
1881 static int remove_audio_file(__a_unused struct osl_table *table,
1882 struct osl_row *row, const char *name, void *data)
1884 struct com_rm_data *crd = data;
1887 if (crd->flags & RM_FLAG_VERBOSE)
1888 para_printf(&crd->pb, "removing %s\n", name);
1889 afs_event(AUDIO_FILE_REMOVE, &crd->pb, row);
1890 ret = osl_del_row(audio_file_table, row);
1892 para_printf(&crd->pb, "%s: %s\n", name, PARA_STRERROR(-ret));
1898 static int com_rm_callback(const struct osl_object *query,
1899 __a_unused struct osl_object *result)
1901 struct com_rm_data crd = {.flags = *(uint32_t *)query->data};
1903 struct pattern_match_data pmd = {
1904 .table = audio_file_table,
1905 .loop_col_num = AFTCOL_HASH,
1906 .match_col_num = AFTCOL_PATH,
1907 .patterns = {.data = (char *)query->data + sizeof(uint32_t),
1908 .size = query->size - sizeof(uint32_t)},
1910 .action = remove_audio_file
1912 if (crd.flags & RM_FLAG_FNM_PATHNAME)
1913 pmd.fnmatch_flags |= FNM_PATHNAME;
1914 ret = for_each_matching_row(&pmd);
1916 para_printf(&crd.pb, "%s\n", PARA_STRERROR(-ret));
1917 if (!crd.num_removed && !(crd.flags & RM_FLAG_FORCE))
1918 para_printf(&crd.pb, "no matches -- nothing removed\n");
1920 if (crd.flags & RM_FLAG_VERBOSE)
1921 para_printf(&crd.pb, "removed %u files\n", crd.num_removed);
1924 result->data = crd.pb.buf;
1925 result->size = crd.pb.size;
1928 return ret < 0? ret : 0;
1931 /* TODO options: -r (recursive) */
1932 int com_afs_rm(int fd, int argc, char * const * const argv)
1935 struct osl_object query = {.data = &flags, .size = sizeof(flags)},
1939 for (i = 1; i < argc; i++) {
1940 const char *arg = argv[i];
1943 if (!strcmp(arg, "--")) {
1947 if (!strcmp(arg, "-f")) {
1948 flags |= RM_FLAG_FORCE;
1951 if (!strcmp(arg, "-p")) {
1952 flags |= RM_FLAG_FNM_PATHNAME;
1955 if (!strcmp(arg, "-v")) {
1956 flags |= RM_FLAG_VERBOSE;
1962 return -E_AFT_SYNTAX;
1963 ret = send_option_arg_callback_request(&query, argc - i, argv + i,
1964 com_rm_callback, &result);
1966 send_buffer(fd, (char *)result.data);
1969 send_va_buffer(fd, "%s\n", PARA_STRERROR(-ret));
1974 * Flags used by the cpsi command.
1979 /** Whether the lyrics id should be copied. */
1980 CPSI_FLAG_COPY_LYRICS_ID = 1,
1981 /** Whether the image id should be copied. */
1982 CPSI_FLAG_COPY_IMAGE_ID = 2,
1983 /** Whether the lastplayed time should be copied. */
1984 CPSI_FLAG_COPY_LASTPLAYED = 4,
1985 /** Whether the numplayed count should be copied. */
1986 CPSI_FLAG_COPY_NUMPLAYED = 8,
1987 /** Whether the attributes should be copied. */
1988 CPSI_FLAG_COPY_ATTRIBUTES = 16,
1989 /** Activates verbose mode. */
1990 CPSI_FLAG_VERBOSE = 32,
1993 struct cpsi_action_data {
1995 unsigned num_copied;
1996 struct para_buffer pb;
1997 struct afs_info source_afsi;
2000 static int copy_selector_info(__a_unused struct osl_table *table,
2001 struct osl_row *row, const char *name, void *data)
2003 struct cpsi_action_data *cad = data;
2004 struct osl_object target_afsi_obj;
2006 struct afs_info old_afsi, target_afsi;
2007 struct afsi_change_event_data aced;
2009 ret = get_afsi_object_of_row(row, &target_afsi_obj);
2012 load_afsi(&target_afsi, &target_afsi_obj);
2013 old_afsi = target_afsi;
2014 if (cad->flags & CPSI_FLAG_COPY_LYRICS_ID)
2015 target_afsi.lyrics_id = cad->source_afsi.lyrics_id;
2016 if (cad->flags & CPSI_FLAG_COPY_IMAGE_ID)
2017 target_afsi.image_id = cad->source_afsi.image_id;
2018 if (cad->flags & CPSI_FLAG_COPY_LASTPLAYED)
2019 target_afsi.last_played = cad->source_afsi.last_played;
2020 if (cad->flags & CPSI_FLAG_COPY_NUMPLAYED)
2021 target_afsi.num_played = cad->source_afsi.num_played;
2022 if (cad->flags & CPSI_FLAG_COPY_ATTRIBUTES)
2023 target_afsi.attributes = cad->source_afsi.attributes;
2024 save_afsi(&target_afsi, &target_afsi_obj); /* in-place update */
2026 if (cad->flags & CPSI_FLAG_VERBOSE)
2027 para_printf(&cad->pb, "copied afsi to %s\n", name);
2029 aced.old_afsi = &old_afsi;
2030 afs_event(AFSI_CHANGE, &cad->pb, &aced);
2034 static int com_cpsi_callback(const struct osl_object *query,
2035 struct osl_object *result)
2037 struct cpsi_action_data cad = {.flags = *(unsigned *)query->data};
2039 char *source_path = (char *)query->data + sizeof(cad.flags);
2041 ret = get_afsi_of_path(source_path, &cad.source_afsi);
2044 struct pattern_match_data pmd = {
2045 .table = audio_file_table,
2046 .loop_col_num = AFTCOL_HASH,
2047 .match_col_num = AFTCOL_PATH,
2048 .patterns = {.data = source_path + strlen(source_path) + 1,
2049 .size = query->size - sizeof(cad.flags)
2050 - strlen(source_path) - 1},
2052 .action = copy_selector_info
2054 ret = for_each_matching_row(&pmd);
2057 para_printf(&cad.pb, "%s\n", PARA_STRERROR(-ret));
2058 if (cad.flags & CPSI_FLAG_VERBOSE) {
2060 para_printf(&cad.pb, "copied requested afsi from %s "
2062 source_path, cad.num_copied);
2064 para_printf(&cad.pb, "nothing copied\n");
2067 result->data = cad.pb.buf;
2068 result->size = cad.pb.size;
2071 return ret < 0? ret : 0;
2074 int com_cpsi(int fd, int argc, char * const * const argv)
2078 struct osl_object options = {.data = &flags, .size = sizeof(flags)},
2081 for (i = 1; i < argc; i++) {
2082 const char *arg = argv[i];
2085 if (!strcmp(arg, "--")) {
2089 if (!strcmp(arg, "-y")) {
2090 flags |= CPSI_FLAG_COPY_LYRICS_ID;
2093 if (!strcmp(arg, "-i")) {
2094 flags |= CPSI_FLAG_COPY_IMAGE_ID;
2097 if (!strcmp(arg, "-l")) {
2098 flags |= CPSI_FLAG_COPY_LASTPLAYED;
2101 if (!strcmp(arg, "-n")) {
2102 flags |= CPSI_FLAG_COPY_NUMPLAYED;
2105 if (!strcmp(arg, "-a")) {
2106 flags |= CPSI_FLAG_COPY_ATTRIBUTES;
2109 if (!strcmp(arg, "-v")) {
2110 flags |= CPSI_FLAG_VERBOSE;
2115 if (i + 1 >= argc) /* need at least souce file and pattern */
2116 return -E_AFT_SYNTAX;
2117 if (!(flags & ~CPSI_FLAG_VERBOSE)) /* no copy flags given */
2118 flags = ~(unsigned)CPSI_FLAG_VERBOSE | flags;
2119 ret = send_option_arg_callback_request(&options, argc - i, argv + i,
2120 com_cpsi_callback, &result);
2122 send_buffer(fd, (char *)result.data);
2125 send_va_buffer(fd, "%s\n", PARA_STRERROR(-ret));
2129 /* TODO: optionally fix problems by removing offending rows */
2130 static int check_audio_file(struct osl_row *row, void *data)
2133 struct para_buffer *pb = data;
2134 struct stat statbuf;
2135 int ret = get_audio_file_path_of_row(row, &path);
2136 struct afs_info afsi;
2140 para_printf(pb, "%s\n", PARA_STRERROR(-ret));
2143 if (stat(path, &statbuf) < 0)
2144 para_printf(pb, "%s: stat error (%s)\n", path, strerror(errno));
2146 if (!S_ISREG(statbuf.st_mode))
2147 para_printf(pb, "%s: not a regular file\n", path);
2149 ret = get_afsi_of_row(row, &afsi);
2151 para_printf(pb, "%s: %s\n", path, PARA_STRERROR(-ret));
2154 ret = lyr_get_name_by_id(afsi.lyrics_id, &blob_name);
2156 para_printf(pb, "%s lyrics id %u: %s\n", path, afsi.lyrics_id,
2157 PARA_STRERROR(-ret));
2158 ret = img_get_name_by_id(afsi.image_id, &blob_name);
2160 para_printf(pb, "%s image id %u: %s\n", path, afsi.image_id,
2161 PARA_STRERROR(-ret));
2166 * Check the audio file table for inconsistencies.
2168 * \param query Unused.
2169 * \param result Contains message string upon return.
2171 * This function always succeeds.
2175 int aft_check_callback(__a_unused const struct osl_object *query, struct osl_object *result)
2177 struct para_buffer pb = {.buf = NULL};
2179 para_printf(&pb, "checking audio file table...\n");
2180 audio_file_loop(&pb, check_audio_file);
2181 result->data = pb.buf;
2182 result->size = pb.size;
2188 * Close the audio file table.
2190 * \param flags Ususal flags that are passed to osl_close_table().
2192 * \sa osl_close_table().
2194 static void aft_close(void)
2196 osl_close_table(audio_file_table, OSL_MARK_CLEAN);
2197 audio_file_table = NULL;
2201 * Open the audio file table.
2203 * \param dir The database directory.
2207 * \sa osl_open_table().
2209 static int aft_open(const char *dir)
2213 audio_file_table_desc.dir = dir;
2214 ret = osl_open_table(&audio_file_table_desc, &audio_file_table);
2217 osl_get_num_rows(audio_file_table, &num);
2218 PARA_INFO_LOG("audio file table contains %d files\n", num);
2221 PARA_INFO_LOG("failed to open audio file table\n");
2222 audio_file_table = NULL;
2223 if (ret >= 0 || is_errno(-ret, ENOENT))
2228 static int aft_create(const char *dir)
2230 audio_file_table_desc.dir = dir;
2231 return osl_create_table(&audio_file_table_desc);
2234 static int clear_attribute(struct osl_row *row, void *data)
2236 struct rmatt_event_data *red = data;
2237 struct afs_info afsi;
2238 struct osl_object obj;
2239 int ret = get_afsi_object_of_row(row, &obj);
2240 uint64_t mask = ~(1ULL << red->bitnum);
2244 ret = load_afsi(&afsi, &obj);
2247 afsi.attributes &= mask;
2248 save_afsi(&afsi, &obj);
2252 static int aft_event_handler(enum afs_events event, struct para_buffer *pb,
2256 case ATTRIBUTE_REMOVE: {
2257 const struct rmatt_event_data *red = data;
2258 para_printf(pb, "clearing attribute %s (bit %u) from all "
2259 "entries in the audio file table\n", red->name,
2261 return audio_file_loop(data, clear_attribute);
2268 void aft_init(struct afs_table *t)
2270 t->name = audio_file_table_desc.name;
2272 t->close = aft_close;
2273 t->create = aft_create;
2274 t->event_handler = aft_event_handler;