1 /* Copyright (C) 2007 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
3 /** \file aft.c Audio file table functions. */
12 #include "server_cmd.lsg.h"
21 #include "portable_io.h"
25 /* Data about one audio file. Needed for ls and stat output. */
27 /* Usual audio format handler information. */
29 /* Audio file selector information. */
31 /* The full path of the audio file. */
33 /* The score value (if -a was given). */
35 /* The hash value of the audio file data. */
40 * The internal state of the audio file table is described by the following
41 * variables which are private to aft.c.
43 static struct osl_table *audio_file_table; /* NULL if table not open */
44 static struct osl_row *current_aft_row; /* NULL if no audio file open */
45 static unsigned char current_hash[HASH_SIZE]; /* only used on sighup */
47 static char *status_items;
48 static char *parser_friendly_status_items;
49 static struct ls_data status_item_ls_data;
51 /** The different sorting methods of the ls command. */
52 enum ls_sorting_method {
58 LS_SORT_BY_LAST_PLAYED,
60 LS_SORT_BY_NUM_PLAYED,
74 LS_SORT_BY_AUDIO_FORMAT,
79 /** The different listing modes of the ls command. */
80 enum ls_listing_mode {
81 /** Default listing mode. */
96 * The size of the individual output fields of the ls command.
98 * These depend on the content being listed. For example, if each listed file
99 * is shorter than an hour, the duration format is set to mm:ss. Otherwise it
100 * is set to hh:mm:ss.
103 /** size of the score field. */
104 unsigned short score_width;
105 /** size of the image id field. */
106 unsigned short image_id_width;
107 /** size of the lyrics id field. */
108 unsigned short lyrics_id_width;
109 /** size of the bitrate field. */
110 unsigned short bitrate_width;
111 /** size of the frequency field. */
112 unsigned short frequency_width;
113 /** size of the duration field. */
114 unsigned short duration_width;
115 /** size of the num played field. */
116 unsigned short num_played_width;
117 /** size of the amp field. */
118 unsigned short amp_width;
119 /** size of the audio format field. */
120 unsigned short audio_format_width;
123 /** Data passed from the ls command handler to its callback function. */
125 struct lls_parse_result *lpr;
126 /* Derived from lpr */
127 enum ls_sorting_method sorting;
128 /* Derived from lpr */
129 enum ls_listing_mode mode;
130 /** Used for long listing mode to align the output fields. */
131 struct ls_widths widths;
132 /** Size of the \a data array. */
134 /** Number of used entries in the data array. */
135 uint32_t num_matching_paths;
136 /** Array of matching entries. */
137 struct ls_data *data;
138 /** Used to sort the array. */
139 struct ls_data **data_ptr;
143 * Describes the layout of the mmapped-afs info struct.
145 * \sa struct \ref afs_info.
148 /** Where .last_played is stored. */
149 AFSI_LAST_PLAYED_OFFSET = 0,
150 /** Storage position of the attributes bitmap. */
151 AFSI_ATTRIBUTES_OFFSET = 8,
152 /** Storage position of the .num_played field. */
153 AFSI_NUM_PLAYED_OFFSET = 16,
154 /** Storage position of the .image_id field. */
155 AFSI_IMAGE_ID_OFFSET = 20,
156 /** Storage position of the .lyrics_id field. */
157 AFSI_LYRICS_ID_OFFSET = 24,
158 /** Storage position of the .audio_format_id field. */
159 AFSI_AUDIO_FORMAT_ID_OFFSET = 28,
160 /** Storage position of the amplification field. */
161 AFSI_AMP_OFFSET = 29,
162 /** 2 bytes reserved space for future usage. */
163 AFSI_AUDIO_FORMAT_UNUSED_OFFSET = 30,
164 /** On-disk storage space needed. */
169 * Convert a struct afs_info to an osl object.
171 * \param afsi Pointer to the audio file info to be converted.
172 * \param obj Result pointer.
174 * \sa \ref load_afsi().
176 static void save_afsi(struct afs_info *afsi, struct osl_object *obj)
178 char *buf = obj->data;
180 write_u64(buf + AFSI_LAST_PLAYED_OFFSET, afsi->last_played);
181 write_u64(buf + AFSI_ATTRIBUTES_OFFSET, afsi->attributes);
182 write_u32(buf + AFSI_NUM_PLAYED_OFFSET, afsi->num_played);
183 write_u32(buf + AFSI_IMAGE_ID_OFFSET, afsi->image_id);
184 write_u32(buf + AFSI_LYRICS_ID_OFFSET, afsi->lyrics_id);
185 write_u8(buf + AFSI_AUDIO_FORMAT_ID_OFFSET,
186 afsi->audio_format_id);
187 write_u8(buf + AFSI_AMP_OFFSET, afsi->amp);
188 memset(buf + AFSI_AUDIO_FORMAT_UNUSED_OFFSET, 0, 2);
192 * Get the audio file selector info struct stored in an osl object.
194 * \param afsi Points to the audio_file info structure to be filled in.
195 * \param obj The osl object holding the data.
199 * \sa \ref save_afsi().
201 static int load_afsi(struct afs_info *afsi, struct osl_object *obj)
203 char *buf = obj->data;
204 if (obj->size < AFSI_SIZE)
206 afsi->last_played = read_u64(buf + AFSI_LAST_PLAYED_OFFSET);
207 afsi->attributes = read_u64(buf + AFSI_ATTRIBUTES_OFFSET);
208 afsi->num_played = read_u32(buf + AFSI_NUM_PLAYED_OFFSET);
209 afsi->image_id = read_u32(buf + AFSI_IMAGE_ID_OFFSET);
210 afsi->lyrics_id = read_u32(buf + AFSI_LYRICS_ID_OFFSET);
211 afsi->audio_format_id = read_u8(buf +
212 AFSI_AUDIO_FORMAT_ID_OFFSET);
213 afsi->amp = read_u8(buf + AFSI_AMP_OFFSET);
217 /** The columns of the audio file table. */
218 enum audio_file_table_columns {
219 /** The hash on the content of the audio file. */
221 /** The full path in the filesystem. */
223 /** The audio file selector info. */
225 /** The audio format handler info. */
227 /** The chunk table info and the chunk table of the audio file. */
229 /** The number of columns of this table. */
233 /* compare function for the hash column */
234 static int aft_hash_compare(const struct osl_object *obj1,
235 const struct osl_object *obj2)
237 return hash_compare((unsigned char *)obj1->data,
238 (unsigned char *)obj2->data);
241 static struct osl_column_description aft_cols[] = {
243 .storage_type = OSL_MAPPED_STORAGE,
244 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE | OSL_UNIQUE,
246 .compare_function = aft_hash_compare,
247 .data_size = HASH_SIZE
250 .storage_type = OSL_MAPPED_STORAGE,
251 .storage_flags = OSL_RBTREE | OSL_UNIQUE,
253 .compare_function = string_compare,
256 .storage_type = OSL_MAPPED_STORAGE,
257 .storage_flags = OSL_FIXED_SIZE,
259 .data_size = AFSI_SIZE
262 .storage_type = OSL_MAPPED_STORAGE,
266 .storage_type = OSL_DISK_STORAGE,
271 static struct osl_table_description audio_file_table_desc = {
272 .name = "audio_files",
273 .num_columns = NUM_AFT_COLUMNS,
274 .flags = OSL_LARGE_TABLE,
275 .column_descriptions = aft_cols
279 * Produce a canonicalized absolute pathname.
281 * Returns one if the resolved path a directory, zero if it is a regular file,
282 * negative on errors.
284 static int verify_path(const char *orig_path, char **resolved_path)
290 if (*orig_path != '/') /* we only accept absolute paths */
292 path = realpath(orig_path, NULL);
295 if (stat(path, &statbuf) < 0)
297 if (S_ISREG(statbuf.st_mode))
299 else if (S_ISDIR(statbuf.st_mode))
303 *resolved_path = path;
306 *resolved_path = NULL;
311 /** The on-disk layout of a afhi struct. */
313 /** Where the number of seconds is stored. */
314 AFHI_SECONDS_TOTAL_OFFSET = 0,
315 /** Position of the bitrate. */
316 AFHI_BITRATE_OFFSET = 4,
317 /** Position of the frequency. */
318 AFHI_FREQUENCY_OFFSET = 8,
319 /** Was: Location of the audio file header. */
320 AFHI_UNUSED1_OFFSET = 12,
321 /* Length of the audio file header. Zero means: No header. */
322 AFHI_HEADER_LEN_OFFSET = 16,
323 /** The total number of chunks (4 bytes). */
324 CHUNKS_TOTAL_OFFSET = 20,
325 /** The length of the audio file header (4 bytes). */
326 HEADER_LEN_OFFSET = 24,
327 /** Size of the largest chunk in bytes. (4 bytes). */
328 AFHI_MAX_CHUNK_SIZE_OFFSET = 28,
329 /** The seconds part of the chunk time (4 bytes). */
330 CHUNK_TV_TV_SEC_OFFSET = 32,
331 /** The microseconds part of the chunk time (4 bytes). */
332 CHUNK_TV_TV_USEC_OFFSET = 36,
333 /** Number of channels is stored here. (1 byte) */
334 AFHI_CHANNELS_OFFSET = 40,
335 /** The tag info position. */
336 AFHI_INFO_STRING_OFFSET = 41,
337 /** Minimal on-disk size of a valid afhi struct. */
338 MIN_AFHI_SIZE = 47, /* at least 6 null bytes for techinfo/tags */
341 static unsigned sizeof_afhi_buf(const struct afh_info *afhi)
346 + strlen(afhi->techinfo)
347 + strlen(afhi->tags.artist)
348 + strlen(afhi->tags.title)
349 + strlen(afhi->tags.year)
350 + strlen(afhi->tags.album)
351 + strlen(afhi->tags.comment);
354 static void save_afhi(struct afh_info *afhi, char *buf)
360 write_u32(buf + AFHI_SECONDS_TOTAL_OFFSET, afhi->seconds_total);
361 write_u32(buf + AFHI_BITRATE_OFFSET, afhi->bitrate);
362 write_u32(buf + AFHI_FREQUENCY_OFFSET, afhi->frequency);
363 write_u32(buf + AFHI_UNUSED1_OFFSET, 0);
364 write_u32(buf + AFHI_HEADER_LEN_OFFSET, afhi->header_len);
365 write_u8(buf + AFHI_CHANNELS_OFFSET, afhi->channels);
366 write_u32(buf + CHUNKS_TOTAL_OFFSET, afhi->chunks_total);
367 write_u32(buf + HEADER_LEN_OFFSET, afhi->header_len);
368 write_u32(buf + AFHI_MAX_CHUNK_SIZE_OFFSET, afhi->max_chunk_size);
369 write_u32(buf + CHUNK_TV_TV_SEC_OFFSET, afhi->chunk_tv.tv_sec);
370 write_u32(buf + CHUNK_TV_TV_USEC_OFFSET, afhi->chunk_tv.tv_usec);
371 p = buf + AFHI_INFO_STRING_OFFSET;
373 * The below sprintf(3) calls are OK because our caller already made
374 * sure that buf is large enough.
376 p += sprintf(p, "%s", afhi->techinfo) + 1;
377 p += sprintf(p, "%s", afhi->tags.artist) + 1;
378 p += sprintf(p, "%s", afhi->tags.title) + 1;
379 p += sprintf(p, "%s", afhi->tags.year) + 1;
380 p += sprintf(p, "%s", afhi->tags.album) + 1;
381 sprintf(p, "%s", afhi->tags.comment);
384 /* does not load the chunk table */
385 static void load_afhi(const char *buf, struct afh_info *afhi)
387 afhi->seconds_total = read_u32(buf + AFHI_SECONDS_TOTAL_OFFSET);
388 afhi->bitrate = read_u32(buf + AFHI_BITRATE_OFFSET);
389 afhi->frequency = read_u32(buf + AFHI_FREQUENCY_OFFSET);
390 afhi->header_len = read_u32(buf + AFHI_HEADER_LEN_OFFSET);
391 afhi->channels = read_u8(buf + AFHI_CHANNELS_OFFSET);
392 afhi->chunks_total = read_u32(buf + CHUNKS_TOTAL_OFFSET);
393 afhi->header_len = read_u32(buf + HEADER_LEN_OFFSET);
394 afhi->max_chunk_size = read_u32(buf + AFHI_MAX_CHUNK_SIZE_OFFSET);
395 afhi->chunk_tv.tv_sec = read_u32(buf + CHUNK_TV_TV_SEC_OFFSET);
396 afhi->chunk_tv.tv_usec = read_u32(buf + CHUNK_TV_TV_USEC_OFFSET);
397 afhi->techinfo = (char *)buf + AFHI_INFO_STRING_OFFSET;
398 afhi->tags.artist = afhi->techinfo + strlen(afhi->techinfo) + 1;
399 afhi->tags.title = afhi->tags.artist + strlen(afhi->tags.artist) + 1;
400 afhi->tags.year = afhi->tags.title + strlen(afhi->tags.title) + 1;
401 afhi->tags.album = afhi->tags.year + strlen(afhi->tags.year) + 1;
402 afhi->tags.comment = afhi->tags.album + strlen(afhi->tags.album) + 1;
405 /* Only used for saving the chunk table, but not for loading. */
406 static unsigned sizeof_chunk_table(struct afh_info *afhi)
408 if (!afhi || !afhi->chunk_table)
410 return 4 * (afhi->chunks_total + 1);
413 static void save_chunk_table(struct afh_info *afhi, char *buf)
417 if (!afhi->chunk_table)
419 for (n = 0; n <= afhi->chunks_total; n++)
420 write_u32(buf + 4 * n, afhi->chunk_table[n]);
423 static void load_chunk_table(struct afh_info *afhi, const struct osl_object *ct)
428 if (!ct->data || ct->size < 4) {
429 afhi->chunk_table = NULL;
432 sz = PARA_MIN(((size_t)afhi->chunks_total + 1) * 4, ct->size) + 1;
433 afhi->chunk_table = para_malloc(sz);
434 for (i = 0; i <= afhi->chunks_total && i * 4 + 3 < ct->size; i++)
435 afhi->chunk_table[i] = read_u32(ct->data + 4 * i);
439 * Get the row of the audio file table corresponding to the given path.
441 * \param path The full path of the audio file.
442 * \param row Result pointer.
446 int aft_get_row_of_path(const char *path, struct osl_row **row)
448 struct osl_object obj = {.data = (char *)path, .size = strlen(path) + 1};
450 return osl(osl_get_row(audio_file_table, AFTCOL_PATH, &obj, row));
454 * Get the row of the audio file table corresponding to the given hash value.
456 * \param hash The hash value of the desired audio file.
457 * \param row Result pointer.
461 static int aft_get_row_of_hash(unsigned char *hash, struct osl_row **row)
463 const struct osl_object obj = {.data = hash, .size = HASH_SIZE};
464 return osl(osl_get_row(audio_file_table, AFTCOL_HASH, &obj, row));
468 * Get the audio file selector info object of a row.
470 * \param row Pointer to a row in the audio file table.
471 * \param obj Result pointer.
475 static int get_afsi_object_of_row(const struct osl_row *row,
476 struct osl_object *obj)
478 return osl(osl_get_object(audio_file_table, row, AFTCOL_AFSI, obj));
482 * Get the osl object holding the audio file selector info, given a path.
485 * \param path The full path of the audio file.
486 * \param obj Result pointer.
488 * \return Positive on success, negative on errors.
490 static int get_afsi_object_of_path(const char *path, struct osl_object *obj)
493 int ret = aft_get_row_of_path(path, &row);
496 return get_afsi_object_of_row(row, obj);
500 * Get the audio file selector info, given a row of the audio file table.
502 * \param row Pointer to a row in the audio file table.
503 * \param afsi Result pointer.
505 * \return Positive on success, negative on errors.
507 int get_afsi_of_row(const struct osl_row *row, struct afs_info *afsi)
509 struct osl_object obj;
510 int ret = get_afsi_object_of_row(row, &obj);
513 return load_afsi(afsi, &obj);
517 * Get the audio file selector info, given the path of an audio table.
519 * \param path The full path of the audio file.
520 * \param afsi Result pointer.
524 static int get_afsi_of_path(const char *path, struct afs_info *afsi)
526 struct osl_object obj;
527 int ret = get_afsi_object_of_path(path, &obj);
530 return load_afsi(afsi, &obj);
534 * Get the path of an audio file, given a row of the audio file table.
536 * \param row Pointer to a row in the audio file table.
537 * \param path Result pointer.
539 * The result is a pointer to memory-mapped data. The caller must not attempt
544 int get_audio_file_path_of_row(const struct osl_row *row, char **path)
546 struct osl_object path_obj;
547 int ret = osl(osl_get_object(audio_file_table, row, AFTCOL_PATH,
553 *path = path_obj.data;
558 * Get the object containing the hash value of an audio file, given a row.
560 * \param row Pointer to a row of the audio file table.
561 * \param obj Result pointer.
563 * \return The return value of the underlying call to osl_get_object().
565 * \sa \ref get_hash_of_row().
567 static int get_hash_object_of_aft_row(const struct osl_row *row,
568 struct osl_object *obj)
570 return osl(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, unsigned char **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 * After the call the members of the afhi structure point to mapped memory
604 * which is owned by the osl table, Hence the caller must not attempt to free
605 * this memory by calling \ref clear_afhi().
607 int get_afhi_of_row(const struct osl_row *row, struct afh_info *afhi)
609 struct osl_object obj;
610 int ret = osl(osl_get_object(audio_file_table, row, AFTCOL_AFHI,
614 load_afhi(obj.data, afhi);
618 /* returns shmid on success */
619 static int save_afd(struct audio_file_data *afd)
621 size_t size = sizeof(*afd) + sizeof_chunk_table(&afd->afhi);
622 int shmid, ret = shm_new(size);
629 ret = shm_attach(shmid, ATTACH_RW, &shm_afd);
634 save_chunk_table(&afd->afhi, buf);
635 if (afd->afhi.max_chunk_size == 0) { /* v0.5.x on-disk afhi */
636 set_max_chunk_size(&afd->afhi);
637 PARA_NOTICE_LOG("max chunk size unset, re-add required\n");
639 PARA_INFO_LOG("using max chunk size from afhi\n");
640 afd->max_chunk_size = afd->afhi.max_chunk_size;
641 *(struct audio_file_data *)shm_afd = *afd;
650 * Extract a afd stored in a shared memory area.
652 * Attach the shared memory area given by \a shmid, load the audio file data
653 * stored therein and detach the area afterwards. Called by vss, after
654 * receiving a positive response to the request for the next audio file.
656 * \param shmid The identifier of the shared memory area containing the afd.
657 * \param afd Result pointer.
661 int load_afd(int shmid, struct audio_file_data *afd)
665 struct osl_object obj;
667 ret = shm_attach(shmid, ATTACH_RO, &shm_afd);
670 ret = shm_size(shmid, &obj.size);
673 *afd = *(struct audio_file_data *)shm_afd;
674 obj.data = shm_afd + sizeof(*afd);
675 obj.size -= sizeof(*afd);
676 load_chunk_table(&afd->afhi, &obj);
683 static int get_local_time(uint64_t *seconds, char *buf, size_t size,
684 time_t current_time, enum ls_listing_mode lm)
688 * Omit year but show time if the given value is closer to the current
689 * time than this many seconds.
691 const time_t m = 6 * 30 * 24 * 3600; /* six months */
693 tm = localtime((time_t *)seconds);
696 if (lm == LS_MODE_MBOX) {
697 if (!strftime(buf, size, "%c", tm))
701 if (*seconds > current_time - m && *seconds < current_time + m) {
702 if (!strftime(buf, size, "%b %e %k:%M", tm))
707 * If the given time is more than six month away from the current time,
708 * we print only the year. The additional space character in the format
709 * string below makes the formatted date align nicely with dates that
710 * contain the time (those written by the above strftime() statement).
712 if (!strftime(buf, size, "%b %e %Y", tm))
717 /** Compute the number of (decimal) digits of a number. */
718 #define GET_NUM_DIGITS(x, num) { \
719 typeof((x)) _tmp = PARA_ABS(x); \
722 while ((_tmp) > 9) { \
728 __a_const static short unsigned get_duration_width(int seconds)
730 short unsigned width;
731 unsigned hours = seconds / 3600, mins = (seconds % 3600) / 60;
733 if (!hours) /* less than one hour => m:ss or mm:ss => 4 or 5 digits */
734 return 4 + (mins > 9);
735 /* more than one hour => h:mm:ss, hh:mm:ss, hhh:mm:ss, ... */
736 GET_NUM_DIGITS(hours, &width);
740 static void get_duration_buf(int seconds, char *buf, struct ls_options *opts)
742 unsigned hours = seconds / 3600, mins = (seconds % 3600) / 60;
743 short unsigned max_width;
745 if (!hours) { /* m:ss or mm:ss */
746 max_width = opts->mode == LS_MODE_LONG?
747 opts->widths.duration_width : 4;
748 sprintf(buf, "%*u:%02d", max_width - 3, mins, seconds % 60);
749 } else { /* more than one hour => h:mm:ss, hh:mm:ss, hhh:mm:ss, ... */
750 max_width = opts->mode == LS_MODE_LONG?
751 opts->widths.duration_width : 7;
752 sprintf(buf, "%*u:%02u:%02d", max_width - 6, hours, mins,
757 static int write_attribute_items(struct para_buffer *b,
758 const char *att_bitmap, struct afs_info *afsi)
763 WRITE_STATUS_ITEM(b, SI_attributes_bitmap, "%s\n", att_bitmap);
764 ret = get_attribute_text(&afsi->attributes, " ", &att_text);
767 WRITE_STATUS_ITEM(b, SI_attributes_txt, "%s\n", att_text);
772 static void write_lyrics_items(struct para_buffer *b, struct afs_info *afsi)
776 WRITE_STATUS_ITEM(b, SI_lyrics_id, "%u\n", afsi->lyrics_id);
777 lyr_get_name_by_id(afsi->lyrics_id, &lyrics_name);
778 WRITE_STATUS_ITEM(b, SI_lyrics_name, "%s\n", lyrics_name?
779 lyrics_name : "(none)");
782 static void write_image_items(struct para_buffer *b, struct afs_info *afsi)
786 WRITE_STATUS_ITEM(b, SI_image_id, "%u\n", afsi->image_id);
787 img_get_name_by_id(afsi->image_id, &image_name);
788 WRITE_STATUS_ITEM(b, SI_image_name, "%s\n", image_name?
789 image_name : "(none)");
792 static void write_filename_items(struct para_buffer *b, const char *path,
798 WRITE_STATUS_ITEM(b, SI_basename, "%s\n", path);
801 WRITE_STATUS_ITEM(b, SI_path, "%s\n", path);
802 val = para_basename(path);
803 WRITE_STATUS_ITEM(b, SI_basename, "%s\n", val? val : "");
804 val = para_dirname(path);
805 WRITE_STATUS_ITEM(b, SI_directory, "%s\n", val? val : "");
809 static int print_chunk_table(struct ls_data *d, struct para_buffer *b)
811 struct osl_object chunk_table_obj;
812 struct osl_row *aft_row;
816 ret = aft_get_row_of_hash(d->hash, &aft_row);
819 ret = osl(osl_open_disk_object(audio_file_table, aft_row,
820 AFTCOL_CHUNKS, &chunk_table_obj));
823 para_printf(b, "%s\n"
824 "chunk_time: %lu:%lu\nchunk_offsets: ",
826 (long unsigned) d->afhi.chunk_tv.tv_sec,
827 (long unsigned) d->afhi.chunk_tv.tv_usec
829 buf = chunk_table_obj.data;
832 i <= d->afhi.chunks_total && 4 * i + 3 < chunk_table_obj.size;
835 para_printf(b, "%u ", (unsigned) read_u32(buf + 4 * i));
836 para_printf(b, "\n");
838 osl_close_disk_object(&chunk_table_obj);
842 static int print_list_item(struct ls_data *d, struct ls_options *opts,
843 struct para_buffer *b, time_t current_time)
845 const struct lls_opt_result *r_a = SERVER_CMD_OPT_RESULT(LS, ADMISSIBLE, opts->lpr);
846 const struct lls_opt_result *r_b = SERVER_CMD_OPT_RESULT(LS, BASENAME, opts->lpr);
847 const struct lls_opt_result *r_d = SERVER_CMD_OPT_RESULT(LS, UNIX_DATE, opts->lpr);
850 char last_played_time[30];
851 char duration_buf[30]; /* nobody has an audio file long enough to overflow this */
852 struct afs_info *afsi = &d->afsi;
853 struct afh_info *afhi = &d->afhi;
854 char asc_hash[2 * HASH_SIZE + 1];
856 if (opts->mode == LS_MODE_SHORT) {
857 para_printf(b, "%s\n", d->path);
861 if (opts->mode == LS_MODE_CHUNKS) {
862 ret = print_chunk_table(d, b);
865 get_attribute_bitmap(&afsi->attributes, att_buf);
866 if (lls_opt_given(r_d))
867 sprintf(last_played_time, "%llu",
868 (long long unsigned)afsi->last_played);
870 ret = get_local_time(&afsi->last_played, last_played_time,
871 sizeof(last_played_time), current_time, opts->mode);
875 get_duration_buf(afhi->seconds_total, duration_buf, opts);
876 if (opts->mode == LS_MODE_LONG) {
877 struct ls_widths *w = &opts->widths;
878 if (lls_opt_given(r_a))
879 para_printf(b, "%*li ", opts->widths.score_width,
882 "%s " /* attributes */
884 "%*u " /* image_id */
885 "%*u " /* lyrics_id */
887 "%*s " /* audio format */
888 "%*u " /* frequency */
891 "%*u " /* num_played */
892 "%s " /* last_played */
895 w->amp_width, afsi->amp,
896 w->image_id_width, afsi->image_id,
897 w->lyrics_id_width, afsi->lyrics_id,
898 w->bitrate_width, afhi->bitrate,
899 w->audio_format_width,
900 audio_format_name(afsi->audio_format_id),
901 w->frequency_width, afhi->frequency,
904 w->num_played_width, afsi->num_played,
911 if (opts->mode == LS_MODE_MBOX) {
912 const char *bn = para_basename(d->path);
914 "From foo@localhost %s\n"
915 "Received: from\nTo: bar\nFrom: a\n"
920 write_filename_items(b, d->path, lls_opt_given(r_b));
921 if (lls_opt_given(r_a))
922 WRITE_STATUS_ITEM(b, SI_score, "%li\n", d->score);
923 ret = write_attribute_items(b, att_buf, afsi);
926 write_image_items(b, afsi);
927 write_lyrics_items(b, afsi);
928 hash_to_asc(d->hash, asc_hash);
929 WRITE_STATUS_ITEM(b, SI_hash, "%s\n", asc_hash);
930 WRITE_STATUS_ITEM(b, SI_bitrate, "%dkbit/s\n", afhi->bitrate);
931 WRITE_STATUS_ITEM(b, SI_format, "%s\n",
932 audio_format_name(afsi->audio_format_id));
933 WRITE_STATUS_ITEM(b, SI_frequency, "%dHz\n", afhi->frequency);
934 WRITE_STATUS_ITEM(b, SI_channels, "%d\n", afhi->channels);
935 WRITE_STATUS_ITEM(b, SI_duration, "%s\n", duration_buf);
936 WRITE_STATUS_ITEM(b, SI_seconds_total, "%" PRIu32 "\n",
937 afhi->seconds_total);
938 WRITE_STATUS_ITEM(b, SI_last_played, "%s\n", last_played_time);
939 WRITE_STATUS_ITEM(b, SI_num_played, "%u\n", afsi->num_played);
940 WRITE_STATUS_ITEM(b, SI_amplification, "%u\n", afsi->amp);
941 WRITE_STATUS_ITEM(b, SI_chunk_time, "%lu\n", tv2ms(&afhi->chunk_tv));
942 WRITE_STATUS_ITEM(b, SI_num_chunks, "%" PRIu32 "\n",
944 WRITE_STATUS_ITEM(b, SI_max_chunk_size, "%" PRIu32 "\n",
945 afhi->max_chunk_size);
946 WRITE_STATUS_ITEM(b, SI_techinfo, "%s\n", afhi->techinfo);
947 WRITE_STATUS_ITEM(b, SI_artist, "%s\n", afhi->tags.artist);
948 WRITE_STATUS_ITEM(b, SI_title, "%s\n", afhi->tags.title);
949 WRITE_STATUS_ITEM(b, SI_year, "%s\n", afhi->tags.year);
950 WRITE_STATUS_ITEM(b, SI_album, "%s\n", afhi->tags.album);
951 WRITE_STATUS_ITEM(b, SI_comment, "%s\n", afhi->tags.comment);
952 if (opts->mode == LS_MODE_MBOX) {
953 struct osl_object lyrics_def;
954 lyr_get_def_by_id(afsi->lyrics_id, &lyrics_def);
955 if (lyrics_def.data) {
956 para_printf(b, "Lyrics:\n~~~~~~~\n%s",
957 (char *)lyrics_def.data);
958 osl_close_disk_object(&lyrics_def);
965 static void make_inode_status_items(struct para_buffer *pb)
967 struct stat statbuf = {.st_size = 0};
968 char *path, mtime_str[30] = "\0";
972 ret = get_audio_file_path_of_row(current_aft_row, &path);
975 ret = stat(path, &statbuf);
978 localtime_r(&statbuf.st_mtime, &mtime_tm);
979 ret = strftime(mtime_str, 29, "%b %d %Y", &mtime_tm);
980 assert(ret > 0); /* number of bytes placed in mtime_str */
982 WRITE_STATUS_ITEM(pb, SI_mtime, "%s\n", mtime_str);
983 WRITE_STATUS_ITEM(pb, SI_file_size, "%ld\n", statbuf.st_size / 1024);
986 static int make_status_items(void)
988 const struct lls_command *cmd = SERVER_CMD_CMD_PTR(LS);
989 char *argv[] = {"ls", "--admissible", "--listing-mode=verbose"};
990 struct ls_options opts = {.mode = LS_MODE_VERBOSE};
991 struct para_buffer pb = {.max_size = shm_get_shmmax() - 1};
995 if (!status_item_ls_data.path) /* no audio file open */
997 ret = lls_parse(ARRAY_SIZE(argv), argv, cmd, &opts.lpr, NULL);
1000 ret = print_list_item(&status_item_ls_data, &opts, &pb, current_time);
1003 make_inode_status_items(&pb);
1005 status_items = pb.buf;
1007 memset(&pb, 0, sizeof(pb));
1008 pb.max_size = shm_get_shmmax() - 1;
1009 pb.flags = PBF_SIZE_PREFIX;
1010 ret = print_list_item(&status_item_ls_data, &opts, &pb, current_time);
1013 status_items = NULL;
1016 make_inode_status_items(&pb);
1017 free(parser_friendly_status_items);
1018 parser_friendly_status_items = pb.buf;
1021 lls_free_parse_result(opts.lpr, cmd);
1026 * Open the audio file with highest score and set up an afd structure.
1028 * \param afd Result pointer.
1030 * On success, the numplayed field of the audio file selector info is increased
1031 * and the lastplayed time is set to the current time. Finally, the score of
1032 * the audio file is updated.
1034 * \return Positive shmid on success, negative on errors.
1036 int open_and_update_audio_file(struct audio_file_data *afd)
1038 unsigned char file_hash[HASH_SIZE];
1039 struct osl_object afsi_obj;
1040 struct afs_info new_afsi;
1042 struct afsi_change_event_data aced;
1043 struct osl_object map, chunk_table_obj;
1044 struct ls_data *d = &status_item_ls_data;
1046 ret = score_get_best(¤t_aft_row, &d->score);
1049 ret = get_hash_of_row(current_aft_row, &d->hash);
1052 ret = get_audio_file_path_of_row(current_aft_row, &d->path);
1055 PARA_NOTICE_LOG("%s\n", d->path);
1056 ret = get_afsi_object_of_row(current_aft_row, &afsi_obj);
1059 ret = load_afsi(&d->afsi, &afsi_obj);
1062 ret = get_afhi_of_row(current_aft_row, &afd->afhi);
1065 d->afhi = afd->afhi;
1066 d->afhi.chunk_table = afd->afhi.chunk_table = NULL;
1067 ret = osl(osl_open_disk_object(audio_file_table, current_aft_row,
1068 AFTCOL_CHUNKS, &chunk_table_obj));
1070 if (!afh_supports_dynamic_chunks(d->afsi.audio_format_id))
1072 PARA_INFO_LOG("no chunk table for %s\n", d->path);
1073 chunk_table_obj.data = NULL;
1074 chunk_table_obj.size = 0;
1076 PARA_INFO_LOG("chunk table: %zu bytes\n", chunk_table_obj.size);
1078 ret = mmap_full_file(d->path, O_RDONLY, &map.data, &map.size, &afd->fd);
1081 hash_function(map.data, map.size, file_hash);
1082 ret = hash_compare(file_hash, d->hash);
1083 para_munmap(map.data, map.size);
1085 ret = -E_HASH_MISMATCH;
1089 new_afsi.num_played++;
1090 new_afsi.last_played = time(NULL);
1091 save_afsi(&new_afsi, &afsi_obj); /* in-place update */
1093 afd->audio_format_id = d->afsi.audio_format_id;
1094 load_chunk_table(&afd->afhi, &chunk_table_obj);
1095 aced.aft_row = current_aft_row;
1096 aced.old_afsi = &d->afsi;
1098 * No need to update the status items as the AFSI_CHANGE event will
1101 ret = afs_event(AFSI_CHANGE, NULL, &aced);
1104 ret = save_afd(afd);
1106 free(afd->afhi.chunk_table);
1107 if (chunk_table_obj.data)
1108 osl_close_disk_object(&chunk_table_obj);
1110 PARA_ERROR_LOG("%s: %s\n", d->path, para_strerror(-ret));
1111 ret = score_delete(current_aft_row);
1118 static int ls_hash_compare(const void *a, const void *b)
1120 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1121 return memcmp(d1->hash, d2->hash, HASH_SIZE);
1124 static int ls_audio_format_compare(const void *a, const void *b)
1126 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1127 return NUM_COMPARE(d1->afsi.audio_format_id, d2->afsi.audio_format_id);
1130 static int ls_duration_compare(const void *a, const void *b)
1132 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1133 return NUM_COMPARE(d1->afhi.seconds_total, d2->afhi.seconds_total);
1136 static int ls_bitrate_compare(const void *a, const void *b)
1138 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1139 return NUM_COMPARE(d1->afhi.bitrate, d2->afhi.bitrate);
1142 static int ls_lyrics_id_compare(const void *a, const void *b)
1144 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1145 return NUM_COMPARE(d1->afsi.lyrics_id, d2->afsi.lyrics_id);
1148 static int ls_image_id_compare(const void *a, const void *b)
1150 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1151 return NUM_COMPARE(d1->afsi.image_id, d2->afsi.image_id);
1154 static int ls_channels_compare(const void *a, const void *b)
1156 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1157 return NUM_COMPARE(d1->afhi.channels, d2->afhi.channels);
1160 static int ls_frequency_compare(const void *a, const void *b)
1162 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1163 return NUM_COMPARE(d1->afhi.frequency, d2->afhi.frequency);
1166 static int ls_num_played_compare(const void *a, const void *b)
1168 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1169 return NUM_COMPARE(d1->afsi.num_played, d2->afsi.num_played);
1172 static int ls_last_played_compare(const void *a, const void *b)
1174 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1175 return NUM_COMPARE(d1->afsi.last_played, d2->afsi.last_played);
1178 static int ls_score_compare(const void *a, const void *b)
1180 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1181 return NUM_COMPARE(d1->score, d2->score);
1184 static int ls_path_compare(const void *a, const void *b)
1186 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1187 return strcmp(d1->path, d2->path);
1190 static inline bool admissible_only(struct ls_options *opts)
1192 return SERVER_CMD_OPT_GIVEN(LS, ADMISSIBLE, opts->lpr)
1193 || opts->sorting == LS_SORT_BY_SCORE;
1196 static int sort_matching_paths(struct ls_options *options)
1198 const struct lls_opt_result *r_b = SERVER_CMD_OPT_RESULT(LS, BASENAME,
1200 size_t nmemb = options->num_matching_paths;
1201 size_t size = sizeof(*options->data_ptr);
1202 int (*compar)(const void *, const void *);
1205 options->data_ptr = para_malloc(nmemb * sizeof(*options->data_ptr));
1206 for (i = 0; i < nmemb; i++)
1207 options->data_ptr[i] = options->data + i;
1209 /* In these cases the array is already sorted */
1210 if (admissible_only(options)) {
1211 if (options->sorting == LS_SORT_BY_SCORE)
1214 if (options->sorting == LS_SORT_BY_PATH && !lls_opt_given(r_b))
1218 switch (options->sorting) {
1219 case LS_SORT_BY_PATH:
1220 compar = ls_path_compare; break;
1221 case LS_SORT_BY_SCORE:
1222 compar = ls_score_compare; break;
1223 case LS_SORT_BY_LAST_PLAYED:
1224 compar = ls_last_played_compare; break;
1225 case LS_SORT_BY_NUM_PLAYED:
1226 compar = ls_num_played_compare; break;
1227 case LS_SORT_BY_FREQUENCY:
1228 compar = ls_frequency_compare; break;
1229 case LS_SORT_BY_CHANNELS:
1230 compar = ls_channels_compare; break;
1231 case LS_SORT_BY_IMAGE_ID:
1232 compar = ls_image_id_compare; break;
1233 case LS_SORT_BY_LYRICS_ID:
1234 compar = ls_lyrics_id_compare; break;
1235 case LS_SORT_BY_BITRATE:
1236 compar = ls_bitrate_compare; break;
1237 case LS_SORT_BY_DURATION:
1238 compar = ls_duration_compare; break;
1239 case LS_SORT_BY_AUDIO_FORMAT:
1240 compar = ls_audio_format_compare; break;
1241 case LS_SORT_BY_HASH:
1242 compar = ls_hash_compare; break;
1246 qsort(options->data_ptr, nmemb, size, compar);
1250 /* row is either an aft_row or a row of the score table */
1251 /* TODO: Only compute widths if we need them */
1252 static int prepare_ls_row(struct osl_row *row, void *ls_opts)
1255 struct ls_options *options = ls_opts;
1256 bool basename_given = SERVER_CMD_OPT_GIVEN(LS, BASENAME, options->lpr);
1258 struct ls_widths *w;
1259 unsigned short num_digits;
1260 unsigned tmp, num_inputs;
1261 struct osl_row *aft_row;
1265 if (admissible_only(options)) {
1266 ret = get_score_and_aft_row(row, &score, &aft_row);
1273 ret = get_audio_file_path_of_row(aft_row, &path);
1276 if (basename_given) {
1277 char *p = strrchr(path, '/');
1281 num_inputs = lls_num_inputs(options->lpr);
1282 if (num_inputs > 0) {
1283 for (i = 0; i < num_inputs; i++) {
1284 ret = fnmatch(lls_input(i, options->lpr), path, 0);
1287 if (ret == FNM_NOMATCH)
1291 if (i >= num_inputs) /* no match */
1294 tmp = options->num_matching_paths++;
1295 if (options->num_matching_paths > options->array_size) {
1296 options->array_size++;
1297 options->array_size *= 2;
1298 options->data = para_realloc(options->data, options->array_size
1299 * sizeof(*options->data));
1301 d = options->data + tmp;
1302 ret = get_afsi_of_row(aft_row, &d->afsi);
1305 ret = get_afhi_of_row(aft_row, &d->afhi);
1309 ret = get_hash_of_row(aft_row, &d->hash);
1312 w = &options->widths;
1313 GET_NUM_DIGITS(d->afsi.image_id, &num_digits);
1314 w->image_id_width = PARA_MAX(w->image_id_width, num_digits);
1315 GET_NUM_DIGITS(d->afsi.lyrics_id, &num_digits);
1316 w->lyrics_id_width = PARA_MAX(w->lyrics_id_width, num_digits);
1317 GET_NUM_DIGITS(d->afhi.bitrate, &num_digits);
1318 w->bitrate_width = PARA_MAX(w->bitrate_width, num_digits);
1319 GET_NUM_DIGITS(d->afhi.frequency, &num_digits);
1320 w->frequency_width = PARA_MAX(w->frequency_width, num_digits);
1321 GET_NUM_DIGITS(d->afsi.num_played, &num_digits);
1322 w->num_played_width = PARA_MAX(w->num_played_width, num_digits);
1323 /* get the number of chars to print this amount of time */
1324 num_digits = get_duration_width(d->afhi.seconds_total);
1325 w->duration_width = PARA_MAX(w->duration_width, num_digits);
1326 GET_NUM_DIGITS(d->afsi.amp, &num_digits);
1327 w->amp_width = PARA_MAX(w->amp_width, num_digits);
1328 num_digits = strlen(audio_format_name(d->afsi.audio_format_id));
1329 w->audio_format_width = PARA_MAX(w->audio_format_width, num_digits);
1330 if (admissible_only(options)) {
1331 GET_NUM_DIGITS(score, &num_digits);
1332 num_digits++; /* add one for the sign (space or "-") */
1333 w->score_width = PARA_MAX(w->score_width, num_digits);
1341 static int com_ls_callback(struct afs_callback_arg *aca)
1343 const struct lls_command *cmd = SERVER_CMD_CMD_PTR(LS);
1344 struct ls_options *opts = aca->query.data;
1346 time_t current_time;
1347 const struct lls_opt_result *r_r;
1349 ret = lls_deserialize_parse_result(
1350 (char *)aca->query.data + sizeof(*opts), cmd, &opts->lpr);
1352 r_r = SERVER_CMD_OPT_RESULT(LS, REVERSE, opts->lpr);
1354 aca->pbout.flags = (opts->mode == LS_MODE_PARSER)? PBF_SIZE_PREFIX : 0;
1355 if (admissible_only(opts))
1356 ret = admissible_file_loop(opts, prepare_ls_row);
1358 ret = osl(osl_rbtree_loop(audio_file_table, AFTCOL_PATH, opts,
1362 if (opts->num_matching_paths == 0) {
1363 ret = lls_num_inputs(opts->lpr) > 0? -E_NO_MATCH : 0;
1366 ret = sort_matching_paths(opts);
1369 time(¤t_time);
1370 if (lls_opt_given(r_r))
1371 for (i = opts->num_matching_paths - 1; i >= 0; i--) {
1372 ret = print_list_item(opts->data_ptr[i], opts,
1373 &aca->pbout, current_time);
1378 for (i = 0; i < opts->num_matching_paths; i++) {
1379 ret = print_list_item(opts->data_ptr[i], opts,
1380 &aca->pbout, current_time);
1385 lls_free_parse_result(opts->lpr, cmd);
1387 free(opts->data_ptr);
1391 static int com_ls(struct command_context *cc, struct lls_parse_result *lpr)
1393 const struct lls_command *cmd = SERVER_CMD_CMD_PTR(LS);
1394 struct ls_options *opts;
1395 struct osl_object query;
1396 const struct lls_opt_result *r_l = SERVER_CMD_OPT_RESULT(LS, LISTING_MODE,
1398 const struct lls_opt_result *r_s = SERVER_CMD_OPT_RESULT(LS, SORT, lpr);
1402 ret = lls_serialize_parse_result(lpr, cmd, NULL, &query.size);
1404 query.size += sizeof(*opts);
1405 query.data = para_malloc(query.size);
1407 memset(opts, 0, sizeof(*opts));
1408 slpr = query.data + sizeof(*opts);
1409 ret = lls_serialize_parse_result(lpr, cmd, &slpr, NULL);
1411 opts->mode = LS_MODE_SHORT;
1412 opts->sorting = LS_SORT_BY_PATH;
1413 if (lls_opt_given(r_l)) {
1414 const char *val = lls_string_val(0, r_l);
1415 if (!strcmp(val, "l") || !strcmp(val, "long"))
1416 opts->mode = LS_MODE_LONG;
1417 else if (!strcmp(val, "s") || !strcmp(val, "short"))
1418 opts->mode = LS_MODE_SHORT;
1419 else if (!strcmp(val, "v") || !strcmp(val, "verbose"))
1420 opts->mode = LS_MODE_VERBOSE;
1421 else if (!strcmp(val, "m") || !strcmp(val, "mbox"))
1422 opts->mode = LS_MODE_MBOX;
1423 else if (!strcmp(val, "c") || !strcmp(val, "chunk-table"))
1424 opts->mode = LS_MODE_MBOX;
1425 else if (!strcmp(val, "p") || !strcmp(val, "parser-friendly"))
1426 opts->mode = LS_MODE_PARSER;
1428 ret = -E_AFT_SYNTAX;
1432 if (lls_opt_given(r_s)) {
1433 const char *val = lls_string_val(0, r_s);
1434 if (!strcmp(val, "p") || !strcmp(val, "path"))
1435 opts->sorting = LS_SORT_BY_PATH;
1436 else if (!strcmp(val, "s") || !strcmp(val, "score"))
1437 opts->sorting = LS_SORT_BY_SCORE;
1438 else if (!strcmp(val, "l") || !strcmp(val, "lastplayed"))
1439 opts->sorting = LS_SORT_BY_LAST_PLAYED;
1440 else if (!strcmp(val, "n") || !strcmp(val, "numplayed"))
1441 opts->sorting = LS_SORT_BY_NUM_PLAYED;
1442 else if (!strcmp(val, "f") || !strcmp(val, "frquency"))
1443 opts->sorting = LS_SORT_BY_FREQUENCY;
1444 else if (!strcmp(val, "c") || !strcmp(val, "channels"))
1445 opts->sorting = LS_SORT_BY_CHANNELS;
1446 else if (!strcmp(val, "i") || !strcmp(val, "image-id"))
1447 opts->sorting = LS_SORT_BY_IMAGE_ID;
1448 else if (!strcmp(val, "y") || !strcmp(val, "lyrics-id"))
1449 opts->sorting = LS_SORT_BY_LYRICS_ID;
1450 else if (!strcmp(val, "b") || !strcmp(val, "bitrate"))
1451 opts->sorting = LS_SORT_BY_BITRATE;
1452 else if (!strcmp(val, "d") || !strcmp(val, "duration"))
1453 opts->sorting = LS_SORT_BY_DURATION;
1454 else if (!strcmp(val, "a") || !strcmp(val, "audio-format"))
1455 opts->sorting = LS_SORT_BY_AUDIO_FORMAT;
1456 else if (!strcmp(val, "h") || !strcmp(val, "hash"))
1457 opts->sorting = LS_SORT_BY_HASH;
1459 ret = -E_AFT_SYNTAX;
1463 ret = send_callback_request(com_ls_callback, &query,
1464 afs_cb_result_handler, cc);
1469 EXPORT_SERVER_CMD_HANDLER(ls);
1472 * Call the given function for each file in the audio file table.
1474 * \param private_data An arbitrary data pointer, passed to \a func.
1475 * \param func The custom function to be called.
1479 int audio_file_loop(void *private_data, osl_rbtree_loop_func *func)
1481 return osl(osl_rbtree_loop(audio_file_table, AFTCOL_HASH, private_data,
1485 static int find_hash_sister(unsigned char *hash, struct osl_row **result)
1487 int ret = aft_get_row_of_hash(hash, result);
1489 if (ret == -OSL_ERRNO_TO_PARA_ERROR(E_OSL_RB_KEY_NOT_FOUND))
1494 static int find_path_brother(const char *path, struct osl_row **result)
1496 int ret = aft_get_row_of_path(path, result);
1498 if (ret == -OSL_ERRNO_TO_PARA_ERROR(E_OSL_RB_KEY_NOT_FOUND))
1503 /** The format of the data stored by save_audio_file_data(). */
1504 enum com_add_buffer_offsets {
1505 /* afhi (if present) starts at this offset. */
1506 CAB_AFHI_OFFSET_POS = 0,
1507 /** Start of the chunk table (if present). */
1508 CAB_CHUNKS_OFFSET_POS = 4,
1509 /** Start of the (serialized) lopsub parse result. */
1511 /** Audio format id. */
1512 CAB_AUDIO_FORMAT_ID_OFFSET = 12,
1513 /** The hash of the audio file being added. */
1514 CAB_HASH_OFFSET = 13,
1515 /** Start of the path of the audio file. */
1516 CAB_PATH_OFFSET = (CAB_HASH_OFFSET + HASH_SIZE),
1520 * Store the given data to a single buffer. Doesn't need the audio file selector
1521 * info struct as the server knows it as well.
1523 * It's OK to call this with afhi == NULL. In this case, the audio format
1524 * handler info won't be stored in the buffer.
1526 static void save_add_callback_buffer(unsigned char *hash, const char *path,
1527 struct afh_info *afhi, const char *slpr, size_t slpr_size,
1528 uint8_t audio_format_num, struct osl_object *obj)
1530 size_t path_len = strlen(path) + 1;
1531 size_t afhi_size = sizeof_afhi_buf(afhi);
1532 size_t size = CAB_PATH_OFFSET + path_len + afhi_size
1533 + sizeof_chunk_table(afhi) + slpr_size;
1534 char *buf = para_malloc(size);
1537 assert(size <= ~(uint32_t)0);
1538 write_u8(buf + CAB_AUDIO_FORMAT_ID_OFFSET, audio_format_num);
1539 memcpy(buf + CAB_HASH_OFFSET, hash, HASH_SIZE);
1540 strcpy(buf + CAB_PATH_OFFSET, path);
1541 pos = CAB_PATH_OFFSET + path_len;
1542 write_u32(buf + CAB_AFHI_OFFSET_POS, pos);
1543 save_afhi(afhi, buf + pos);
1545 write_u32(buf + CAB_CHUNKS_OFFSET_POS, pos);
1547 save_chunk_table(afhi, buf + pos);
1548 pos += sizeof_chunk_table(afhi);
1550 write_u32(buf + CAB_LPR_OFFSET, pos);
1551 memcpy(buf + pos, slpr, slpr_size);
1552 assert(pos + slpr_size == size);
1559 Overview of the add command.
1561 Input: What was passed to the callback by the command handler.
1563 HS: Hash sister. Whether an audio file with identical hash
1564 already exists in the osl database.
1566 PB: Path brother. Whether a file with the given path exists
1569 F: Force flag given. Whether add was called with -f.
1571 output: Action performed by the callback.
1573 AFHI: Whether afhi and chunk table are computed and sent.
1574 ACTION: Table modifications to be done by the callback.
1576 +----+----+---+------+---------------------------------------------------+
1577 | HS | PB | F | AFHI | ACTION
1578 +----+----+---+------+---------------------------------------------------+
1579 | Y | Y | Y | Y | if HS != PB: remove PB. HS: force afhi update,
1580 | | update path, keep afsi
1581 +----+----+---+------+---------------------------------------------------+
1582 | Y | Y | N | N | if HS == PB: do not send callback request at all.
1583 | | otherwise: remove PB, HS: update path, keep afhi,
1585 +----+----+---+------+---------------------------------------------------+
1586 | Y | N | Y | Y | (rename) force afhi update of HS, update path of
1588 +----+----+---+------+---------------------------------------------------+
1589 | Y | N | N | N | (file rename) update path of HS, keep afsi, afhi
1590 +----+----+---+------+---------------------------------------------------+
1591 | N | Y | Y | Y | (file change) update afhi, hash, of PB, keep afsi
1592 | | (force has no effect)
1593 +----+----+---+------+---------------------------------------------------+
1594 | N | Y | N | Y | (file change) update afhi, hash of PB, keep afsi
1595 +----+----+---+------+---------------------------------------------------+
1596 | N | N | Y | Y | (new file) create new entry (force has no effect)
1597 +----+----+---+------+---------------------------------------------------+
1598 | N | N | N | Y | (new file) create new entry
1599 +----+----+---+------+---------------------------------------------------+
1603 afhi <=> force or no HS
1608 static int com_add_callback(struct afs_callback_arg *aca)
1610 char *buf = aca->query.data, *path;
1611 struct osl_row *pb, *aft_row;
1613 struct osl_object objs[NUM_AFT_COLUMNS];
1614 unsigned char *hash;
1615 char asc[2 * HASH_SIZE + 1];
1617 char afsi_buf[AFSI_SIZE];
1618 char *slpr = buf + read_u32(buf + CAB_LPR_OFFSET);
1619 struct afs_info default_afsi = {.last_played = 0};
1620 uint16_t afhi_offset, chunks_offset;
1621 const struct lls_command *cmd = SERVER_CMD_CMD_PTR(ADD);
1622 const struct lls_opt_result *r_f, *r_v;
1624 ret = lls_deserialize_parse_result(slpr, cmd, &aca->lpr);
1626 r_f = SERVER_CMD_OPT_RESULT(ADD, FORCE, aca->lpr);
1627 r_v = SERVER_CMD_OPT_RESULT(ADD, VERBOSE, aca->lpr);
1629 hash = (unsigned char *)buf + CAB_HASH_OFFSET;
1630 hash_to_asc(hash, asc);
1631 objs[AFTCOL_HASH].data = buf + CAB_HASH_OFFSET;
1632 objs[AFTCOL_HASH].size = HASH_SIZE;
1634 path = buf + CAB_PATH_OFFSET;
1635 objs[AFTCOL_PATH].data = path;
1636 objs[AFTCOL_PATH].size = strlen(path) + 1;
1638 PARA_INFO_LOG("request to add %s\n", path);
1639 ret = find_hash_sister(hash, &hs);
1642 ret = find_path_brother(path, &pb);
1645 if (hs && pb && hs == pb && !lls_opt_given(r_f)) {
1646 if (lls_opt_given(r_v))
1647 para_printf(&aca->pbout, "ignoring duplicate\n");
1651 if (hs && hs != pb) {
1652 struct osl_object obj;
1653 if (pb) { /* hs trumps pb, remove pb */
1654 if (lls_opt_given(r_v))
1655 para_printf(&aca->pbout, "removing %s\n", path);
1656 ret = afs_event(AUDIO_FILE_REMOVE, &aca->pbout, pb);
1659 ret = osl(osl_del_row(audio_file_table, pb));
1664 /* file rename, update hs' path */
1665 if (lls_opt_given(r_v)) {
1666 ret = osl(osl_get_object(audio_file_table, hs,
1667 AFTCOL_PATH, &obj));
1670 para_printf(&aca->pbout, "renamed from %s\n",
1673 ret = osl(osl_update_object(audio_file_table, hs, AFTCOL_PATH,
1674 &objs[AFTCOL_PATH]));
1677 ret = afs_event(AUDIO_FILE_RENAME, &aca->pbout, hs);
1680 if (!lls_opt_given(r_f))
1683 /* no hs or force mode, child must have sent afhi */
1684 afhi_offset = read_u32(buf + CAB_AFHI_OFFSET_POS);
1685 chunks_offset = read_u32(buf + CAB_CHUNKS_OFFSET_POS);
1687 objs[AFTCOL_AFHI].data = buf + afhi_offset;
1688 objs[AFTCOL_AFHI].size = chunks_offset - afhi_offset;
1690 if (!objs[AFTCOL_AFHI].size) /* "impossible" */
1692 objs[AFTCOL_CHUNKS].data = buf + chunks_offset;
1693 objs[AFTCOL_CHUNKS].size = aca->query.size - chunks_offset;
1694 if (pb && !hs) { /* update pb's hash */
1695 char old_asc[2 * HASH_SIZE + 1];
1696 unsigned char *old_hash;
1697 ret = get_hash_of_row(pb, &old_hash);
1700 hash_to_asc(old_hash, old_asc);
1701 if (lls_opt_given(r_v))
1702 para_printf(&aca->pbout, "file change: %s -> %s\n",
1704 ret = osl(osl_update_object(audio_file_table, pb, AFTCOL_HASH,
1705 &objs[AFTCOL_HASH]));
1709 if (hs || pb) { /* (hs != NULL and pb != NULL) implies hs == pb */
1710 struct osl_row *row = pb? pb : hs;
1711 /* update afhi and chunk_table */
1712 if (lls_opt_given(r_v))
1713 para_printf(&aca->pbout,
1714 "updating afhi and chunk table\n");
1715 ret = osl(osl_update_object(audio_file_table, row, AFTCOL_AFHI,
1716 &objs[AFTCOL_AFHI]));
1719 /* truncate the file to size zero if there is no chunk table */
1720 ret = osl(osl_update_object(audio_file_table, row, AFTCOL_CHUNKS,
1721 &objs[AFTCOL_CHUNKS]));
1724 ret = afs_event(AFHI_CHANGE, &aca->pbout, row);
1727 /* new entry, use default afsi */
1728 if (lls_opt_given(r_v))
1729 para_printf(&aca->pbout, "new file\n");
1730 default_afsi.last_played = time(NULL) - 365 * 24 * 60 * 60;
1731 default_afsi.audio_format_id = read_u8(buf + CAB_AUDIO_FORMAT_ID_OFFSET);
1733 objs[AFTCOL_AFSI].data = &afsi_buf;
1734 objs[AFTCOL_AFSI].size = AFSI_SIZE;
1735 save_afsi(&default_afsi, &objs[AFTCOL_AFSI]);
1736 ret = osl(osl_add_and_get_row(audio_file_table, objs, &aft_row));
1739 ret = afs_event(AUDIO_FILE_ADD, &aca->pbout, aft_row);
1742 para_printf(&aca->pbout, "could not add %s\n", path);
1743 lls_free_parse_result(aca->lpr, cmd);
1747 /* Used by com_add(). */
1748 struct private_add_data {
1749 /* The pointer passed to the original command handler. */
1750 struct command_context *cc;
1751 /* Contains the flags given at the command line. */
1752 struct lls_parse_result *lpr;
1753 /* Serialized lopsub parse result. */
1755 /* Number of bytes. */
1759 static int path_brother_callback(struct afs_callback_arg *aca)
1761 char *path = aca->query.data;
1762 struct osl_row *path_brother;
1763 int ret = find_path_brother(path, &path_brother);
1766 return pass_buffer_as_shm(aca->fd, SBD_OUTPUT, (char *)&path_brother,
1767 sizeof(path_brother));
1770 static int hash_sister_callback(struct afs_callback_arg *aca)
1772 unsigned char *hash = aca->query.data;
1773 struct osl_row *hash_sister;
1774 int ret = find_hash_sister(hash, &hash_sister);
1778 return pass_buffer_as_shm(aca->fd, SBD_OUTPUT, (char *)&hash_sister,
1779 sizeof(hash_sister));
1782 static int get_row_pointer_from_result(struct osl_object *result,
1783 __a_unused uint8_t band, void *private)
1785 struct osl_row **row = private;
1787 if (band == SBD_OUTPUT)
1788 *row = *(struct osl_row **)(result->data);
1792 static int add_one_audio_file(const char *path, void *private_data)
1794 int ret, send_ret = 1, fd;
1795 uint8_t format_num = -1;
1796 struct private_add_data *pad = private_data;
1797 struct afh_info afhi, *afhi_ptr = NULL;
1798 struct osl_row *pb = NULL, *hs = NULL; /* path brother/hash sister */
1799 struct osl_object map, obj = {.data = NULL}, query;
1800 unsigned char hash[HASH_SIZE];
1801 bool a_given = SERVER_CMD_OPT_GIVEN(ADD, ALL, pad->lpr);
1802 bool f_given = SERVER_CMD_OPT_GIVEN(ADD, FORCE, pad->lpr);
1803 bool l_given = SERVER_CMD_OPT_GIVEN(ADD, LAZY, pad->lpr);
1804 bool v_given = SERVER_CMD_OPT_GIVEN(ADD, VERBOSE, pad->lpr);
1806 ret = guess_audio_format(path);
1807 if (ret < 0 && !a_given) {
1811 query.data = (char *)path;
1812 query.size = strlen(path) + 1;
1813 ret = send_callback_request(path_brother_callback, &query,
1814 get_row_pointer_from_result, &pb);
1815 if (ret < 0 && ret != -OSL_ERRNO_TO_PARA_ERROR(E_OSL_RB_KEY_NOT_FOUND))
1818 if (pb && l_given) { /* lazy is really cheap */
1820 send_ret = send_sb_va(&pad->cc->scc, SBD_OUTPUT,
1821 "lazy-ignore: %s\n", path);
1824 /* We still want to add this file. Compute its hash. */
1825 ret = mmap_full_file(path, O_RDONLY, &map.data, &map.size, &fd);
1828 hash_function(map.data, map.size, hash);
1830 /* Check whether the database contains a file with the same hash. */
1832 query.size = HASH_SIZE;
1833 ret = send_callback_request(hash_sister_callback, &query,
1834 get_row_pointer_from_result, &hs);
1837 /* Return success if we already know this file. */
1839 if (pb && hs && hs == pb && !f_given) {
1841 send_ret = send_sb_va(&pad->cc->scc, SBD_OUTPUT,
1842 "%s exists, not forcing update\n", path);
1846 * We won't recalculate the audio format info and the chunk table if
1847 * there is a hash sister and FORCE was not given.
1849 if (!hs || f_given) {
1850 ret = compute_afhi(path, map.data, map.size, fd, &afhi);
1856 munmap(map.data, map.size);
1859 send_ret = send_sb_va(&pad->cc->scc, SBD_OUTPUT,
1860 "adding %s\n", path);
1864 save_add_callback_buffer(hash, path, afhi_ptr, pad->slpr,
1865 pad->slpr_size, format_num, &obj);
1866 /* Ask afs to consider this entry for adding. */
1867 ret = send_callback_request(com_add_callback, &obj,
1868 afs_cb_result_handler, pad->cc);
1873 munmap(map.data, map.size);
1875 if (ret < 0 && send_ret >= 0)
1876 send_ret = send_sb_va(&pad->cc->scc, SBD_ERROR_LOG,
1877 "failed to add %s (%s)\n", path, para_strerror(-ret));
1879 clear_afhi(afhi_ptr);
1880 /* Stop adding files only on send errors. */
1884 static int com_add(struct command_context *cc, struct lls_parse_result *lpr)
1887 struct private_add_data pad = {.cc = cc, .lpr = lpr};
1888 const struct lls_command *cmd = SERVER_CMD_CMD_PTR(ADD);
1889 unsigned num_inputs;
1892 ret = lls(lls_check_arg_count(lpr, 1, INT_MAX, &errctx));
1894 send_errctx(cc, errctx);
1897 ret = lls_serialize_parse_result(lpr, cmd, &pad.slpr, &pad.slpr_size);
1899 num_inputs = lls_num_inputs(lpr);
1900 for (i = 0; i < num_inputs; i++) {
1902 ret = verify_path(lls_input(i, lpr), &path);
1904 ret = send_sb_va(&cc->scc, SBD_ERROR_LOG, "%s: %s\n",
1905 lls_input(i, lpr), para_strerror(-ret));
1910 if (ret == 1) /* directory */
1911 ret = for_each_file_in_dir(path, add_one_audio_file,
1913 else /* regular file */
1914 ret = add_one_audio_file(path, &pad);
1916 send_sb_va(&cc->scc, SBD_OUTPUT, "%s: %s\n", path,
1917 para_strerror(-ret));
1928 EXPORT_SERVER_CMD_HANDLER(add);
1930 /** Flags used by the touch command. */
1932 /** Whether the \p FNM_PATHNAME flag should be passed to fnmatch(). */
1933 TOUCH_FLAG_FNM_PATHNAME = 1,
1934 /** Activates verbose mode. */
1935 TOUCH_FLAG_VERBOSE = 2
1938 static int touch_audio_file(__a_unused struct osl_table *table,
1939 struct osl_row *row, const char *name, void *data)
1941 struct afs_callback_arg *aca = data;
1942 bool v_given = SERVER_CMD_OPT_GIVEN(TOUCH, VERBOSE, aca->lpr);
1943 const struct lls_opt_result *r_n, *r_l, *r_i, *r_y, *r_a;
1945 struct osl_object obj;
1946 struct afs_info old_afsi, new_afsi;
1948 struct afsi_change_event_data aced;
1950 r_n = SERVER_CMD_OPT_RESULT(TOUCH, NUMPLAYED, aca->lpr);
1951 r_l = SERVER_CMD_OPT_RESULT(TOUCH, LASTPLAYED, aca->lpr);
1952 r_i = SERVER_CMD_OPT_RESULT(TOUCH, IMAGE_ID, aca->lpr);
1953 r_y = SERVER_CMD_OPT_RESULT(TOUCH, LYRICS_ID, aca->lpr);
1954 r_a = SERVER_CMD_OPT_RESULT(TOUCH, AMP, aca->lpr);
1955 no_options = !lls_opt_given(r_n) && !lls_opt_given(r_l) && !lls_opt_given(r_i)
1956 && !lls_opt_given(r_y) && !lls_opt_given(r_a);
1958 ret = get_afsi_object_of_row(row, &obj);
1960 para_printf(&aca->pbout, "cannot touch %s\n", name);
1963 ret = load_afsi(&old_afsi, &obj);
1965 para_printf(&aca->pbout, "cannot touch %s\n", name);
1968 new_afsi = old_afsi;
1970 new_afsi.num_played++;
1971 new_afsi.last_played = time(NULL);
1973 para_printf(&aca->pbout, "%s: num_played = %u, "
1974 "last_played = now()\n", name,
1975 new_afsi.num_played);
1977 if (lls_opt_given(r_l))
1978 new_afsi.last_played = lls_uint64_val(0, r_l);
1979 if (lls_opt_given(r_n))
1980 new_afsi.num_played = lls_uint32_val(0, r_n);
1981 if (lls_opt_given(r_i))
1982 new_afsi.image_id = lls_uint32_val(0, r_i);
1983 if (lls_opt_given(r_y))
1984 new_afsi.lyrics_id = lls_uint32_val(0, r_y);
1985 if (lls_opt_given(r_a))
1986 new_afsi.amp = lls_uint32_val(0, r_a);
1988 para_printf(&aca->pbout, "touching %s\n", name);
1990 save_afsi(&new_afsi, &obj); /* in-place update */
1992 aced.old_afsi = &old_afsi;
1993 return afs_event(AFSI_CHANGE, &aca->pbout, &aced);
1996 static int com_touch_callback(struct afs_callback_arg *aca)
1998 const struct lls_command *cmd = SERVER_CMD_CMD_PTR(TOUCH);
2000 const struct lls_opt_result *r_i, *r_y;
2002 struct pattern_match_data pmd = {
2003 .table = audio_file_table,
2004 .loop_col_num = AFTCOL_HASH,
2005 .match_col_num = AFTCOL_PATH,
2007 .action = touch_audio_file
2010 ret = lls_deserialize_parse_result(aca->query.data, cmd, &aca->lpr);
2014 r_i = SERVER_CMD_OPT_RESULT(TOUCH, IMAGE_ID, aca->lpr);
2015 if (lls_opt_given(r_i)) {
2016 uint32_t id = lls_uint32_val(0, r_i);
2017 ret = img_get_name_by_id(id, NULL);
2019 para_printf(&aca->pbout, "invalid image ID: %u\n", id);
2023 r_y = SERVER_CMD_OPT_RESULT(TOUCH, LYRICS_ID, aca->lpr);
2024 if (lls_opt_given(r_y)) {
2025 uint32_t id = lls_uint32_val(0, r_y);
2026 ret = lyr_get_name_by_id(id, NULL);
2028 para_printf(&aca->pbout, "invalid lyrics ID: %u\n", id);
2032 p_given = SERVER_CMD_OPT_GIVEN(TOUCH, PATHNAME_MATCH, aca->lpr);
2034 pmd.fnmatch_flags |= FNM_PATHNAME;
2035 ret = for_each_matching_row(&pmd);
2036 if (ret >= 0 && pmd.num_matches == 0)
2038 lls_free_parse_result(aca->lpr, cmd);
2042 static int com_touch(struct command_context *cc, struct lls_parse_result *lpr)
2044 const struct lls_command *cmd = SERVER_CMD_CMD_PTR(TOUCH);
2048 ret = lls(lls_check_arg_count(lpr, 1, INT_MAX, &errctx));
2050 send_errctx(cc, errctx);
2053 return send_lls_callback_request(com_touch_callback, cmd, lpr, cc);
2055 EXPORT_SERVER_CMD_HANDLER(touch);
2057 static int remove_audio_file(__a_unused struct osl_table *table,
2058 struct osl_row *row, const char *name, void *data)
2060 struct afs_callback_arg *aca = data;
2061 bool v_given = SERVER_CMD_OPT_GIVEN(RM, VERBOSE, aca->lpr);
2065 para_printf(&aca->pbout, "removing %s\n", name);
2066 ret = afs_event(AUDIO_FILE_REMOVE, &aca->pbout, row);
2069 ret = osl(osl_del_row(audio_file_table, row));
2071 para_printf(&aca->pbout, "cannot remove %s\n", name);
2075 static int com_rm_callback(struct afs_callback_arg *aca)
2077 const struct lls_command *cmd = SERVER_CMD_CMD_PTR(RM);
2079 struct pattern_match_data pmd = {
2080 .table = audio_file_table,
2081 .loop_col_num = AFTCOL_HASH,
2082 .match_col_num = AFTCOL_PATH,
2084 .action = remove_audio_file
2086 bool v_given, p_given, f_given;
2088 ret = lls_deserialize_parse_result(aca->query.data, cmd, &aca->lpr);
2091 v_given = SERVER_CMD_OPT_GIVEN(RM, VERBOSE, aca->lpr);
2092 p_given = SERVER_CMD_OPT_GIVEN(RM, PATHNAME_MATCH, aca->lpr);
2093 f_given = SERVER_CMD_OPT_GIVEN(RM, FORCE, aca->lpr);
2096 pmd.fnmatch_flags |= FNM_PATHNAME;
2097 ret = for_each_matching_row(&pmd);
2100 if (pmd.num_matches == 0) {
2104 para_printf(&aca->pbout, "removed %u file(s)\n",
2107 lls_free_parse_result(aca->lpr, cmd);
2111 /* TODO options: -r (recursive) */
2112 static int com_rm(struct command_context *cc, struct lls_parse_result *lpr)
2114 const struct lls_command *cmd = SERVER_CMD_CMD_PTR(RM);
2118 ret = lls(lls_check_arg_count(lpr, 1, INT_MAX, &errctx));
2120 send_errctx(cc, errctx);
2123 return send_lls_callback_request(com_rm_callback, cmd, lpr, cc);
2125 EXPORT_SERVER_CMD_HANDLER(rm);
2127 /** Data passed to the action handler of com_cpsi(). */
2128 struct cpsi_action_data {
2129 /** Values are copied from here. */
2130 struct afs_info source_afsi;
2131 /** What was passed to com_cpsi_callback(). */
2132 struct afs_callback_arg *aca;
2136 static int copy_selector_info(__a_unused struct osl_table *table,
2137 struct osl_row *row, const char *name, void *data)
2139 struct cpsi_action_data *cad = data;
2140 struct osl_object target_afsi_obj;
2142 struct afs_info old_afsi, target_afsi;
2143 struct afsi_change_event_data aced;
2144 bool a_given, y_given, i_given, l_given, n_given, v_given;
2146 a_given = SERVER_CMD_OPT_GIVEN(CPSI, ATTRIBUTE_BITMAP, cad->aca->lpr);
2147 y_given = SERVER_CMD_OPT_GIVEN(CPSI, LYRICS_ID, cad->aca->lpr);
2148 i_given = SERVER_CMD_OPT_GIVEN(CPSI, IMAGE_ID, cad->aca->lpr);
2149 l_given = SERVER_CMD_OPT_GIVEN(CPSI, LASTPLAYED, cad->aca->lpr);
2150 n_given = SERVER_CMD_OPT_GIVEN(CPSI, NUMPLAYED, cad->aca->lpr);
2151 v_given = SERVER_CMD_OPT_GIVEN(CPSI, VERBOSE, cad->aca->lpr);
2153 ret = get_afsi_object_of_row(row, &target_afsi_obj);
2156 ret = load_afsi(&target_afsi, &target_afsi_obj);
2159 old_afsi = target_afsi;
2160 if (cad->copy_all || y_given)
2161 target_afsi.lyrics_id = cad->source_afsi.lyrics_id;
2162 if (cad->copy_all || i_given)
2163 target_afsi.image_id = cad->source_afsi.image_id;
2164 if (cad->copy_all || l_given)
2165 target_afsi.last_played = cad->source_afsi.last_played;
2166 if (cad->copy_all || n_given)
2167 target_afsi.num_played = cad->source_afsi.num_played;
2168 if (cad->copy_all || a_given)
2169 target_afsi.attributes = cad->source_afsi.attributes;
2170 save_afsi(&target_afsi, &target_afsi_obj); /* in-place update */
2172 para_printf(&cad->aca->pbout, "copied afsi to %s\n", name);
2174 aced.old_afsi = &old_afsi;
2175 return afs_event(AFSI_CHANGE, &cad->aca->pbout, &aced);
2178 static int com_cpsi_callback(struct afs_callback_arg *aca)
2180 const struct lls_command *cmd = SERVER_CMD_CMD_PTR(CPSI);
2181 bool a_given, y_given, i_given, l_given, n_given, v_given;
2182 struct cpsi_action_data cad = {.aca = aca};
2184 struct pattern_match_data pmd = {
2185 .table = audio_file_table,
2186 .loop_col_num = AFTCOL_HASH,
2187 .match_col_num = AFTCOL_PATH,
2188 .input_skip = 1, /* skip first argument (source file) */
2190 .action = copy_selector_info
2193 ret = lls_deserialize_parse_result(aca->query.data, cmd, &aca->lpr);
2197 a_given = SERVER_CMD_OPT_GIVEN(CPSI, ATTRIBUTE_BITMAP, aca->lpr);
2198 y_given = SERVER_CMD_OPT_GIVEN(CPSI, LYRICS_ID, aca->lpr);
2199 i_given = SERVER_CMD_OPT_GIVEN(CPSI, IMAGE_ID, aca->lpr);
2200 l_given = SERVER_CMD_OPT_GIVEN(CPSI, LASTPLAYED, aca->lpr);
2201 n_given = SERVER_CMD_OPT_GIVEN(CPSI, NUMPLAYED, aca->lpr);
2202 v_given = SERVER_CMD_OPT_GIVEN(CPSI, VERBOSE, aca->lpr);
2203 cad.copy_all = !a_given && !y_given && !i_given && !l_given && !n_given;
2205 ret = get_afsi_of_path(lls_input(0, aca->lpr), &cad.source_afsi);
2208 ret = for_each_matching_row(&pmd);
2211 if (pmd.num_matches > 0) {
2213 para_printf(&aca->pbout, "updated afsi of %u file(s)\n",
2218 lls_free_parse_result(aca->lpr, cmd);
2222 static int com_cpsi(struct command_context *cc, struct lls_parse_result *lpr)
2224 const struct lls_command *cmd = SERVER_CMD_CMD_PTR(CPSI);
2226 int ret = lls(lls_check_arg_count(lpr, 2, INT_MAX, &errctx));
2228 send_errctx(cc, errctx);
2231 return send_lls_callback_request(com_cpsi_callback, cmd, lpr, cc);
2233 EXPORT_SERVER_CMD_HANDLER(cpsi);
2235 struct change_atts_data {
2236 uint64_t add_mask, del_mask;
2237 struct afs_callback_arg *aca;
2240 static int change_atts(__a_unused struct osl_table *table,
2241 struct osl_row *row, __a_unused const char *name, void *data)
2244 struct osl_object obj;
2245 struct afs_info old_afsi, new_afsi;
2246 struct afsi_change_event_data aced = {
2248 .old_afsi = &old_afsi
2250 struct change_atts_data *cad = data;
2252 ret = get_afsi_object_of_row(row, &obj);
2255 ret = load_afsi(&old_afsi, &obj);
2258 new_afsi = old_afsi;
2259 new_afsi.attributes |= cad->add_mask;
2260 new_afsi.attributes &= ~cad->del_mask;
2261 save_afsi(&new_afsi, &obj); /* in-place update */
2262 return afs_event(AFSI_CHANGE, &cad->aca->pbout, &aced);
2265 static int com_setatt_callback(struct afs_callback_arg *aca)
2267 const struct lls_command *cmd = SERVER_CMD_CMD_PTR(SETATT);
2269 struct change_atts_data cad = {.aca = aca};
2270 struct pattern_match_data pmd = {
2271 .table = audio_file_table,
2272 .loop_col_num = AFTCOL_HASH,
2273 .match_col_num = AFTCOL_PATH,
2274 .pm_flags = PM_SKIP_EMPTY_NAME,
2276 .action = change_atts
2278 unsigned num_inputs;
2280 ret = lls_deserialize_parse_result(aca->query.data, cmd, &aca->lpr);
2284 num_inputs = lls_num_inputs(aca->lpr);
2285 for (i = 0; i < num_inputs; i++) {
2286 unsigned char bitnum;
2288 const char *arg = lls_input(i, aca->lpr);
2290 size_t len = strlen(arg);
2292 ret = -E_ATTR_SYNTAX;
2296 if (c != '+' && c != '-') {
2297 if (cad.add_mask == 0 && cad.del_mask == 0)
2298 goto out; /* no attribute modifier given */
2301 p = para_malloc(len);
2302 memcpy(p, arg, len - 1);
2304 ret = get_attribute_bitnum_by_name(p, &bitnum);
2307 para_printf(&aca->pbout, "invalid argument: %s\n", arg);
2311 cad.add_mask |= (one << bitnum);
2313 cad.del_mask |= (one << bitnum);
2315 /* no pattern given */
2316 ret = -E_ATTR_SYNTAX;
2320 ret = for_each_matching_row(&pmd);
2321 if (ret >= 0 && pmd.num_matches == 0)
2324 lls_free_parse_result(aca->lpr, cmd);
2328 static int com_setatt(struct command_context *cc, struct lls_parse_result *lpr)
2330 const struct lls_command *cmd = SERVER_CMD_CMD_PTR(SETATT);
2332 int ret = lls(lls_check_arg_count(lpr, 2, INT_MAX, &errctx));
2335 send_errctx(cc, errctx);
2338 return send_lls_callback_request(com_setatt_callback, cmd, lpr, cc);
2340 EXPORT_SERVER_CMD_HANDLER(setatt);
2342 static int afs_stat_callback(struct afs_callback_arg *aca)
2344 int *parser_friendly = aca->query.data;
2345 char *buf = *parser_friendly?
2346 parser_friendly_status_items : status_items;
2350 return pass_buffer_as_shm(aca->fd, SBD_OUTPUT, buf, strlen(buf));
2354 * Get the current afs status items from the afs process and send it.
2356 * \param cc The command context, used e.g. for data encryption.
2357 * \param parser_friendly Whether parser-friendly output format should be used.
2359 * As the contents of the afs status items change in time and the command
2360 * handler only has a COW version created at fork time, it can not send
2361 * up-to-date afs status items directly. Therefore the usual callback mechanism
2362 * is used to pass the status items from the afs process to the command handler
2363 * via a shared memory area and a pipe.
2365 * \return The return value of the underlying call to \ref send_callback_request().
2367 int send_afs_status(struct command_context *cc, int parser_friendly)
2369 struct osl_object query = {.data = &parser_friendly,
2370 .size = sizeof(parser_friendly)};
2372 return send_callback_request(afs_stat_callback, &query,
2373 afs_cb_result_handler, cc);
2376 /* returns success on non-fatal errors to keep the loop going */
2377 static int check_audio_file(struct osl_row *row, void *data)
2380 struct para_buffer *pb = data;
2381 struct stat statbuf;
2382 int ret = get_audio_file_path_of_row(row, &path);
2383 struct afs_info afsi;
2387 para_printf(pb, "%s\n", para_strerror(-ret));
2390 if (stat(path, &statbuf) < 0)
2391 para_printf(pb, "%s: stat error (%s)\n", path, strerror(errno));
2392 else if (!S_ISREG(statbuf.st_mode))
2393 para_printf(pb, "%s: not a regular file\n", path);
2394 ret = get_afsi_of_row(row, &afsi);
2396 para_printf(pb, "%s: %s\n", path, para_strerror(-ret));
2399 ret = lyr_get_name_by_id(afsi.lyrics_id, &blob_name);
2401 para_printf(pb, "%s lyrics id %u: %s\n", path, afsi.lyrics_id,
2402 para_strerror(-ret));
2403 ret = img_get_name_by_id(afsi.image_id, &blob_name);
2405 para_printf(pb, "%s image id %u: %s\n", path, afsi.image_id,
2406 para_strerror(-ret));
2411 * Check the audio file table for inconsistencies.
2413 * \param aca Only ->pbout is used for diagnostics.
2415 * \return Standard. Inconsistencies are reported but not regarded as an error.
2417 int aft_check_callback(struct afs_callback_arg *aca)
2419 para_printf(&aca->pbout, "checking audio file table...\n");
2420 return audio_file_loop(&aca->pbout, check_audio_file);
2423 struct aft_check_atts_data {
2425 struct para_buffer *pb;
2428 static int check_atts_of_audio_file(struct osl_row *row, void *data)
2430 struct aft_check_atts_data *acad = data;
2432 struct afs_info afsi;
2436 ret = get_afsi_of_row(row, &afsi);
2438 para_printf(acad->pb, "cannot get afsi\n");
2441 bad_bits = afsi.attributes & ~acad->att_mask;
2442 if (bad_bits == 0) /* OK */
2444 ret = get_audio_file_path_of_row(row, &path);
2446 para_printf(acad->pb, "cannot get path\n");
2449 para_printf(acad->pb, "invalid attribute bits (%" PRIu64 "): %s\n",
2451 /* return success to keep looping */
2456 * Iterate over all audio files and check the attribute bit mask.
2458 * \param att_mask The mask of all valid attributes.
2459 * \param pb Used for reporting inconsistencies.
2461 * This reads the attribute bit mask of each audio file from the afs info
2462 * structure stored in the audio file table and verifies that all set bits are
2463 * also turned on in \a att_mask, i.e., correspond to an attribute of the
2464 * attribute table. Audio files for which this is not the case are reported via
2467 * \return Standard. Inconsistencies are not regarded as errors.
2469 * \sa \ref attribute_check_callback().
2471 int aft_check_attributes(uint64_t att_mask, struct para_buffer *pb)
2473 struct aft_check_atts_data acad = {.att_mask = att_mask, .pb = pb};
2475 para_printf(pb, "checking attributes, mask: %" PRIx64 "\n", att_mask);
2476 return audio_file_loop(&acad, check_atts_of_audio_file);
2480 * This sets audio_file_table to NULL, but leaves current_aft_row unmodified,
2481 * though stale (pointing to unmapped memory). If the table is being closed
2482 * because we received SIGHUP, the table will be reopened after the config file
2483 * has been reloaded. We remember the hash of the current audio file here so
2484 * that aft_open() can initialize current_aft_row by looking up the saved hash.
2486 static void aft_close(void)
2491 if (current_aft_row) {
2492 ret = get_hash_of_row(current_aft_row, &p);
2494 PARA_WARNING_LOG("hash lookup failure\n");
2495 current_aft_row = NULL;
2497 memcpy(current_hash, p, HASH_SIZE);
2499 osl_close_table(audio_file_table, OSL_MARK_CLEAN);
2500 audio_file_table = NULL;
2503 static int aft_open(const char *dir)
2507 audio_file_table_desc.dir = dir;
2508 ret = osl(osl_open_table(&audio_file_table_desc, &audio_file_table));
2511 osl_get_num_rows(audio_file_table, &num);
2512 PARA_INFO_LOG("audio file table contains %u files\n", num);
2513 if (!current_aft_row) {
2514 PARA_DEBUG_LOG("no current aft row\n");
2517 /* SIGHUP case, update current_aft_row */
2518 ret = aft_get_row_of_hash(current_hash, ¤t_aft_row);
2519 if (ret < 0) { /* not fatal */
2520 PARA_WARNING_LOG("current hash lookup failure: %s\n",
2521 para_strerror(-ret));
2522 current_aft_row = NULL;
2525 PARA_NOTICE_LOG("current audio file hash lookup: success\n");
2528 PARA_NOTICE_LOG("failed to open audio file table\n");
2529 audio_file_table = NULL;
2530 if (ret == -OSL_ERRNO_TO_PARA_ERROR(E_OSL_NOENT))
2535 static int aft_create(const char *dir)
2537 audio_file_table_desc.dir = dir;
2538 return osl(osl_create_table(&audio_file_table_desc));
2541 static int clear_attribute(struct osl_row *row, void *data)
2543 struct rmatt_event_data *red = data;
2544 struct afs_info afsi;
2545 struct osl_object obj;
2546 int ret = get_afsi_object_of_row(row, &obj);
2547 uint64_t mask = ~(1ULL << red->bitnum);
2551 ret = load_afsi(&afsi, &obj);
2554 afsi.attributes &= mask;
2555 save_afsi(&afsi, &obj);
2559 static int aft_event_handler(enum afs_events event, struct para_buffer *pb,
2565 case ATTRIBUTE_REMOVE: {
2566 const struct rmatt_event_data *red = data;
2567 para_printf(pb, "clearing attribute %s (bit %u) from all "
2568 "entries in the audio file table\n", red->name,
2570 return audio_file_loop(data, clear_attribute);
2571 } case AFSI_CHANGE: {
2572 struct afsi_change_event_data *aced = data;
2573 uint64_t old_last_played = status_item_ls_data.afsi.last_played;
2574 if (aced->aft_row != current_aft_row)
2576 ret = get_afsi_of_row(aced->aft_row, &status_item_ls_data.afsi);
2579 status_item_ls_data.afsi.last_played = old_last_played;
2580 make_status_items();
2582 } case AUDIO_FILE_RENAME: {
2584 if (data != current_aft_row)
2586 ret = get_audio_file_path_of_row(current_aft_row, &path);
2589 status_item_ls_data.path = path;
2590 make_status_items();
2592 } case AFHI_CHANGE: {
2593 if (data != current_aft_row)
2595 ret = get_afhi_of_row(data, &status_item_ls_data.afhi);
2598 make_status_items();
2600 } case AUDIO_FILE_REMOVE: {
2601 if (data == current_aft_row)
2602 current_aft_row = NULL;
2609 * These events are rare. We don't bother to check whether the
2610 * current status items are affected and simply recreate them
2613 make_status_items();
2621 * Initialize the audio file table.
2623 * \param t Pointer to the structure to be initialized.
2625 void aft_init(struct afs_table *t)
2628 t->close = aft_close;
2629 t->create = aft_create;
2630 t->event_handler = aft_event_handler;