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. */
9 #include <dirent.h> /* readdir() */
22 static struct osl_table *audio_file_table;
24 /** The different sorting methods of the ls command. */
25 enum ls_sorting_method {
31 LS_SORT_BY_LAST_PLAYED,
33 LS_SORT_BY_NUM_PLAYED,
47 LS_SORT_BY_AUDIO_FORMAT,
52 /** The different listing modes of the ls command. */
53 enum ls_listing_mode {
54 /** Default listing mode. */
64 /** The flags accepted by the ls command. */
67 LS_FLAG_FULL_PATH = 1,
69 LS_FLAG_ADMISSIBLE_ONLY = 2,
75 * The size of the individual output fields of the ls command.
77 * These depend on the actual content being listed. If, for instance only files
78 * with duration less than an hour are being listed, then the duration with is
79 * made smaller because then the duration is listed as mm:ss rather than
83 /** size of the score field. */
84 unsigned short score_width;
85 /** size of the image id field. */
86 unsigned short image_id_width;
87 /** size of the lyrics id field. */
88 unsigned short lyrics_id_width;
89 /** size of the bitrate field. */
90 unsigned short bitrate_width;
91 /** size of the frequency field. */
92 unsigned short frequency_width;
93 /** size of the duration field. */
94 unsigned short duration_width;
95 /** size of the num played field. */
96 unsigned short num_played_width;
99 /** Data passed to the different compare functions (called by qsort()). */
101 /** Usual audio format handler information. */
102 struct audio_format_info afhi;
103 /** Audio file selector information. */
104 struct afs_info afsi;
105 /** The full path of the audio file. */
107 /** The score value (if -a was given). */
109 /** The sha1 hash of audio file. */
115 enum ls_sorting_method sorting;
116 enum ls_listing_mode mode;
119 struct ls_widths widths;
121 uint32_t num_matching_paths;
122 struct ls_data *data;
123 struct ls_data **data_ptr;
127 * Describes the layout of the mmapped-afs info struct.
129 * \sa struct afs_info.
132 /** Where .last_played is stored. */
133 AFSI_LAST_PLAYED_OFFSET = 0,
134 /** Storage position of the attributes bitmap. */
135 AFSI_ATTRIBUTES_OFFSET = 8,
136 /** Storage position of the .num_played field. */
137 AFSI_NUM_PLAYED_OFFSET = 16,
138 /** Storage position of the .image_id field. */
139 AFSI_IMAGE_ID_OFFSET = 20,
140 /** Storage position of the .lyrics_id field. */
141 AFSI_LYRICS_ID_OFFSET = 24,
142 /** Storage position of the .audio_format_id field. */
143 AFSI_AUDIO_FORMAT_ID_OFFSET = 28,
144 /** 3 bytes reserved space for future usage. */
145 AFSI_AUDIO_FORMAT_UNUSED_OFFSET = 29,
146 /** On-disk storage space needed. */
151 * Convert a struct afs_info to an osl object.
153 * \param afsi Pointer to the audio file info to be converted.
154 * \param obj Result pointer.
158 void save_afsi(struct afs_info *afsi, struct osl_object *obj)
160 char *buf = obj->data;
162 write_u64(buf + AFSI_LAST_PLAYED_OFFSET, afsi->last_played);
163 write_u64(buf + AFSI_ATTRIBUTES_OFFSET, afsi->attributes);
164 write_u32(buf + AFSI_NUM_PLAYED_OFFSET, afsi->num_played);
165 write_u32(buf + AFSI_IMAGE_ID_OFFSET, afsi->image_id);
166 write_u32(buf + AFSI_LYRICS_ID_OFFSET, afsi->lyrics_id);
167 write_u8(buf + AFSI_AUDIO_FORMAT_ID_OFFSET,
168 afsi->audio_format_id);
169 memset(buf + AFSI_AUDIO_FORMAT_UNUSED_OFFSET, 0, 3);
173 * Get the audio file selector info struct stored in an osl object.
175 * \param afsi Points to the audio_file info structure to be filled in.
176 * \param obj The osl object holding the data.
178 * \return Positive on success, negative on errors. Possible errors: \p E_BAD_AFS.
182 int load_afsi(struct afs_info *afsi, struct osl_object *obj)
184 char *buf = obj->data;
185 if (obj->size < AFSI_SIZE)
187 afsi->last_played = read_u64(buf + AFSI_LAST_PLAYED_OFFSET);
188 afsi->attributes = read_u64(buf + AFSI_ATTRIBUTES_OFFSET);
189 afsi->num_played = read_u32(buf + AFSI_NUM_PLAYED_OFFSET);
190 afsi->image_id = read_u32(buf + AFSI_IMAGE_ID_OFFSET);
191 afsi->lyrics_id = read_u32(buf + AFSI_LYRICS_ID_OFFSET);
192 afsi->audio_format_id = read_u8(buf +
193 AFSI_AUDIO_FORMAT_ID_OFFSET);
197 /** The columns of the audio file table. */
198 enum audio_file_table_columns {
199 /** The hash on the content of the audio file. */
201 /** The full path in the filesystem. */
203 /** The audio file selector info. */
205 /** The audio format handler info. */
207 /** The chunk table info and the chunk table of the audio file. */
209 /** The number of columns of this table. */
213 static struct osl_column_description aft_cols[] = {
215 .storage_type = OSL_MAPPED_STORAGE,
216 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE | OSL_UNIQUE,
218 .compare_function = osl_hash_compare,
219 .data_size = HASH_SIZE
222 .storage_type = OSL_MAPPED_STORAGE,
223 .storage_flags = OSL_RBTREE | OSL_UNIQUE,
225 .compare_function = string_compare,
228 .storage_type = OSL_MAPPED_STORAGE,
229 .storage_flags = OSL_FIXED_SIZE,
231 .data_size = AFSI_SIZE
234 .storage_type = OSL_MAPPED_STORAGE,
238 .storage_type = OSL_DISK_STORAGE,
243 static struct osl_table_description audio_file_table_desc = {
244 .name = "audio_files",
245 .num_columns = NUM_AFT_COLUMNS,
246 .flags = OSL_LARGE_TABLE,
247 .column_descriptions = aft_cols
250 /* We don't want * dot or dot-dot anywhere. */
251 static int verify_dotfile(const char *rest)
254 * The first character was '.', but that has already been discarded, we
258 case '\0': case '/': /* /foo/. and /foo/./bar are not ok */
260 case '.': /* path start with /foo/.. */
261 if (rest[1] == '\0' || rest[1] == '/')
262 return -1; /* /foo/.. or /foo/../bar are not ok */
263 /* /foo/..bar is ok */
269 * We fundamentally don't like some paths: We don't want double slashes or
270 * slashes at the end that can make pathnames ambiguous.
272 static int verify_path(const char *orig_path, char **resolved_path)
278 if (*orig_path != '/') /* we only accept absolute paths */
280 len = strlen(orig_path);
281 *resolved_path = para_strdup(orig_path);
282 path = *resolved_path;
283 while (len > 1 && path[--len] == '/')
284 path[len] = '\0'; /* remove slash at the end */
290 case '/': /* double slash */
293 if (verify_dotfile(path) < 0)
303 free(*resolved_path);
307 /** The on-disk layout of a afhi struct. */
309 /** Where the number of seconds is stored. */
310 AFHI_SECONDS_TOTAL_OFFSET = 0,
311 /** Position of the bitrate. */
312 AFHI_BITRATE_OFFSET = 4,
313 /** Position of the frequency. */
314 AFHI_FREQUENCY_OFFSET = 8,
315 /** Number of channels is stored here. */
316 AFHI_CHANNELS_OFFSET = 12,
317 /** The tag info position. */
318 AFHI_INFO_STRING_OFFSET = 13,
319 /** Minimal on-disk size of a valid afhi struct. */
323 static unsigned sizeof_afhi_buf(const struct audio_format_info *afhi)
327 return strlen(afhi->info_string) + MIN_AFHI_SIZE;
330 static void save_afhi(struct audio_format_info *afhi, char *buf)
334 write_u32(buf + AFHI_SECONDS_TOTAL_OFFSET,
335 afhi->seconds_total);
336 write_u32(buf + AFHI_BITRATE_OFFSET, afhi->bitrate);
337 write_u32(buf + AFHI_FREQUENCY_OFFSET, afhi->frequency);
338 write_u8(buf + AFHI_CHANNELS_OFFSET, afhi->channels);
339 strcpy(buf + AFHI_INFO_STRING_OFFSET, afhi->info_string); /* OK */
340 PARA_DEBUG_LOG("last byte written: %p\n", buf + AFHI_INFO_STRING_OFFSET + strlen(afhi->info_string));
343 static void load_afhi(const char *buf, struct audio_format_info *afhi)
345 afhi->seconds_total = read_u32(buf + AFHI_SECONDS_TOTAL_OFFSET);
346 afhi->bitrate = read_u32(buf + AFHI_BITRATE_OFFSET);
347 afhi->frequency = read_u32(buf + AFHI_FREQUENCY_OFFSET);
348 afhi->channels = read_u8(buf + AFHI_CHANNELS_OFFSET);
349 strcpy(afhi->info_string, buf + AFHI_INFO_STRING_OFFSET);
352 //#define SIZEOF_CHUNK_TABLE(afhi) (((afhi)->chunks_total + 1) * sizeof(uint32_t))
354 static unsigned sizeof_chunk_info_buf(struct audio_format_info *afhi)
358 return 4 * (afhi->chunks_total + 1) + 20;
362 /** The offsets of the data contained in the AFTCOL_CHUNKS column. */
363 enum chunk_info_offsets{
364 /** The total number of chunks (4 bytes). */
365 CHUNKS_TOTAL_OFFSET = 0,
366 /** The length of the audio file header (4 bytes). */
367 HEADER_LEN_OFFSET = 4,
368 /** The start of the audio file header (4 bytes). */
369 HEADER_OFFSET_OFFSET = 8,
370 /** The seconds part of the chunk time (4 bytes). */
371 CHUNK_TV_TV_SEC_OFFSET = 12,
372 /** The microseconds part of the chunk time (4 bytes). */
373 CHUNK_TV_TV_USEC = 16,
374 /** Chunk table entries start here. */
375 CHUNK_TABLE_OFFSET = 20,
378 static void save_chunk_table(struct audio_format_info *afhi, char *buf)
382 PARA_NOTICE_LOG("%lu chunks\n", afhi->chunks_total);
383 for (i = 0; i <= afhi->chunks_total; i++)
384 write_u32(buf + 4 * i, afhi->chunk_table[i]);
387 static void load_chunk_table(struct audio_format_info *afhi, char *buf)
390 for (i = 0; i <= afhi->chunks_total; i++)
391 afhi->chunk_table[i] = read_u32(buf + 4 * i);
394 /* TODO: audio format handlers could just produce this */
395 static void save_chunk_info(struct audio_format_info *afhi, char *buf)
399 write_u32(buf + CHUNKS_TOTAL_OFFSET, afhi->chunks_total);
400 write_u32(buf + HEADER_LEN_OFFSET, afhi->header_len);
401 write_u32(buf + HEADER_OFFSET_OFFSET, afhi->header_offset);
402 write_u32(buf + CHUNK_TV_TV_SEC_OFFSET, afhi->chunk_tv.tv_sec);
403 write_u32(buf + CHUNK_TV_TV_USEC, afhi->chunk_tv.tv_usec);
404 save_chunk_table(afhi, buf + CHUNK_TABLE_OFFSET);
407 static int load_chunk_info(struct osl_object *obj, struct audio_format_info *afhi)
409 char *buf = obj->data;
411 if (obj->size < CHUNK_TABLE_OFFSET)
412 return -E_BAD_DATA_SIZE;
414 afhi->chunks_total = read_u32(buf + CHUNKS_TOTAL_OFFSET);
415 afhi->header_len = read_u32(buf + HEADER_LEN_OFFSET);
416 afhi->header_offset = read_u32(buf + HEADER_OFFSET_OFFSET);
417 afhi->chunk_tv.tv_sec = read_u32(buf + CHUNK_TV_TV_SEC_OFFSET);
418 afhi->chunk_tv.tv_usec = read_u32(buf + CHUNK_TV_TV_USEC);
420 if ((afhi->chunks_total + 1) * 4 + CHUNK_TABLE_OFFSET > obj->size)
421 return -E_BAD_DATA_SIZE;
422 afhi->chunk_table = para_malloc((afhi->chunks_total + 1) * 4);
423 load_chunk_table(afhi, buf + CHUNK_TABLE_OFFSET);
428 * Get the row of the audio file table corresponding to the given path.
430 * \param path The full path of the audio file.
431 * \param row Result pointer.
433 * \return The return value of the underlying call to osl_get_row().
435 int aft_get_row_of_path(const char *path, struct osl_row **row)
437 struct osl_object obj = {.data = (char *)path, .size = strlen(path) + 1};
439 return osl_get_row(audio_file_table, AFTCOL_PATH, &obj, row);
443 * Get the row of the audio file table corresponding to the given hash value.
445 * \param hash The hash value of the desired audio file.
446 * \param row resul pointer.
448 * \return The return value of the underlying call to osl_get_row().
450 int aft_get_row_of_hash(HASH_TYPE *hash, struct osl_row **row)
452 const struct osl_object obj = {.data = hash, .size = HASH_SIZE};
453 return osl_get_row(audio_file_table, AFTCOL_HASH, &obj, row);
457 * Get the osl object holding the audio file selector info of a row.
459 * \param row Pointer to a row in the audio file table.
460 * \param obj Result pointer.
462 * \return The return value of the underlying call to osl_get_object().
464 int get_afsi_object_of_row(const struct osl_row *row, struct osl_object *obj)
466 return osl_get_object(audio_file_table, row, AFTCOL_AFSI, obj);
470 * Get the osl object holding the audio file selector info, given a path.
473 * \param path The full path of the audio file.
474 * \param obj Result pointer.
476 * \return Positive on success, negative on errors.
478 int get_afsi_object_of_path(const char *path, struct osl_object *obj)
481 int ret = aft_get_row_of_path(path, &row);
484 return get_afsi_object_of_row(row, obj);
488 * Get the audio file selector info, given a row of the audio file table.
490 * \param row Pointer to a row in the audio file table.
491 * \param afsi Result pointer.
493 * \return Positive on success, negative on errors.
495 int get_afsi_of_row(const struct osl_row *row, struct afs_info *afsi)
497 struct osl_object obj;
498 int ret = get_afsi_object_of_row(row, &obj);
501 return load_afsi(afsi, &obj);
505 * Get the audio file selector info, given the path of an audio table.
507 * \param path The full path of the audio file.
508 * \param afsi Result pointer.
510 * \return Positive on success, negative on errors.
512 int get_afsi_of_path(const char *path, struct afs_info *afsi)
514 struct osl_object obj;
515 int ret = get_afsi_object_of_path(path, &obj);
518 return load_afsi(afsi, &obj);
522 * Get the path of an audio file, given a row of the audio file table.
524 * \param row Pointer to a row in the audio file table.
525 * \param path Result pointer.
527 * \return Positive on success, negative on errors.
529 int get_audio_file_path_of_row(const struct osl_row *row, char **path)
531 struct osl_object path_obj;
532 int ret = osl_get_object(audio_file_table, row, AFTCOL_PATH,
536 *path = path_obj.data;
541 * Get the object containing the hash value of an audio file, given a row.
543 * \param row Pointer to a row of the audio file table.
544 * \param obj Result pointer.
546 * \return The return value of the underlying call to osl_get_object().
548 * \sa get_hash_of_row().
550 static int get_hash_object_of_aft_row(const struct osl_row *row, struct osl_object *obj)
552 return osl_get_object(audio_file_table, row, AFTCOL_HASH, obj);
556 * Get the hash value of an audio file, given a row of the audio file table.
558 * \param row Pointer to a row of the audio file table.
559 * \param hash Result pointer.
561 * \a hash points to mapped data and must not be freed by the caller.
563 * \return The return value of the underlying call to
564 * get_hash_object_of_aft_row().
566 static int get_hash_of_row(const struct osl_row *row, HASH_TYPE **hash)
568 struct osl_object obj;
569 int ret = get_hash_object_of_aft_row(row, &obj);
578 * Get the audio format handler info, given a row of the audio file table.
580 * \param row Pointer to a row of the audio file table.
581 * \param afhi Result pointer.
583 * \return The return value of the underlying call to osl_get_object().
585 * \sa get_chunk_table_of_row().
587 int get_afhi_of_row(const struct osl_row *row, struct audio_format_info *afhi)
589 struct osl_object obj;
590 int ret = osl_get_object(audio_file_table, row, AFTCOL_AFHI,
594 load_afhi(obj.data, afhi);
598 /* returns shmid on success */
599 static int save_afd(struct audio_file_data *afd)
601 size_t path_size = strlen(afd->path) + 1;
602 size_t size = sizeof(*afd) + path_size
603 + 4 * (afd->afhi.chunks_total + 1);
605 PARA_NOTICE_LOG("size: %zu\n", size);
606 int shmid, ret = shm_new(size);
613 ret = shm_attach(shmid, ATTACH_RW, &shm_afd);
616 *(struct audio_file_data *)shm_afd = *afd;
619 strcpy(buf, afd->path);
621 save_chunk_table(&afd->afhi, buf);
629 int load_afd(int shmid, struct audio_file_data *afd)
635 ret = shm_attach(shmid, ATTACH_RO, &shm_afd);
638 *afd = *(struct audio_file_data *)shm_afd;
641 afd->path = para_strdup(buf);
642 buf += strlen(buf) + 1;
643 afd->afhi.chunk_table = para_malloc((afd->afhi.chunks_total + 1) * 4);
644 load_chunk_table(&afd->afhi, buf);
650 * Mmap the given audio file and update statistics.
652 * \param aft_row Determines the audio file to be opened and updated.
653 * \param afd Result pointer.
655 * On success, the numplayed field of the audio file selector info is increased
656 * and the lastplayed time is set to the current time. Finally, the score of
657 * the audio file is updated.
659 * \return Positive on success, negative on errors.
661 int open_and_update_audio_file(struct osl_row *aft_row, struct audio_file_data *afd)
663 HASH_TYPE *aft_hash, file_hash[HASH_SIZE];
664 struct osl_object afsi_obj;
665 struct afs_info new_afsi;
666 int ret = get_hash_of_row(aft_row, &aft_hash);
667 struct afsi_change_event_data aced;
668 struct osl_object map, chunk_table_obj;
672 ret = get_audio_file_path_of_row(aft_row, &afd->path);
675 ret = get_afsi_object_of_row(aft_row, &afsi_obj);
678 ret = load_afsi(&afd->afsi, &afsi_obj);
681 ret = get_afhi_of_row(aft_row, &afd->afhi);
684 ret = osl_open_disk_object(audio_file_table, aft_row,
685 AFTCOL_CHUNKS, &chunk_table_obj);
688 ret = mmap_full_file(afd->path, O_RDONLY, &map.data,
689 &map.size, &afd->fd);
692 hash_function(map.data, map.size, file_hash);
693 ret = hash_compare(file_hash, aft_hash);
694 para_munmap(map.data, map.size);
696 ret = -E_HASH_MISMATCH;
699 new_afsi = afd->afsi;
700 new_afsi.num_played++;
701 new_afsi.last_played = time(NULL);
702 save_afsi(&new_afsi, &afsi_obj); /* in-place update */
704 ret = load_chunk_info(&chunk_table_obj, &afd->afhi);
708 aced.aft_row = aft_row;
709 aced.old_afsi = &afd->afsi;
710 afs_event(AFSI_CHANGE, NULL, &aced);
714 free(afd->afhi.chunk_table);
716 osl_close_disk_object(&chunk_table_obj);
720 static int get_local_time(uint64_t *seconds, char *buf, size_t size,
721 time_t current_time, enum ls_listing_mode lm)
725 if (!localtime_r((time_t *)seconds, &t))
727 if (lm == LS_MODE_MBOX) {
728 if (!strftime(buf, size, "%c", &t))
732 if (*seconds + 6 * 30 * 24 * 3600 > current_time) {
733 if (!strftime(buf, size, "%b %e %k:%M", &t))
737 if (!strftime(buf, size, "%b %e %Y", &t))
742 /** Compute the number of (decimal) digits of a number. */
743 #define GET_NUM_DIGITS(x, num) { \
744 typeof((x)) _tmp = PARA_ABS(x); \
747 while ((_tmp) > 9) { \
753 static short unsigned get_duration_width(int seconds)
755 short unsigned width;
756 unsigned hours = seconds / 3600, mins = (seconds % 3600) / 60;
758 if (!hours) /* less than one hour => m:ss or mm:ss => 4 or 5 digits */
759 return 4 + (mins > 9);
760 /* more than one hour => h:mm:ss, hh:mm:ss, hhh:mm:ss, ... */
761 GET_NUM_DIGITS(hours, &width);
765 static void get_duration_buf(int seconds, char *buf, short unsigned max_width)
767 unsigned hours = seconds / 3600, mins = (seconds % 3600) / 60;
769 if (!hours) /* m:ss or mm:ss */
770 sprintf(buf, "%*u:%02u", max_width - 3, mins, seconds % 60);
771 else /* more than one hour => h:mm:ss, hh:mm:ss, hhh:mm:ss, ... */
772 sprintf(buf, "%*u:%02u:%02u", max_width - 6, hours, mins,
776 static char *make_attribute_line(const char *att_bitmap, struct afs_info *afsi)
778 char *att_text, *att_line;
780 get_attribute_text(&afsi->attributes, " ", &att_text);
782 return para_strdup(att_bitmap);
783 att_line = make_message("%s (%s)", att_bitmap, att_text);
788 static char *make_lyrics_line(struct afs_info *afsi)
792 lyr_get_name_by_id(afsi->lyrics_id, &lyrics_name);
794 return make_message("%u", afsi->lyrics_id);
795 return make_message("%u (%s)", afsi->lyrics_id, lyrics_name);
798 static char *make_image_line(struct afs_info *afsi)
801 img_get_name_by_id(afsi->image_id, &image_name);
803 return make_message("%u", afsi->image_id);
804 return make_message("%u (%s)", afsi->image_id, image_name);
807 static int print_list_item(struct ls_data *d, struct ls_options *opts,
808 struct para_buffer *b, time_t current_time)
812 char last_played_time[30];
813 char duration_buf[30]; /* nobody has an audio file long enough to overflow this */
814 char score_buf[30] = "";
815 struct afs_info *afsi = &d->afsi;
816 struct audio_format_info *afhi = &d->afhi;
817 struct ls_widths *w = &opts->widths;
818 int have_score = opts->flags & LS_FLAG_ADMISSIBLE_ONLY;
819 char asc_hash[2 * HASH_SIZE + 1];
820 char *att_line, *lyrics_line, *image_line;
822 if (opts->mode == LS_MODE_SHORT) {
823 para_printf(b, "%s\n", d->path);
826 get_attribute_bitmap(&afsi->attributes, att_buf);
827 ret = get_local_time(&afsi->last_played, last_played_time,
828 sizeof(last_played_time), current_time, opts->mode);
831 get_duration_buf(afhi->seconds_total, duration_buf, w->duration_width);
833 if (opts->mode == LS_MODE_LONG)
834 sprintf(score_buf, "%*li ", w->score_width, d->score);
836 sprintf(score_buf, "%li ", d->score);
839 if (opts->mode == LS_MODE_LONG) {
842 "%s " /* attributes */
843 "%*d " /* image_id */
844 "%*d " /* lyrics_id */
846 "%s " /* audio format */
847 "%*d " /* frequency */
850 "%*d " /* num_played */
851 "%s " /* last_played */
855 w->image_id_width, afsi->image_id,
856 w->lyrics_id_width, afsi->lyrics_id,
857 w->bitrate_width, afhi->bitrate,
858 audio_format_name(afsi->audio_format_id),
859 w->frequency_width, afhi->frequency,
862 w->num_played_width, afsi->num_played,
868 hash_to_asc(d->hash, asc_hash);
869 att_line = make_attribute_line(att_buf, afsi);
870 lyrics_line = make_lyrics_line(afsi);
871 image_line = make_image_line(afsi);
872 if (opts->mode == LS_MODE_VERBOSE) {
875 "%s: %s\n" /* path */
881 "bitrate: %dkbit/s\n"
889 (opts->flags & LS_FLAG_FULL_PATH)?
890 "path" : "file", d->path,
891 have_score? "score: " : "", score_buf,
892 have_score? "\n" : "",
898 audio_format_name(afsi->audio_format_id),
906 } else { /* mbox mode */
907 struct osl_object lyrics_def;
908 lyr_get_def_by_id(afsi->lyrics_id, &lyrics_def);
910 "From foo@localhost %s\n"
911 "Received: from\nTo: bar\nFrom: a\n"
912 "Subject: %s\n\n" /* path */
918 "bitrate: %dkbit/s\n"
928 have_score? "score: " : "", score_buf,
929 have_score? "\n" : "",
935 audio_format_name(afsi->audio_format_id),
941 lyrics_def.data? "Lyrics:\n~~~~~~~\n" : "",
942 lyrics_def.data? (char *)lyrics_def.data : ""
945 osl_close_disk_object(lyrics_def.data);
953 static int ls_audio_format_compare(const void *a, const void *b)
955 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
956 return NUM_COMPARE(d1->afsi.audio_format_id, d2->afsi.audio_format_id);
959 static int ls_duration_compare(const void *a, const void *b)
961 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
962 return NUM_COMPARE(d1->afhi.seconds_total, d2->afhi.seconds_total);
965 static int ls_bitrate_compare(const void *a, const void *b)
967 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
968 return NUM_COMPARE(d1->afhi.bitrate, d2->afhi.bitrate);
971 static int ls_lyrics_id_compare(const void *a, const void *b)
973 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
974 return NUM_COMPARE(d1->afsi.lyrics_id, d2->afsi.lyrics_id);
977 static int ls_image_id_compare(const void *a, const void *b)
979 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
980 return NUM_COMPARE(d1->afsi.image_id, d2->afsi.image_id);
983 static int ls_channels_compare(const void *a, const void *b)
985 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
986 return NUM_COMPARE(d1->afhi.channels, d2->afhi.channels);
989 static int ls_frequency_compare(const void *a, const void *b)
991 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
992 return NUM_COMPARE(d1->afhi.frequency, d2->afhi.frequency);
995 static int ls_num_played_compare(const void *a, const void *b)
997 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
998 return NUM_COMPARE(d1->afsi.num_played, d2->afsi.num_played);
1001 static int ls_last_played_compare(const void *a, const void *b)
1003 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1004 return NUM_COMPARE(d1->afsi.last_played, d2->afsi.last_played);
1007 static int ls_score_compare(const void *a, const void *b)
1009 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1010 return NUM_COMPARE(d1->score, d2->score);
1013 static int ls_path_compare(const void *a, const void *b)
1015 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1016 return strcmp(d1->path, d2->path);
1019 static int sort_matching_paths(struct ls_options *options)
1021 size_t nmemb = options->num_matching_paths;
1022 size_t size = sizeof(*options->data_ptr);
1023 int (*compar)(const void *, const void *);
1026 options->data_ptr = para_malloc(nmemb * sizeof(*options->data_ptr));
1027 for (i = 0; i < nmemb; i++)
1028 options->data_ptr[i] = options->data + i;
1030 /* In these cases the array is already sorted */
1031 if (options->sorting == LS_SORT_BY_PATH
1032 && !(options->flags & LS_FLAG_ADMISSIBLE_ONLY)
1033 && (options->flags & LS_FLAG_FULL_PATH))
1035 if (options->sorting == LS_SORT_BY_SCORE &&
1036 options->flags & LS_FLAG_ADMISSIBLE_ONLY)
1039 switch (options->sorting) {
1040 case LS_SORT_BY_PATH:
1041 compar = ls_path_compare; break;
1042 case LS_SORT_BY_SCORE:
1043 compar = ls_score_compare; break;
1044 case LS_SORT_BY_LAST_PLAYED:
1045 compar = ls_last_played_compare; break;
1046 case LS_SORT_BY_NUM_PLAYED:
1047 compar = ls_num_played_compare; break;
1048 case LS_SORT_BY_FREQUENCY:
1049 compar = ls_frequency_compare; break;
1050 case LS_SORT_BY_CHANNELS:
1051 compar = ls_channels_compare; break;
1052 case LS_SORT_BY_IMAGE_ID:
1053 compar = ls_image_id_compare; break;
1054 case LS_SORT_BY_LYRICS_ID:
1055 compar = ls_lyrics_id_compare; break;
1056 case LS_SORT_BY_BITRATE:
1057 compar = ls_bitrate_compare; break;
1058 case LS_SORT_BY_DURATION:
1059 compar = ls_duration_compare; break;
1060 case LS_SORT_BY_AUDIO_FORMAT:
1061 compar = ls_audio_format_compare; break;
1065 qsort(options->data_ptr, nmemb, size, compar);
1069 /* row is either an aft_row or a row of the score table */
1070 /* TODO: Only compute widths if we need them */
1071 static int prepare_ls_row(struct osl_row *row, void *ls_opts)
1074 struct ls_options *options = ls_opts;
1076 struct ls_widths *w;
1077 unsigned short num_digits;
1079 struct osl_row *aft_row;
1083 if (options->flags & LS_FLAG_ADMISSIBLE_ONLY) {
1084 ret = get_score_and_aft_row(row, &score, &aft_row);
1089 ret = get_audio_file_path_of_row(aft_row, &path);
1092 if (!(options->flags & LS_FLAG_FULL_PATH)) {
1093 char *p = strrchr(path, '/');
1097 if (options->num_patterns) {
1098 for (i = 0; i < options->num_patterns; i++) {
1099 ret = fnmatch(options->patterns[i], path, 0);
1102 if (ret == FNM_NOMATCH)
1106 if (i >= options->num_patterns) /* no match */
1109 tmp = options->num_matching_paths++;
1110 if (options->num_matching_paths > options->array_size) {
1111 options->array_size++;
1112 options->array_size *= 2;
1113 options->data = para_realloc(options->data, options->array_size
1114 * sizeof(*options->data));
1116 d = options->data + tmp;
1117 ret = get_afsi_of_row(aft_row, &d->afsi);
1120 ret = get_afhi_of_row(aft_row, &d->afhi);
1124 ret = get_hash_of_row(aft_row, &d->hash);
1127 w = &options->widths;
1128 GET_NUM_DIGITS(d->afsi.image_id, &num_digits);
1129 w->image_id_width = PARA_MAX(w->image_id_width, num_digits);
1130 GET_NUM_DIGITS(d->afsi.lyrics_id, &num_digits);
1131 w->lyrics_id_width = PARA_MAX(w->lyrics_id_width, num_digits);
1132 GET_NUM_DIGITS(d->afhi.bitrate, &num_digits);
1133 w->bitrate_width = PARA_MAX(w->bitrate_width, num_digits);
1134 GET_NUM_DIGITS(d->afhi.frequency, &num_digits);
1135 w->frequency_width = PARA_MAX(w->frequency_width, num_digits);
1136 GET_NUM_DIGITS(d->afsi.num_played, &num_digits);
1137 w->num_played_width = PARA_MAX(w->num_played_width, num_digits);
1138 /* get the number of chars to print this amount of time */
1139 tmp = get_duration_width(d->afhi.seconds_total);
1140 w->duration_width = PARA_MAX(w->duration_width, tmp);
1141 if (options->flags & LS_FLAG_ADMISSIBLE_ONLY) {
1142 GET_NUM_DIGITS(score, &num_digits);
1143 num_digits++; /* add one for the sign (space or "-") */
1144 w->score_width = PARA_MAX(w->score_width, num_digits);
1150 static int com_ls_callback(const struct osl_object *query,
1151 struct osl_object *ls_output)
1153 struct ls_options *opts = query->data;
1154 char *p, *pattern_start = (char *)query->data + sizeof(*opts);
1155 struct para_buffer b = {.buf = NULL, .size = 0};
1157 time_t current_time;
1160 if (opts->num_patterns) {
1161 opts->patterns = para_malloc(opts->num_patterns * sizeof(char *));
1162 for (i = 0, p = pattern_start; i < opts->num_patterns; i++) {
1163 opts->patterns[i] = p;
1167 opts->patterns = NULL;
1168 if (opts->flags & LS_FLAG_ADMISSIBLE_ONLY)
1169 ret = admissible_file_loop(opts, prepare_ls_row);
1171 ret = osl_rbtree_loop(audio_file_table, AFTCOL_PATH, opts,
1175 ret = opts->num_patterns? -E_NO_MATCH : 0;
1176 if (!opts->num_matching_paths)
1178 ret = sort_matching_paths(opts);
1181 time(¤t_time);
1182 if (opts->flags & LS_FLAG_REVERSE)
1183 for (i = opts->num_matching_paths - 1; i >= 0; i--) {
1184 ret = print_list_item(opts->data_ptr[i], opts, &b, current_time);
1189 for (i = 0; i < opts->num_matching_paths; i++) {
1190 ret = print_list_item(opts->data_ptr[i], opts, &b, current_time);
1196 ls_output->data = b.buf;
1197 ls_output->size = b.size;
1199 free(opts->data_ptr);
1200 free(opts->patterns);
1205 * TODO: flags -h (sort by hash) -lm (list in mbox format)
1207 * long list: list hash, attributes as (xx--x-x-), file size, lastplayed
1208 * full list: list everything, including afsi, afhi, atts as clear text
1211 int com_ls(int fd, int argc, char * const * const argv)
1215 enum ls_sorting_method sort = LS_SORT_BY_PATH;
1216 enum ls_listing_mode mode = LS_MODE_SHORT;
1217 struct ls_options opts = {.patterns = NULL};
1218 struct osl_object query = {.data = &opts, .size = sizeof(opts)},
1221 for (i = 1; i < argc; i++) {
1222 const char *arg = argv[i];
1225 if (!strcmp(arg, "--")) {
1229 if (!strncmp(arg, "-l", 2)) {
1231 mode = LS_MODE_LONG;
1235 return -E_AFT_SYNTAX;
1236 switch(*(arg + 2)) {
1238 mode = LS_MODE_SHORT;
1241 mode = LS_MODE_LONG;
1244 mode = LS_MODE_VERBOSE;
1247 mode = LS_MODE_MBOX;
1250 return -E_AFT_SYNTAX;
1253 if (!strcmp(arg, "-p")) {
1254 flags |= LS_FLAG_FULL_PATH;
1257 if (!strcmp(arg, "-a")) {
1258 flags |= LS_FLAG_ADMISSIBLE_ONLY;
1261 if (!strcmp(arg, "-r")) {
1262 flags |= LS_FLAG_REVERSE;
1265 if (!strncmp(arg, "-s", 2)) {
1266 if (!*(arg + 2) || *(arg + 3))
1267 return -E_AFT_SYNTAX;
1268 switch(*(arg + 2)) {
1270 sort = LS_SORT_BY_PATH;
1272 case 's': /* -ss implies -a */
1273 sort = LS_SORT_BY_SCORE;
1274 flags |= LS_FLAG_ADMISSIBLE_ONLY;
1277 sort = LS_SORT_BY_LAST_PLAYED;
1280 sort = LS_SORT_BY_NUM_PLAYED;
1283 sort = LS_SORT_BY_FREQUENCY;
1286 sort = LS_SORT_BY_CHANNELS;
1289 sort = LS_SORT_BY_IMAGE_ID;
1292 sort = LS_SORT_BY_LYRICS_ID;
1295 sort = LS_SORT_BY_BITRATE;
1298 sort = LS_SORT_BY_DURATION;
1301 sort = LS_SORT_BY_AUDIO_FORMAT;
1304 return -E_AFT_SYNTAX;
1307 return -E_AFT_SYNTAX;
1310 opts.sorting = sort;
1312 opts.num_patterns = argc - i;
1313 ret = send_option_arg_callback_request(&query, opts.num_patterns,
1314 argv + i, com_ls_callback, &ls_output);
1316 ret = send_buffer(fd, (char *)ls_output.data);
1317 free(ls_output.data);
1323 * Call the given function for each file in the audio file table.
1325 * \param private_data An arbitrary data pointer, passed to \a func.
1326 * \param func The custom function to be called.
1328 * \return The return value of the underlying call to osl_rbtree_loop().
1330 int audio_file_loop(void *private_data, osl_rbtree_loop_func *func)
1332 return osl_rbtree_loop(audio_file_table, AFTCOL_HASH, private_data,
1336 static struct osl_row *find_hash_sister(HASH_TYPE *hash)
1338 const struct osl_object obj = {.data = hash, .size = HASH_SIZE};
1339 struct osl_row *row;
1341 osl_get_row(audio_file_table, AFTCOL_HASH, &obj, &row);
1345 enum aft_row_offsets {
1346 AFTROW_AFHI_OFFSET_POS = 0,
1347 AFTROW_CHUNKS_OFFSET_POS = 2,
1348 AFTROW_AUDIO_FORMAT_OFFSET = 4,
1349 AFTROW_FLAGS_OFFSET = 5,
1350 AFTROW_HASH_OFFSET = 9,
1351 AFTROW_PATH_OFFSET = (AFTROW_HASH_OFFSET + HASH_SIZE),
1354 /* never save the afsi, as the server knows it too. Note that afhi might be NULL.
1355 * In this case, afhi won't be stored in the buffer */
1356 static void save_audio_file_info(HASH_TYPE *hash, const char *path,
1357 struct audio_format_info *afhi, uint32_t flags,
1358 uint8_t audio_format_num, struct osl_object *obj)
1360 size_t path_len = strlen(path) + 1;
1361 size_t afhi_size = sizeof_afhi_buf(afhi);
1362 size_t size = AFTROW_PATH_OFFSET + path_len + afhi_size
1363 + sizeof_chunk_info_buf(afhi);
1364 char *buf = para_malloc(size);
1367 write_u8(buf + AFTROW_AUDIO_FORMAT_OFFSET, audio_format_num);
1368 write_u32(buf + AFTROW_FLAGS_OFFSET, flags);
1370 memcpy(buf + AFTROW_HASH_OFFSET, hash, HASH_SIZE);
1371 strcpy(buf + AFTROW_PATH_OFFSET, path);
1373 pos = AFTROW_PATH_OFFSET + path_len;
1374 PARA_DEBUG_LOG("size: %zu, afhi starts at %d\n", size, pos);
1375 PARA_DEBUG_LOG("last afhi byte: %p, pos %zu\n", buf + pos + afhi_size - 1,
1376 pos + afhi_size - 1);
1377 write_u16(buf + AFTROW_AFHI_OFFSET_POS, pos);
1378 save_afhi(afhi, buf + pos);
1381 PARA_DEBUG_LOG("size: %zu, chunks start at %d\n", size, pos);
1382 write_u16(buf + AFTROW_CHUNKS_OFFSET_POS, pos);
1383 save_chunk_info(afhi, buf + pos);
1384 PARA_DEBUG_LOG("last byte in buf: %p\n", buf + size - 1);
1398 AFHI: whether afhi and chunk table are computed and sent
1399 ACTION: table modifications to be performed
1401 +---+----+-----+------+---------------------------------------------------+
1402 | HS | PB | F | AFHI | ACTION
1403 +---+----+-----+------+---------------------------------------------------+
1404 | Y | Y | Y | Y | if HS != PB: remove PB. HS: force afhi update,
1405 | | update path, keep afsi
1406 +---+----+-----+------+---------------------------------------------------+
1407 | Y | Y | N | N | if HS == PB: do not send callback request at all.
1408 | | otherwise: remove PB, HS: update path, keep afhi,
1410 +---+----+-----+------+---------------------------------------------------+
1411 | Y | N | Y | Y | (rename) force afhi update of HS, update path of
1413 +---+----+-----+------+---------------------------------------------------+
1414 | Y | N | N | N | (file rename) update path of HS, keep afsi, afhi
1415 +---+----+-----+------+---------------------------------------------------+
1416 | N | Y | Y | Y | (file change) update afhi, hash, of PB, keep afsi
1417 | | (force has no effect)
1418 +---+----+-----+------+---------------------------------------------------+
1419 | N | Y | N | Y | (file change) update afhi, hash of PB, keep afsi
1420 +---+----+-----+------+---------------------------------------------------+
1421 | N | N | Y | Y | (new file) create new entry (force has no effect)
1422 +---+----+-----+------+---------------------------------------------------+
1423 | N | N | N | Y | (new file) create new entry
1424 +---+----+-----+------+---------------------------------------------------+
1426 afhi <=> force or no HS
1430 /** Flags passed to the add command. */
1431 enum com_add_flags {
1432 /** Skip paths that exist already. */
1434 /** Force adding. */
1436 /** Print what is being done. */
1437 ADD_FLAG_VERBOSE = 4,
1438 /** Try to add files with unknown suffixes. */
1442 static int com_add_callback(const struct osl_object *query,
1443 struct osl_object *result)
1445 char *buf = query->data, *path;
1446 struct osl_row *pb, *aft_row;
1448 struct osl_object objs[NUM_AFT_COLUMNS];
1450 char asc[2 * HASH_SIZE + 1];
1452 char afsi_buf[AFSI_SIZE];
1453 uint32_t flags = read_u32(buf + AFTROW_FLAGS_OFFSET);
1454 struct afs_info default_afsi = {.last_played = 0};
1455 struct para_buffer msg = {.buf = NULL};
1457 hash = (HASH_TYPE *)buf + AFTROW_HASH_OFFSET;
1458 hash_to_asc(hash, asc);;
1459 objs[AFTCOL_HASH].data = buf + AFTROW_HASH_OFFSET;
1460 objs[AFTCOL_HASH].size = HASH_SIZE;
1462 path = buf + AFTROW_PATH_OFFSET;
1463 objs[AFTCOL_PATH].data = path;
1464 objs[AFTCOL_PATH].size = strlen(path) + 1;
1466 PARA_INFO_LOG("request to add %s\n", path);
1467 hs = find_hash_sister(hash);
1468 ret = aft_get_row_of_path(path, &pb);
1469 if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
1471 if (hs && pb && hs == pb && !(flags & ADD_FLAG_FORCE)) {
1472 if (flags & ADD_FLAG_VERBOSE)
1473 para_printf(&msg, "ignoring duplicate\n");
1477 if (hs && hs != pb) {
1478 struct osl_object obj;
1479 if (pb) { /* hs trumps pb, remove pb */
1480 if (flags & ADD_FLAG_VERBOSE)
1481 para_printf(&msg, "removing path brother\n");
1482 ret = osl_del_row(audio_file_table, pb);
1487 /* file rename, update hs' path */
1488 if (flags & ADD_FLAG_VERBOSE) {
1489 ret = osl_get_object(audio_file_table, hs,
1493 para_printf(&msg, "renamed from %s\n", (char *)obj.data);
1495 ret = osl_update_object(audio_file_table, hs, AFTCOL_PATH,
1496 &objs[AFTCOL_PATH]);
1499 afs_event(AUDIO_FILE_RENAME, &msg, hs);
1500 if (!(flags & ADD_FLAG_FORCE))
1503 /* no hs or force mode, child must have sent afhi */
1504 uint16_t afhi_offset = read_u16(buf + AFTROW_AFHI_OFFSET_POS);
1505 uint16_t chunks_offset = read_u16(buf + AFTROW_CHUNKS_OFFSET_POS);
1507 objs[AFTCOL_AFHI].data = buf + afhi_offset;
1508 objs[AFTCOL_AFHI].size = chunks_offset - afhi_offset;
1510 if (!objs[AFTCOL_AFHI].size) /* "impossible" */
1512 objs[AFTCOL_CHUNKS].data = buf + chunks_offset;
1513 objs[AFTCOL_CHUNKS].size = query->size - chunks_offset;
1514 if (pb && !hs) { /* update pb's hash */
1515 char old_asc[2 * HASH_SIZE + 1];
1516 HASH_TYPE *old_hash;
1517 ret = get_hash_of_row(pb, &old_hash);
1520 hash_to_asc(old_hash, old_asc);
1521 if (flags & ADD_FLAG_VERBOSE)
1522 para_printf(&msg, "file change: %s -> %s\n",
1524 ret = osl_update_object(audio_file_table, pb, AFTCOL_HASH,
1525 &objs[AFTCOL_HASH]);
1529 if (hs || pb) { /* (hs != NULL and pb != NULL) implies hs == pb */
1530 struct osl_row *row = pb? pb : hs;
1531 /* update afhi and chunk_table */
1532 if (flags & ADD_FLAG_VERBOSE)
1533 para_printf(&msg, "updating afhi and chunk table\n");
1534 ret = osl_update_object(audio_file_table, row, AFTCOL_AFHI,
1535 &objs[AFTCOL_AFHI]);
1538 ret = osl_update_object(audio_file_table, row, AFTCOL_CHUNKS,
1539 &objs[AFTCOL_CHUNKS]);
1542 afs_event(AFHI_CHANGE, &msg, row);
1545 /* new entry, use default afsi */
1546 if (flags & ADD_FLAG_VERBOSE)
1547 para_printf(&msg, "new file\n");
1548 default_afsi.last_played = time(NULL) - 365 * 24 * 60 * 60;
1549 default_afsi.audio_format_id = read_u8(buf + AFTROW_AUDIO_FORMAT_OFFSET);
1551 objs[AFTCOL_AFSI].data = &afsi_buf;
1552 objs[AFTCOL_AFSI].size = AFSI_SIZE;
1553 save_afsi(&default_afsi, &objs[AFTCOL_AFSI]);
1554 ret = osl_add_and_get_row(audio_file_table, objs, &aft_row);
1557 para_printf(&msg, "%s\n", PARA_STRERROR(-ret));
1560 result->data = msg.buf;
1561 result->size = msg.size;
1562 afs_event(AUDIO_FILE_ADD, &msg, aft_row);
1566 struct private_add_data {
1571 static int path_brother_callback(const struct osl_object *query,
1572 struct osl_object *result)
1574 char *path = query->data;
1575 struct osl_row *path_brother;
1576 int ret = aft_get_row_of_path(path, &path_brother);
1579 result->data = para_malloc(sizeof(path_brother));
1580 result->size = sizeof(path_brother);
1581 *(struct osl_row **)(result->data) = path_brother;
1585 static int hash_sister_callback(const struct osl_object *query,
1586 struct osl_object *result)
1588 HASH_TYPE *hash = query->data;
1589 struct osl_row *hash_sister;
1591 hash_sister = find_hash_sister(hash);
1593 return -E_RB_KEY_NOT_FOUND;
1594 result->data = para_malloc(sizeof(hash_sister));
1595 result->size = sizeof(hash_sister);
1596 *(struct osl_row **)(result->data) = hash_sister;
1600 static int add_one_audio_file(const char *path, const void *private_data)
1603 uint8_t format_num = -1;
1604 const struct private_add_data *pad = private_data;
1605 struct audio_format_info afhi, *afhi_ptr = NULL;
1606 struct osl_row *pb = NULL, *hs = NULL; /* path brother/hash sister */
1607 struct osl_object map, obj = {.data = NULL}, query, result = {.data = NULL};
1608 HASH_TYPE hash[HASH_SIZE];
1610 afhi.header_offset = 0;
1611 afhi.header_len = 0;
1612 ret = guess_audio_format(path);
1613 if (ret < 0 && !(pad->flags & ADD_FLAG_ALL))
1615 query.data = (char *)path;
1616 query.size = strlen(path) + 1;
1617 ret = send_callback_request(path_brother_callback, &query, &result);
1618 if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
1621 pb = *(struct osl_row **)result.data;
1625 if (pb && (pad->flags & ADD_FLAG_LAZY)) { /* lazy is really cheap */
1626 if (pad->flags & ADD_FLAG_VERBOSE)
1627 ret = send_va_buffer(pad->fd, "lazy-ignore: %s\n", path);
1630 /* We still want to add this file. Compute its hash. */
1631 ret = mmap_full_file(path, O_RDONLY, &map.data, &map.size, NULL);
1634 hash_function(map.data, map.size, hash);
1636 /* Check whether database contains file with the same hash. */
1638 query.size = HASH_SIZE;
1639 ret = send_callback_request(hash_sister_callback, &query, &result);
1640 if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
1643 hs = *(struct osl_row **)result.data;
1646 /* Return success if we already know this file. */
1648 if (pb && hs && hs == pb && (!(pad->flags & ADD_FLAG_FORCE))) {
1649 if (pad->flags & ADD_FLAG_VERBOSE)
1650 ret = send_va_buffer(pad->fd,
1651 "%s exists, not forcing update\n", path);
1655 * we won't recalculate the audio format info and the chunk table if
1656 * there is a hash sister unless in FORCE mode.
1658 if (!hs || (pad->flags & ADD_FLAG_FORCE)) {
1659 ret = compute_afhi(path, map.data, map.size, &afhi);
1665 if (pad->flags & ADD_FLAG_VERBOSE) {
1666 ret = send_va_buffer(pad->fd, "adding %s\n", path);
1670 munmap(map.data, map.size);
1671 save_audio_file_info(hash, path, afhi_ptr, pad->flags, format_num, &obj);
1672 /* Ask afs to consider this entry for adding. */
1673 ret = send_callback_request(com_add_callback, &obj, &result);
1674 if (ret >= 0 && result.data && result.size) {
1675 ret2 = send_va_buffer(pad->fd, "%s", (char *)result.data);
1677 if (ret >= 0 && ret2 < 0)
1683 munmap(map.data, map.size);
1685 if (ret < 0 && ret != -E_SEND)
1686 send_va_buffer(pad->fd, "failed to add %s (%s)\n", path,
1687 PARA_STRERROR(-ret));
1690 free(afhi_ptr->chunk_table);
1691 /* it's not an error if not all files could be added */
1692 return ret == -E_SEND? ret : 1;
1695 int com_add(int fd, int argc, char * const * const argv)
1698 struct private_add_data pad = {.fd = fd, .flags = 0};
1699 struct stat statbuf;
1701 for (i = 1; i < argc; i++) {
1702 const char *arg = argv[i];
1705 if (!strcmp(arg, "--")) {
1709 if (!strcmp(arg, "-a")) {
1710 pad.flags |= ADD_FLAG_ALL;
1713 if (!strcmp(arg, "-l")) {
1714 pad.flags |= ADD_FLAG_LAZY;
1717 if (!strcmp(arg, "-f")) {
1718 pad.flags |= ADD_FLAG_FORCE;
1721 if (!strcmp(arg, "-v")) {
1722 pad.flags |= ADD_FLAG_VERBOSE;
1727 return -E_AFT_SYNTAX;
1728 for (; i < argc; i++) {
1730 ret = verify_path(argv[i], &path);
1732 ret = send_va_buffer(fd, "%s: %s\n", argv[i], PARA_STRERROR(-ret));
1737 ret = stat(path, &statbuf);
1739 ret = send_va_buffer(fd, "failed to stat %s (%s)\n", path,
1746 if (S_ISDIR(statbuf.st_mode))
1747 ret = for_each_file_in_dir(path, add_one_audio_file,
1750 ret = add_one_audio_file(path, &pad);
1752 send_va_buffer(fd, "%s: %s\n", path, PARA_STRERROR(-ret));
1763 * Flags used by the touch command.
1768 /** Whether the \p FNM_PATHNAME flag should be passed to fnmatch(). */
1769 TOUCH_FLAG_FNM_PATHNAME = 1,
1770 /** Activates verbose mode. */
1771 TOUCH_FLAG_VERBOSE = 2
1774 struct com_touch_options {
1776 int64_t last_played;
1782 struct touch_action_data {
1783 struct com_touch_options *cto;
1784 struct para_buffer pb;
1787 static int touch_audio_file(__a_unused struct osl_table *table,
1788 struct osl_row *row, const char *name, void *data)
1790 struct touch_action_data *tad = data;
1791 struct osl_object obj;
1792 struct afs_info old_afsi, new_afsi;
1793 int ret, no_options = tad->cto->num_played < 0 && tad->cto->last_played < 0 &&
1794 tad->cto->lyrics_id < 0 && tad->cto->image_id < 0;
1795 struct afsi_change_event_data aced;
1797 ret = get_afsi_object_of_row(row, &obj);
1799 para_printf(&tad->pb, "%s: %s\n", name, PARA_STRERROR(-ret));
1802 ret = load_afsi(&old_afsi, &obj);
1804 para_printf(&tad->pb, "%s: %s\n", name, PARA_STRERROR(-ret));
1807 new_afsi = old_afsi;
1809 new_afsi.num_played++;
1810 new_afsi.last_played = time(NULL);
1811 if (tad->cto->flags & TOUCH_FLAG_VERBOSE)
1812 para_printf(&tad->pb, "%s: num_played = %u, "
1813 "last_played = now()\n", name,
1814 new_afsi.num_played);
1816 if (tad->cto->flags & TOUCH_FLAG_VERBOSE)
1817 para_printf(&tad->pb, "touching %s\n", name);
1818 if (tad->cto->lyrics_id >= 0)
1819 new_afsi.lyrics_id = tad->cto->lyrics_id;
1820 if (tad->cto->image_id >= 0)
1821 new_afsi.image_id = tad->cto->image_id;
1822 if (tad->cto->num_played >= 0)
1823 new_afsi.num_played = tad->cto->num_played;
1824 if (tad->cto->last_played >= 0)
1825 new_afsi.last_played = tad->cto->last_played;
1827 save_afsi(&new_afsi, &obj); /* in-place update */
1829 aced.old_afsi = &old_afsi;
1830 afs_event(AFSI_CHANGE, &tad->pb, &aced);
1834 static int com_touch_callback(const struct osl_object *query,
1835 struct osl_object *result)
1837 struct touch_action_data tad = {.cto = query->data};
1839 struct pattern_match_data pmd = {
1840 .table = audio_file_table,
1841 .loop_col_num = AFTCOL_HASH,
1842 .match_col_num = AFTCOL_PATH,
1843 .patterns = {.data = (char *)query->data + sizeof(*tad.cto),
1844 .size = query->size - sizeof(*tad.cto)},
1846 .action = touch_audio_file
1848 if (tad.cto->flags & TOUCH_FLAG_FNM_PATHNAME)
1849 pmd.fnmatch_flags |= FNM_PATHNAME;
1850 ret = for_each_matching_row(&pmd);
1852 para_printf(&tad.pb, "%s\n", PARA_STRERROR(-ret));
1854 result->data = tad.pb.buf;
1855 result->size = tad.pb.size;
1858 return ret < 0? ret : 0;
1861 int com_touch(int fd, int argc, char * const * const argv)
1863 struct com_touch_options cto = {
1869 struct osl_object query = {.data = &cto, .size = sizeof(cto)},
1874 for (i = 1; i < argc; i++) {
1875 const char *arg = argv[i];
1878 if (!strcmp(arg, "--")) {
1882 if (!strncmp(arg, "-n", 2)) {
1883 ret = para_atoi32(arg + 2, &cto.num_played);
1888 if (!strncmp(arg, "-l", 2)) {
1889 ret = para_atoi64(arg + 2, &cto.last_played);
1894 if (!strncmp(arg, "-y", 2)) {
1895 ret = para_atoi32(arg + 2, &cto.lyrics_id);
1900 if (!strncmp(arg, "-i", 2)) {
1901 ret = para_atoi32(arg + 2, &cto.image_id);
1906 if (!strcmp(arg, "-p")) {
1907 cto.flags |= TOUCH_FLAG_FNM_PATHNAME;
1910 if (!strcmp(arg, "-v")) {
1911 cto.flags |= TOUCH_FLAG_VERBOSE;
1914 break; /* non-option starting with dash */
1917 return -E_AFT_SYNTAX;
1918 ret = send_option_arg_callback_request(&query, argc - i,
1919 argv + i, com_touch_callback, &result);
1921 send_buffer(fd, (char *)result.data);
1924 send_va_buffer(fd, "%s\n", PARA_STRERROR(-ret));
1929 RM_FLAG_VERBOSE = 1,
1931 RM_FLAG_FNM_PATHNAME = 4
1934 struct com_rm_data {
1936 struct para_buffer pb;
1937 unsigned num_removed;
1940 static int remove_audio_file(__a_unused struct osl_table *table,
1941 struct osl_row *row, const char *name, void *data)
1943 struct com_rm_data *crd = data;
1946 if (crd->flags & RM_FLAG_VERBOSE)
1947 para_printf(&crd->pb, "removing %s\n", name);
1948 afs_event(AUDIO_FILE_REMOVE, &crd->pb, row);
1949 ret = osl_del_row(audio_file_table, row);
1951 para_printf(&crd->pb, "%s: %s\n", name, PARA_STRERROR(-ret));
1957 static int com_rm_callback(const struct osl_object *query,
1958 __a_unused struct osl_object *result)
1960 struct com_rm_data crd = {.flags = *(uint32_t *)query->data};
1962 struct pattern_match_data pmd = {
1963 .table = audio_file_table,
1964 .loop_col_num = AFTCOL_HASH,
1965 .match_col_num = AFTCOL_PATH,
1966 .patterns = {.data = (char *)query->data + sizeof(uint32_t),
1967 .size = query->size - sizeof(uint32_t)},
1969 .action = remove_audio_file
1971 if (crd.flags & RM_FLAG_FNM_PATHNAME)
1972 pmd.fnmatch_flags |= FNM_PATHNAME;
1973 ret = for_each_matching_row(&pmd);
1975 para_printf(&crd.pb, "%s\n", PARA_STRERROR(-ret));
1976 if (!crd.num_removed && !(crd.flags & RM_FLAG_FORCE))
1977 para_printf(&crd.pb, "no matches -- nothing removed\n");
1979 if (crd.flags & RM_FLAG_VERBOSE)
1980 para_printf(&crd.pb, "removed %u files\n", crd.num_removed);
1983 result->data = crd.pb.buf;
1984 result->size = crd.pb.size;
1987 return ret < 0? ret : 0;
1990 /* TODO options: -r (recursive) */
1991 int com_rm(int fd, int argc, char * const * const argv)
1994 struct osl_object query = {.data = &flags, .size = sizeof(flags)},
1998 for (i = 1; i < argc; i++) {
1999 const char *arg = argv[i];
2002 if (!strcmp(arg, "--")) {
2006 if (!strcmp(arg, "-f")) {
2007 flags |= RM_FLAG_FORCE;
2010 if (!strcmp(arg, "-p")) {
2011 flags |= RM_FLAG_FNM_PATHNAME;
2014 if (!strcmp(arg, "-v")) {
2015 flags |= RM_FLAG_VERBOSE;
2021 return -E_AFT_SYNTAX;
2022 ret = send_option_arg_callback_request(&query, argc - i, argv + i,
2023 com_rm_callback, &result);
2025 send_buffer(fd, (char *)result.data);
2028 send_va_buffer(fd, "%s\n", PARA_STRERROR(-ret));
2033 * Flags used by the cpsi command.
2038 /** Whether the lyrics id should be copied. */
2039 CPSI_FLAG_COPY_LYRICS_ID = 1,
2040 /** Whether the image id should be copied. */
2041 CPSI_FLAG_COPY_IMAGE_ID = 2,
2042 /** Whether the lastplayed time should be copied. */
2043 CPSI_FLAG_COPY_LASTPLAYED = 4,
2044 /** Whether the numplayed count should be copied. */
2045 CPSI_FLAG_COPY_NUMPLAYED = 8,
2046 /** Whether the attributes should be copied. */
2047 CPSI_FLAG_COPY_ATTRIBUTES = 16,
2048 /** Activates verbose mode. */
2049 CPSI_FLAG_VERBOSE = 32,
2052 struct cpsi_action_data {
2054 unsigned num_copied;
2055 struct para_buffer pb;
2056 struct afs_info source_afsi;
2059 static int copy_selector_info(__a_unused struct osl_table *table,
2060 struct osl_row *row, const char *name, void *data)
2062 struct cpsi_action_data *cad = data;
2063 struct osl_object target_afsi_obj;
2065 struct afs_info old_afsi, target_afsi;
2066 struct afsi_change_event_data aced;
2068 ret = get_afsi_object_of_row(row, &target_afsi_obj);
2071 load_afsi(&target_afsi, &target_afsi_obj);
2072 old_afsi = target_afsi;
2073 if (cad->flags & CPSI_FLAG_COPY_LYRICS_ID)
2074 target_afsi.lyrics_id = cad->source_afsi.lyrics_id;
2075 if (cad->flags & CPSI_FLAG_COPY_IMAGE_ID)
2076 target_afsi.image_id = cad->source_afsi.image_id;
2077 if (cad->flags & CPSI_FLAG_COPY_LASTPLAYED)
2078 target_afsi.last_played = cad->source_afsi.last_played;
2079 if (cad->flags & CPSI_FLAG_COPY_NUMPLAYED)
2080 target_afsi.num_played = cad->source_afsi.num_played;
2081 if (cad->flags & CPSI_FLAG_COPY_ATTRIBUTES)
2082 target_afsi.attributes = cad->source_afsi.attributes;
2083 save_afsi(&target_afsi, &target_afsi_obj); /* in-place update */
2085 if (cad->flags & CPSI_FLAG_VERBOSE)
2086 para_printf(&cad->pb, "copied afsi to %s\n", name);
2088 aced.old_afsi = &old_afsi;
2089 afs_event(AFSI_CHANGE, &cad->pb, &aced);
2093 static int com_cpsi_callback(const struct osl_object *query,
2094 struct osl_object *result)
2096 struct cpsi_action_data cad = {.flags = *(unsigned *)query->data};
2098 char *source_path = (char *)query->data + sizeof(cad.flags);
2100 ret = get_afsi_of_path(source_path, &cad.source_afsi);
2103 struct pattern_match_data pmd = {
2104 .table = audio_file_table,
2105 .loop_col_num = AFTCOL_HASH,
2106 .match_col_num = AFTCOL_PATH,
2107 .patterns = {.data = source_path + strlen(source_path) + 1,
2108 .size = query->size - sizeof(cad.flags)
2109 - strlen(source_path) - 1},
2111 .action = copy_selector_info
2113 ret = for_each_matching_row(&pmd);
2116 para_printf(&cad.pb, "%s\n", PARA_STRERROR(-ret));
2117 if (cad.flags & CPSI_FLAG_VERBOSE) {
2119 para_printf(&cad.pb, "copied requested afsi from %s "
2121 source_path, cad.num_copied);
2123 para_printf(&cad.pb, "nothing copied\n");
2126 result->data = cad.pb.buf;
2127 result->size = cad.pb.size;
2130 return ret < 0? ret : 0;
2133 int com_cpsi(int fd, int argc, char * const * const argv)
2137 struct osl_object options = {.data = &flags, .size = sizeof(flags)},
2140 for (i = 1; i < argc; i++) {
2141 const char *arg = argv[i];
2144 if (!strcmp(arg, "--")) {
2148 if (!strcmp(arg, "-y")) {
2149 flags |= CPSI_FLAG_COPY_LYRICS_ID;
2152 if (!strcmp(arg, "-i")) {
2153 flags |= CPSI_FLAG_COPY_IMAGE_ID;
2156 if (!strcmp(arg, "-l")) {
2157 flags |= CPSI_FLAG_COPY_LASTPLAYED;
2160 if (!strcmp(arg, "-n")) {
2161 flags |= CPSI_FLAG_COPY_NUMPLAYED;
2164 if (!strcmp(arg, "-a")) {
2165 flags |= CPSI_FLAG_COPY_ATTRIBUTES;
2168 if (!strcmp(arg, "-v")) {
2169 flags |= CPSI_FLAG_VERBOSE;
2174 if (i + 1 >= argc) /* need at least souce file and pattern */
2175 return -E_AFT_SYNTAX;
2176 if (!(flags & ~CPSI_FLAG_VERBOSE)) /* no copy flags given */
2177 flags = ~(unsigned)CPSI_FLAG_VERBOSE | flags;
2178 ret = send_option_arg_callback_request(&options, argc - i, argv + i,
2179 com_cpsi_callback, &result);
2181 send_buffer(fd, (char *)result.data);
2184 send_va_buffer(fd, "%s\n", PARA_STRERROR(-ret));
2188 /* TODO: optionally fix problems by removing offending rows */
2189 static int check_audio_file(struct osl_row *row, void *data)
2192 struct para_buffer *pb = data;
2193 struct stat statbuf;
2194 int ret = get_audio_file_path_of_row(row, &path);
2195 struct afs_info afsi;
2199 para_printf(pb, "%s\n", PARA_STRERROR(-ret));
2202 if (stat(path, &statbuf) < 0)
2203 para_printf(pb, "%s: stat error (%s)\n", path, strerror(errno));
2205 if (!S_ISREG(statbuf.st_mode))
2206 para_printf(pb, "%s: not a regular file\n", path);
2208 ret = get_afsi_of_row(row, &afsi);
2210 para_printf(pb, "%s: %s\n", path, PARA_STRERROR(-ret));
2213 ret = lyr_get_name_by_id(afsi.lyrics_id, &blob_name);
2215 para_printf(pb, "%s lyrics id %u: %s\n", path, afsi.lyrics_id,
2216 PARA_STRERROR(-ret));
2217 ret = img_get_name_by_id(afsi.image_id, &blob_name);
2219 para_printf(pb, "%s image id %u: %s\n", path, afsi.image_id,
2220 PARA_STRERROR(-ret));
2225 * Check the audio file table for inconsistencies.
2227 * \param query Unused.
2228 * \param result Contains message string upon return.
2230 * This function always succeeds.
2234 int aft_check_callback(__a_unused const struct osl_object *query, struct osl_object *result)
2236 struct para_buffer pb = {.buf = NULL};
2238 para_printf(&pb, "checking audio file table...\n");
2239 audio_file_loop(&pb, check_audio_file);
2240 result->data = pb.buf;
2241 result->size = pb.size;
2247 * Close the audio file table.
2249 * \param flags Ususal flags that are passed to osl_close_table().
2251 * \sa osl_close_table().
2253 static void aft_close(void)
2255 osl_close_table(audio_file_table, OSL_MARK_CLEAN);
2256 audio_file_table = NULL;
2260 * Open the audio file table.
2262 * \param dir The database directory.
2266 * \sa osl_open_table().
2268 static int aft_open(const char *dir)
2272 audio_file_table_desc.dir = dir;
2273 ret = osl_open_table(&audio_file_table_desc, &audio_file_table);
2276 osl_get_num_rows(audio_file_table, &num);
2277 PARA_INFO_LOG("audio file table contains %d files\n", num);
2280 PARA_INFO_LOG("failed to open audio file table\n");
2281 audio_file_table = NULL;
2282 if (ret >= 0 || is_errno(-ret, ENOENT))
2287 static int aft_create(const char *dir)
2289 audio_file_table_desc.dir = dir;
2290 return osl_create_table(&audio_file_table_desc);
2293 static int clear_attribute(struct osl_row *row, void *data)
2295 struct rmatt_event_data *red = data;
2296 struct afs_info afsi;
2297 struct osl_object obj;
2298 int ret = get_afsi_object_of_row(row, &obj);
2299 uint64_t mask = ~(1ULL << red->bitnum);
2303 ret = load_afsi(&afsi, &obj);
2306 afsi.attributes &= mask;
2307 save_afsi(&afsi, &obj);
2311 static int aft_event_handler(enum afs_events event, struct para_buffer *pb,
2315 case ATTRIBUTE_REMOVE: {
2316 const struct rmatt_event_data *red = data;
2317 para_printf(pb, "clearing attribute %s (bit %u) from all "
2318 "entries in the audio file table\n", red->name,
2320 return audio_file_loop(data, clear_attribute);
2327 void aft_init(struct afs_table *t)
2329 t->name = audio_file_table_desc.name;
2331 t->close = aft_close;
2332 t->create = aft_create;
2333 t->event_handler = aft_event_handler;