2 * Copyright (C) 2007 Andre Noll <maan@tuebingen.mpg.de>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file aft.c Audio file table functions. */
16 #include "server_cmd.lsg.h"
25 #include "portable_io.h"
29 static struct osl_table *audio_file_table;
30 static char *status_items;
31 static char *parser_friendly_status_items;
33 /** The different sorting methods of the ls command. */
34 enum ls_sorting_method {
40 LS_SORT_BY_LAST_PLAYED,
42 LS_SORT_BY_NUM_PLAYED,
56 LS_SORT_BY_AUDIO_FORMAT,
61 /** The different listing modes of the ls command. */
62 enum ls_listing_mode {
63 /** Default listing mode. */
77 /* Data about one audio file. Needed for ls and stat output. */
79 /* Usual audio format handler information. */
81 /* Audio file selector information. */
83 /* The full path of the audio file. */
85 /* The score value (if -a was given). */
87 /* The hash value of the audio file data. */
92 * The size of the individual output fields of the ls command.
94 * These depend on the content being listed. For example, if each listed file
95 * is shorter than an hour, the duration format is set to mm:ss. Otherwise it
99 /** size of the score field. */
100 unsigned short score_width;
101 /** size of the image id field. */
102 unsigned short image_id_width;
103 /** size of the lyrics id field. */
104 unsigned short lyrics_id_width;
105 /** size of the bitrate field. */
106 unsigned short bitrate_width;
107 /** size of the frequency field. */
108 unsigned short frequency_width;
109 /** size of the duration field. */
110 unsigned short duration_width;
111 /** size of the num played field. */
112 unsigned short num_played_width;
113 /** size of the amp field. */
114 unsigned short amp_width;
115 /** size of the audio format field. */
116 unsigned short audio_format_width;
119 /** Data passed from the ls command handler to its callback function. */
121 struct lls_parse_result *lpr;
122 /* Derived from lpr */
123 enum ls_sorting_method sorting;
124 /* Derived from lpr */
125 enum ls_listing_mode mode;
126 /** Used for long listing mode to align the output fields. */
127 struct ls_widths widths;
128 /** Size of the \a data array. */
130 /** Number of used entries in the data array. */
131 uint32_t num_matching_paths;
132 /** Array of matching entries. */
133 struct ls_data *data;
134 /** Used to sort the array. */
135 struct ls_data **data_ptr;
139 * Describes the layout of the mmapped-afs info struct.
141 * \sa struct \ref afs_info.
144 /** Where .last_played is stored. */
145 AFSI_LAST_PLAYED_OFFSET = 0,
146 /** Storage position of the attributes bitmap. */
147 AFSI_ATTRIBUTES_OFFSET = 8,
148 /** Storage position of the .num_played field. */
149 AFSI_NUM_PLAYED_OFFSET = 16,
150 /** Storage position of the .image_id field. */
151 AFSI_IMAGE_ID_OFFSET = 20,
152 /** Storage position of the .lyrics_id field. */
153 AFSI_LYRICS_ID_OFFSET = 24,
154 /** Storage position of the .audio_format_id field. */
155 AFSI_AUDIO_FORMAT_ID_OFFSET = 28,
156 /** Storage position of the amplification field. */
157 AFSI_AMP_OFFSET = 29,
158 /** 2 bytes reserved space for future usage. */
159 AFSI_AUDIO_FORMAT_UNUSED_OFFSET = 30,
160 /** On-disk storage space needed. */
165 * Convert a struct afs_info to an osl object.
167 * \param afsi Pointer to the audio file info to be converted.
168 * \param obj Result pointer.
170 * \sa \ref load_afsi().
172 static void save_afsi(struct afs_info *afsi, struct osl_object *obj)
174 char *buf = obj->data;
176 write_u64(buf + AFSI_LAST_PLAYED_OFFSET, afsi->last_played);
177 write_u64(buf + AFSI_ATTRIBUTES_OFFSET, afsi->attributes);
178 write_u32(buf + AFSI_NUM_PLAYED_OFFSET, afsi->num_played);
179 write_u32(buf + AFSI_IMAGE_ID_OFFSET, afsi->image_id);
180 write_u32(buf + AFSI_LYRICS_ID_OFFSET, afsi->lyrics_id);
181 write_u8(buf + AFSI_AUDIO_FORMAT_ID_OFFSET,
182 afsi->audio_format_id);
183 write_u8(buf + AFSI_AMP_OFFSET, afsi->amp);
184 memset(buf + AFSI_AUDIO_FORMAT_UNUSED_OFFSET, 0, 2);
188 * Get the audio file selector info struct stored in an osl object.
190 * \param afsi Points to the audio_file info structure to be filled in.
191 * \param obj The osl object holding the data.
195 * \sa \ref save_afsi().
197 static int load_afsi(struct afs_info *afsi, struct osl_object *obj)
199 char *buf = obj->data;
200 if (obj->size < AFSI_SIZE)
202 afsi->last_played = read_u64(buf + AFSI_LAST_PLAYED_OFFSET);
203 afsi->attributes = read_u64(buf + AFSI_ATTRIBUTES_OFFSET);
204 afsi->num_played = read_u32(buf + AFSI_NUM_PLAYED_OFFSET);
205 afsi->image_id = read_u32(buf + AFSI_IMAGE_ID_OFFSET);
206 afsi->lyrics_id = read_u32(buf + AFSI_LYRICS_ID_OFFSET);
207 afsi->audio_format_id = read_u8(buf +
208 AFSI_AUDIO_FORMAT_ID_OFFSET);
209 afsi->amp = read_u8(buf + AFSI_AMP_OFFSET);
213 /** The columns of the audio file table. */
214 enum audio_file_table_columns {
215 /** The hash on the content of the audio file. */
217 /** The full path in the filesystem. */
219 /** The audio file selector info. */
221 /** The audio format handler info. */
223 /** The chunk table info and the chunk table of the audio file. */
225 /** The number of columns of this table. */
229 /* compare function for the hash column */
230 static int aft_hash_compare(const struct osl_object *obj1,
231 const struct osl_object *obj2)
233 return hash_compare((unsigned char *)obj1->data,
234 (unsigned char *)obj2->data);
237 static struct osl_column_description aft_cols[] = {
239 .storage_type = OSL_MAPPED_STORAGE,
240 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE | OSL_UNIQUE,
242 .compare_function = aft_hash_compare,
243 .data_size = HASH_SIZE
246 .storage_type = OSL_MAPPED_STORAGE,
247 .storage_flags = OSL_RBTREE | OSL_UNIQUE,
249 .compare_function = string_compare,
252 .storage_type = OSL_MAPPED_STORAGE,
253 .storage_flags = OSL_FIXED_SIZE,
255 .data_size = AFSI_SIZE
258 .storage_type = OSL_MAPPED_STORAGE,
262 .storage_type = OSL_DISK_STORAGE,
267 static struct osl_table_description audio_file_table_desc = {
268 .name = "audio_files",
269 .num_columns = NUM_AFT_COLUMNS,
270 .flags = OSL_LARGE_TABLE,
271 .column_descriptions = aft_cols
275 * Produce a canonicalized absolute pathname.
277 * Returns one if the resolved path a directory, zero if it is a regular file,
278 * negative on errors.
280 static int verify_path(const char *orig_path, char **resolved_path)
286 if (*orig_path != '/') /* we only accept absolute paths */
288 path = realpath(orig_path, NULL);
291 if (stat(path, &statbuf) < 0)
293 if (S_ISREG(statbuf.st_mode))
295 else if (S_ISDIR(statbuf.st_mode))
299 *resolved_path = path;
302 *resolved_path = NULL;
307 /** The on-disk layout of a afhi struct. */
309 /** Where the number of seconds is stored. */
310 AFHI_SECONDS_TOTAL_OFFSET = 0,
311 /** Position of the bitrate. */
312 AFHI_BITRATE_OFFSET = 4,
313 /** Position of the frequency. */
314 AFHI_FREQUENCY_OFFSET = 8,
315 /** Was: Location of the audio file header. */
316 AFHI_UNUSED1_OFFSET = 12,
317 /* Length of the audio file header. Zero means: No header. */
318 AFHI_HEADER_LEN_OFFSET = 16,
319 /** The total number of chunks (4 bytes). */
320 CHUNKS_TOTAL_OFFSET = 20,
321 /** The length of the audio file header (4 bytes). */
322 HEADER_LEN_OFFSET = 24,
323 /** Size of the largest chunk in bytes. (4 bytes). */
324 AFHI_MAX_CHUNK_SIZE_OFFSET = 28,
325 /** The seconds part of the chunk time (4 bytes). */
326 CHUNK_TV_TV_SEC_OFFSET = 32,
327 /** The microseconds part of the chunk time (4 bytes). */
328 CHUNK_TV_TV_USEC_OFFSET = 36,
329 /** Number of channels is stored here. (1 byte) */
330 AFHI_CHANNELS_OFFSET = 40,
331 /** The tag info position. */
332 AFHI_INFO_STRING_OFFSET = 41,
333 /** Minimal on-disk size of a valid afhi struct. */
334 MIN_AFHI_SIZE = 47, /* at least 6 null bytes for techinfo/tags */
337 static unsigned sizeof_afhi_buf(const struct afh_info *afhi)
342 + strlen(afhi->techinfo)
343 + strlen(afhi->tags.artist)
344 + strlen(afhi->tags.title)
345 + strlen(afhi->tags.year)
346 + strlen(afhi->tags.album)
347 + strlen(afhi->tags.comment);
350 static void save_afhi(struct afh_info *afhi, char *buf)
356 write_u32(buf + AFHI_SECONDS_TOTAL_OFFSET, afhi->seconds_total);
357 write_u32(buf + AFHI_BITRATE_OFFSET, afhi->bitrate);
358 write_u32(buf + AFHI_FREQUENCY_OFFSET, afhi->frequency);
359 write_u32(buf + AFHI_UNUSED1_OFFSET, 0);
360 write_u32(buf + AFHI_HEADER_LEN_OFFSET, afhi->header_len);
361 write_u8(buf + AFHI_CHANNELS_OFFSET, afhi->channels);
362 write_u32(buf + CHUNKS_TOTAL_OFFSET, afhi->chunks_total);
363 write_u32(buf + HEADER_LEN_OFFSET, afhi->header_len);
364 write_u32(buf + AFHI_MAX_CHUNK_SIZE_OFFSET, afhi->max_chunk_size);
365 write_u32(buf + CHUNK_TV_TV_SEC_OFFSET, afhi->chunk_tv.tv_sec);
366 write_u32(buf + CHUNK_TV_TV_USEC_OFFSET, afhi->chunk_tv.tv_usec);
367 p = buf + AFHI_INFO_STRING_OFFSET;
369 * The below sprintf(3) calls are OK because our caller already made
370 * sure that buf is large enough.
372 p += sprintf(p, "%s", afhi->techinfo) + 1;
373 p += sprintf(p, "%s", afhi->tags.artist) + 1;
374 p += sprintf(p, "%s", afhi->tags.title) + 1;
375 p += sprintf(p, "%s", afhi->tags.year) + 1;
376 p += sprintf(p, "%s", afhi->tags.album) + 1;
377 sprintf(p, "%s", afhi->tags.comment);
380 /* does not load the chunk table */
381 static void load_afhi(const char *buf, struct afh_info *afhi)
383 afhi->seconds_total = read_u32(buf + AFHI_SECONDS_TOTAL_OFFSET);
384 afhi->bitrate = read_u32(buf + AFHI_BITRATE_OFFSET);
385 afhi->frequency = read_u32(buf + AFHI_FREQUENCY_OFFSET);
386 afhi->header_len = read_u32(buf + AFHI_HEADER_LEN_OFFSET);
387 afhi->channels = read_u8(buf + AFHI_CHANNELS_OFFSET);
388 afhi->chunks_total = read_u32(buf + CHUNKS_TOTAL_OFFSET);
389 afhi->header_len = read_u32(buf + HEADER_LEN_OFFSET);
390 afhi->max_chunk_size = read_u32(buf + AFHI_MAX_CHUNK_SIZE_OFFSET);
391 afhi->chunk_tv.tv_sec = read_u32(buf + CHUNK_TV_TV_SEC_OFFSET);
392 afhi->chunk_tv.tv_usec = read_u32(buf + CHUNK_TV_TV_USEC_OFFSET);
393 afhi->techinfo = (char *)buf + AFHI_INFO_STRING_OFFSET;
394 afhi->tags.artist = afhi->techinfo + strlen(afhi->techinfo) + 1;
395 afhi->tags.title = afhi->tags.artist + strlen(afhi->tags.artist) + 1;
396 afhi->tags.year = afhi->tags.title + strlen(afhi->tags.title) + 1;
397 afhi->tags.album = afhi->tags.year + strlen(afhi->tags.year) + 1;
398 afhi->tags.comment = afhi->tags.album + strlen(afhi->tags.album) + 1;
401 /* Only used for saving the chunk table, but not for loading. */
402 static unsigned sizeof_chunk_table(struct afh_info *afhi)
404 if (!afhi || !afhi->chunk_table)
406 return 4 * (afhi->chunks_total + 1);
409 static void save_chunk_table(struct afh_info *afhi, char *buf)
413 if (!afhi->chunk_table)
415 for (n = 0; n <= afhi->chunks_total; n++)
416 write_u32(buf + 4 * n, afhi->chunk_table[n]);
419 static void load_chunk_table(struct afh_info *afhi, const struct osl_object *ct)
424 if (!ct->data || ct->size < 4) {
425 afhi->chunk_table = NULL;
428 sz = PARA_MIN(((size_t)afhi->chunks_total + 1) * 4, ct->size) + 1;
429 afhi->chunk_table = para_malloc(sz);
430 for (i = 0; i <= afhi->chunks_total && i * 4 + 3 < ct->size; i++)
431 afhi->chunk_table[i] = read_u32(ct->data + 4 * i);
435 * Get the row of the audio file table corresponding to the given path.
437 * \param path The full path of the audio file.
438 * \param row Result pointer.
442 int aft_get_row_of_path(const char *path, struct osl_row **row)
444 struct osl_object obj = {.data = (char *)path, .size = strlen(path) + 1};
446 return osl(osl_get_row(audio_file_table, AFTCOL_PATH, &obj, row));
450 * Get the row of the audio file table corresponding to the given hash value.
452 * \param hash The hash value of the desired audio file.
453 * \param row Result pointer.
457 static int aft_get_row_of_hash(unsigned char *hash, struct osl_row **row)
459 const struct osl_object obj = {.data = hash, .size = HASH_SIZE};
460 return osl(osl_get_row(audio_file_table, AFTCOL_HASH, &obj, row));
464 * Get the audio file selector info object of a row.
466 * \param row Pointer to a row in the audio file table.
467 * \param obj Result pointer.
471 static int get_afsi_object_of_row(const struct osl_row *row,
472 struct osl_object *obj)
474 return osl(osl_get_object(audio_file_table, row, AFTCOL_AFSI, obj));
478 * Get the osl object holding the audio file selector info, given a path.
481 * \param path The full path of the audio file.
482 * \param obj Result pointer.
484 * \return Positive on success, negative on errors.
486 static int get_afsi_object_of_path(const char *path, struct osl_object *obj)
489 int ret = aft_get_row_of_path(path, &row);
492 return get_afsi_object_of_row(row, obj);
496 * Get the audio file selector info, given a row of the audio file table.
498 * \param row Pointer to a row in the audio file table.
499 * \param afsi Result pointer.
501 * \return Positive on success, negative on errors.
503 int get_afsi_of_row(const struct osl_row *row, struct afs_info *afsi)
505 struct osl_object obj;
506 int ret = get_afsi_object_of_row(row, &obj);
509 return load_afsi(afsi, &obj);
513 * Get the audio file selector info, given the path of an audio table.
515 * \param path The full path of the audio file.
516 * \param afsi Result pointer.
520 static int get_afsi_of_path(const char *path, struct afs_info *afsi)
522 struct osl_object obj;
523 int ret = get_afsi_object_of_path(path, &obj);
526 return load_afsi(afsi, &obj);
530 * Get the path of an audio file, given a row of the audio file table.
532 * \param row Pointer to a row in the audio file table.
533 * \param path Result pointer.
535 * The result is a pointer to memory-mapped data. The caller must not attempt
540 int get_audio_file_path_of_row(const struct osl_row *row, char **path)
542 struct osl_object path_obj;
543 int ret = osl(osl_get_object(audio_file_table, row, AFTCOL_PATH,
549 *path = path_obj.data;
554 * Get the object containing the hash value of an audio file, given a row.
556 * \param row Pointer to a row of the audio file table.
557 * \param obj Result pointer.
559 * \return The return value of the underlying call to osl_get_object().
561 * \sa \ref get_hash_of_row().
563 static int get_hash_object_of_aft_row(const struct osl_row *row,
564 struct osl_object *obj)
566 return osl(osl_get_object(audio_file_table, row, AFTCOL_HASH, obj));
570 * Get the hash value of an audio file, given a row of the audio file table.
572 * \param row Pointer to a row of the audio file table.
573 * \param hash Result pointer.
575 * \a hash points to mapped data and must not be freed by the caller.
577 * \return The return value of the underlying call to
578 * get_hash_object_of_aft_row().
580 static int get_hash_of_row(const struct osl_row *row, unsigned char **hash)
582 struct osl_object obj;
583 int ret = get_hash_object_of_aft_row(row, &obj);
592 * Get the audio format handler info, given a row of the audio file table.
594 * \param row Pointer to a row of the audio file table.
595 * \param afhi Result pointer.
597 * \return The return value of the underlying call to osl_get_object().
599 * After the call the members of the afhi structure point to mapped memory
600 * which is owned by the osl table, Hence the caller must not attempt to free
601 * this memory by calling \ref clear_afhi().
603 int get_afhi_of_row(const struct osl_row *row, struct afh_info *afhi)
605 struct osl_object obj;
606 int ret = osl(osl_get_object(audio_file_table, row, AFTCOL_AFHI,
610 load_afhi(obj.data, afhi);
614 /* returns shmid on success */
615 static int save_afd(struct audio_file_data *afd)
617 size_t size = sizeof(*afd) + sizeof_chunk_table(&afd->afhi);
618 int shmid, ret = shm_new(size);
625 ret = shm_attach(shmid, ATTACH_RW, &shm_afd);
630 save_chunk_table(&afd->afhi, buf);
631 if (afd->afhi.max_chunk_size == 0) { /* v0.5.x on-disk afhi */
632 set_max_chunk_size(&afd->afhi);
633 PARA_NOTICE_LOG("max chunk size unset, re-add required\n");
635 PARA_INFO_LOG("using max chunk size from afhi\n");
636 afd->max_chunk_size = afd->afhi.max_chunk_size;
637 *(struct audio_file_data *)shm_afd = *afd;
646 * Extract a afd stored in a shared memory area.
648 * Attach the shared memory area given by \a shmid, load the audio file data
649 * stored therein and detach the area afterwards. Called by vss, after
650 * receiving a positive response to the request for the next audio file.
652 * \param shmid The identifier of the shared memory area containing the afd.
653 * \param afd Result pointer.
657 int load_afd(int shmid, struct audio_file_data *afd)
661 struct osl_object obj;
663 ret = shm_attach(shmid, ATTACH_RO, &shm_afd);
666 ret = shm_size(shmid, &obj.size);
669 *afd = *(struct audio_file_data *)shm_afd;
670 obj.data = shm_afd + sizeof(*afd);
671 obj.size -= sizeof(*afd);
672 load_chunk_table(&afd->afhi, &obj);
679 static int get_local_time(uint64_t *seconds, char *buf, size_t size,
680 time_t current_time, enum ls_listing_mode lm)
684 * Omit year but show time if the given value is closer to the current
685 * time than this many seconds.
687 const time_t m = 6 * 30 * 24 * 3600; /* six months */
689 tm = localtime((time_t *)seconds);
692 if (lm == LS_MODE_MBOX) {
693 if (!strftime(buf, size, "%c", tm))
697 if (*seconds > current_time - m && *seconds < current_time + m) {
698 if (!strftime(buf, size, "%b %e %k:%M", tm))
703 * If the given time is more than six month away from the current time,
704 * we print only the year. The additional space character in the format
705 * string below makes the formatted date align nicely with dates that
706 * contain the time (those written by the above strftime() statement).
708 if (!strftime(buf, size, "%b %e %Y", tm))
713 /** Compute the number of (decimal) digits of a number. */
714 #define GET_NUM_DIGITS(x, num) { \
715 typeof((x)) _tmp = PARA_ABS(x); \
718 while ((_tmp) > 9) { \
724 __a_const static short unsigned get_duration_width(int seconds)
726 short unsigned width;
727 unsigned hours = seconds / 3600, mins = (seconds % 3600) / 60;
729 if (!hours) /* less than one hour => m:ss or mm:ss => 4 or 5 digits */
730 return 4 + (mins > 9);
731 /* more than one hour => h:mm:ss, hh:mm:ss, hhh:mm:ss, ... */
732 GET_NUM_DIGITS(hours, &width);
736 static void get_duration_buf(int seconds, char *buf, struct ls_options *opts)
738 unsigned hours = seconds / 3600, mins = (seconds % 3600) / 60;
739 short unsigned max_width;
741 if (!hours) { /* m:ss or mm:ss */
742 max_width = opts->mode == LS_MODE_LONG?
743 opts->widths.duration_width : 4;
744 sprintf(buf, "%*u:%02d", max_width - 3, mins, seconds % 60);
745 } else { /* more than one hour => h:mm:ss, hh:mm:ss, hhh:mm:ss, ... */
746 max_width = opts->mode == LS_MODE_LONG?
747 opts->widths.duration_width : 7;
748 sprintf(buf, "%*u:%02u:%02d", max_width - 6, hours, mins,
753 static int write_attribute_items(struct para_buffer *b,
754 const char *att_bitmap, struct afs_info *afsi)
759 WRITE_STATUS_ITEM(b, SI_ATTRIBUTES_BITMAP, "%s\n", att_bitmap);
760 ret = get_attribute_text(&afsi->attributes, " ", &att_text);
763 WRITE_STATUS_ITEM(b, SI_ATTRIBUTES_TXT, "%s\n", att_text);
768 static void write_lyrics_items(struct para_buffer *b, struct afs_info *afsi)
772 WRITE_STATUS_ITEM(b, SI_LYRICS_ID, "%u\n", afsi->lyrics_id);
773 lyr_get_name_by_id(afsi->lyrics_id, &lyrics_name);
774 WRITE_STATUS_ITEM(b, SI_LYRICS_NAME, "%s\n", lyrics_name?
775 lyrics_name : "(none)");
778 static void write_image_items(struct para_buffer *b, struct afs_info *afsi)
782 WRITE_STATUS_ITEM(b, SI_IMAGE_ID, "%u\n", afsi->image_id);
783 img_get_name_by_id(afsi->image_id, &image_name);
784 WRITE_STATUS_ITEM(b, SI_IMAGE_NAME, "%s\n", image_name?
785 image_name : "(none)");
788 static void write_filename_items(struct para_buffer *b, const char *path,
794 WRITE_STATUS_ITEM(b, SI_BASENAME, "%s\n", path);
797 WRITE_STATUS_ITEM(b, SI_PATH, "%s\n", path);
798 val = para_basename(path);
799 WRITE_STATUS_ITEM(b, SI_BASENAME, "%s\n", val? val : "");
800 val = para_dirname(path);
801 WRITE_STATUS_ITEM(b, SI_DIRECTORY, "%s\n", val? val : "");
805 static int print_chunk_table(struct ls_data *d, struct para_buffer *b)
807 struct osl_object chunk_table_obj;
808 struct osl_row *aft_row;
812 ret = aft_get_row_of_hash(d->hash, &aft_row);
815 ret = osl(osl_open_disk_object(audio_file_table, aft_row,
816 AFTCOL_CHUNKS, &chunk_table_obj));
819 para_printf(b, "%s\n"
820 "chunk_time: %lu:%lu\nchunk_offsets: ",
822 (long unsigned) d->afhi.chunk_tv.tv_sec,
823 (long unsigned) d->afhi.chunk_tv.tv_usec
825 buf = chunk_table_obj.data;
828 i <= d->afhi.chunks_total && 4 * i + 3 < chunk_table_obj.size;
831 para_printf(b, "%u ", (unsigned) read_u32(buf + 4 * i));
832 para_printf(b, "\n");
834 osl_close_disk_object(&chunk_table_obj);
838 static int print_list_item(struct ls_data *d, struct ls_options *opts,
839 struct para_buffer *b, time_t current_time)
841 const struct lls_opt_result *r_a = SERVER_CMD_OPT_RESULT(LS, ADMISSIBLE, opts->lpr);
842 const struct lls_opt_result *r_b = SERVER_CMD_OPT_RESULT(LS, BASENAME, opts->lpr);
843 const struct lls_opt_result *r_d = SERVER_CMD_OPT_RESULT(LS, UNIX_DATE, opts->lpr);
846 char last_played_time[30];
847 char duration_buf[30]; /* nobody has an audio file long enough to overflow this */
848 struct afs_info *afsi = &d->afsi;
849 struct afh_info *afhi = &d->afhi;
850 char asc_hash[2 * HASH_SIZE + 1];
852 if (opts->mode == LS_MODE_SHORT) {
853 para_printf(b, "%s\n", d->path);
857 if (opts->mode == LS_MODE_CHUNKS) {
858 ret = print_chunk_table(d, b);
861 get_attribute_bitmap(&afsi->attributes, att_buf);
862 if (lls_opt_given(r_d))
863 sprintf(last_played_time, "%llu",
864 (long long unsigned)afsi->last_played);
866 ret = get_local_time(&afsi->last_played, last_played_time,
867 sizeof(last_played_time), current_time, opts->mode);
871 get_duration_buf(afhi->seconds_total, duration_buf, opts);
872 if (opts->mode == LS_MODE_LONG) {
873 struct ls_widths *w = &opts->widths;
874 if (lls_opt_given(r_a))
875 para_printf(b, "%*li ", opts->widths.score_width,
878 "%s " /* attributes */
880 "%*u " /* image_id */
881 "%*u " /* lyrics_id */
883 "%*s " /* audio format */
884 "%*u " /* frequency */
887 "%*u " /* num_played */
888 "%s " /* last_played */
891 w->amp_width, afsi->amp,
892 w->image_id_width, afsi->image_id,
893 w->lyrics_id_width, afsi->lyrics_id,
894 w->bitrate_width, afhi->bitrate,
895 w->audio_format_width,
896 audio_format_name(afsi->audio_format_id),
897 w->frequency_width, afhi->frequency,
900 w->num_played_width, afsi->num_played,
907 if (opts->mode == LS_MODE_MBOX) {
908 const char *bn = para_basename(d->path);
910 "From foo@localhost %s\n"
911 "Received: from\nTo: bar\nFrom: a\n"
916 write_filename_items(b, d->path, lls_opt_given(r_b));
917 if (lls_opt_given(r_a))
918 WRITE_STATUS_ITEM(b, SI_SCORE, "%li\n", d->score);
919 ret = write_attribute_items(b, att_buf, afsi);
922 write_image_items(b, afsi);
923 write_lyrics_items(b, afsi);
924 hash_to_asc(d->hash, asc_hash);
925 WRITE_STATUS_ITEM(b, SI_HASH, "%s\n", asc_hash);
926 WRITE_STATUS_ITEM(b, SI_BITRATE, "%dkbit/s\n", afhi->bitrate);
927 WRITE_STATUS_ITEM(b, SI_FORMAT, "%s\n",
928 audio_format_name(afsi->audio_format_id));
929 WRITE_STATUS_ITEM(b, SI_FREQUENCY, "%dHz\n", afhi->frequency);
930 WRITE_STATUS_ITEM(b, SI_CHANNELS, "%d\n", afhi->channels);
931 WRITE_STATUS_ITEM(b, SI_DURATION, "%s\n", duration_buf);
932 WRITE_STATUS_ITEM(b, SI_SECONDS_TOTAL, "%" PRIu32 "\n",
933 afhi->seconds_total);
934 WRITE_STATUS_ITEM(b, SI_LAST_PLAYED, "%s\n", last_played_time);
935 WRITE_STATUS_ITEM(b, SI_NUM_PLAYED, "%u\n", afsi->num_played);
936 WRITE_STATUS_ITEM(b, SI_AMPLIFICATION, "%u\n", afsi->amp);
937 WRITE_STATUS_ITEM(b, SI_CHUNK_TIME, "%lu\n", tv2ms(&afhi->chunk_tv));
938 WRITE_STATUS_ITEM(b, SI_NUM_CHUNKS, "%" PRIu32 "\n",
940 WRITE_STATUS_ITEM(b, SI_MAX_CHUNK_SIZE, "%" PRIu32 "\n",
941 afhi->max_chunk_size);
942 WRITE_STATUS_ITEM(b, SI_TECHINFO, "%s\n", afhi->techinfo);
943 WRITE_STATUS_ITEM(b, SI_ARTIST, "%s\n", afhi->tags.artist);
944 WRITE_STATUS_ITEM(b, SI_TITLE, "%s\n", afhi->tags.title);
945 WRITE_STATUS_ITEM(b, SI_YEAR, "%s\n", afhi->tags.year);
946 WRITE_STATUS_ITEM(b, SI_ALBUM, "%s\n", afhi->tags.album);
947 WRITE_STATUS_ITEM(b, SI_COMMENT, "%s\n", afhi->tags.comment);
948 if (opts->mode == LS_MODE_MBOX) {
949 struct osl_object lyrics_def;
950 lyr_get_def_by_id(afsi->lyrics_id, &lyrics_def);
951 if (lyrics_def.data) {
952 para_printf(b, "Lyrics:\n~~~~~~~\n%s",
953 (char *)lyrics_def.data);
954 osl_close_disk_object(&lyrics_def);
961 static struct ls_data status_item_ls_data;
962 static struct osl_row *current_aft_row;
964 static void make_inode_status_items(struct para_buffer *pb)
966 struct stat statbuf = {.st_size = 0};
967 char *path, mtime_str[30] = "\0";
971 ret = get_audio_file_path_of_row(current_aft_row, &path);
974 ret = stat(path, &statbuf);
977 localtime_r(&statbuf.st_mtime, &mtime_tm);
978 ret = strftime(mtime_str, 29, "%b %d %Y", &mtime_tm);
979 assert(ret > 0); /* number of bytes placed in mtime_str */
981 WRITE_STATUS_ITEM(pb, SI_MTIME, "%s\n", mtime_str);
982 WRITE_STATUS_ITEM(pb, SI_FILE_SIZE, "%ld\n", statbuf.st_size / 1024);
985 static int make_status_items(void)
987 const struct lls_command *cmd = SERVER_CMD_CMD_PTR(LS);
988 char *argv[] = {"ls", "--admissible", "--listing-mode=verbose"};
989 struct ls_options opts = {.mode = LS_MODE_VERBOSE};
990 struct para_buffer pb = {.max_size = shm_get_shmmax() - 1};
994 if (!status_item_ls_data.path) /* no audio file open */
996 ret = lls_parse(ARRAY_SIZE(argv), argv, cmd, &opts.lpr, NULL);
999 ret = print_list_item(&status_item_ls_data, &opts, &pb, current_time);
1002 make_inode_status_items(&pb);
1004 status_items = pb.buf;
1006 memset(&pb, 0, sizeof(pb));
1007 pb.max_size = shm_get_shmmax() - 1;
1008 pb.flags = PBF_SIZE_PREFIX;
1009 ret = print_list_item(&status_item_ls_data, &opts, &pb, current_time);
1012 status_items = NULL;
1015 make_inode_status_items(&pb);
1016 free(parser_friendly_status_items);
1017 parser_friendly_status_items = pb.buf;
1020 lls_free_parse_result(opts.lpr, cmd);
1025 * Open the audio file with highest score and set up an afd structure.
1027 * \param afd Result pointer.
1029 * On success, the numplayed field of the audio file selector info is increased
1030 * and the lastplayed time is set to the current time. Finally, the score of
1031 * the audio file is updated.
1033 * \return Positive shmid on success, negative on errors.
1035 int open_and_update_audio_file(struct audio_file_data *afd)
1037 unsigned char file_hash[HASH_SIZE];
1038 struct osl_object afsi_obj;
1039 struct afs_info new_afsi;
1041 struct afsi_change_event_data aced;
1042 struct osl_object map, chunk_table_obj;
1043 struct ls_data *d = &status_item_ls_data;
1045 ret = score_get_best(¤t_aft_row, &d->score);
1048 ret = get_hash_of_row(current_aft_row, &d->hash);
1051 ret = get_audio_file_path_of_row(current_aft_row, &d->path);
1054 PARA_NOTICE_LOG("%s\n", d->path);
1055 ret = get_afsi_object_of_row(current_aft_row, &afsi_obj);
1058 ret = load_afsi(&d->afsi, &afsi_obj);
1061 ret = get_afhi_of_row(current_aft_row, &afd->afhi);
1064 d->afhi = afd->afhi;
1065 d->afhi.chunk_table = afd->afhi.chunk_table = NULL;
1066 ret = osl(osl_open_disk_object(audio_file_table, current_aft_row,
1067 AFTCOL_CHUNKS, &chunk_table_obj));
1069 if (!afh_supports_dynamic_chunks(d->afsi.audio_format_id))
1071 PARA_INFO_LOG("no chunk table for %s\n", d->path);
1072 chunk_table_obj.data = NULL;
1073 chunk_table_obj.size = 0;
1075 PARA_INFO_LOG("chunk table: %zu bytes\n", chunk_table_obj.size);
1077 ret = mmap_full_file(d->path, O_RDONLY, &map.data, &map.size, &afd->fd);
1080 hash_function(map.data, map.size, file_hash);
1081 ret = hash_compare(file_hash, d->hash);
1082 para_munmap(map.data, map.size);
1084 ret = -E_HASH_MISMATCH;
1088 new_afsi.num_played++;
1089 new_afsi.last_played = time(NULL);
1090 save_afsi(&new_afsi, &afsi_obj); /* in-place update */
1092 afd->audio_format_id = d->afsi.audio_format_id;
1093 load_chunk_table(&afd->afhi, &chunk_table_obj);
1094 aced.aft_row = current_aft_row;
1095 aced.old_afsi = &d->afsi;
1097 * No need to update the status items as the AFSI_CHANGE event will
1100 ret = afs_event(AFSI_CHANGE, NULL, &aced);
1103 ret = save_afd(afd);
1105 free(afd->afhi.chunk_table);
1106 if (chunk_table_obj.data)
1107 osl_close_disk_object(&chunk_table_obj);
1109 PARA_ERROR_LOG("%s: %s\n", d->path, para_strerror(-ret));
1110 ret = score_delete(current_aft_row);
1117 static int ls_hash_compare(const void *a, const void *b)
1119 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1120 return memcmp(d1->hash, d2->hash, HASH_SIZE);
1123 static int ls_audio_format_compare(const void *a, const void *b)
1125 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1126 return NUM_COMPARE(d1->afsi.audio_format_id, d2->afsi.audio_format_id);
1129 static int ls_duration_compare(const void *a, const void *b)
1131 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1132 return NUM_COMPARE(d1->afhi.seconds_total, d2->afhi.seconds_total);
1135 static int ls_bitrate_compare(const void *a, const void *b)
1137 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1138 return NUM_COMPARE(d1->afhi.bitrate, d2->afhi.bitrate);
1141 static int ls_lyrics_id_compare(const void *a, const void *b)
1143 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1144 return NUM_COMPARE(d1->afsi.lyrics_id, d2->afsi.lyrics_id);
1147 static int ls_image_id_compare(const void *a, const void *b)
1149 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1150 return NUM_COMPARE(d1->afsi.image_id, d2->afsi.image_id);
1153 static int ls_channels_compare(const void *a, const void *b)
1155 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1156 return NUM_COMPARE(d1->afhi.channels, d2->afhi.channels);
1159 static int ls_frequency_compare(const void *a, const void *b)
1161 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1162 return NUM_COMPARE(d1->afhi.frequency, d2->afhi.frequency);
1165 static int ls_num_played_compare(const void *a, const void *b)
1167 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1168 return NUM_COMPARE(d1->afsi.num_played, d2->afsi.num_played);
1171 static int ls_last_played_compare(const void *a, const void *b)
1173 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1174 return NUM_COMPARE(d1->afsi.last_played, d2->afsi.last_played);
1177 static int ls_score_compare(const void *a, const void *b)
1179 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1180 return NUM_COMPARE(d1->score, d2->score);
1183 static int ls_path_compare(const void *a, const void *b)
1185 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1186 return strcmp(d1->path, d2->path);
1189 static inline bool admissible_only(struct ls_options *opts)
1191 return SERVER_CMD_OPT_GIVEN(LS, ADMISSIBLE, opts->lpr)
1192 || opts->sorting == LS_SORT_BY_SCORE;
1195 static int sort_matching_paths(struct ls_options *options)
1197 const struct lls_opt_result *r_b = SERVER_CMD_OPT_RESULT(LS, BASENAME,
1199 size_t nmemb = options->num_matching_paths;
1200 size_t size = sizeof(*options->data_ptr);
1201 int (*compar)(const void *, const void *);
1204 options->data_ptr = para_malloc(nmemb * sizeof(*options->data_ptr));
1205 for (i = 0; i < nmemb; i++)
1206 options->data_ptr[i] = options->data + i;
1208 /* In these cases the array is already sorted */
1209 if (admissible_only(options)) {
1210 if (options->sorting == LS_SORT_BY_SCORE)
1213 if (options->sorting == LS_SORT_BY_PATH && !lls_opt_given(r_b))
1217 switch (options->sorting) {
1218 case LS_SORT_BY_PATH:
1219 compar = ls_path_compare; break;
1220 case LS_SORT_BY_SCORE:
1221 compar = ls_score_compare; break;
1222 case LS_SORT_BY_LAST_PLAYED:
1223 compar = ls_last_played_compare; break;
1224 case LS_SORT_BY_NUM_PLAYED:
1225 compar = ls_num_played_compare; break;
1226 case LS_SORT_BY_FREQUENCY:
1227 compar = ls_frequency_compare; break;
1228 case LS_SORT_BY_CHANNELS:
1229 compar = ls_channels_compare; break;
1230 case LS_SORT_BY_IMAGE_ID:
1231 compar = ls_image_id_compare; break;
1232 case LS_SORT_BY_LYRICS_ID:
1233 compar = ls_lyrics_id_compare; break;
1234 case LS_SORT_BY_BITRATE:
1235 compar = ls_bitrate_compare; break;
1236 case LS_SORT_BY_DURATION:
1237 compar = ls_duration_compare; break;
1238 case LS_SORT_BY_AUDIO_FORMAT:
1239 compar = ls_audio_format_compare; break;
1240 case LS_SORT_BY_HASH:
1241 compar = ls_hash_compare; break;
1245 qsort(options->data_ptr, nmemb, size, compar);
1249 /* row is either an aft_row or a row of the score table */
1250 /* TODO: Only compute widths if we need them */
1251 static int prepare_ls_row(struct osl_row *row, void *ls_opts)
1254 struct ls_options *options = ls_opts;
1255 bool basename_given = SERVER_CMD_OPT_GIVEN(LS, BASENAME, options->lpr);
1257 struct ls_widths *w;
1258 unsigned short num_digits;
1259 unsigned tmp, num_inputs;
1260 struct osl_row *aft_row;
1264 if (admissible_only(options)) {
1265 ret = get_score_and_aft_row(row, &score, &aft_row);
1272 ret = get_audio_file_path_of_row(aft_row, &path);
1275 if (basename_given) {
1276 char *p = strrchr(path, '/');
1280 num_inputs = lls_num_inputs(options->lpr);
1281 if (num_inputs > 0) {
1282 for (i = 0; i < num_inputs; i++) {
1283 ret = fnmatch(lls_input(i, options->lpr), path, 0);
1286 if (ret == FNM_NOMATCH)
1290 if (i >= num_inputs) /* no match */
1293 tmp = options->num_matching_paths++;
1294 if (options->num_matching_paths > options->array_size) {
1295 options->array_size++;
1296 options->array_size *= 2;
1297 options->data = para_realloc(options->data, options->array_size
1298 * sizeof(*options->data));
1300 d = options->data + tmp;
1301 ret = get_afsi_of_row(aft_row, &d->afsi);
1304 ret = get_afhi_of_row(aft_row, &d->afhi);
1308 ret = get_hash_of_row(aft_row, &d->hash);
1311 w = &options->widths;
1312 GET_NUM_DIGITS(d->afsi.image_id, &num_digits);
1313 w->image_id_width = PARA_MAX(w->image_id_width, num_digits);
1314 GET_NUM_DIGITS(d->afsi.lyrics_id, &num_digits);
1315 w->lyrics_id_width = PARA_MAX(w->lyrics_id_width, num_digits);
1316 GET_NUM_DIGITS(d->afhi.bitrate, &num_digits);
1317 w->bitrate_width = PARA_MAX(w->bitrate_width, num_digits);
1318 GET_NUM_DIGITS(d->afhi.frequency, &num_digits);
1319 w->frequency_width = PARA_MAX(w->frequency_width, num_digits);
1320 GET_NUM_DIGITS(d->afsi.num_played, &num_digits);
1321 w->num_played_width = PARA_MAX(w->num_played_width, num_digits);
1322 /* get the number of chars to print this amount of time */
1323 num_digits = get_duration_width(d->afhi.seconds_total);
1324 w->duration_width = PARA_MAX(w->duration_width, num_digits);
1325 GET_NUM_DIGITS(d->afsi.amp, &num_digits);
1326 w->amp_width = PARA_MAX(w->amp_width, num_digits);
1327 num_digits = strlen(audio_format_name(d->afsi.audio_format_id));
1328 w->audio_format_width = PARA_MAX(w->audio_format_width, num_digits);
1329 if (admissible_only(options)) {
1330 GET_NUM_DIGITS(score, &num_digits);
1331 num_digits++; /* add one for the sign (space or "-") */
1332 w->score_width = PARA_MAX(w->score_width, num_digits);
1340 static int com_ls_callback(struct afs_callback_arg *aca)
1342 const struct lls_command *cmd = SERVER_CMD_CMD_PTR(LS);
1343 struct ls_options *opts = aca->query.data;
1345 time_t current_time;
1346 const struct lls_opt_result *r_r;
1348 ret = lls_deserialize_parse_result(
1349 (char *)aca->query.data + sizeof(*opts), cmd, &opts->lpr);
1351 r_r = SERVER_CMD_OPT_RESULT(LS, REVERSE, opts->lpr);
1353 aca->pbout.flags = (opts->mode == LS_MODE_PARSER)? PBF_SIZE_PREFIX : 0;
1354 if (admissible_only(opts))
1355 ret = admissible_file_loop(opts, prepare_ls_row);
1357 ret = osl(osl_rbtree_loop(audio_file_table, AFTCOL_PATH, opts,
1361 if (opts->num_matching_paths == 0) {
1362 ret = lls_num_inputs(opts->lpr) > 0? -E_NO_MATCH : 0;
1365 ret = sort_matching_paths(opts);
1368 time(¤t_time);
1369 if (lls_opt_given(r_r))
1370 for (i = opts->num_matching_paths - 1; i >= 0; i--) {
1371 ret = print_list_item(opts->data_ptr[i], opts,
1372 &aca->pbout, current_time);
1377 for (i = 0; i < opts->num_matching_paths; i++) {
1378 ret = print_list_item(opts->data_ptr[i], opts,
1379 &aca->pbout, current_time);
1384 lls_free_parse_result(opts->lpr, cmd);
1386 free(opts->data_ptr);
1390 static int com_ls(struct command_context *cc, struct lls_parse_result *lpr)
1392 const struct lls_command *cmd = SERVER_CMD_CMD_PTR(LS);
1393 struct ls_options *opts;
1394 struct osl_object query;
1395 const struct lls_opt_result *r_l = SERVER_CMD_OPT_RESULT(LS, LISTING_MODE,
1397 const struct lls_opt_result *r_s = SERVER_CMD_OPT_RESULT(LS, SORT, lpr);
1401 ret = lls_serialize_parse_result(lpr, cmd, NULL, &query.size);
1403 query.size += sizeof(*opts);
1404 query.data = para_malloc(query.size);
1406 memset(opts, 0, sizeof(*opts));
1407 slpr = query.data + sizeof(*opts);
1408 ret = lls_serialize_parse_result(lpr, cmd, &slpr, NULL);
1410 opts->mode = LS_MODE_SHORT;
1411 opts->sorting = LS_SORT_BY_PATH;
1412 if (lls_opt_given(r_l)) {
1413 const char *val = lls_string_val(0, r_l);
1414 if (!strcmp(val, "l") || !strcmp(val, "long"))
1415 opts->mode = LS_MODE_LONG;
1416 else if (!strcmp(val, "s") || !strcmp(val, "short"))
1417 opts->mode = LS_MODE_SHORT;
1418 else if (!strcmp(val, "v") || !strcmp(val, "verbose"))
1419 opts->mode = LS_MODE_VERBOSE;
1420 else if (!strcmp(val, "m") || !strcmp(val, "mbox"))
1421 opts->mode = LS_MODE_MBOX;
1422 else if (!strcmp(val, "c") || !strcmp(val, "chunk-table"))
1423 opts->mode = LS_MODE_MBOX;
1424 else if (!strcmp(val, "p") || !strcmp(val, "parser-friendly"))
1425 opts->mode = LS_MODE_PARSER;
1427 ret = -E_AFT_SYNTAX;
1431 if (lls_opt_given(r_s)) {
1432 const char *val = lls_string_val(0, r_s);
1433 if (!strcmp(val, "p") || !strcmp(val, "path"))
1434 opts->sorting = LS_SORT_BY_PATH;
1435 else if (!strcmp(val, "s") || !strcmp(val, "score"))
1436 opts->sorting = LS_SORT_BY_SCORE;
1437 else if (!strcmp(val, "l") || !strcmp(val, "lastplayed"))
1438 opts->sorting = LS_SORT_BY_LAST_PLAYED;
1439 else if (!strcmp(val, "n") || !strcmp(val, "numplayed"))
1440 opts->sorting = LS_SORT_BY_NUM_PLAYED;
1441 else if (!strcmp(val, "f") || !strcmp(val, "frquency"))
1442 opts->sorting = LS_SORT_BY_FREQUENCY;
1443 else if (!strcmp(val, "c") || !strcmp(val, "channels"))
1444 opts->sorting = LS_SORT_BY_CHANNELS;
1445 else if (!strcmp(val, "i") || !strcmp(val, "image-id"))
1446 opts->sorting = LS_SORT_BY_IMAGE_ID;
1447 else if (!strcmp(val, "y") || !strcmp(val, "lyrics-id"))
1448 opts->sorting = LS_SORT_BY_LYRICS_ID;
1449 else if (!strcmp(val, "b") || !strcmp(val, "bitrate"))
1450 opts->sorting = LS_SORT_BY_BITRATE;
1451 else if (!strcmp(val, "d") || !strcmp(val, "duration"))
1452 opts->sorting = LS_SORT_BY_DURATION;
1453 else if (!strcmp(val, "a") || !strcmp(val, "audio-format"))
1454 opts->sorting = LS_SORT_BY_AUDIO_FORMAT;
1455 else if (!strcmp(val, "h") || !strcmp(val, "hash"))
1456 opts->sorting = LS_SORT_BY_HASH;
1458 ret = -E_AFT_SYNTAX;
1462 ret = send_callback_request(com_ls_callback, &query,
1463 afs_cb_result_handler, cc);
1468 EXPORT_SERVER_CMD_HANDLER(ls);
1471 * Call the given function for each file in the audio file table.
1473 * \param private_data An arbitrary data pointer, passed to \a func.
1474 * \param func The custom function to be called.
1478 int audio_file_loop(void *private_data, osl_rbtree_loop_func *func)
1480 return osl(osl_rbtree_loop(audio_file_table, AFTCOL_HASH, private_data,
1484 static int find_hash_sister(unsigned char *hash, struct osl_row **result)
1486 int ret = aft_get_row_of_hash(hash, result);
1488 if (ret == -OSL_ERRNO_TO_PARA_ERROR(E_OSL_RB_KEY_NOT_FOUND))
1493 static int find_path_brother(const char *path, struct osl_row **result)
1495 int ret = aft_get_row_of_path(path, result);
1497 if (ret == -OSL_ERRNO_TO_PARA_ERROR(E_OSL_RB_KEY_NOT_FOUND))
1502 /** The format of the data stored by save_audio_file_data(). */
1503 enum com_add_buffer_offsets {
1504 /* afhi (if present) starts at this offset. */
1505 CAB_AFHI_OFFSET_POS = 0,
1506 /** Start of the chunk table (if present). */
1507 CAB_CHUNKS_OFFSET_POS = 4,
1508 /** Start of the (serialized) lopsub parse result. */
1510 /** Audio format id. */
1511 CAB_AUDIO_FORMAT_ID_OFFSET = 12,
1512 /** The hash of the audio file being added. */
1513 CAB_HASH_OFFSET = 13,
1514 /** Start of the path of the audio file. */
1515 CAB_PATH_OFFSET = (CAB_HASH_OFFSET + HASH_SIZE),
1519 * Store the given data to a single buffer. Doesn't need the audio file selector
1520 * info struct as the server knows it as well.
1522 * It's OK to call this with afhi == NULL. In this case, the audio format
1523 * handler info won't be stored in the buffer.
1525 static void save_add_callback_buffer(unsigned char *hash, const char *path,
1526 struct afh_info *afhi, const char *slpr, size_t slpr_size,
1527 uint8_t audio_format_num, struct osl_object *obj)
1529 size_t path_len = strlen(path) + 1;
1530 size_t afhi_size = sizeof_afhi_buf(afhi);
1531 size_t size = CAB_PATH_OFFSET + path_len + afhi_size
1532 + sizeof_chunk_table(afhi) + slpr_size;
1533 char *buf = para_malloc(size);
1536 assert(size <= ~(uint32_t)0);
1537 write_u8(buf + CAB_AUDIO_FORMAT_ID_OFFSET, audio_format_num);
1538 memcpy(buf + CAB_HASH_OFFSET, hash, HASH_SIZE);
1539 strcpy(buf + CAB_PATH_OFFSET, path);
1540 pos = CAB_PATH_OFFSET + path_len;
1541 write_u32(buf + CAB_AFHI_OFFSET_POS, pos);
1542 save_afhi(afhi, buf + pos);
1544 write_u32(buf + CAB_CHUNKS_OFFSET_POS, pos);
1546 save_chunk_table(afhi, buf + pos);
1547 pos += sizeof_chunk_table(afhi);
1549 write_u32(buf + CAB_LPR_OFFSET, pos);
1550 memcpy(buf + pos, slpr, slpr_size);
1551 assert(pos + slpr_size == size);
1558 Overview of the add command.
1560 Input: What was passed to the callback by the command handler.
1562 HS: Hash sister. Whether an audio file with identical hash
1563 already exists in the osl database.
1565 PB: Path brother. Whether a file with the given path exists
1568 F: Force flag given. Whether add was called with -f.
1570 output: Action performed by the callback.
1572 AFHI: Whether afhi and chunk table are computed and sent.
1573 ACTION: Table modifications to be done by the callback.
1575 +----+----+---+------+---------------------------------------------------+
1576 | HS | PB | F | AFHI | ACTION
1577 +----+----+---+------+---------------------------------------------------+
1578 | Y | Y | Y | Y | if HS != PB: remove PB. HS: force afhi update,
1579 | | update path, keep afsi
1580 +----+----+---+------+---------------------------------------------------+
1581 | Y | Y | N | N | if HS == PB: do not send callback request at all.
1582 | | otherwise: remove PB, HS: update path, keep afhi,
1584 +----+----+---+------+---------------------------------------------------+
1585 | Y | N | Y | Y | (rename) force afhi update of HS, update path of
1587 +----+----+---+------+---------------------------------------------------+
1588 | Y | N | N | N | (file rename) update path of HS, keep afsi, afhi
1589 +----+----+---+------+---------------------------------------------------+
1590 | N | Y | Y | Y | (file change) update afhi, hash, of PB, keep afsi
1591 | | (force has no effect)
1592 +----+----+---+------+---------------------------------------------------+
1593 | N | Y | N | Y | (file change) update afhi, hash of PB, keep afsi
1594 +----+----+---+------+---------------------------------------------------+
1595 | N | N | Y | Y | (new file) create new entry (force has no effect)
1596 +----+----+---+------+---------------------------------------------------+
1597 | N | N | N | Y | (new file) create new entry
1598 +----+----+---+------+---------------------------------------------------+
1602 afhi <=> force or no HS
1607 static int com_add_callback(struct afs_callback_arg *aca)
1609 char *buf = aca->query.data, *path;
1610 struct osl_row *pb, *aft_row;
1612 struct osl_object objs[NUM_AFT_COLUMNS];
1613 unsigned char *hash;
1614 char asc[2 * HASH_SIZE + 1];
1616 char afsi_buf[AFSI_SIZE];
1617 char *slpr = buf + read_u32(buf + CAB_LPR_OFFSET);
1618 struct afs_info default_afsi = {.last_played = 0};
1619 uint16_t afhi_offset, chunks_offset;
1620 const struct lls_command *cmd = SERVER_CMD_CMD_PTR(ADD);
1621 const struct lls_opt_result *r_f, *r_v;
1623 ret = lls_deserialize_parse_result(slpr, cmd, &aca->lpr);
1625 r_f = SERVER_CMD_OPT_RESULT(ADD, FORCE, aca->lpr);
1626 r_v = SERVER_CMD_OPT_RESULT(ADD, VERBOSE, aca->lpr);
1628 hash = (unsigned char *)buf + CAB_HASH_OFFSET;
1629 hash_to_asc(hash, asc);
1630 objs[AFTCOL_HASH].data = buf + CAB_HASH_OFFSET;
1631 objs[AFTCOL_HASH].size = HASH_SIZE;
1633 path = buf + CAB_PATH_OFFSET;
1634 objs[AFTCOL_PATH].data = path;
1635 objs[AFTCOL_PATH].size = strlen(path) + 1;
1637 PARA_INFO_LOG("request to add %s\n", path);
1638 ret = find_hash_sister(hash, &hs);
1641 ret = find_path_brother(path, &pb);
1644 if (hs && pb && hs == pb && !lls_opt_given(r_f)) {
1645 if (lls_opt_given(r_v))
1646 para_printf(&aca->pbout, "ignoring duplicate\n");
1650 if (hs && hs != pb) {
1651 struct osl_object obj;
1652 if (pb) { /* hs trumps pb, remove pb */
1653 if (lls_opt_given(r_v))
1654 para_printf(&aca->pbout, "removing %s\n", path);
1655 ret = afs_event(AUDIO_FILE_REMOVE, &aca->pbout, pb);
1658 ret = osl(osl_del_row(audio_file_table, pb));
1663 /* file rename, update hs' path */
1664 if (lls_opt_given(r_v)) {
1665 ret = osl(osl_get_object(audio_file_table, hs,
1666 AFTCOL_PATH, &obj));
1669 para_printf(&aca->pbout, "renamed from %s\n",
1672 ret = osl(osl_update_object(audio_file_table, hs, AFTCOL_PATH,
1673 &objs[AFTCOL_PATH]));
1676 ret = afs_event(AUDIO_FILE_RENAME, &aca->pbout, hs);
1679 if (!lls_opt_given(r_f))
1682 /* no hs or force mode, child must have sent afhi */
1683 afhi_offset = read_u32(buf + CAB_AFHI_OFFSET_POS);
1684 chunks_offset = read_u32(buf + CAB_CHUNKS_OFFSET_POS);
1686 objs[AFTCOL_AFHI].data = buf + afhi_offset;
1687 objs[AFTCOL_AFHI].size = chunks_offset - afhi_offset;
1689 if (!objs[AFTCOL_AFHI].size) /* "impossible" */
1691 objs[AFTCOL_CHUNKS].data = buf + chunks_offset;
1692 objs[AFTCOL_CHUNKS].size = aca->query.size - chunks_offset;
1693 if (pb && !hs) { /* update pb's hash */
1694 char old_asc[2 * HASH_SIZE + 1];
1695 unsigned char *old_hash;
1696 ret = get_hash_of_row(pb, &old_hash);
1699 hash_to_asc(old_hash, old_asc);
1700 if (lls_opt_given(r_v))
1701 para_printf(&aca->pbout, "file change: %s -> %s\n",
1703 ret = osl(osl_update_object(audio_file_table, pb, AFTCOL_HASH,
1704 &objs[AFTCOL_HASH]));
1708 if (hs || pb) { /* (hs != NULL and pb != NULL) implies hs == pb */
1709 struct osl_row *row = pb? pb : hs;
1710 /* update afhi and chunk_table */
1711 if (lls_opt_given(r_v))
1712 para_printf(&aca->pbout,
1713 "updating afhi and chunk table\n");
1714 ret = osl(osl_update_object(audio_file_table, row, AFTCOL_AFHI,
1715 &objs[AFTCOL_AFHI]));
1718 /* truncate the file to size zero if there is no chunk table */
1719 ret = osl(osl_update_object(audio_file_table, row, AFTCOL_CHUNKS,
1720 &objs[AFTCOL_CHUNKS]));
1723 ret = afs_event(AFHI_CHANGE, &aca->pbout, row);
1726 /* new entry, use default afsi */
1727 if (lls_opt_given(r_v))
1728 para_printf(&aca->pbout, "new file\n");
1729 default_afsi.last_played = time(NULL) - 365 * 24 * 60 * 60;
1730 default_afsi.audio_format_id = read_u8(buf + CAB_AUDIO_FORMAT_ID_OFFSET);
1732 objs[AFTCOL_AFSI].data = &afsi_buf;
1733 objs[AFTCOL_AFSI].size = AFSI_SIZE;
1734 save_afsi(&default_afsi, &objs[AFTCOL_AFSI]);
1735 ret = osl(osl_add_and_get_row(audio_file_table, objs, &aft_row));
1738 ret = afs_event(AUDIO_FILE_ADD, &aca->pbout, aft_row);
1741 para_printf(&aca->pbout, "could not add %s\n", path);
1742 lls_free_parse_result(aca->lpr, cmd);
1746 /* Used by com_add(). */
1747 struct private_add_data {
1748 /* The pointer passed to the original command handler. */
1749 struct command_context *cc;
1750 /* Contains the flags given at the command line. */
1751 struct lls_parse_result *lpr;
1752 /* Serialized lopsub parse result. */
1754 /* Number of bytes. */
1758 static int path_brother_callback(struct afs_callback_arg *aca)
1760 char *path = aca->query.data;
1761 struct osl_row *path_brother;
1762 int ret = find_path_brother(path, &path_brother);
1765 return pass_buffer_as_shm(aca->fd, SBD_OUTPUT, (char *)&path_brother,
1766 sizeof(path_brother));
1769 static int hash_sister_callback(struct afs_callback_arg *aca)
1771 unsigned char *hash = aca->query.data;
1772 struct osl_row *hash_sister;
1773 int ret = find_hash_sister(hash, &hash_sister);
1777 return pass_buffer_as_shm(aca->fd, SBD_OUTPUT, (char *)&hash_sister,
1778 sizeof(hash_sister));
1781 static int get_row_pointer_from_result(struct osl_object *result,
1782 __a_unused uint8_t band, void *private)
1784 struct osl_row **row = private;
1786 if (band == SBD_OUTPUT)
1787 *row = *(struct osl_row **)(result->data);
1791 static int add_one_audio_file(const char *path, void *private_data)
1793 int ret, send_ret = 1, fd;
1794 uint8_t format_num = -1;
1795 struct private_add_data *pad = private_data;
1796 struct afh_info afhi, *afhi_ptr = NULL;
1797 struct osl_row *pb = NULL, *hs = NULL; /* path brother/hash sister */
1798 struct osl_object map, obj = {.data = NULL}, query;
1799 unsigned char hash[HASH_SIZE];
1800 bool a_given = SERVER_CMD_OPT_GIVEN(ADD, ALL, pad->lpr);
1801 bool f_given = SERVER_CMD_OPT_GIVEN(ADD, FORCE, pad->lpr);
1802 bool l_given = SERVER_CMD_OPT_GIVEN(ADD, LAZY, pad->lpr);
1803 bool v_given = SERVER_CMD_OPT_GIVEN(ADD, VERBOSE, pad->lpr);
1805 ret = guess_audio_format(path);
1806 if (ret < 0 && !a_given) {
1810 query.data = (char *)path;
1811 query.size = strlen(path) + 1;
1812 ret = send_callback_request(path_brother_callback, &query,
1813 get_row_pointer_from_result, &pb);
1814 if (ret < 0 && ret != -OSL_ERRNO_TO_PARA_ERROR(E_OSL_RB_KEY_NOT_FOUND))
1817 if (pb && l_given) { /* lazy is really cheap */
1819 send_ret = send_sb_va(&pad->cc->scc, SBD_OUTPUT,
1820 "lazy-ignore: %s\n", path);
1823 /* We still want to add this file. Compute its hash. */
1824 ret = mmap_full_file(path, O_RDONLY, &map.data, &map.size, &fd);
1827 hash_function(map.data, map.size, hash);
1829 /* Check whether the database contains a file with the same hash. */
1831 query.size = HASH_SIZE;
1832 ret = send_callback_request(hash_sister_callback, &query,
1833 get_row_pointer_from_result, &hs);
1836 /* Return success if we already know this file. */
1838 if (pb && hs && hs == pb && !f_given) {
1840 send_ret = send_sb_va(&pad->cc->scc, SBD_OUTPUT,
1841 "%s exists, not forcing update\n", path);
1845 * We won't recalculate the audio format info and the chunk table if
1846 * there is a hash sister and FORCE was not given.
1848 if (!hs || f_given) {
1849 ret = compute_afhi(path, map.data, map.size, fd, &afhi);
1855 munmap(map.data, map.size);
1858 send_ret = send_sb_va(&pad->cc->scc, SBD_OUTPUT,
1859 "adding %s\n", path);
1863 save_add_callback_buffer(hash, path, afhi_ptr, pad->slpr,
1864 pad->slpr_size, format_num, &obj);
1865 /* Ask afs to consider this entry for adding. */
1866 ret = send_callback_request(com_add_callback, &obj,
1867 afs_cb_result_handler, pad->cc);
1872 munmap(map.data, map.size);
1874 if (ret < 0 && send_ret >= 0)
1875 send_ret = send_sb_va(&pad->cc->scc, SBD_ERROR_LOG,
1876 "failed to add %s (%s)\n", path, para_strerror(-ret));
1878 clear_afhi(afhi_ptr);
1879 /* Stop adding files only on send errors. */
1883 static int com_add(struct command_context *cc, struct lls_parse_result *lpr)
1886 struct private_add_data pad = {.cc = cc, .lpr = lpr};
1887 const struct lls_command *cmd = SERVER_CMD_CMD_PTR(ADD);
1888 unsigned num_inputs;
1891 ret = lls(lls_check_arg_count(lpr, 1, INT_MAX, &errctx));
1893 send_errctx(cc, errctx);
1896 ret = lls_serialize_parse_result(lpr, cmd, &pad.slpr, &pad.slpr_size);
1898 num_inputs = lls_num_inputs(lpr);
1899 for (i = 0; i < num_inputs; i++) {
1901 ret = verify_path(lls_input(i, lpr), &path);
1903 ret = send_sb_va(&cc->scc, SBD_ERROR_LOG, "%s: %s\n",
1904 lls_input(i, lpr), para_strerror(-ret));
1909 if (ret == 1) /* directory */
1910 ret = for_each_file_in_dir(path, add_one_audio_file,
1912 else /* regular file */
1913 ret = add_one_audio_file(path, &pad);
1915 send_sb_va(&cc->scc, SBD_OUTPUT, "%s: %s\n", path,
1916 para_strerror(-ret));
1927 EXPORT_SERVER_CMD_HANDLER(add);
1929 /** Flags used by the touch command. */
1931 /** Whether the \p FNM_PATHNAME flag should be passed to fnmatch(). */
1932 TOUCH_FLAG_FNM_PATHNAME = 1,
1933 /** Activates verbose mode. */
1934 TOUCH_FLAG_VERBOSE = 2
1937 static int touch_audio_file(__a_unused struct osl_table *table,
1938 struct osl_row *row, const char *name, void *data)
1940 struct afs_callback_arg *aca = data;
1941 bool v_given = SERVER_CMD_OPT_GIVEN(TOUCH, VERBOSE, aca->lpr);
1942 const struct lls_opt_result *r_n, *r_l, *r_i, *r_y, *r_a;
1944 struct osl_object obj;
1945 struct afs_info old_afsi, new_afsi;
1947 struct afsi_change_event_data aced;
1949 r_n = SERVER_CMD_OPT_RESULT(TOUCH, NUMPLAYED, aca->lpr);
1950 r_l = SERVER_CMD_OPT_RESULT(TOUCH, LASTPLAYED, aca->lpr);
1951 r_i = SERVER_CMD_OPT_RESULT(TOUCH, IMAGE_ID, aca->lpr);
1952 r_y = SERVER_CMD_OPT_RESULT(TOUCH, LYRICS_ID, aca->lpr);
1953 r_a = SERVER_CMD_OPT_RESULT(TOUCH, AMP, aca->lpr);
1954 no_options = !lls_opt_given(r_n) && !lls_opt_given(r_l) && !lls_opt_given(r_i)
1955 && !lls_opt_given(r_y) && !lls_opt_given(r_a);
1957 ret = get_afsi_object_of_row(row, &obj);
1959 para_printf(&aca->pbout, "cannot touch %s\n", name);
1962 ret = load_afsi(&old_afsi, &obj);
1964 para_printf(&aca->pbout, "cannot touch %s\n", name);
1967 new_afsi = old_afsi;
1969 new_afsi.num_played++;
1970 new_afsi.last_played = time(NULL);
1972 para_printf(&aca->pbout, "%s: num_played = %u, "
1973 "last_played = now()\n", name,
1974 new_afsi.num_played);
1976 if (lls_opt_given(r_l))
1977 new_afsi.last_played = lls_uint64_val(0, r_l);
1978 if (lls_opt_given(r_n))
1979 new_afsi.num_played = lls_uint32_val(0, r_n);
1980 if (lls_opt_given(r_i))
1981 new_afsi.image_id = lls_uint32_val(0, r_i);
1982 if (lls_opt_given(r_y))
1983 new_afsi.lyrics_id = lls_uint32_val(0, r_y);
1984 if (lls_opt_given(r_a))
1985 new_afsi.amp = lls_uint32_val(0, r_a);
1987 para_printf(&aca->pbout, "touching %s\n", name);
1989 save_afsi(&new_afsi, &obj); /* in-place update */
1991 aced.old_afsi = &old_afsi;
1992 return afs_event(AFSI_CHANGE, &aca->pbout, &aced);
1995 static int com_touch_callback(struct afs_callback_arg *aca)
1997 const struct lls_command *cmd = SERVER_CMD_CMD_PTR(TOUCH);
1999 const struct lls_opt_result *r_i, *r_y;
2001 struct pattern_match_data pmd = {
2002 .table = audio_file_table,
2003 .loop_col_num = AFTCOL_HASH,
2004 .match_col_num = AFTCOL_PATH,
2006 .action = touch_audio_file
2009 ret = lls_deserialize_parse_result(aca->query.data, cmd, &aca->lpr);
2013 r_i = SERVER_CMD_OPT_RESULT(TOUCH, IMAGE_ID, aca->lpr);
2014 if (lls_opt_given(r_i)) {
2015 uint32_t id = lls_uint32_val(0, r_i);
2016 ret = img_get_name_by_id(id, NULL);
2018 para_printf(&aca->pbout, "invalid image ID: %u\n", id);
2022 r_y = SERVER_CMD_OPT_RESULT(TOUCH, LYRICS_ID, aca->lpr);
2023 if (lls_opt_given(r_y)) {
2024 uint32_t id = lls_uint32_val(0, r_y);
2025 ret = lyr_get_name_by_id(id, NULL);
2027 para_printf(&aca->pbout, "invalid lyrics ID: %u\n", id);
2031 p_given = SERVER_CMD_OPT_GIVEN(TOUCH, PATHNAME_MATCH, aca->lpr);
2033 pmd.fnmatch_flags |= FNM_PATHNAME;
2034 ret = for_each_matching_row(&pmd);
2035 if (ret >= 0 && pmd.num_matches == 0)
2037 lls_free_parse_result(aca->lpr, cmd);
2041 static int com_touch(struct command_context *cc, struct lls_parse_result *lpr)
2043 const struct lls_command *cmd = SERVER_CMD_CMD_PTR(TOUCH);
2047 ret = lls(lls_check_arg_count(lpr, 1, INT_MAX, &errctx));
2049 send_errctx(cc, errctx);
2052 return send_lls_callback_request(com_touch_callback, cmd, lpr, cc);
2054 EXPORT_SERVER_CMD_HANDLER(touch);
2056 static int remove_audio_file(__a_unused struct osl_table *table,
2057 struct osl_row *row, const char *name, void *data)
2059 struct afs_callback_arg *aca = data;
2060 bool v_given = SERVER_CMD_OPT_GIVEN(RM, VERBOSE, aca->lpr);
2064 para_printf(&aca->pbout, "removing %s\n", name);
2065 ret = afs_event(AUDIO_FILE_REMOVE, &aca->pbout, row);
2068 ret = osl(osl_del_row(audio_file_table, row));
2070 para_printf(&aca->pbout, "cannot remove %s\n", name);
2074 static int com_rm_callback(struct afs_callback_arg *aca)
2076 const struct lls_command *cmd = SERVER_CMD_CMD_PTR(RM);
2078 struct pattern_match_data pmd = {
2079 .table = audio_file_table,
2080 .loop_col_num = AFTCOL_HASH,
2081 .match_col_num = AFTCOL_PATH,
2083 .action = remove_audio_file
2085 bool v_given, p_given, f_given;
2087 ret = lls_deserialize_parse_result(aca->query.data, cmd, &aca->lpr);
2090 v_given = SERVER_CMD_OPT_GIVEN(RM, VERBOSE, aca->lpr);
2091 p_given = SERVER_CMD_OPT_GIVEN(RM, PATHNAME_MATCH, aca->lpr);
2092 f_given = SERVER_CMD_OPT_GIVEN(RM, FORCE, aca->lpr);
2095 pmd.fnmatch_flags |= FNM_PATHNAME;
2096 ret = for_each_matching_row(&pmd);
2099 if (pmd.num_matches == 0) {
2103 para_printf(&aca->pbout, "removed %u file(s)\n",
2106 lls_free_parse_result(aca->lpr, cmd);
2110 /* TODO options: -r (recursive) */
2111 static int com_rm(struct command_context *cc, struct lls_parse_result *lpr)
2113 const struct lls_command *cmd = SERVER_CMD_CMD_PTR(RM);
2117 ret = lls(lls_check_arg_count(lpr, 1, INT_MAX, &errctx));
2119 send_errctx(cc, errctx);
2122 return send_lls_callback_request(com_rm_callback, cmd, lpr, cc);
2124 EXPORT_SERVER_CMD_HANDLER(rm);
2126 /** Data passed to the action handler of com_cpsi(). */
2127 struct cpsi_action_data {
2128 /** Values are copied from here. */
2129 struct afs_info source_afsi;
2130 /** What was passed to com_cpsi_callback(). */
2131 struct afs_callback_arg *aca;
2135 static int copy_selector_info(__a_unused struct osl_table *table,
2136 struct osl_row *row, const char *name, void *data)
2138 struct cpsi_action_data *cad = data;
2139 struct osl_object target_afsi_obj;
2141 struct afs_info old_afsi, target_afsi;
2142 struct afsi_change_event_data aced;
2143 bool a_given, y_given, i_given, l_given, n_given, v_given;
2145 a_given = SERVER_CMD_OPT_GIVEN(CPSI, ATTRIBUTE_BITMAP, cad->aca->lpr);
2146 y_given = SERVER_CMD_OPT_GIVEN(CPSI, LYRICS_ID, cad->aca->lpr);
2147 i_given = SERVER_CMD_OPT_GIVEN(CPSI, IMAGE_ID, cad->aca->lpr);
2148 l_given = SERVER_CMD_OPT_GIVEN(CPSI, LASTPLAYED, cad->aca->lpr);
2149 n_given = SERVER_CMD_OPT_GIVEN(CPSI, NUMPLAYED, cad->aca->lpr);
2150 v_given = SERVER_CMD_OPT_GIVEN(CPSI, VERBOSE, cad->aca->lpr);
2152 ret = get_afsi_object_of_row(row, &target_afsi_obj);
2155 ret = load_afsi(&target_afsi, &target_afsi_obj);
2158 old_afsi = target_afsi;
2159 if (cad->copy_all || y_given)
2160 target_afsi.lyrics_id = cad->source_afsi.lyrics_id;
2161 if (cad->copy_all || i_given)
2162 target_afsi.image_id = cad->source_afsi.image_id;
2163 if (cad->copy_all || l_given)
2164 target_afsi.last_played = cad->source_afsi.last_played;
2165 if (cad->copy_all || n_given)
2166 target_afsi.num_played = cad->source_afsi.num_played;
2167 if (cad->copy_all || a_given)
2168 target_afsi.attributes = cad->source_afsi.attributes;
2169 save_afsi(&target_afsi, &target_afsi_obj); /* in-place update */
2171 para_printf(&cad->aca->pbout, "copied afsi to %s\n", name);
2173 aced.old_afsi = &old_afsi;
2174 return afs_event(AFSI_CHANGE, &cad->aca->pbout, &aced);
2177 static int com_cpsi_callback(struct afs_callback_arg *aca)
2179 const struct lls_command *cmd = SERVER_CMD_CMD_PTR(CPSI);
2180 bool a_given, y_given, i_given, l_given, n_given, v_given;
2181 struct cpsi_action_data cad = {.aca = aca};
2183 struct pattern_match_data pmd = {
2184 .table = audio_file_table,
2185 .loop_col_num = AFTCOL_HASH,
2186 .match_col_num = AFTCOL_PATH,
2187 .input_skip = 1, /* skip first argument (source file) */
2189 .action = copy_selector_info
2192 ret = lls_deserialize_parse_result(aca->query.data, cmd, &aca->lpr);
2196 a_given = SERVER_CMD_OPT_GIVEN(CPSI, ATTRIBUTE_BITMAP, aca->lpr);
2197 y_given = SERVER_CMD_OPT_GIVEN(CPSI, LYRICS_ID, aca->lpr);
2198 i_given = SERVER_CMD_OPT_GIVEN(CPSI, IMAGE_ID, aca->lpr);
2199 l_given = SERVER_CMD_OPT_GIVEN(CPSI, LASTPLAYED, aca->lpr);
2200 n_given = SERVER_CMD_OPT_GIVEN(CPSI, NUMPLAYED, aca->lpr);
2201 v_given = SERVER_CMD_OPT_GIVEN(CPSI, VERBOSE, aca->lpr);
2202 cad.copy_all = !a_given && !y_given && !i_given && !l_given && !n_given;
2204 ret = get_afsi_of_path(lls_input(0, aca->lpr), &cad.source_afsi);
2207 ret = for_each_matching_row(&pmd);
2210 if (pmd.num_matches > 0) {
2212 para_printf(&aca->pbout, "updated afsi of %u file(s)\n",
2217 lls_free_parse_result(aca->lpr, cmd);
2221 static int com_cpsi(struct command_context *cc, struct lls_parse_result *lpr)
2223 const struct lls_command *cmd = SERVER_CMD_CMD_PTR(CPSI);
2225 int ret = lls(lls_check_arg_count(lpr, 2, INT_MAX, &errctx));
2227 send_errctx(cc, errctx);
2230 return send_lls_callback_request(com_cpsi_callback, cmd, lpr, cc);
2232 EXPORT_SERVER_CMD_HANDLER(cpsi);
2234 struct change_atts_data {
2235 uint64_t add_mask, del_mask;
2236 struct afs_callback_arg *aca;
2239 static int change_atts(__a_unused struct osl_table *table,
2240 struct osl_row *row, __a_unused const char *name, void *data)
2243 struct osl_object obj;
2244 struct afs_info old_afsi, new_afsi;
2245 struct afsi_change_event_data aced = {
2247 .old_afsi = &old_afsi
2249 struct change_atts_data *cad = data;
2251 ret = get_afsi_object_of_row(row, &obj);
2254 ret = load_afsi(&old_afsi, &obj);
2257 new_afsi = old_afsi;
2258 new_afsi.attributes |= cad->add_mask;
2259 new_afsi.attributes &= ~cad->del_mask;
2260 save_afsi(&new_afsi, &obj); /* in-place update */
2261 return afs_event(AFSI_CHANGE, &cad->aca->pbout, &aced);
2264 static int com_setatt_callback(struct afs_callback_arg *aca)
2266 const struct lls_command *cmd = SERVER_CMD_CMD_PTR(SETATT);
2268 struct change_atts_data cad = {.aca = aca};
2269 struct pattern_match_data pmd = {
2270 .table = audio_file_table,
2271 .loop_col_num = AFTCOL_HASH,
2272 .match_col_num = AFTCOL_PATH,
2273 .pm_flags = PM_SKIP_EMPTY_NAME,
2275 .action = change_atts
2277 unsigned num_inputs;
2279 ret = lls_deserialize_parse_result(aca->query.data, cmd, &aca->lpr);
2283 num_inputs = lls_num_inputs(aca->lpr);
2284 for (i = 0; i < num_inputs; i++) {
2285 unsigned char bitnum;
2287 const char *arg = lls_input(i, aca->lpr);
2289 size_t len = strlen(arg);
2291 ret = -E_ATTR_SYNTAX;
2295 if (c != '+' && c != '-') {
2296 if (cad.add_mask == 0 && cad.del_mask == 0)
2297 goto out; /* no attribute modifier given */
2300 p = para_malloc(len);
2301 memcpy(p, arg, len - 1);
2303 ret = get_attribute_bitnum_by_name(p, &bitnum);
2306 para_printf(&aca->pbout, "invalid argument: %s\n", arg);
2310 cad.add_mask |= (one << bitnum);
2312 cad.del_mask |= (one << bitnum);
2314 /* no pattern given */
2315 ret = -E_ATTR_SYNTAX;
2319 ret = for_each_matching_row(&pmd);
2320 if (ret >= 0 && pmd.num_matches == 0)
2323 lls_free_parse_result(aca->lpr, cmd);
2327 static int com_setatt(struct command_context *cc, struct lls_parse_result *lpr)
2329 const struct lls_command *cmd = SERVER_CMD_CMD_PTR(SETATT);
2331 int ret = lls(lls_check_arg_count(lpr, 2, INT_MAX, &errctx));
2334 send_errctx(cc, errctx);
2337 return send_lls_callback_request(com_setatt_callback, cmd, lpr, cc);
2339 EXPORT_SERVER_CMD_HANDLER(setatt);
2341 static int afs_stat_callback(struct afs_callback_arg *aca)
2343 int *parser_friendly = aca->query.data;
2344 char *buf = *parser_friendly?
2345 parser_friendly_status_items : status_items;
2349 return pass_buffer_as_shm(aca->fd, SBD_OUTPUT, buf, strlen(buf));
2353 * Get the current afs status items from the afs process and send it.
2355 * \param cc The command context, used e.g. for data encryption.
2356 * \param parser_friendly Whether parser-friendly output format should be used.
2358 * As the contents of the afs status items change in time and the command
2359 * handler only has a COW version created at fork time, it can not send
2360 * up-to-date afs status items directly. Therefore the usual callback mechanism
2361 * is used to pass the status items from the afs process to the command handler
2362 * via a shared memory area and a pipe.
2364 * \return The return value of the underlying call to \ref send_callback_request().
2366 int send_afs_status(struct command_context *cc, int parser_friendly)
2368 struct osl_object query = {.data = &parser_friendly,
2369 .size = sizeof(parser_friendly)};
2371 return send_callback_request(afs_stat_callback, &query,
2372 afs_cb_result_handler, cc);
2375 /* returns success on non-fatal errors to keep the loop going */
2376 static int check_audio_file(struct osl_row *row, void *data)
2379 struct para_buffer *pb = data;
2380 struct stat statbuf;
2381 int ret = get_audio_file_path_of_row(row, &path);
2382 struct afs_info afsi;
2386 para_printf(pb, "%s\n", para_strerror(-ret));
2389 if (stat(path, &statbuf) < 0)
2390 para_printf(pb, "%s: stat error (%s)\n", path, strerror(errno));
2391 else if (!S_ISREG(statbuf.st_mode))
2392 para_printf(pb, "%s: not a regular file\n", path);
2393 ret = get_afsi_of_row(row, &afsi);
2395 para_printf(pb, "%s: %s\n", path, para_strerror(-ret));
2398 ret = lyr_get_name_by_id(afsi.lyrics_id, &blob_name);
2400 para_printf(pb, "%s lyrics id %u: %s\n", path, afsi.lyrics_id,
2401 para_strerror(-ret));
2402 ret = img_get_name_by_id(afsi.image_id, &blob_name);
2404 para_printf(pb, "%s image id %u: %s\n", path, afsi.image_id,
2405 para_strerror(-ret));
2410 * Check the audio file table for inconsistencies.
2412 * \param aca Only ->pbout is used for diagnostics.
2414 * \return Standard. Inconsistencies are reported but not regarded as an error.
2416 int aft_check_callback(struct afs_callback_arg *aca)
2418 para_printf(&aca->pbout, "checking audio file table...\n");
2419 return audio_file_loop(&aca->pbout, check_audio_file);
2422 struct aft_check_atts_data {
2424 struct para_buffer *pb;
2427 static int check_atts_of_audio_file(struct osl_row *row, void *data)
2429 struct aft_check_atts_data *acad = data;
2431 struct afs_info afsi;
2435 ret = get_afsi_of_row(row, &afsi);
2437 para_printf(acad->pb, "cannot get afsi\n");
2440 bad_bits = afsi.attributes & ~acad->att_mask;
2441 if (bad_bits == 0) /* OK */
2443 ret = get_audio_file_path_of_row(row, &path);
2445 para_printf(acad->pb, "cannot get path\n");
2448 para_printf(acad->pb, "invalid attribute bits (%" PRIu64 "): %s\n",
2450 /* return success to keep looping */
2455 * Iterate over all audio files and check the attribute bit mask.
2457 * \param att_mask The mask of all valid attributes.
2458 * \param pb Used for reporting inconsistencies.
2460 * This reads the attribute bit mask of each audio file from the afs info
2461 * structure stored in the audio file table and verifies that all set bits are
2462 * also turned on in \a att_mask, i.e., correspond to an attribute of the
2463 * attribute table. Audio files for which this is not the case are reported via
2466 * \return Standard. Inconsistencies are not regarded as errors.
2468 * \sa \ref attribute_check_callback().
2470 int aft_check_attributes(uint64_t att_mask, struct para_buffer *pb)
2472 struct aft_check_atts_data acad = {.att_mask = att_mask, .pb = pb};
2474 para_printf(pb, "checking attributes, mask: %" PRIx64 "\n", att_mask);
2475 return audio_file_loop(&acad, check_atts_of_audio_file);
2479 * Close the audio file table.
2481 * \param flags Usual flags that are passed to osl_close_table().
2483 * \sa \ref osl_close_table().
2485 static void aft_close(void)
2487 osl_close_table(audio_file_table, OSL_MARK_CLEAN);
2488 audio_file_table = NULL;
2492 * Open the audio file table.
2494 * \param dir The database directory.
2498 * \sa \ref osl_open_table().
2500 static int aft_open(const char *dir)
2504 audio_file_table_desc.dir = dir;
2505 ret = osl(osl_open_table(&audio_file_table_desc, &audio_file_table));
2508 osl_get_num_rows(audio_file_table, &num);
2509 PARA_INFO_LOG("audio file table contains %u files\n", num);
2512 PARA_NOTICE_LOG("failed to open audio file table\n");
2513 audio_file_table = NULL;
2514 if (ret == -OSL_ERRNO_TO_PARA_ERROR(E_OSL_NOENT))
2519 static int aft_create(const char *dir)
2521 audio_file_table_desc.dir = dir;
2522 return osl(osl_create_table(&audio_file_table_desc));
2525 static int clear_attribute(struct osl_row *row, void *data)
2527 struct rmatt_event_data *red = data;
2528 struct afs_info afsi;
2529 struct osl_object obj;
2530 int ret = get_afsi_object_of_row(row, &obj);
2531 uint64_t mask = ~(1ULL << red->bitnum);
2535 ret = load_afsi(&afsi, &obj);
2538 afsi.attributes &= mask;
2539 save_afsi(&afsi, &obj);
2543 static int aft_event_handler(enum afs_events event, struct para_buffer *pb,
2549 case ATTRIBUTE_REMOVE: {
2550 const struct rmatt_event_data *red = data;
2551 para_printf(pb, "clearing attribute %s (bit %u) from all "
2552 "entries in the audio file table\n", red->name,
2554 return audio_file_loop(data, clear_attribute);
2555 } case AFSI_CHANGE: {
2556 struct afsi_change_event_data *aced = data;
2557 uint64_t old_last_played = status_item_ls_data.afsi.last_played;
2558 if (aced->aft_row != current_aft_row)
2560 ret = get_afsi_of_row(aced->aft_row, &status_item_ls_data.afsi);
2563 status_item_ls_data.afsi.last_played = old_last_played;
2564 make_status_items();
2566 } case AFHI_CHANGE: {
2567 if (data != current_aft_row)
2569 ret = get_afhi_of_row(data, &status_item_ls_data.afhi);
2572 make_status_items();
2579 * These events are rare. We don't bother to check whether the
2580 * current status items are affected and simply recreate them
2583 make_status_items();
2590 * Initialize the audio file table.
2592 * \param t Pointer to the structure to be initialized.
2594 void aft_init(struct afs_table *t)
2597 t->close = aft_close;
2598 t->create = aft_create;
2599 t->event_handler = aft_event_handler;