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 afh_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. */
113 /** Data passed from the ls command handler to its callback function. */
115 /** The given command line flags. */
117 /** The sorting method given at the command line. */
118 enum ls_sorting_method sorting;
119 /** The given listing mode (short, long, verbose, mbox). */
120 enum ls_listing_mode mode;
121 /** The arguments passed to the ls command. */
123 /** Number of non-option arguments. */
125 /** Used for long listing mode to align the output fields. */
126 struct ls_widths widths;
127 /** Size of the \a data array. */
129 /** Number of used entries in the data array. */
130 uint32_t num_matching_paths;
131 /** Array of matching entries. */
132 struct ls_data *data;
133 /** Used to sort the array. */
134 struct ls_data **data_ptr;
138 * Describes the layout of the mmapped-afs info struct.
140 * \sa struct afs_info.
143 /** Where .last_played is stored. */
144 AFSI_LAST_PLAYED_OFFSET = 0,
145 /** Storage position of the attributes bitmap. */
146 AFSI_ATTRIBUTES_OFFSET = 8,
147 /** Storage position of the .num_played field. */
148 AFSI_NUM_PLAYED_OFFSET = 16,
149 /** Storage position of the .image_id field. */
150 AFSI_IMAGE_ID_OFFSET = 20,
151 /** Storage position of the .lyrics_id field. */
152 AFSI_LYRICS_ID_OFFSET = 24,
153 /** Storage position of the .audio_format_id field. */
154 AFSI_AUDIO_FORMAT_ID_OFFSET = 28,
155 /** 3 bytes reserved space for future usage. */
156 AFSI_AUDIO_FORMAT_UNUSED_OFFSET = 29,
157 /** On-disk storage space needed. */
162 * Convert a struct afs_info to an osl object.
164 * \param afsi Pointer to the audio file info to be converted.
165 * \param obj Result pointer.
169 void save_afsi(struct afs_info *afsi, struct osl_object *obj)
171 char *buf = obj->data;
173 write_u64(buf + AFSI_LAST_PLAYED_OFFSET, afsi->last_played);
174 write_u64(buf + AFSI_ATTRIBUTES_OFFSET, afsi->attributes);
175 write_u32(buf + AFSI_NUM_PLAYED_OFFSET, afsi->num_played);
176 write_u32(buf + AFSI_IMAGE_ID_OFFSET, afsi->image_id);
177 write_u32(buf + AFSI_LYRICS_ID_OFFSET, afsi->lyrics_id);
178 write_u8(buf + AFSI_AUDIO_FORMAT_ID_OFFSET,
179 afsi->audio_format_id);
180 memset(buf + AFSI_AUDIO_FORMAT_UNUSED_OFFSET, 0, 3);
184 * Get the audio file selector info struct stored in an osl object.
186 * \param afsi Points to the audio_file info structure to be filled in.
187 * \param obj The osl object holding the data.
189 * \return Positive on success, negative on errors. Possible errors: \p E_BAD_AFS.
193 int load_afsi(struct afs_info *afsi, struct osl_object *obj)
195 char *buf = obj->data;
196 if (obj->size < AFSI_SIZE)
198 afsi->last_played = read_u64(buf + AFSI_LAST_PLAYED_OFFSET);
199 afsi->attributes = read_u64(buf + AFSI_ATTRIBUTES_OFFSET);
200 afsi->num_played = read_u32(buf + AFSI_NUM_PLAYED_OFFSET);
201 afsi->image_id = read_u32(buf + AFSI_IMAGE_ID_OFFSET);
202 afsi->lyrics_id = read_u32(buf + AFSI_LYRICS_ID_OFFSET);
203 afsi->audio_format_id = read_u8(buf +
204 AFSI_AUDIO_FORMAT_ID_OFFSET);
208 /** The columns of the audio file table. */
209 enum audio_file_table_columns {
210 /** The hash on the content of the audio file. */
212 /** The full path in the filesystem. */
214 /** The audio file selector info. */
216 /** The audio format handler info. */
218 /** The chunk table info and the chunk table of the audio file. */
220 /** The number of columns of this table. */
224 static struct osl_column_description aft_cols[] = {
226 .storage_type = OSL_MAPPED_STORAGE,
227 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE | OSL_UNIQUE,
229 .compare_function = osl_hash_compare,
230 .data_size = HASH_SIZE
233 .storage_type = OSL_MAPPED_STORAGE,
234 .storage_flags = OSL_RBTREE | OSL_UNIQUE,
236 .compare_function = string_compare,
239 .storage_type = OSL_MAPPED_STORAGE,
240 .storage_flags = OSL_FIXED_SIZE,
242 .data_size = AFSI_SIZE
245 .storage_type = OSL_MAPPED_STORAGE,
249 .storage_type = OSL_DISK_STORAGE,
254 static struct osl_table_description audio_file_table_desc = {
255 .name = "audio_files",
256 .num_columns = NUM_AFT_COLUMNS,
257 .flags = OSL_LARGE_TABLE,
258 .column_descriptions = aft_cols
261 /* We don't want * dot or dot-dot anywhere. */
262 static int verify_dotfile(const char *rest)
265 * The first character was '.', but that has already been discarded, we
269 case '\0': case '/': /* /foo/. and /foo/./bar are not ok */
271 case '.': /* path start with /foo/.. */
272 if (rest[1] == '\0' || rest[1] == '/')
273 return -1; /* /foo/.. or /foo/../bar are not ok */
274 /* /foo/..bar is ok */
280 * We fundamentally don't like some paths: We don't want double slashes or
281 * slashes at the end that can make pathnames ambiguous.
283 static int verify_path(const char *orig_path, char **resolved_path)
289 if (*orig_path != '/') /* we only accept absolute paths */
291 len = strlen(orig_path);
292 *resolved_path = para_strdup(orig_path);
293 path = *resolved_path;
294 while (len > 1 && path[--len] == '/')
295 path[len] = '\0'; /* remove slash at the end */
301 case '/': /* double slash */
304 if (verify_dotfile(path) < 0)
314 free(*resolved_path);
318 /** The on-disk layout of a afhi struct. */
320 /** Where the number of seconds is stored. */
321 AFHI_SECONDS_TOTAL_OFFSET = 0,
322 /** Position of the bitrate. */
323 AFHI_BITRATE_OFFSET = 4,
324 /** Position of the frequency. */
325 AFHI_FREQUENCY_OFFSET = 8,
326 /** Number of channels is stored here. */
327 AFHI_CHANNELS_OFFSET = 12,
328 /** EOF timeout in ms. */
329 AFHI_EOF_OFFSET = 13,
330 /** The tag info position. */
331 AFHI_INFO_STRING_OFFSET = 15,
332 /** Minimal on-disk size of a valid afhi struct. */
336 static unsigned sizeof_afhi_buf(const struct afh_info *afhi)
340 return strlen(afhi->info_string) + MIN_AFHI_SIZE;
343 static void save_afhi(struct afh_info *afhi, char *buf)
347 write_u32(buf + AFHI_SECONDS_TOTAL_OFFSET,
348 afhi->seconds_total);
349 write_u32(buf + AFHI_BITRATE_OFFSET, afhi->bitrate);
350 write_u32(buf + AFHI_FREQUENCY_OFFSET, afhi->frequency);
351 write_u8(buf + AFHI_CHANNELS_OFFSET, afhi->channels);
352 write_u16(buf + AFHI_EOF_OFFSET, tv2ms(&afhi->eof_tv));
353 strcpy(buf + AFHI_INFO_STRING_OFFSET, afhi->info_string); /* OK */
354 PARA_DEBUG_LOG("last byte written: %p\n", buf + AFHI_INFO_STRING_OFFSET + strlen(afhi->info_string));
357 static void load_afhi(const char *buf, struct afh_info *afhi)
359 afhi->seconds_total = read_u32(buf + AFHI_SECONDS_TOTAL_OFFSET);
360 afhi->bitrate = read_u32(buf + AFHI_BITRATE_OFFSET);
361 afhi->frequency = read_u32(buf + AFHI_FREQUENCY_OFFSET);
362 afhi->channels = read_u8(buf + AFHI_CHANNELS_OFFSET);
363 ms2tv(read_u16(buf + AFHI_EOF_OFFSET), &afhi->eof_tv);
364 strcpy(afhi->info_string, buf + AFHI_INFO_STRING_OFFSET);
367 //#define SIZEOF_CHUNK_TABLE(afhi) (((afhi)->chunks_total + 1) * sizeof(uint32_t))
369 static unsigned sizeof_chunk_info_buf(struct afh_info *afhi)
373 return 4 * (afhi->chunks_total + 1) + 20;
377 /** The offsets of the data contained in the AFTCOL_CHUNKS column. */
378 enum chunk_info_offsets{
379 /** The total number of chunks (4 bytes). */
380 CHUNKS_TOTAL_OFFSET = 0,
381 /** The length of the audio file header (4 bytes). */
382 HEADER_LEN_OFFSET = 4,
383 /** The start of the audio file header (4 bytes). */
384 HEADER_OFFSET_OFFSET = 8,
385 /** The seconds part of the chunk time (4 bytes). */
386 CHUNK_TV_TV_SEC_OFFSET = 12,
387 /** The microseconds part of the chunk time (4 bytes). */
388 CHUNK_TV_TV_USEC = 16,
389 /** Chunk table entries start here. */
390 CHUNK_TABLE_OFFSET = 20,
393 static void save_chunk_table(struct afh_info *afhi, char *buf)
397 PARA_DEBUG_LOG("%lu chunks\n", afhi->chunks_total);
398 for (i = 0; i <= afhi->chunks_total; i++)
399 write_u32(buf + 4 * i, afhi->chunk_table[i]);
402 static void load_chunk_table(struct afh_info *afhi, char *buf)
405 for (i = 0; i <= afhi->chunks_total; i++)
406 afhi->chunk_table[i] = read_u32(buf + 4 * i);
409 /* TODO: audio format handlers could just produce this */
410 static void save_chunk_info(struct afh_info *afhi, char *buf)
414 write_u32(buf + CHUNKS_TOTAL_OFFSET, afhi->chunks_total);
415 write_u32(buf + HEADER_LEN_OFFSET, afhi->header_len);
416 write_u32(buf + HEADER_OFFSET_OFFSET, afhi->header_offset);
417 write_u32(buf + CHUNK_TV_TV_SEC_OFFSET, afhi->chunk_tv.tv_sec);
418 write_u32(buf + CHUNK_TV_TV_USEC, afhi->chunk_tv.tv_usec);
419 save_chunk_table(afhi, buf + CHUNK_TABLE_OFFSET);
422 static int load_chunk_info(struct osl_object *obj, struct afh_info *afhi)
424 char *buf = obj->data;
426 if (obj->size < CHUNK_TABLE_OFFSET)
427 return -E_BAD_DATA_SIZE;
429 afhi->chunks_total = read_u32(buf + CHUNKS_TOTAL_OFFSET);
430 afhi->header_len = read_u32(buf + HEADER_LEN_OFFSET);
431 afhi->header_offset = read_u32(buf + HEADER_OFFSET_OFFSET);
432 afhi->chunk_tv.tv_sec = read_u32(buf + CHUNK_TV_TV_SEC_OFFSET);
433 afhi->chunk_tv.tv_usec = read_u32(buf + CHUNK_TV_TV_USEC);
435 if ((afhi->chunks_total + 1) * 4 + CHUNK_TABLE_OFFSET > obj->size)
436 return -E_BAD_DATA_SIZE;
437 afhi->chunk_table = para_malloc((afhi->chunks_total + 1) * 4);
438 load_chunk_table(afhi, buf + CHUNK_TABLE_OFFSET);
443 * Get the row of the audio file table corresponding to the given path.
445 * \param path The full path of the audio file.
446 * \param row Result pointer.
448 * \return The return value of the underlying call to osl_get_row().
450 int aft_get_row_of_path(const char *path, struct osl_row **row)
452 struct osl_object obj = {.data = (char *)path, .size = strlen(path) + 1};
454 return osl_get_row(audio_file_table, AFTCOL_PATH, &obj, row);
458 * Get the row of the audio file table corresponding to the given hash value.
460 * \param hash The hash value of the desired audio file.
461 * \param row resul pointer.
463 * \return The return value of the underlying call to osl_get_row().
465 int aft_get_row_of_hash(HASH_TYPE *hash, struct osl_row **row)
467 const struct osl_object obj = {.data = hash, .size = HASH_SIZE};
468 return osl_get_row(audio_file_table, AFTCOL_HASH, &obj, row);
472 * Get the osl object holding the audio file selector info of a row.
474 * \param row Pointer to a row in the audio file table.
475 * \param obj Result pointer.
477 * \return The return value of the underlying call to osl_get_object().
479 int get_afsi_object_of_row(const struct osl_row *row, struct osl_object *obj)
481 return osl_get_object(audio_file_table, row, AFTCOL_AFSI, obj);
485 * Get the osl object holding the audio file selector info, given a path.
488 * \param path The full path of the audio file.
489 * \param obj Result pointer.
491 * \return Positive on success, negative on errors.
493 int get_afsi_object_of_path(const char *path, struct osl_object *obj)
496 int ret = aft_get_row_of_path(path, &row);
499 return get_afsi_object_of_row(row, obj);
503 * Get the audio file selector info, given a row of the audio file table.
505 * \param row Pointer to a row in the audio file table.
506 * \param afsi Result pointer.
508 * \return Positive on success, negative on errors.
510 int get_afsi_of_row(const struct osl_row *row, struct afs_info *afsi)
512 struct osl_object obj;
513 int ret = get_afsi_object_of_row(row, &obj);
516 return load_afsi(afsi, &obj);
520 * Get the audio file selector info, given the path of an audio table.
522 * \param path The full path of the audio file.
523 * \param afsi Result pointer.
525 * \return Positive on success, negative on errors.
527 int get_afsi_of_path(const char *path, struct afs_info *afsi)
529 struct osl_object obj;
530 int ret = get_afsi_object_of_path(path, &obj);
533 return load_afsi(afsi, &obj);
537 * Get the path of an audio file, given a row of the audio file table.
539 * \param row Pointer to a row in the audio file table.
540 * \param path Result pointer.
542 * The result is a pointer to mmapped data. The caller must not attempt
547 int get_audio_file_path_of_row(const struct osl_row *row, char **path)
549 struct osl_object path_obj;
550 int ret = osl_get_object(audio_file_table, row, AFTCOL_PATH,
554 *path = path_obj.data;
559 * Get the object containing the hash value of an audio file, given a row.
561 * \param row Pointer to a row of the audio file table.
562 * \param obj Result pointer.
564 * \return The return value of the underlying call to osl_get_object().
566 * \sa get_hash_of_row().
568 static int get_hash_object_of_aft_row(const struct osl_row *row, struct osl_object *obj)
570 return osl_get_object(audio_file_table, row, AFTCOL_HASH, obj);
574 * Get the hash value of an audio file, given a row of the audio file table.
576 * \param row Pointer to a row of the audio file table.
577 * \param hash Result pointer.
579 * \a hash points to mapped data and must not be freed by the caller.
581 * \return The return value of the underlying call to
582 * get_hash_object_of_aft_row().
584 static int get_hash_of_row(const struct osl_row *row, HASH_TYPE **hash)
586 struct osl_object obj;
587 int ret = get_hash_object_of_aft_row(row, &obj);
596 * Get the audio format handler info, given a row of the audio file table.
598 * \param row Pointer to a row of the audio file table.
599 * \param afhi Result pointer.
601 * \return The return value of the underlying call to osl_get_object().
603 * \sa get_chunk_table_of_row().
605 int get_afhi_of_row(const struct osl_row *row, struct afh_info *afhi)
607 struct osl_object obj;
608 int ret = osl_get_object(audio_file_table, row, AFTCOL_AFHI,
612 load_afhi(obj.data, afhi);
616 /* returns shmid on success */
617 static int save_afd(struct audio_file_data *afd)
619 size_t size = sizeof(*afd)
620 + 4 * (afd->afhi.chunks_total + 1);
622 PARA_DEBUG_LOG("size: %zu\n", size);
623 int shmid, ret = shm_new(size);
630 ret = shm_attach(shmid, ATTACH_RW, &shm_afd);
633 *(struct audio_file_data *)shm_afd = *afd;
636 save_chunk_table(&afd->afhi, buf);
644 int load_afd(int shmid, struct audio_file_data *afd)
650 ret = shm_attach(shmid, ATTACH_RO, &shm_afd);
653 *afd = *(struct audio_file_data *)shm_afd;
656 afd->afhi.chunk_table = para_malloc((afd->afhi.chunks_total + 1) * 4);
657 load_chunk_table(&afd->afhi, buf);
663 * Mmap the given audio file and update statistics.
665 * \param aft_row Determines the audio file to be opened and updated.
666 * \param afd Result pointer.
668 * On success, the numplayed field of the audio file selector info is increased
669 * and the lastplayed time is set to the current time. Finally, the score of
670 * the audio file is updated.
672 * \return Positive on success, negative on errors.
674 int open_and_update_audio_file(struct osl_row *aft_row, struct audio_file_data *afd)
676 HASH_TYPE *aft_hash, file_hash[HASH_SIZE];
677 struct osl_object afsi_obj;
678 struct afs_info new_afsi;
679 int ret = get_hash_of_row(aft_row, &aft_hash);
680 struct afsi_change_event_data aced;
681 struct osl_object map, chunk_table_obj;
686 ret = get_audio_file_path_of_row(aft_row, &path);
689 strncpy(afd->path, path, sizeof(afd->path) - 1);
690 afd->path[sizeof(afd->path) - 1] = '\0';
691 ret = get_afsi_object_of_row(aft_row, &afsi_obj);
694 ret = load_afsi(&afd->afsi, &afsi_obj);
697 ret = get_afhi_of_row(aft_row, &afd->afhi);
700 ret = osl_open_disk_object(audio_file_table, aft_row,
701 AFTCOL_CHUNKS, &chunk_table_obj);
704 ret = mmap_full_file(path, O_RDONLY, &map.data,
705 &map.size, &afd->fd);
708 hash_function(map.data, map.size, file_hash);
709 ret = hash_compare(file_hash, aft_hash);
710 para_munmap(map.data, map.size);
712 ret = -E_HASH_MISMATCH;
715 new_afsi = afd->afsi;
716 new_afsi.num_played++;
717 new_afsi.last_played = time(NULL);
718 save_afsi(&new_afsi, &afsi_obj); /* in-place update */
720 ret = load_chunk_info(&chunk_table_obj, &afd->afhi);
723 ret = get_attribute_text(&afd->afsi.attributes, " ", &tmp);
727 strncpy(afd->attributes_string, tmp, sizeof(afd->attributes_string));
728 afd->attributes_string[sizeof(afd->attributes_string) - 1] = '\0';
731 aced.aft_row = aft_row;
732 aced.old_afsi = &afd->afsi;
733 afs_event(AFSI_CHANGE, NULL, &aced);
737 free(afd->afhi.chunk_table);
739 osl_close_disk_object(&chunk_table_obj);
743 static int get_local_time(uint64_t *seconds, char *buf, size_t size,
744 time_t current_time, enum ls_listing_mode lm)
748 if (!localtime_r((time_t *)seconds, &t))
750 if (lm == LS_MODE_MBOX) {
751 if (!strftime(buf, size, "%c", &t))
755 if (*seconds + 6 * 30 * 24 * 3600 > current_time) {
756 if (!strftime(buf, size, "%b %e %k:%M", &t))
760 if (!strftime(buf, size, "%b %e %Y", &t))
765 /** Compute the number of (decimal) digits of a number. */
766 #define GET_NUM_DIGITS(x, num) { \
767 typeof((x)) _tmp = PARA_ABS(x); \
770 while ((_tmp) > 9) { \
776 static short unsigned get_duration_width(int seconds)
778 short unsigned width;
779 unsigned hours = seconds / 3600, mins = (seconds % 3600) / 60;
781 if (!hours) /* less than one hour => m:ss or mm:ss => 4 or 5 digits */
782 return 4 + (mins > 9);
783 /* more than one hour => h:mm:ss, hh:mm:ss, hhh:mm:ss, ... */
784 GET_NUM_DIGITS(hours, &width);
788 static void get_duration_buf(int seconds, char *buf, short unsigned max_width)
790 unsigned hours = seconds / 3600, mins = (seconds % 3600) / 60;
792 if (!hours) /* m:ss or mm:ss */
793 sprintf(buf, "%*u:%02u", max_width - 3, mins, seconds % 60);
794 else /* more than one hour => h:mm:ss, hh:mm:ss, hhh:mm:ss, ... */
795 sprintf(buf, "%*u:%02u:%02u", max_width - 6, hours, mins,
799 static char *make_attribute_lines(const char *att_bitmap, struct afs_info *afsi)
801 char *att_text, *att_lines;
803 get_attribute_text(&afsi->attributes, " ", &att_text);
805 return para_strdup(att_bitmap);
806 att_lines = make_message("%s\nattributes_txt: %s",
807 att_bitmap, att_text);
812 static char *make_lyrics_line(struct afs_info *afsi)
816 lyr_get_name_by_id(afsi->lyrics_id, &lyrics_name);
818 return make_message("%u", afsi->lyrics_id);
819 return make_message("%u (%s)", afsi->lyrics_id, lyrics_name);
822 static char *make_image_line(struct afs_info *afsi)
825 img_get_name_by_id(afsi->image_id, &image_name);
827 return make_message("%u", afsi->image_id);
828 return make_message("%u (%s)", afsi->image_id, image_name);
831 static int print_list_item(struct ls_data *d, struct ls_options *opts,
832 struct para_buffer *b, time_t current_time)
836 char last_played_time[30];
837 char duration_buf[30]; /* nobody has an audio file long enough to overflow this */
838 char score_buf[30] = "";
839 struct afs_info *afsi = &d->afsi;
840 struct afh_info *afhi = &d->afhi;
841 struct ls_widths *w = &opts->widths;
842 int have_score = opts->flags & LS_FLAG_ADMISSIBLE_ONLY;
843 char asc_hash[2 * HASH_SIZE + 1];
844 char *att_lines, *lyrics_line, *image_line;
846 if (opts->mode == LS_MODE_SHORT) {
847 para_printf(b, "%s\n", d->path);
850 get_attribute_bitmap(&afsi->attributes, att_buf);
851 ret = get_local_time(&afsi->last_played, last_played_time,
852 sizeof(last_played_time), current_time, opts->mode);
855 get_duration_buf(afhi->seconds_total, duration_buf, w->duration_width);
857 if (opts->mode == LS_MODE_LONG)
858 sprintf(score_buf, "%*li ", w->score_width, d->score);
860 sprintf(score_buf, "%li ", d->score);
863 if (opts->mode == LS_MODE_LONG) {
866 "%s " /* attributes */
867 "%*d " /* image_id */
868 "%*d " /* lyrics_id */
870 "%s " /* audio format */
871 "%*d " /* frequency */
874 "%*d " /* num_played */
875 "%s " /* last_played */
879 w->image_id_width, afsi->image_id,
880 w->lyrics_id_width, afsi->lyrics_id,
881 w->bitrate_width, afhi->bitrate,
882 audio_format_name(afsi->audio_format_id),
883 w->frequency_width, afhi->frequency,
886 w->num_played_width, afsi->num_played,
892 hash_to_asc(d->hash, asc_hash);
893 att_lines = make_attribute_lines(att_buf, afsi);
894 lyrics_line = make_lyrics_line(afsi);
895 image_line = make_image_line(afsi);
896 /* TODO: Merge this with status items */
897 if (opts->mode == LS_MODE_VERBOSE) {
899 "%s: %s\n" /* path */
905 "bitrate: %dkbit/s\n"
913 (opts->flags & LS_FLAG_FULL_PATH)?
914 "path" : "file", d->path,
915 have_score? "score: " : "", score_buf,
916 have_score? "\n" : "",
922 audio_format_name(afsi->audio_format_id),
930 } else { /* mbox mode */
931 struct osl_object lyrics_def;
932 lyr_get_def_by_id(afsi->lyrics_id, &lyrics_def);
934 "From foo@localhost %s\n"
935 "Received: from\nTo: bar\nFrom: a\n"
936 "Subject: %s\n\n" /* path */
942 "bitrate: %dkbit/s\n"
952 have_score? "score: " : "", score_buf,
953 have_score? "\n" : "",
959 audio_format_name(afsi->audio_format_id),
965 lyrics_def.data? "Lyrics:\n~~~~~~~\n" : "",
966 lyrics_def.data? (char *)lyrics_def.data : ""
969 osl_close_disk_object(lyrics_def.data);
977 static int ls_audio_format_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.audio_format_id, d2->afsi.audio_format_id);
983 static int ls_duration_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.seconds_total, d2->afhi.seconds_total);
989 static int ls_bitrate_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.bitrate, d2->afhi.bitrate);
995 static int ls_lyrics_id_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.lyrics_id, d2->afsi.lyrics_id);
1001 static int ls_image_id_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.image_id, d2->afsi.image_id);
1007 static int ls_channels_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->afhi.channels, d2->afhi.channels);
1013 static int ls_frequency_compare(const void *a, const void *b)
1015 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1016 return NUM_COMPARE(d1->afhi.frequency, d2->afhi.frequency);
1019 static int ls_num_played_compare(const void *a, const void *b)
1021 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1022 return NUM_COMPARE(d1->afsi.num_played, d2->afsi.num_played);
1025 static int ls_last_played_compare(const void *a, const void *b)
1027 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1028 return NUM_COMPARE(d1->afsi.last_played, d2->afsi.last_played);
1031 static int ls_score_compare(const void *a, const void *b)
1033 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1034 return NUM_COMPARE(d1->score, d2->score);
1037 static int ls_path_compare(const void *a, const void *b)
1039 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1040 return strcmp(d1->path, d2->path);
1043 static int sort_matching_paths(struct ls_options *options)
1045 size_t nmemb = options->num_matching_paths;
1046 size_t size = sizeof(*options->data_ptr);
1047 int (*compar)(const void *, const void *);
1050 options->data_ptr = para_malloc(nmemb * sizeof(*options->data_ptr));
1051 for (i = 0; i < nmemb; i++)
1052 options->data_ptr[i] = options->data + i;
1054 /* In these cases the array is already sorted */
1055 if (options->sorting == LS_SORT_BY_PATH
1056 && !(options->flags & LS_FLAG_ADMISSIBLE_ONLY)
1057 && (options->flags & LS_FLAG_FULL_PATH))
1059 if (options->sorting == LS_SORT_BY_SCORE &&
1060 options->flags & LS_FLAG_ADMISSIBLE_ONLY)
1063 switch (options->sorting) {
1064 case LS_SORT_BY_PATH:
1065 compar = ls_path_compare; break;
1066 case LS_SORT_BY_SCORE:
1067 compar = ls_score_compare; break;
1068 case LS_SORT_BY_LAST_PLAYED:
1069 compar = ls_last_played_compare; break;
1070 case LS_SORT_BY_NUM_PLAYED:
1071 compar = ls_num_played_compare; break;
1072 case LS_SORT_BY_FREQUENCY:
1073 compar = ls_frequency_compare; break;
1074 case LS_SORT_BY_CHANNELS:
1075 compar = ls_channels_compare; break;
1076 case LS_SORT_BY_IMAGE_ID:
1077 compar = ls_image_id_compare; break;
1078 case LS_SORT_BY_LYRICS_ID:
1079 compar = ls_lyrics_id_compare; break;
1080 case LS_SORT_BY_BITRATE:
1081 compar = ls_bitrate_compare; break;
1082 case LS_SORT_BY_DURATION:
1083 compar = ls_duration_compare; break;
1084 case LS_SORT_BY_AUDIO_FORMAT:
1085 compar = ls_audio_format_compare; break;
1089 qsort(options->data_ptr, nmemb, size, compar);
1093 /* row is either an aft_row or a row of the score table */
1094 /* TODO: Only compute widths if we need them */
1095 static int prepare_ls_row(struct osl_row *row, void *ls_opts)
1098 struct ls_options *options = ls_opts;
1100 struct ls_widths *w;
1101 unsigned short num_digits;
1103 struct osl_row *aft_row;
1107 if (options->flags & LS_FLAG_ADMISSIBLE_ONLY) {
1108 ret = get_score_and_aft_row(row, &score, &aft_row);
1113 ret = get_audio_file_path_of_row(aft_row, &path);
1116 if (!(options->flags & LS_FLAG_FULL_PATH)) {
1117 char *p = strrchr(path, '/');
1121 if (options->num_patterns) {
1122 for (i = 0; i < options->num_patterns; i++) {
1123 ret = fnmatch(options->patterns[i], path, 0);
1126 if (ret == FNM_NOMATCH)
1130 if (i >= options->num_patterns) /* no match */
1133 tmp = options->num_matching_paths++;
1134 if (options->num_matching_paths > options->array_size) {
1135 options->array_size++;
1136 options->array_size *= 2;
1137 options->data = para_realloc(options->data, options->array_size
1138 * sizeof(*options->data));
1140 d = options->data + tmp;
1141 ret = get_afsi_of_row(aft_row, &d->afsi);
1144 ret = get_afhi_of_row(aft_row, &d->afhi);
1148 ret = get_hash_of_row(aft_row, &d->hash);
1151 w = &options->widths;
1152 GET_NUM_DIGITS(d->afsi.image_id, &num_digits);
1153 w->image_id_width = PARA_MAX(w->image_id_width, num_digits);
1154 GET_NUM_DIGITS(d->afsi.lyrics_id, &num_digits);
1155 w->lyrics_id_width = PARA_MAX(w->lyrics_id_width, num_digits);
1156 GET_NUM_DIGITS(d->afhi.bitrate, &num_digits);
1157 w->bitrate_width = PARA_MAX(w->bitrate_width, num_digits);
1158 GET_NUM_DIGITS(d->afhi.frequency, &num_digits);
1159 w->frequency_width = PARA_MAX(w->frequency_width, num_digits);
1160 GET_NUM_DIGITS(d->afsi.num_played, &num_digits);
1161 w->num_played_width = PARA_MAX(w->num_played_width, num_digits);
1162 /* get the number of chars to print this amount of time */
1163 tmp = get_duration_width(d->afhi.seconds_total);
1164 w->duration_width = PARA_MAX(w->duration_width, tmp);
1165 if (options->flags & LS_FLAG_ADMISSIBLE_ONLY) {
1166 GET_NUM_DIGITS(score, &num_digits);
1167 num_digits++; /* add one for the sign (space or "-") */
1168 w->score_width = PARA_MAX(w->score_width, num_digits);
1174 static int com_ls_callback(const struct osl_object *query,
1175 struct osl_object *ls_output)
1177 struct ls_options *opts = query->data;
1178 char *p, *pattern_start = (char *)query->data + sizeof(*opts);
1179 struct para_buffer b = {.buf = NULL, .size = 0};
1181 time_t current_time;
1184 if (opts->num_patterns) {
1185 opts->patterns = para_malloc(opts->num_patterns * sizeof(char *));
1186 for (i = 0, p = pattern_start; i < opts->num_patterns; i++) {
1187 opts->patterns[i] = p;
1191 opts->patterns = NULL;
1192 if (opts->flags & LS_FLAG_ADMISSIBLE_ONLY)
1193 ret = admissible_file_loop(opts, prepare_ls_row);
1195 ret = osl_rbtree_loop(audio_file_table, AFTCOL_PATH, opts,
1199 ret = opts->num_patterns? -E_NO_MATCH : 0;
1200 if (!opts->num_matching_paths)
1202 ret = sort_matching_paths(opts);
1205 time(¤t_time);
1206 if (opts->flags & LS_FLAG_REVERSE)
1207 for (i = opts->num_matching_paths - 1; i >= 0; i--) {
1208 ret = print_list_item(opts->data_ptr[i], opts, &b, current_time);
1213 for (i = 0; i < opts->num_matching_paths; i++) {
1214 ret = print_list_item(opts->data_ptr[i], opts, &b, current_time);
1220 ls_output->data = b.buf;
1221 ls_output->size = b.size;
1223 free(opts->data_ptr);
1224 free(opts->patterns);
1229 * TODO: flags -h (sort by hash)
1231 int com_ls(int fd, int argc, char * const * const argv)
1235 enum ls_sorting_method sort = LS_SORT_BY_PATH;
1236 enum ls_listing_mode mode = LS_MODE_SHORT;
1237 struct ls_options opts = {.patterns = NULL};
1238 struct osl_object query = {.data = &opts, .size = sizeof(opts)},
1241 for (i = 1; i < argc; i++) {
1242 const char *arg = argv[i];
1245 if (!strcmp(arg, "--")) {
1249 if (!strncmp(arg, "-l", 2)) {
1251 mode = LS_MODE_LONG;
1255 return -E_AFT_SYNTAX;
1256 switch(*(arg + 2)) {
1258 mode = LS_MODE_SHORT;
1261 mode = LS_MODE_LONG;
1264 mode = LS_MODE_VERBOSE;
1267 mode = LS_MODE_MBOX;
1270 return -E_AFT_SYNTAX;
1273 if (!strcmp(arg, "-p")) {
1274 flags |= LS_FLAG_FULL_PATH;
1277 if (!strcmp(arg, "-a")) {
1278 flags |= LS_FLAG_ADMISSIBLE_ONLY;
1281 if (!strcmp(arg, "-r")) {
1282 flags |= LS_FLAG_REVERSE;
1285 if (!strncmp(arg, "-s", 2)) {
1286 if (!*(arg + 2) || *(arg + 3))
1287 return -E_AFT_SYNTAX;
1288 switch(*(arg + 2)) {
1290 sort = LS_SORT_BY_PATH;
1292 case 's': /* -ss implies -a */
1293 sort = LS_SORT_BY_SCORE;
1294 flags |= LS_FLAG_ADMISSIBLE_ONLY;
1297 sort = LS_SORT_BY_LAST_PLAYED;
1300 sort = LS_SORT_BY_NUM_PLAYED;
1303 sort = LS_SORT_BY_FREQUENCY;
1306 sort = LS_SORT_BY_CHANNELS;
1309 sort = LS_SORT_BY_IMAGE_ID;
1312 sort = LS_SORT_BY_LYRICS_ID;
1315 sort = LS_SORT_BY_BITRATE;
1318 sort = LS_SORT_BY_DURATION;
1321 sort = LS_SORT_BY_AUDIO_FORMAT;
1324 return -E_AFT_SYNTAX;
1327 return -E_AFT_SYNTAX;
1330 opts.sorting = sort;
1332 opts.num_patterns = argc - i;
1333 ret = send_option_arg_callback_request(&query, opts.num_patterns,
1334 argv + i, com_ls_callback, &ls_output);
1336 ret = send_buffer(fd, (char *)ls_output.data);
1337 free(ls_output.data);
1343 * Call the given function for each file in the audio file table.
1345 * \param private_data An arbitrary data pointer, passed to \a func.
1346 * \param func The custom function to be called.
1348 * \return The return value of the underlying call to osl_rbtree_loop().
1350 int audio_file_loop(void *private_data, osl_rbtree_loop_func *func)
1352 return osl_rbtree_loop(audio_file_table, AFTCOL_HASH, private_data,
1356 static struct osl_row *find_hash_sister(HASH_TYPE *hash)
1358 const struct osl_object obj = {.data = hash, .size = HASH_SIZE};
1359 struct osl_row *row;
1361 osl_get_row(audio_file_table, AFTCOL_HASH, &obj, &row);
1365 enum aft_row_offsets {
1366 AFTROW_AFHI_OFFSET_POS = 0,
1367 AFTROW_CHUNKS_OFFSET_POS = 2,
1368 AFTROW_AUDIO_FORMAT_OFFSET = 4,
1369 AFTROW_FLAGS_OFFSET = 5,
1370 AFTROW_HASH_OFFSET = 9,
1371 AFTROW_PATH_OFFSET = (AFTROW_HASH_OFFSET + HASH_SIZE),
1374 /* never save the afsi, as the server knows it too. Note that afhi might be NULL.
1375 * In this case, afhi won't be stored in the buffer */
1376 static void save_audio_file_info(HASH_TYPE *hash, const char *path,
1377 struct afh_info *afhi, uint32_t flags,
1378 uint8_t audio_format_num, struct osl_object *obj)
1380 size_t path_len = strlen(path) + 1;
1381 size_t afhi_size = sizeof_afhi_buf(afhi);
1382 size_t size = AFTROW_PATH_OFFSET + path_len + afhi_size
1383 + sizeof_chunk_info_buf(afhi);
1384 char *buf = para_malloc(size);
1387 write_u8(buf + AFTROW_AUDIO_FORMAT_OFFSET, audio_format_num);
1388 write_u32(buf + AFTROW_FLAGS_OFFSET, flags);
1390 memcpy(buf + AFTROW_HASH_OFFSET, hash, HASH_SIZE);
1391 strcpy(buf + AFTROW_PATH_OFFSET, path);
1393 pos = AFTROW_PATH_OFFSET + path_len;
1394 PARA_DEBUG_LOG("size: %zu, afhi starts at %d\n", size, pos);
1395 PARA_DEBUG_LOG("last afhi byte: %p, pos %zu\n", buf + pos + afhi_size - 1,
1396 pos + afhi_size - 1);
1397 write_u16(buf + AFTROW_AFHI_OFFSET_POS, pos);
1398 save_afhi(afhi, buf + pos);
1401 PARA_DEBUG_LOG("size: %zu, chunks start at %d\n", size, pos);
1402 write_u16(buf + AFTROW_CHUNKS_OFFSET_POS, pos);
1403 save_chunk_info(afhi, buf + pos);
1404 PARA_DEBUG_LOG("last byte in buf: %p\n", buf + size - 1);
1418 AFHI: whether afhi and chunk table are computed and sent
1419 ACTION: table modifications to be performed
1421 +---+----+-----+------+---------------------------------------------------+
1422 | HS | PB | F | AFHI | ACTION
1423 +---+----+-----+------+---------------------------------------------------+
1424 | Y | Y | Y | Y | if HS != PB: remove PB. HS: force afhi update,
1425 | | update path, keep afsi
1426 +---+----+-----+------+---------------------------------------------------+
1427 | Y | Y | N | N | if HS == PB: do not send callback request at all.
1428 | | otherwise: remove PB, HS: update path, keep afhi,
1430 +---+----+-----+------+---------------------------------------------------+
1431 | Y | N | Y | Y | (rename) force afhi update of HS, update path of
1433 +---+----+-----+------+---------------------------------------------------+
1434 | Y | N | N | N | (file rename) update path of HS, keep afsi, afhi
1435 +---+----+-----+------+---------------------------------------------------+
1436 | N | Y | Y | Y | (file change) update afhi, hash, of PB, keep afsi
1437 | | (force has no effect)
1438 +---+----+-----+------+---------------------------------------------------+
1439 | N | Y | N | Y | (file change) update afhi, hash of PB, keep afsi
1440 +---+----+-----+------+---------------------------------------------------+
1441 | N | N | Y | Y | (new file) create new entry (force has no effect)
1442 +---+----+-----+------+---------------------------------------------------+
1443 | N | N | N | Y | (new file) create new entry
1444 +---+----+-----+------+---------------------------------------------------+
1446 afhi <=> force or no HS
1450 /** Flags passed to the add command. */
1451 enum com_add_flags {
1452 /** Skip paths that exist already. */
1454 /** Force adding. */
1456 /** Print what is being done. */
1457 ADD_FLAG_VERBOSE = 4,
1458 /** Try to add files with unknown suffixes. */
1462 static int com_add_callback(const struct osl_object *query,
1463 struct osl_object *result)
1465 char *buf = query->data, *path;
1466 struct osl_row *pb, *aft_row;
1468 struct osl_object objs[NUM_AFT_COLUMNS];
1470 char asc[2 * HASH_SIZE + 1];
1472 char afsi_buf[AFSI_SIZE];
1473 uint32_t flags = read_u32(buf + AFTROW_FLAGS_OFFSET);
1474 struct afs_info default_afsi = {.last_played = 0};
1475 struct para_buffer msg = {.buf = NULL};
1477 hash = (HASH_TYPE *)buf + AFTROW_HASH_OFFSET;
1478 hash_to_asc(hash, asc);;
1479 objs[AFTCOL_HASH].data = buf + AFTROW_HASH_OFFSET;
1480 objs[AFTCOL_HASH].size = HASH_SIZE;
1482 path = buf + AFTROW_PATH_OFFSET;
1483 objs[AFTCOL_PATH].data = path;
1484 objs[AFTCOL_PATH].size = strlen(path) + 1;
1486 PARA_INFO_LOG("request to add %s\n", path);
1487 hs = find_hash_sister(hash);
1488 ret = aft_get_row_of_path(path, &pb);
1489 if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
1491 if (hs && pb && hs == pb && !(flags & ADD_FLAG_FORCE)) {
1492 if (flags & ADD_FLAG_VERBOSE)
1493 para_printf(&msg, "ignoring duplicate\n");
1497 if (hs && hs != pb) {
1498 struct osl_object obj;
1499 if (pb) { /* hs trumps pb, remove pb */
1500 if (flags & ADD_FLAG_VERBOSE)
1501 para_printf(&msg, "removing path brother\n");
1502 ret = osl_del_row(audio_file_table, pb);
1507 /* file rename, update hs' path */
1508 if (flags & ADD_FLAG_VERBOSE) {
1509 ret = osl_get_object(audio_file_table, hs,
1513 para_printf(&msg, "renamed from %s\n", (char *)obj.data);
1515 ret = osl_update_object(audio_file_table, hs, AFTCOL_PATH,
1516 &objs[AFTCOL_PATH]);
1519 afs_event(AUDIO_FILE_RENAME, &msg, hs);
1520 if (!(flags & ADD_FLAG_FORCE))
1523 /* no hs or force mode, child must have sent afhi */
1524 uint16_t afhi_offset = read_u16(buf + AFTROW_AFHI_OFFSET_POS);
1525 uint16_t chunks_offset = read_u16(buf + AFTROW_CHUNKS_OFFSET_POS);
1527 objs[AFTCOL_AFHI].data = buf + afhi_offset;
1528 objs[AFTCOL_AFHI].size = chunks_offset - afhi_offset;
1530 if (!objs[AFTCOL_AFHI].size) /* "impossible" */
1532 objs[AFTCOL_CHUNKS].data = buf + chunks_offset;
1533 objs[AFTCOL_CHUNKS].size = query->size - chunks_offset;
1534 if (pb && !hs) { /* update pb's hash */
1535 char old_asc[2 * HASH_SIZE + 1];
1536 HASH_TYPE *old_hash;
1537 ret = get_hash_of_row(pb, &old_hash);
1540 hash_to_asc(old_hash, old_asc);
1541 if (flags & ADD_FLAG_VERBOSE)
1542 para_printf(&msg, "file change: %s -> %s\n",
1544 ret = osl_update_object(audio_file_table, pb, AFTCOL_HASH,
1545 &objs[AFTCOL_HASH]);
1549 if (hs || pb) { /* (hs != NULL and pb != NULL) implies hs == pb */
1550 struct osl_row *row = pb? pb : hs;
1551 /* update afhi and chunk_table */
1552 if (flags & ADD_FLAG_VERBOSE)
1553 para_printf(&msg, "updating afhi and chunk table\n");
1554 ret = osl_update_object(audio_file_table, row, AFTCOL_AFHI,
1555 &objs[AFTCOL_AFHI]);
1558 ret = osl_update_object(audio_file_table, row, AFTCOL_CHUNKS,
1559 &objs[AFTCOL_CHUNKS]);
1562 afs_event(AFHI_CHANGE, &msg, row);
1565 /* new entry, use default afsi */
1566 if (flags & ADD_FLAG_VERBOSE)
1567 para_printf(&msg, "new file\n");
1568 default_afsi.last_played = time(NULL) - 365 * 24 * 60 * 60;
1569 default_afsi.audio_format_id = read_u8(buf + AFTROW_AUDIO_FORMAT_OFFSET);
1571 objs[AFTCOL_AFSI].data = &afsi_buf;
1572 objs[AFTCOL_AFSI].size = AFSI_SIZE;
1573 save_afsi(&default_afsi, &objs[AFTCOL_AFSI]);
1574 ret = osl_add_and_get_row(audio_file_table, objs, &aft_row);
1577 para_printf(&msg, "%s\n", PARA_STRERROR(-ret));
1580 result->data = msg.buf;
1581 result->size = msg.size;
1582 afs_event(AUDIO_FILE_ADD, &msg, aft_row);
1586 /** Used by com_add(). */
1587 struct private_add_data {
1588 /** The socket file descriptor. */
1590 /** The given add flags. */
1594 static int path_brother_callback(const struct osl_object *query,
1595 struct osl_object *result)
1597 char *path = query->data;
1598 struct osl_row *path_brother;
1599 int ret = aft_get_row_of_path(path, &path_brother);
1602 result->data = para_malloc(sizeof(path_brother));
1603 result->size = sizeof(path_brother);
1604 *(struct osl_row **)(result->data) = path_brother;
1608 static int hash_sister_callback(const struct osl_object *query,
1609 struct osl_object *result)
1611 HASH_TYPE *hash = query->data;
1612 struct osl_row *hash_sister;
1614 hash_sister = find_hash_sister(hash);
1616 return -E_RB_KEY_NOT_FOUND;
1617 result->data = para_malloc(sizeof(hash_sister));
1618 result->size = sizeof(hash_sister);
1619 *(struct osl_row **)(result->data) = hash_sister;
1623 static int add_one_audio_file(const char *path, const void *private_data)
1626 uint8_t format_num = -1;
1627 const struct private_add_data *pad = private_data;
1628 struct afh_info afhi, *afhi_ptr = NULL;
1629 struct osl_row *pb = NULL, *hs = NULL; /* path brother/hash sister */
1630 struct osl_object map, obj = {.data = NULL}, query, result = {.data = NULL};
1631 HASH_TYPE hash[HASH_SIZE];
1633 afhi.header_offset = 0;
1634 afhi.header_len = 0;
1635 ret = guess_audio_format(path);
1636 if (ret < 0 && !(pad->flags & ADD_FLAG_ALL))
1638 query.data = (char *)path;
1639 query.size = strlen(path) + 1;
1640 ret = send_callback_request(path_brother_callback, &query, &result);
1641 if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
1644 pb = *(struct osl_row **)result.data;
1648 if (pb && (pad->flags & ADD_FLAG_LAZY)) { /* lazy is really cheap */
1649 if (pad->flags & ADD_FLAG_VERBOSE)
1650 ret = send_va_buffer(pad->fd, "lazy-ignore: %s\n", path);
1653 /* We still want to add this file. Compute its hash. */
1654 ret = mmap_full_file(path, O_RDONLY, &map.data, &map.size, NULL);
1657 hash_function(map.data, map.size, hash);
1659 /* Check whether database contains file with the same hash. */
1661 query.size = HASH_SIZE;
1662 ret = send_callback_request(hash_sister_callback, &query, &result);
1663 if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
1666 hs = *(struct osl_row **)result.data;
1669 /* Return success if we already know this file. */
1671 if (pb && hs && hs == pb && (!(pad->flags & ADD_FLAG_FORCE))) {
1672 if (pad->flags & ADD_FLAG_VERBOSE)
1673 ret = send_va_buffer(pad->fd,
1674 "%s exists, not forcing update\n", path);
1678 * we won't recalculate the audio format info and the chunk table if
1679 * there is a hash sister unless in FORCE mode.
1681 if (!hs || (pad->flags & ADD_FLAG_FORCE)) {
1682 ret = compute_afhi(path, map.data, map.size, &afhi);
1688 if (pad->flags & ADD_FLAG_VERBOSE) {
1689 ret = send_va_buffer(pad->fd, "adding %s\n", path);
1693 munmap(map.data, map.size);
1694 save_audio_file_info(hash, path, afhi_ptr, pad->flags, format_num, &obj);
1695 /* Ask afs to consider this entry for adding. */
1696 ret = send_callback_request(com_add_callback, &obj, &result);
1697 if (ret >= 0 && result.data && result.size) {
1698 ret2 = send_va_buffer(pad->fd, "%s", (char *)result.data);
1700 if (ret >= 0 && ret2 < 0)
1706 munmap(map.data, map.size);
1708 if (ret < 0 && ret != -E_SEND)
1709 send_va_buffer(pad->fd, "failed to add %s (%s)\n", path,
1710 PARA_STRERROR(-ret));
1713 free(afhi_ptr->chunk_table);
1714 /* it's not an error if not all files could be added */
1715 return ret == -E_SEND? ret : 1;
1718 int com_add(int fd, int argc, char * const * const argv)
1721 struct private_add_data pad = {.fd = fd, .flags = 0};
1722 struct stat statbuf;
1724 for (i = 1; i < argc; i++) {
1725 const char *arg = argv[i];
1728 if (!strcmp(arg, "--")) {
1732 if (!strcmp(arg, "-a")) {
1733 pad.flags |= ADD_FLAG_ALL;
1736 if (!strcmp(arg, "-l")) {
1737 pad.flags |= ADD_FLAG_LAZY;
1740 if (!strcmp(arg, "-f")) {
1741 pad.flags |= ADD_FLAG_FORCE;
1744 if (!strcmp(arg, "-v")) {
1745 pad.flags |= ADD_FLAG_VERBOSE;
1750 return -E_AFT_SYNTAX;
1751 for (; i < argc; i++) {
1753 ret = verify_path(argv[i], &path);
1755 ret = send_va_buffer(fd, "%s: %s\n", argv[i], PARA_STRERROR(-ret));
1760 ret = stat(path, &statbuf);
1762 ret = send_va_buffer(fd, "failed to stat %s (%s)\n", path,
1769 if (S_ISDIR(statbuf.st_mode))
1770 ret = for_each_file_in_dir(path, add_one_audio_file,
1773 ret = add_one_audio_file(path, &pad);
1775 send_va_buffer(fd, "%s: %s\n", path, PARA_STRERROR(-ret));
1786 * Flags used by the touch command.
1791 /** Whether the \p FNM_PATHNAME flag should be passed to fnmatch(). */
1792 TOUCH_FLAG_FNM_PATHNAME = 1,
1793 /** Activates verbose mode. */
1794 TOUCH_FLAG_VERBOSE = 2
1797 /** Options used by com_touch(). */
1798 struct com_touch_options {
1799 /** New num_played value. */
1801 /** New last played count. */
1802 int64_t last_played;
1803 /** new lyrics id. */
1805 /** new image id. */
1807 /** command line flags (see \ref touch_flags). */
1811 /** Data passed to the action handler of com_touch(). */
1812 struct touch_action_data {
1813 /** Command line options (see \ref com_touch_options). */
1814 struct com_touch_options *cto;
1815 /** Message buffer. */
1816 struct para_buffer pb;
1819 static int touch_audio_file(__a_unused struct osl_table *table,
1820 struct osl_row *row, const char *name, void *data)
1822 struct touch_action_data *tad = data;
1823 struct osl_object obj;
1824 struct afs_info old_afsi, new_afsi;
1825 int ret, no_options = tad->cto->num_played < 0 && tad->cto->last_played < 0 &&
1826 tad->cto->lyrics_id < 0 && tad->cto->image_id < 0;
1827 struct afsi_change_event_data aced;
1829 ret = get_afsi_object_of_row(row, &obj);
1831 para_printf(&tad->pb, "%s: %s\n", name, PARA_STRERROR(-ret));
1834 ret = load_afsi(&old_afsi, &obj);
1836 para_printf(&tad->pb, "%s: %s\n", name, PARA_STRERROR(-ret));
1839 new_afsi = old_afsi;
1841 new_afsi.num_played++;
1842 new_afsi.last_played = time(NULL);
1843 if (tad->cto->flags & TOUCH_FLAG_VERBOSE)
1844 para_printf(&tad->pb, "%s: num_played = %u, "
1845 "last_played = now()\n", name,
1846 new_afsi.num_played);
1848 if (tad->cto->flags & TOUCH_FLAG_VERBOSE)
1849 para_printf(&tad->pb, "touching %s\n", name);
1850 if (tad->cto->lyrics_id >= 0)
1851 new_afsi.lyrics_id = tad->cto->lyrics_id;
1852 if (tad->cto->image_id >= 0)
1853 new_afsi.image_id = tad->cto->image_id;
1854 if (tad->cto->num_played >= 0)
1855 new_afsi.num_played = tad->cto->num_played;
1856 if (tad->cto->last_played >= 0)
1857 new_afsi.last_played = tad->cto->last_played;
1859 save_afsi(&new_afsi, &obj); /* in-place update */
1861 aced.old_afsi = &old_afsi;
1862 afs_event(AFSI_CHANGE, &tad->pb, &aced);
1866 static int com_touch_callback(const struct osl_object *query,
1867 struct osl_object *result)
1869 struct touch_action_data tad = {.cto = query->data};
1871 struct pattern_match_data pmd = {
1872 .table = audio_file_table,
1873 .loop_col_num = AFTCOL_HASH,
1874 .match_col_num = AFTCOL_PATH,
1875 .patterns = {.data = (char *)query->data + sizeof(*tad.cto),
1876 .size = query->size - sizeof(*tad.cto)},
1878 .action = touch_audio_file
1880 if (tad.cto->flags & TOUCH_FLAG_FNM_PATHNAME)
1881 pmd.fnmatch_flags |= FNM_PATHNAME;
1882 ret = for_each_matching_row(&pmd);
1884 para_printf(&tad.pb, "%s\n", PARA_STRERROR(-ret));
1886 result->data = tad.pb.buf;
1887 result->size = tad.pb.size;
1890 return ret < 0? ret : 0;
1893 int com_touch(int fd, int argc, char * const * const argv)
1895 struct com_touch_options cto = {
1901 struct osl_object query = {.data = &cto, .size = sizeof(cto)},
1906 for (i = 1; i < argc; i++) {
1907 const char *arg = argv[i];
1910 if (!strcmp(arg, "--")) {
1914 if (!strncmp(arg, "-n", 2)) {
1915 ret = para_atoi32(arg + 2, &cto.num_played);
1920 if (!strncmp(arg, "-l", 2)) {
1921 ret = para_atoi64(arg + 2, &cto.last_played);
1926 if (!strncmp(arg, "-y", 2)) {
1927 ret = para_atoi32(arg + 2, &cto.lyrics_id);
1932 if (!strncmp(arg, "-i", 2)) {
1933 ret = para_atoi32(arg + 2, &cto.image_id);
1938 if (!strcmp(arg, "-p")) {
1939 cto.flags |= TOUCH_FLAG_FNM_PATHNAME;
1942 if (!strcmp(arg, "-v")) {
1943 cto.flags |= TOUCH_FLAG_VERBOSE;
1946 break; /* non-option starting with dash */
1949 return -E_AFT_SYNTAX;
1950 ret = send_option_arg_callback_request(&query, argc - i,
1951 argv + i, com_touch_callback, &result);
1953 send_buffer(fd, (char *)result.data);
1956 send_va_buffer(fd, "%s\n", PARA_STRERROR(-ret));
1960 /** Flags for com_rm(). */
1963 RM_FLAG_VERBOSE = 1,
1967 RM_FLAG_FNM_PATHNAME = 4
1970 /** Data passed to the action handler of com_rm(). */
1971 struct com_rm_action_data {
1972 /** Command line flags ((see \ref rm_flags). */
1974 /** Message buffer. */
1975 struct para_buffer pb;
1976 /** Number of audio files removed. */
1977 unsigned num_removed;
1980 static int remove_audio_file(__a_unused struct osl_table *table,
1981 struct osl_row *row, const char *name, void *data)
1983 struct com_rm_action_data *crd = data;
1986 if (crd->flags & RM_FLAG_VERBOSE)
1987 para_printf(&crd->pb, "removing %s\n", name);
1988 afs_event(AUDIO_FILE_REMOVE, &crd->pb, row);
1989 ret = osl_del_row(audio_file_table, row);
1991 para_printf(&crd->pb, "%s: %s\n", name, PARA_STRERROR(-ret));
1997 static int com_rm_callback(const struct osl_object *query,
1998 __a_unused struct osl_object *result)
2000 struct com_rm_action_data crd = {.flags = *(uint32_t *)query->data};
2002 struct pattern_match_data pmd = {
2003 .table = audio_file_table,
2004 .loop_col_num = AFTCOL_HASH,
2005 .match_col_num = AFTCOL_PATH,
2006 .patterns = {.data = (char *)query->data + sizeof(uint32_t),
2007 .size = query->size - sizeof(uint32_t)},
2009 .action = remove_audio_file
2011 if (crd.flags & RM_FLAG_FNM_PATHNAME)
2012 pmd.fnmatch_flags |= FNM_PATHNAME;
2013 ret = for_each_matching_row(&pmd);
2015 para_printf(&crd.pb, "%s\n", PARA_STRERROR(-ret));
2016 if (!crd.num_removed && !(crd.flags & RM_FLAG_FORCE))
2017 para_printf(&crd.pb, "no matches -- nothing removed\n");
2019 if (crd.flags & RM_FLAG_VERBOSE)
2020 para_printf(&crd.pb, "removed %u files\n", crd.num_removed);
2023 result->data = crd.pb.buf;
2024 result->size = crd.pb.size;
2027 return ret < 0? ret : 0;
2030 /* TODO options: -r (recursive) */
2031 int com_rm(int fd, int argc, char * const * const argv)
2034 struct osl_object query = {.data = &flags, .size = sizeof(flags)},
2038 for (i = 1; i < argc; i++) {
2039 const char *arg = argv[i];
2042 if (!strcmp(arg, "--")) {
2046 if (!strcmp(arg, "-f")) {
2047 flags |= RM_FLAG_FORCE;
2050 if (!strcmp(arg, "-p")) {
2051 flags |= RM_FLAG_FNM_PATHNAME;
2054 if (!strcmp(arg, "-v")) {
2055 flags |= RM_FLAG_VERBOSE;
2061 return -E_AFT_SYNTAX;
2062 ret = send_option_arg_callback_request(&query, argc - i, argv + i,
2063 com_rm_callback, &result);
2065 send_buffer(fd, (char *)result.data);
2068 send_va_buffer(fd, "%s\n", PARA_STRERROR(-ret));
2073 * Flags used by the cpsi command.
2078 /** Whether the lyrics id should be copied. */
2079 CPSI_FLAG_COPY_LYRICS_ID = 1,
2080 /** Whether the image id should be copied. */
2081 CPSI_FLAG_COPY_IMAGE_ID = 2,
2082 /** Whether the lastplayed time should be copied. */
2083 CPSI_FLAG_COPY_LASTPLAYED = 4,
2084 /** Whether the numplayed count should be copied. */
2085 CPSI_FLAG_COPY_NUMPLAYED = 8,
2086 /** Whether the attributes should be copied. */
2087 CPSI_FLAG_COPY_ATTRIBUTES = 16,
2088 /** Activates verbose mode. */
2089 CPSI_FLAG_VERBOSE = 32,
2092 /** Data passed to the action handler of com_cpsi(). */
2093 struct cpsi_action_data {
2094 /** command line flags (see \ref cpsi_flags). */
2096 /** Number of audio files changed. */
2097 unsigned num_copied;
2098 /** Message buffer. */
2099 struct para_buffer pb;
2100 /** Values are copied from here. */
2101 struct afs_info source_afsi;
2104 static int copy_selector_info(__a_unused struct osl_table *table,
2105 struct osl_row *row, const char *name, void *data)
2107 struct cpsi_action_data *cad = data;
2108 struct osl_object target_afsi_obj;
2110 struct afs_info old_afsi, target_afsi;
2111 struct afsi_change_event_data aced;
2113 ret = get_afsi_object_of_row(row, &target_afsi_obj);
2116 load_afsi(&target_afsi, &target_afsi_obj);
2117 old_afsi = target_afsi;
2118 if (cad->flags & CPSI_FLAG_COPY_LYRICS_ID)
2119 target_afsi.lyrics_id = cad->source_afsi.lyrics_id;
2120 if (cad->flags & CPSI_FLAG_COPY_IMAGE_ID)
2121 target_afsi.image_id = cad->source_afsi.image_id;
2122 if (cad->flags & CPSI_FLAG_COPY_LASTPLAYED)
2123 target_afsi.last_played = cad->source_afsi.last_played;
2124 if (cad->flags & CPSI_FLAG_COPY_NUMPLAYED)
2125 target_afsi.num_played = cad->source_afsi.num_played;
2126 if (cad->flags & CPSI_FLAG_COPY_ATTRIBUTES)
2127 target_afsi.attributes = cad->source_afsi.attributes;
2128 save_afsi(&target_afsi, &target_afsi_obj); /* in-place update */
2130 if (cad->flags & CPSI_FLAG_VERBOSE)
2131 para_printf(&cad->pb, "copied afsi to %s\n", name);
2133 aced.old_afsi = &old_afsi;
2134 afs_event(AFSI_CHANGE, &cad->pb, &aced);
2138 static int com_cpsi_callback(const struct osl_object *query,
2139 struct osl_object *result)
2141 struct cpsi_action_data cad = {.flags = *(unsigned *)query->data};
2143 char *source_path = (char *)query->data + sizeof(cad.flags);
2145 ret = get_afsi_of_path(source_path, &cad.source_afsi);
2148 struct pattern_match_data pmd = {
2149 .table = audio_file_table,
2150 .loop_col_num = AFTCOL_HASH,
2151 .match_col_num = AFTCOL_PATH,
2152 .patterns = {.data = source_path + strlen(source_path) + 1,
2153 .size = query->size - sizeof(cad.flags)
2154 - strlen(source_path) - 1},
2156 .action = copy_selector_info
2158 ret = for_each_matching_row(&pmd);
2161 para_printf(&cad.pb, "%s\n", PARA_STRERROR(-ret));
2162 if (cad.flags & CPSI_FLAG_VERBOSE) {
2164 para_printf(&cad.pb, "copied requested afsi from %s "
2166 source_path, cad.num_copied);
2168 para_printf(&cad.pb, "nothing copied\n");
2171 result->data = cad.pb.buf;
2172 result->size = cad.pb.size;
2175 return ret < 0? ret : 0;
2178 int com_cpsi(int fd, int argc, char * const * const argv)
2182 struct osl_object options = {.data = &flags, .size = sizeof(flags)},
2185 for (i = 1; i < argc; i++) {
2186 const char *arg = argv[i];
2189 if (!strcmp(arg, "--")) {
2193 if (!strcmp(arg, "-y")) {
2194 flags |= CPSI_FLAG_COPY_LYRICS_ID;
2197 if (!strcmp(arg, "-i")) {
2198 flags |= CPSI_FLAG_COPY_IMAGE_ID;
2201 if (!strcmp(arg, "-l")) {
2202 flags |= CPSI_FLAG_COPY_LASTPLAYED;
2205 if (!strcmp(arg, "-n")) {
2206 flags |= CPSI_FLAG_COPY_NUMPLAYED;
2209 if (!strcmp(arg, "-a")) {
2210 flags |= CPSI_FLAG_COPY_ATTRIBUTES;
2213 if (!strcmp(arg, "-v")) {
2214 flags |= CPSI_FLAG_VERBOSE;
2219 if (i + 1 >= argc) /* need at least souce file and pattern */
2220 return -E_AFT_SYNTAX;
2221 if (!(flags & ~CPSI_FLAG_VERBOSE)) /* no copy flags given */
2222 flags = ~(unsigned)CPSI_FLAG_VERBOSE | flags;
2223 ret = send_option_arg_callback_request(&options, argc - i, argv + i,
2224 com_cpsi_callback, &result);
2226 send_buffer(fd, (char *)result.data);
2229 send_va_buffer(fd, "%s\n", PARA_STRERROR(-ret));
2233 /* TODO: optionally fix problems by removing offending rows */
2234 static int check_audio_file(struct osl_row *row, void *data)
2237 struct para_buffer *pb = data;
2238 struct stat statbuf;
2239 int ret = get_audio_file_path_of_row(row, &path);
2240 struct afs_info afsi;
2244 para_printf(pb, "%s\n", PARA_STRERROR(-ret));
2247 if (stat(path, &statbuf) < 0)
2248 para_printf(pb, "%s: stat error (%s)\n", path, strerror(errno));
2250 if (!S_ISREG(statbuf.st_mode))
2251 para_printf(pb, "%s: not a regular file\n", path);
2253 ret = get_afsi_of_row(row, &afsi);
2255 para_printf(pb, "%s: %s\n", path, PARA_STRERROR(-ret));
2258 ret = lyr_get_name_by_id(afsi.lyrics_id, &blob_name);
2260 para_printf(pb, "%s lyrics id %u: %s\n", path, afsi.lyrics_id,
2261 PARA_STRERROR(-ret));
2262 ret = img_get_name_by_id(afsi.image_id, &blob_name);
2264 para_printf(pb, "%s image id %u: %s\n", path, afsi.image_id,
2265 PARA_STRERROR(-ret));
2270 * Check the audio file table for inconsistencies.
2272 * \param query Unused.
2273 * \param result Contains message string upon return.
2275 * This function always succeeds.
2279 int aft_check_callback(__a_unused const struct osl_object *query, struct osl_object *result)
2281 struct para_buffer pb = {.buf = NULL};
2283 para_printf(&pb, "checking audio file table...\n");
2284 audio_file_loop(&pb, check_audio_file);
2285 result->data = pb.buf;
2286 result->size = pb.size;
2292 * Close the audio file table.
2294 * \param flags Usual flags that are passed to osl_close_table().
2296 * \sa osl_close_table().
2298 static void aft_close(void)
2300 osl_close_table(audio_file_table, OSL_MARK_CLEAN);
2301 audio_file_table = NULL;
2305 * Open the audio file table.
2307 * \param dir The database directory.
2311 * \sa osl_open_table().
2313 static int aft_open(const char *dir)
2317 audio_file_table_desc.dir = dir;
2318 ret = osl_open_table(&audio_file_table_desc, &audio_file_table);
2321 osl_get_num_rows(audio_file_table, &num);
2322 PARA_INFO_LOG("audio file table contains %d files\n", num);
2325 PARA_INFO_LOG("failed to open audio file table\n");
2326 audio_file_table = NULL;
2327 if (ret >= 0 || is_errno(-ret, ENOENT))
2332 static int aft_create(const char *dir)
2334 audio_file_table_desc.dir = dir;
2335 return osl_create_table(&audio_file_table_desc);
2338 static int clear_attribute(struct osl_row *row, void *data)
2340 struct rmatt_event_data *red = data;
2341 struct afs_info afsi;
2342 struct osl_object obj;
2343 int ret = get_afsi_object_of_row(row, &obj);
2344 uint64_t mask = ~(1ULL << red->bitnum);
2348 ret = load_afsi(&afsi, &obj);
2351 afsi.attributes &= mask;
2352 save_afsi(&afsi, &obj);
2356 static int aft_event_handler(enum afs_events event, struct para_buffer *pb,
2360 case ATTRIBUTE_REMOVE: {
2361 const struct rmatt_event_data *red = data;
2362 para_printf(pb, "clearing attribute %s (bit %u) from all "
2363 "entries in the audio file table\n", red->name,
2365 return audio_file_loop(data, clear_attribute);
2372 void aft_init(struct afs_table *t)
2374 t->name = audio_file_table_desc.name;
2376 t->close = aft_close;
2377 t->create = aft_create;
2378 t->event_handler = aft_event_handler;