Fix some signedness warnings.
[paraslash.git] / aft.c
1 #include "para.h"
2 #include "error.h"
3 #include <sys/mman.h>
4 #include <fnmatch.h>
5 #include "afs.h"
6 #include "string.h"
7
8 int mp3_get_file_info(char *map, size_t numbytes,
9 struct audio_format_info *afi); /* FXIME */
10
11 #define AFS_AUDIO_FILE_DIR "/home/mp3"
12
13 static void *audio_file_table;
14
15 /**
16 * Describes the structure of the mmapped-afs info struct.
17 *
18 * \sa struct afs_info.
19 */
20 enum afsi_offsets {
21 /** Where .last_played is stored. */
22 AFSI_LAST_PLAYED_OFFSET = 0,
23 /** Storage position of the attributes bitmap. */
24 AFSI_ATTRIBUTES_OFFSET = 8,
25 /** Storage position of the .num_played field. */
26 AFSI_NUM_PLAYED_OFFSET = 16,
27 /** Storage position of the .image_id field. */
28 AFSI_IMAGE_ID_OFFSET = 20,
29 /** Storage position of the .lyrics_id field. */
30 AFSI_LYRICS_ID_OFFSET = 24,
31 /** Storage position of the .audio_format_id field. */
32 AFSI_AUDIO_FORMAT_ID_OFFSET = 28,
33 /** On-disk storage space needed. */
34 AFSI_SIZE = 29
35 };
36
37 /**
38 * Convert a struct afs_info to an osl object.
39 *
40 * \param afsi Pointer to the audio file info to be converted.
41 * \param obj Result pointer.
42 *
43 * \sa load_afsi().
44 */
45 void save_afsi(struct afs_info *afsi, struct osl_object *obj)
46 {
47 struct afs_info default_afs_info = {
48 .last_played = time(NULL) - 365 * 24 * 60 * 60,
49 .attributes = 0,
50 .num_played = 0,
51 .image_id = 0,
52 .lyrics_id = 0,
53 .audio_format_id = 5, /* FIXME */
54 };
55 char *buf = obj->data;
56
57 if (!afsi)
58 afsi = &default_afs_info;
59
60 write_u64(buf + AFSI_LAST_PLAYED_OFFSET, afsi->last_played);
61 write_u64(buf + AFSI_ATTRIBUTES_OFFSET, afsi->attributes);
62 write_u32(buf + AFSI_NUM_PLAYED_OFFSET, afsi->num_played);
63 write_u32(buf + AFSI_IMAGE_ID_OFFSET, afsi->image_id);
64 write_u32(buf + AFSI_LYRICS_ID_OFFSET, afsi->lyrics_id);
65 write_u8(buf + AFSI_AUDIO_FORMAT_ID_OFFSET,
66 afsi->audio_format_id);
67 }
68
69 /**
70 * Get the audio file selector info struct stored in an osl object.
71 *
72 * \param afsi Points to the audio_file info structure to be filled in.
73 * \param obj The osl object holding the data.
74 *
75 * \return Positive on success, negative on errors. Possible errors: \p E_BAD_AFS.
76 *
77 * \sa save_afsi().
78 */
79 int load_afsi(struct afs_info *afsi, struct osl_object *obj)
80 {
81 char *buf = obj->data;
82 if (obj->size < AFSI_SIZE)
83 return -E_BAD_AFS;
84 afsi->last_played = read_u64(buf + AFSI_LAST_PLAYED_OFFSET);
85 afsi->attributes = read_u64(buf + AFSI_ATTRIBUTES_OFFSET);
86 afsi->num_played = read_u32(buf + AFSI_NUM_PLAYED_OFFSET);
87 afsi->image_id = read_u32(buf + AFSI_IMAGE_ID_OFFSET);
88 afsi->lyrics_id = read_u32(buf + AFSI_LYRICS_ID_OFFSET);
89 afsi->audio_format_id = read_u8(buf +
90 AFSI_AUDIO_FORMAT_ID_OFFSET);
91 return 1;
92 }
93
94 /** The columns of the audio file table. */
95 enum audio_file_table_columns {
96 /** The hash on the content of the audio file. */
97 AFTCOL_HASH,
98 /** The full path in the filesystem. */
99 AFTCOL_PATH,
100 /** The audio file selector info. */
101 AFTCOL_AFSI,
102 /** The audio format handler info. */
103 AFTCOL_AFHI,
104 /** The chunk table info and the chunk table of the audio file. */
105 AFTCOL_CHUNKS,
106 /** The number of columns of this table. */
107 NUM_AFT_COLUMNS
108 };
109
110 static struct osl_column_description aft_cols[] = {
111 [AFTCOL_HASH] = {
112 .storage_type = OSL_MAPPED_STORAGE,
113 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE | OSL_UNIQUE,
114 .name = "hash",
115 .compare_function = osl_hash_compare,
116 .data_size = HASH_SIZE
117 },
118 [AFTCOL_PATH] = {
119 .storage_type = OSL_MAPPED_STORAGE,
120 .storage_flags = OSL_RBTREE | OSL_UNIQUE,
121 .name = "path",
122 .compare_function = string_compare,
123 },
124 [AFTCOL_AFSI] = {
125 .storage_type = OSL_MAPPED_STORAGE,
126 .storage_flags = OSL_FIXED_SIZE,
127 .name = "afs_info",
128 .data_size = AFSI_SIZE
129 },
130 [AFTCOL_AFHI] = {
131 .storage_type = OSL_MAPPED_STORAGE,
132 .name = "afh_info",
133 },
134 [AFTCOL_CHUNKS] = {
135 .storage_type = OSL_DISK_STORAGE,
136 .name = "chunks",
137 }
138 };
139
140 static const struct osl_table_description audio_file_table_desc = {
141 .dir = DATABASE_DIR,
142 .name = "audio_files",
143 .num_columns = NUM_AFT_COLUMNS,
144 .flags = OSL_LARGE_TABLE,
145 .column_descriptions = aft_cols
146 };
147
148 static char *prefix_path(const char *prefix, int len, const char *path)
149 {
150 int speclen;
151 char *n;
152
153 for (;;) {
154 char c;
155 if (*path != '.')
156 break;
157 c = path[1];
158 /* "." */
159 if (!c) {
160 path++;
161 break;
162 }
163 /* "./" */
164 if (c == '/') {
165 path += 2;
166 continue;
167 }
168 if (c != '.')
169 break;
170 c = path[2];
171 if (!c)
172 path += 2;
173 else if (c == '/')
174 path += 3;
175 else
176 break;
177 /* ".." and "../" */
178 /* Remove last component of the prefix */
179 do {
180 if (!len)
181 return NULL;
182 len--;
183 } while (len && prefix[len-1] != '/');
184 continue;
185 }
186 if (!len)
187 return para_strdup(path);
188 speclen = strlen(path);
189 n = para_malloc(speclen + len + 1);
190 memcpy(n, prefix, len);
191 memcpy(n + len, path, speclen+1);
192 return n;
193 }
194
195 /*
196 * We fundamentally don't like some paths: we don't want
197 * dot or dot-dot anywhere.
198 *
199 * Also, we don't want double slashes or slashes at the
200 * end that can make pathnames ambiguous.
201 */
202 static int verify_dotfile(const char *rest)
203 {
204 /*
205 * The first character was '.', but that has already been discarded, we
206 * now test the rest.
207 */
208 switch (*rest) {
209 /* "." is not allowed */
210 case '\0': case '/':
211 return 1;
212
213 case '.':
214 if (rest[1] == '\0' || rest[1] == '/')
215 return -1;
216 }
217 return 1;
218 }
219
220 static int verify_path(const char *path, char **resolved_path)
221 {
222 const char *orig_path = path;
223 char c;
224 const char prefix[] = AFS_AUDIO_FILE_DIR "/";
225 const size_t prefix_len = strlen(prefix);
226
227 PARA_DEBUG_LOG("path: %s\n", path);
228 c = *path++;
229 if (!c)
230 return -E_BAD_PATH;
231 while (c) {
232 if (c == '/') {
233 c = *path++;
234 switch (c) {
235 default:
236 continue;
237 case '/': case '\0':
238 break;
239 case '.':
240 if (verify_dotfile(path) > 0)
241 continue;
242 }
243 *resolved_path = NULL;
244 return -E_BAD_PATH;
245 }
246 c = *path++;
247 }
248 if (*orig_path == '/')
249 *resolved_path = prefix_path("", 0, orig_path);
250 else
251 *resolved_path = prefix_path(prefix, prefix_len, orig_path);
252 PARA_DEBUG_LOG("resolved: %s\n", *resolved_path);
253 return *resolved_path? 1: -E_BAD_PATH;
254 }
255
256 enum afhi_offsets {
257 AFHI_SECONDS_TOTAL_OFFSET = 0,
258 AFHI_BITRATE_OFFSET = 4,
259 AFHI_FREQUENCY_OFFSET = 8,
260 AFHI_CHANNELS_OFFSET = 12,
261 AFHI_INFO_STRING_OFFSET = 13,
262 MIN_AFHI_SIZE = 14
263 };
264
265 static unsigned sizeof_afhi_buf(const struct audio_format_info *afhi)
266 {
267 if (!afhi)
268 return 0;
269 return strlen(afhi->info_string) + MIN_AFHI_SIZE;
270 }
271
272 static void save_afhi(struct audio_format_info *afhi, char *buf)
273 {
274 if (!afhi)
275 return;
276 write_u32(buf + AFHI_SECONDS_TOTAL_OFFSET,
277 afhi->seconds_total);
278 write_u32(buf + AFHI_BITRATE_OFFSET, afhi->bitrate);
279 write_u32(buf + AFHI_FREQUENCY_OFFSET, afhi->frequency);
280 write_u8(buf + AFHI_CHANNELS_OFFSET, afhi->channels);
281 strcpy(buf + AFHI_INFO_STRING_OFFSET, afhi->info_string); /* OK */
282 PARA_DEBUG_LOG("last byte written: %p\n", buf + AFHI_INFO_STRING_OFFSET + strlen(afhi->info_string));
283 }
284
285 static void load_afhi(const char *buf, struct audio_format_info *afhi)
286 {
287 afhi->seconds_total = read_u32(buf + AFHI_SECONDS_TOTAL_OFFSET);
288 afhi->bitrate = read_u32(buf + AFHI_BITRATE_OFFSET);
289 afhi->frequency = read_u32(buf + AFHI_FREQUENCY_OFFSET);
290 afhi->channels = read_u8(buf + AFHI_CHANNELS_OFFSET);
291 strcpy(afhi->info_string, buf + AFHI_INFO_STRING_OFFSET);
292 }
293
294 static unsigned sizeof_chunk_info_buf(struct audio_format_info *afhi)
295 {
296 if (!afhi)
297 return 0;
298 return 4 * afhi->chunks_total + 20;
299
300 }
301
302 /** The offsets of the data contained in the AFTCOL_CHUNKS column. */
303 enum chunk_info_offsets {
304 /** The total number of chunks (4 bytes). */
305 CHUNKS_TOTAL_OFFSET = 0,
306 /** The length of the audio file header (4 bytes). */
307 HEADER_LEN_OFFSET = 4,
308 /** The start of the audio file header (4 bytes). */
309 HEADER_OFFSET_OFFSET = 8,
310 /** The seconds part of the chunk time (4 bytes). */
311 CHUNK_TV_TV_SEC_OFFSET = 12,
312 /** The microseconds part of the chunk time (4 bytes). */
313 CHUNK_TV_TV_USEC = 16,
314 /** Chunk table entries start here. */
315 CHUNK_TABLE_OFFSET = 20,
316 };
317
318 /* TODO: audio format handlers could just produce this */
319 static void save_chunk_info(struct audio_format_info *afhi, char *buf)
320 {
321 int i;
322
323 if (!afhi)
324 return;
325 write_u32(buf + CHUNKS_TOTAL_OFFSET, afhi->chunks_total);
326 write_u32(buf + HEADER_LEN_OFFSET, afhi->header_len);
327 write_u32(buf + HEADER_OFFSET_OFFSET, afhi->header_offset);
328 write_u32(buf + CHUNK_TV_TV_SEC_OFFSET, afhi->chunk_tv.tv_sec);
329 write_u32(buf + CHUNK_TV_TV_USEC, afhi->chunk_tv.tv_usec);
330 for (i = 0; i < afhi->chunks_total; i++)
331 write_u32(buf + CHUNK_TABLE_OFFSET + 4 * i, afhi->chunk_table[i]);
332 }
333
334 static int load_chunk_info(struct osl_object *obj, struct audio_format_info *afhi)
335 {
336 char *buf = obj->data;
337 int i;
338
339 if (obj->size < CHUNK_TABLE_OFFSET)
340 return -E_BAD_DATA_SIZE;
341
342 afhi->chunks_total = read_u32(buf + CHUNKS_TOTAL_OFFSET);
343 afhi->header_len = read_u32(buf + HEADER_LEN_OFFSET);
344 afhi->header_offset = read_u32(buf + HEADER_OFFSET_OFFSET);
345 afhi->chunk_tv.tv_sec = read_u32(buf + CHUNK_TV_TV_SEC_OFFSET);
346 afhi->chunk_tv.tv_usec = read_u32(buf + CHUNK_TV_TV_USEC);
347
348 if (afhi->chunks_total * 4 + CHUNK_TABLE_OFFSET > obj->size)
349 return -E_BAD_DATA_SIZE;
350 afhi->chunk_table = para_malloc(afhi->chunks_total * sizeof(size_t));
351 for (i = 0; i < afhi->chunks_total; i++)
352 afhi->chunk_table[i] = read_u32(buf + CHUNK_TABLE_OFFSET + 4 * i);
353 return 1;
354 }
355
356 /**
357 * Get the row of the audio file table corresponding to the given path.
358 *
359 * \param path The full path of the audio file.
360 * \param row Result pointer.
361 *
362 * \return The return value of the underlying call to osl_get_row().
363 */
364 int aft_get_row_of_path(char *path, struct osl_row **row)
365 {
366 struct osl_object obj = {.data = path, .size = strlen(path) + 1};
367 return osl_get_row(audio_file_table, AFTCOL_PATH, &obj, row);
368 }
369
370 /**
371 * Get the row of the audio file table corresponding to the given hash value.
372 *
373 * \param hash The hash value of the desired audio file.
374 * \param row resul pointer.
375 *
376 * \return The return value of the underlying call to osl_get_row().
377 */
378 int aft_get_row_of_hash(HASH_TYPE *hash, struct osl_row **row)
379 {
380 const struct osl_object obj = {.data = hash, .size = HASH_SIZE};
381 return osl_get_row(audio_file_table, AFTCOL_HASH, &obj, row);
382 }
383
384 /**
385 * Get the osl object holding the audio file selector info of a row.
386 *
387 * \param row Pointer to a row in the audio file table.
388 * \param obj Result pointer.
389 *
390 * \return The return value of the underlying call to osl_get_object().
391 */
392 int get_afsi_object_of_row(const void *row, struct osl_object *obj)
393 {
394 return osl_get_object(audio_file_table, row, AFTCOL_AFSI, obj);
395 }
396
397 /**
398 * Get the osl object holding the audio file selector info, given a path.
399 *
400 *
401 * \param path The full path of the audio file.
402 * \param obj Result pointer.
403 *
404 * \return Positive on success, negative on errors.
405 */
406 int get_afsi_object_of_path(char *path, struct osl_object *obj)
407 {
408 struct osl_row *row;
409 int ret = aft_get_row_of_path(path, &row);
410 if (ret < 0)
411 return ret;
412 return get_afsi_object_of_row(row, obj);
413 }
414
415 /**
416 * Get the audio file selector info, given a row of the audio file table.
417 *
418 * \param row Pointer to a row in the audio file table.
419 * \param afsi Result pointer.
420 *
421 * \return Positive on success, negative on errors.
422 */
423 int get_afsi_of_row(const struct osl_row *row, struct afs_info *afsi)
424 {
425 struct osl_object obj;
426 int ret = get_afsi_object_of_row(row, &obj);
427 if (ret < 0)
428 return ret;
429 return load_afsi(afsi, &obj);
430 }
431
432 /**
433 * Get the path of an audio file, given a row of the audio file table.
434 *
435 * \param row Pointer to a row in the audio file table.
436 * \param path Result pointer.
437 *
438 * \return Positive on success, negative on errors.
439 */
440 int get_audio_file_path_of_row(const struct osl_row *row, char **path)
441 {
442 struct osl_object path_obj;
443 int ret = osl_get_object(audio_file_table, row, AFTCOL_PATH,
444 &path_obj);
445 if (ret < 0)
446 return ret;
447 *path = path_obj.data;
448 return 1;
449 }
450
451 /**
452 * Get the object containing the hash value of an audio file, given a row.
453 *
454 * \param row Pointer to a row of the audio file table.
455 * \param obj Result pointer.
456 *
457 * \return The return value of the underlying call to osl_get_object().
458 *
459 * \sa get_hash_of_row().
460 */
461 int get_hash_object_of_aft_row(const void *row, struct osl_object *obj)
462 {
463 return osl_get_object(audio_file_table, row, AFTCOL_HASH, obj);
464 }
465
466 /**
467 * Get the hash value of an audio file, given a row of the audio file table.
468 *
469 * \param row Pointer to a row of the audio file table.
470 * \param hash Result pointer.
471 *
472 * \a hash points to mapped data and must not be freed by the caller.
473 *
474 * \return The return value of the underlying call to
475 * get_hash_object_of_aft_row().
476 */
477 static int get_hash_of_row(const void *row, HASH_TYPE **hash)
478 {
479 struct osl_object obj;
480 int ret = get_hash_object_of_aft_row(row, &obj);
481
482 if (ret < 0)
483 return ret;
484 *hash = obj.data;
485 return 1;
486 }
487
488 /**
489 * Get the audio format handler info, given a row of the audio file table.
490 *
491 * \param row Pointer to a row of the audio file table.
492 * \param afhi Result pointer.
493 *
494 * \return The return value of the underlying call to osl_get_object().
495 *
496 * \sa get_chunk_table_of_row().
497 */
498 int get_afhi_of_row(const void *row, struct audio_format_info *afhi)
499 {
500 struct osl_object obj;
501 int ret = osl_get_object(audio_file_table, row, AFTCOL_AFHI,
502 &obj);
503 if (ret < 0)
504 return ret;
505 load_afhi(obj.data, afhi);
506 return 1;
507 }
508
509 /**
510 * Get the chunk table of an audio file, given a row of the audio file table.
511 *
512 * \param row Pointer to a row of the audio file table.
513 * \param afhi Result pointer.
514 *
515 * \return The return value of the underlying call to osl_open_disk_object().
516 *
517 * \sa get_afhi_of_row().
518 */
519 int get_chunk_table_of_row(const void *row, struct audio_format_info *afhi)
520 {
521 struct osl_object obj;
522 int ret = osl_open_disk_object(audio_file_table, row, AFTCOL_CHUNKS,
523 &obj);
524 if (ret < 0)
525 return ret;
526 ret = load_chunk_info(&obj, afhi);
527 osl_close_disk_object(&obj);
528 return ret;
529 }
530
531 /**
532 * Mmap the given audio file and update statistics.
533 *
534 * \param aft_row Determines the audio file to be opened and updated.
535 * \param afd Result pointer.
536 *
537 * On success, the numplayed field of the audio file selector info is increased
538 * and the lastplayed time is set to the current time. Finally, the score of
539 * the audio file is updated.
540 *
541 * \return Positive on success, negative on errors.
542 */
543 int open_and_update_audio_file(struct osl_row *aft_row, struct audio_file_data *afd)
544 {
545 HASH_TYPE *aft_hash, file_hash[HASH_SIZE];
546 struct osl_object afsi_obj;
547 struct afs_info new_afsi;
548 int ret = get_hash_of_row(aft_row, &aft_hash);
549
550 if (ret < 0)
551 return ret;
552 ret = get_audio_file_path_of_row(aft_row, &afd->path);
553 if (ret < 0)
554 return ret;
555 ret = get_afsi_object_of_row(aft_row, &afsi_obj);
556 if (ret < 0)
557 return ret;
558 ret = load_afsi(&afd->afsi, &afsi_obj);
559 if (ret < 0)
560 return ret;
561 ret = get_afhi_of_row(aft_row, &afd->afhi);
562 if (ret < 0)
563 return ret;
564 ret = get_chunk_table_of_row(aft_row, &afd->afhi);
565 if (ret < 0)
566 return ret;
567 ret = mmap_full_file(afd->path, O_RDONLY, &afd->map);
568 if (ret < 0)
569 goto err;
570 hash_function(afd->map.data, afd->map.size, file_hash);
571 ret = -E_HASH_MISMATCH;
572 if (hash_compare(file_hash, aft_hash))
573 goto err;
574 new_afsi = afd->afsi;
575 new_afsi.num_played++;
576 new_afsi.last_played = time(NULL);
577 save_afsi(&new_afsi, &afsi_obj); /* in-place update */
578 if (afd->current_play_mode == PLAY_MODE_PLAYLIST)
579 ret = playlist_update_audio_file(aft_row);
580 else
581 ret = mood_update_audio_file(aft_row, &afd->afsi);
582 return ret;
583 err:
584 free(afd->afhi.chunk_table);
585 return ret;
586 }
587
588 time_t now;
589
590 static int get_local_time(uint64_t *seconds, char *buf, size_t size)
591 {
592 struct tm t;
593
594 if (!localtime_r((time_t *)seconds, &t))
595 return -E_LOCALTIME;
596 if (*seconds + 6 * 30 * 24 * 3600 > now) {
597 if (!strftime(buf, size, "%b %e %k:%M", &t))
598 return -E_STRFTIME;
599 return 1;
600 }
601 if (!strftime(buf, size, "%b %e %Y", &t))
602 return -E_STRFTIME;
603 return 1;
604 }
605
606 #define GET_NUM_DIGITS(x, num) { \
607 typeof((x)) _tmp = PARA_ABS(x); \
608 *num = 1; \
609 if ((x)) \
610 while ((_tmp) > 9) { \
611 (_tmp) /= 10; \
612 (*num)++; \
613 } \
614 }
615
616 static short unsigned get_duration(int seconds_total, char *buf, short unsigned max_width)
617 {
618 short unsigned width;
619 int s = seconds_total;
620 unsigned hours = s / 3600, mins = (s % 3600) / 60, secs = s % 60;
621
622 if (s < 3600) { /* less than one hour => m:ss or mm:ss */
623 GET_NUM_DIGITS(mins, &width); /* 1 or 2 */
624 width += 3; /* 4 or 5 */
625 if (buf)
626 sprintf(buf, "%*u:%02u", max_width - width + 1, mins, secs);
627 return width;
628 }
629 /* more than one hour => h:mm:ss, hh:mm:ss, hhh:mm:ss, ... */
630 GET_NUM_DIGITS(hours, &width);
631 width += 6;
632 if (buf)
633 sprintf(buf, "%*u:%02u:%02u", max_width - width + 1, hours, mins, secs);
634 return width;
635 }
636
637 static char *make_attribute_line(const char *att_bitmap, struct afs_info *afsi)
638 {
639 char *att_text, *att_line;
640
641 get_attribute_text(&afsi->attributes, " ", &att_text);
642 if (!att_text)
643 return para_strdup(att_bitmap);
644 att_line = make_message("%s (%s)", att_bitmap, att_text);
645 free(att_text);
646 return att_line;
647 }
648
649 static char *make_lyrics_line(struct afs_info *afsi)
650 {
651 char *lyrics_name;
652 lyr_get_name_by_id(afsi->lyrics_id, &lyrics_name);
653 if (!lyrics_name)
654 return make_message("%u", afsi->lyrics_id);
655 return make_message("%u (%s)", afsi->lyrics_id, lyrics_name);
656 }
657
658 static char *make_image_line(struct afs_info *afsi)
659 {
660 char *image_name;
661 img_get_name_by_id(afsi->image_id, &image_name);
662 if (!image_name)
663 return make_message("%u", afsi->image_id);
664 return make_message("%u (%s)", afsi->image_id, image_name);
665 }
666
667 static int print_list_item(struct ls_data *d, struct ls_options *opts,
668 struct para_buffer *b)
669 {
670 int ret;
671 char att_buf[65];
672 char last_played_time[30];
673 char duration_buf[30]; /* nobody has an audio file long enough to overflow this */
674 char score_buf[30] = "";
675 struct afs_info *afsi = &d->afsi;
676 struct audio_format_info *afhi = &d->afhi;
677 struct ls_widths *w = &opts->widths;
678 int have_score = opts->flags & LS_FLAG_ADMISSIBLE_ONLY;
679
680 if (opts->mode == LS_MODE_SHORT) {
681 para_printf(b, "%s\n", d->path);
682 return 1;
683 }
684 get_attribute_bitmap(&afsi->attributes, att_buf);
685 ret = get_local_time(&afsi->last_played, last_played_time,
686 sizeof(last_played_time));
687 if (ret < 0)
688 return ret;
689 get_duration(afhi->seconds_total, duration_buf, w->duration_width);
690 if (have_score) {
691 if (opts->mode == LS_MODE_LONG)
692 sprintf(score_buf, "%*li ", w->score_width, d->score);
693 else
694 sprintf(score_buf, "%li ", d->score);
695 }
696
697 if (opts->mode == LS_MODE_LONG) {
698 para_printf(b,
699 "%s" /* score */
700 "%s " /* attributes */
701 "%*d " /* image_id */
702 "%*d " /* lyrics_id */
703 "%*d " /* bitrate */
704 "%s " /* audio format */
705 "%*d " /* frequency */
706 "%d " /* channels */
707 "%s " /* duration */
708 "%*d " /* num_played */
709 "%s " /* last_played */
710 "%s\n", /* path */
711 score_buf,
712 att_buf,
713 w->image_id_width, afsi->image_id,
714 w->lyrics_id_width, afsi->lyrics_id,
715 w->bitrate_width, afhi->bitrate,
716 "mp3", /* FIXME */
717 w->frequency_width, afhi->frequency,
718 afhi->channels,
719 duration_buf,
720 w->num_played_width, afsi->num_played,
721 last_played_time,
722 d->path
723 );
724 return 1;
725 }
726 if (opts->mode == LS_MODE_VERBOSE) {
727 char asc_hash[2 * HASH_SIZE + 1];
728 char *att_line, *lyrics_line, *image_line;
729
730 hash_to_asc(d->hash, asc_hash);
731 att_line = make_attribute_line(att_buf, afsi);
732 lyrics_line = make_lyrics_line(afsi);
733 image_line = make_image_line(afsi);
734 para_printf(b,
735 "%s: %s\n" /* path */
736 "%s%s%s" /* score */
737 "attributes: %s\n"
738 "hash: %s\n"
739 "image_id: %s\n"
740 "lyrics_id: %s\n"
741 "bitrate: %dkbit/s\n"
742 "format: %s\n"
743 "frequency: %dHz\n"
744 "channels: %d\n"
745 "duration: %s\n"
746 "num_played: %d\n"
747 "last_played: %s\n\n",
748 (opts->flags & LS_FLAG_FULL_PATH)?
749 "path" : "file", d->path,
750 have_score? "score: " : "", score_buf,
751 have_score? "\n" : "",
752 att_line,
753 asc_hash,
754 image_line,
755 lyrics_line,
756 afhi->bitrate,
757 "mp3", /* FIXME */
758 afhi->frequency,
759 afhi->channels,
760 duration_buf,
761 afsi->num_played,
762 last_played_time
763 );
764 free(att_line);
765 free(lyrics_line);
766 free(image_line);
767 return 1;
768 }
769 return 1;
770 }
771
772 static int ls_audio_format_compare(const void *a, const void *b)
773 {
774 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
775 return NUM_COMPARE(d1->afsi.audio_format_id, d2->afsi.audio_format_id);
776 }
777
778 static int ls_duration_compare(const void *a, const void *b)
779 {
780 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
781 return NUM_COMPARE(d1->afhi.seconds_total, d2->afhi.seconds_total);
782 }
783
784 static int ls_bitrate_compare(const void *a, const void *b)
785 {
786 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
787 return NUM_COMPARE(d1->afhi.bitrate, d2->afhi.bitrate);
788 }
789
790 static int ls_lyrics_id_compare(const void *a, const void *b)
791 {
792 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
793 return NUM_COMPARE(d1->afsi.lyrics_id, d2->afsi.lyrics_id);
794 }
795
796 static int ls_image_id_compare(const void *a, const void *b)
797 {
798 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
799 return NUM_COMPARE(d1->afsi.image_id, d2->afsi.image_id);
800 }
801
802 static int ls_channels_compare(const void *a, const void *b)
803 {
804 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
805 return NUM_COMPARE(d1->afhi.channels, d2->afhi.channels);
806 }
807
808 static int ls_frequency_compare(const void *a, const void *b)
809 {
810 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
811 return NUM_COMPARE(d1->afhi.frequency, d2->afhi.frequency);
812 }
813
814 static int ls_num_played_compare(const void *a, const void *b)
815 {
816 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
817 return NUM_COMPARE(d1->afsi.num_played, d2->afsi.num_played);
818 }
819
820 static int ls_last_played_compare(const void *a, const void *b)
821 {
822 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
823 return NUM_COMPARE(d1->afsi.last_played, d2->afsi.last_played);
824 }
825
826 static int ls_score_compare(const void *a, const void *b)
827 {
828 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
829 return NUM_COMPARE(d1->score, d2->score);
830 }
831
832 static int ls_path_compare(const void *a, const void *b)
833 {
834 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
835 return strcmp(d1->path, d2->path);
836 }
837
838 static int sort_matching_paths(struct ls_options *options)
839 {
840 size_t nmemb = options->num_matching_paths;
841 size_t size = sizeof(uint32_t);
842 int (*compar)(const void *, const void *);
843 int i;
844
845 options->data_ptr = para_malloc(nmemb * sizeof(*options->data_ptr));
846 for (i = 0; i < nmemb; i++)
847 options->data_ptr[i] = options->data + i;
848
849 /* In these cases the array is already sorted */
850 if (options->sorting == LS_SORT_BY_PATH
851 && !(options->flags & LS_FLAG_ADMISSIBLE_ONLY)
852 && (options->flags & LS_FLAG_FULL_PATH))
853 return 1;
854 if (options->sorting == LS_SORT_BY_SCORE &&
855 options->flags & LS_FLAG_ADMISSIBLE_ONLY)
856 return 1;
857
858 switch (options->sorting) {
859 case LS_SORT_BY_PATH:
860 compar = ls_path_compare; break;
861 case LS_SORT_BY_SCORE:
862 compar = ls_score_compare; break;
863 case LS_SORT_BY_LAST_PLAYED:
864 compar = ls_last_played_compare; break;
865 case LS_SORT_BY_NUM_PLAYED:
866 compar = ls_num_played_compare; break;
867 case LS_SORT_BY_FREQUENCY:
868 compar = ls_frequency_compare; break;
869 case LS_SORT_BY_CHANNELS:
870 compar = ls_channels_compare; break;
871 case LS_SORT_BY_IMAGE_ID:
872 compar = ls_image_id_compare; break;
873 case LS_SORT_BY_LYRICS_ID:
874 compar = ls_lyrics_id_compare; break;
875 case LS_SORT_BY_BITRATE:
876 compar = ls_bitrate_compare; break;
877 case LS_SORT_BY_DURATION:
878 compar = ls_duration_compare; break;
879 case LS_SORT_BY_AUDIO_FORMAT:
880 compar = ls_audio_format_compare; break;
881 default:
882 return -E_BAD_SORT;
883 }
884 qsort(options->data_ptr, nmemb, size, compar);
885 return 1;
886 }
887
888 /* row is either an aft_row or a row of the score table */
889 /* TODO: Only compute widths if we need them */
890 static int prepare_ls_row(struct osl_row *row, void *ls_opts)
891 {
892 int ret, i;
893 struct ls_options *options = ls_opts;
894 struct ls_data *d;
895 struct ls_widths *w;
896 unsigned short num_digits;
897 unsigned tmp;
898 struct osl_row *aft_row;
899 long score;
900 char *path;
901
902 if (options->flags & LS_FLAG_ADMISSIBLE_ONLY) {
903 ret = get_score_and_aft_row(row, &score, &aft_row);
904 if (ret < 0)
905 return ret;
906 } else
907 aft_row = row;
908 ret = get_audio_file_path_of_row(aft_row, &path);
909 if (ret < 0)
910 return ret;
911 if (!(options->flags & LS_FLAG_FULL_PATH)) {
912 char *p = strrchr(path, '/');
913 if (p)
914 path = p + 1;
915 }
916 if (options->num_patterns) {
917 for (i = 0; i < options->num_patterns; i++) {
918 ret = fnmatch(options->patterns[i], path, FNM_PATHNAME);
919 if (!ret)
920 break;
921 if (ret == FNM_NOMATCH)
922 continue;
923 return -E_FNMATCH;
924 }
925 if (i >= options->num_patterns) /* no match */
926 return 1;
927 }
928 tmp = options->num_matching_paths++;
929 if (options->num_matching_paths > options->array_size) {
930 options->array_size++;
931 options->array_size *= 2;
932 options->data = para_realloc(options->data, options->array_size
933 * sizeof(*options->data));
934 }
935 d = options->data + tmp;
936 ret = get_afsi_of_row(aft_row, &d->afsi);
937 if (ret < 0)
938 return ret;
939 ret = get_afhi_of_row(aft_row, &d->afhi);
940 if (ret < 0)
941 return ret;
942 d->path = path;
943 ret = get_hash_of_row(aft_row, &d->hash);
944 if (ret < 0)
945 return ret;
946 w = &options->widths;
947 GET_NUM_DIGITS(d->afsi.image_id, &num_digits);
948 w->image_id_width = PARA_MAX(w->image_id_width, num_digits);
949 GET_NUM_DIGITS(d->afsi.lyrics_id, &num_digits);
950 w->lyrics_id_width = PARA_MAX(w->lyrics_id_width, num_digits);
951 GET_NUM_DIGITS(d->afhi.bitrate, &num_digits);
952 w->bitrate_width = PARA_MAX(w->bitrate_width, num_digits);
953 GET_NUM_DIGITS(d->afhi.frequency, &num_digits);
954 w->frequency_width = PARA_MAX(w->frequency_width, num_digits);
955 GET_NUM_DIGITS(d->afsi.num_played, &num_digits);
956 w->num_played_width = PARA_MAX(w->num_played_width, num_digits);
957 /* just get the number of chars to print this amount of time */
958 tmp = get_duration(d->afhi.seconds_total, NULL, 0);
959 w->duration_width = PARA_MAX(w->duration_width, tmp);
960 if (options->flags & LS_FLAG_ADMISSIBLE_ONLY) {
961 GET_NUM_DIGITS(score, &num_digits);
962 num_digits++; /* add one for the sign (space or "-") */
963 w->score_width = PARA_MAX(w->score_width, num_digits);
964 d->score = score;
965 }
966 return 1;
967 }
968
969 static int com_ls_callback(const struct osl_object *query,
970 struct osl_object *ls_output)
971 {
972 struct ls_options *opts = query->data;
973 char *p, *pattern_start = (char *)query->data + sizeof(*opts);
974 struct para_buffer b = {.buf = NULL, .size = 0};
975 int i = 0, ret;
976
977 PARA_NOTICE_LOG("%d patterns\n", opts->num_patterns);
978 if (opts->num_patterns) {
979 opts->patterns = para_malloc(opts->num_patterns * sizeof(char *));
980 for (i = 0, p = pattern_start; i < opts->num_patterns; i++) {
981 opts->patterns[i] = p;
982 p += strlen(p) + 1;
983 PARA_NOTICE_LOG("pattern %d: %s\n", i, opts->patterns[i]);
984 }
985 } else
986 opts->patterns = NULL;
987 if (opts->flags & LS_FLAG_ADMISSIBLE_ONLY)
988 ret = admissible_file_loop(opts, prepare_ls_row);
989 else
990 ret = osl_rbtree_loop(audio_file_table, AFTCOL_PATH, opts,
991 prepare_ls_row);
992 if (ret < 0)
993 goto out;
994 ret = opts->num_patterns? -E_NO_MATCH : 1;
995 if (!opts->num_matching_paths) {
996 PARA_NOTICE_LOG("no match, ret: %d\n", ret);
997 goto out;
998 }
999 ret = sort_matching_paths(opts);
1000 if (ret < 0)
1001 goto out;
1002 if (opts->flags & LS_FLAG_REVERSE)
1003 for (i = opts->num_matching_paths - 1; i >= 0; i--) {
1004 ret = print_list_item(opts->data_ptr[i], opts, &b);
1005 if (ret < 0)
1006 break;
1007 }
1008 else
1009 for (i = 0; i < opts->num_matching_paths; i++) {
1010 ret = print_list_item(opts->data_ptr[i], opts, &b);
1011 if (ret < 0)
1012 break;
1013 }
1014 ret = 1;
1015 out:
1016 ls_output->data = b.buf;
1017 ls_output->size = b.size;
1018 free(opts->data);
1019 free(opts->data_ptr);
1020 free(opts->patterns);
1021 return ret;
1022 }
1023
1024 /*
1025 * TODO: flags -h (sort by hash)
1026 *
1027 * long list: list hash, attributes as (xx--x-x-), file size, lastplayed
1028 * full list: list everything, including afsi, afhi, atts as clear text
1029 *
1030 * */
1031 int com_afs_ls(__a_unused int fd, int argc, const char **argv)
1032 {
1033 int i, ret;
1034 unsigned flags = 0;
1035 enum ls_sorting_method sort = LS_SORT_BY_PATH;
1036 enum ls_listing_mode mode = LS_MODE_SHORT;
1037 struct ls_options opts = {.patterns = NULL};
1038 struct osl_object query = {.data = &opts, .size = sizeof(opts)},
1039 ls_output;
1040
1041 for (i = 1; i < argc; i++) {
1042 const char *arg = argv[i];
1043 if (arg[0] != '-')
1044 break;
1045 if (!strcmp(arg, "--")) {
1046 i++;
1047 break;
1048 }
1049 if (!strncmp(arg, "-l", 2)) {
1050 if (!*(arg + 2)) {
1051 mode = LS_MODE_LONG;
1052 continue;
1053 }
1054 if (*(arg + 3))
1055 return -E_AFT_SYNTAX;
1056 switch(*(arg + 2)) {
1057 case 's':
1058 mode = LS_MODE_SHORT;
1059 continue;
1060 case 'l':
1061 mode = LS_MODE_LONG;
1062 continue;
1063 case 'v':
1064 mode = LS_MODE_VERBOSE;
1065 continue;
1066 case 'm':
1067 mode = LS_MODE_MBOX;
1068 continue;
1069 default:
1070 return -E_AFT_SYNTAX;
1071 }
1072 }
1073 if (!strcmp(arg, "-p")) {
1074 flags |= LS_FLAG_FULL_PATH;
1075 continue;
1076 }
1077 if (!strcmp(arg, "-a")) {
1078 flags |= LS_FLAG_ADMISSIBLE_ONLY;
1079 continue;
1080 }
1081 if (!strcmp(arg, "-r")) {
1082 flags |= LS_FLAG_REVERSE;
1083 continue;
1084 }
1085 if (!strncmp(arg, "-s", 2)) {
1086 if (!*(arg + 2) || *(arg + 3))
1087 return -E_AFT_SYNTAX;
1088 switch(*(arg + 2)) {
1089 case 'p':
1090 sort = LS_SORT_BY_PATH;
1091 continue;
1092 case 's': /* -ss implies -a */
1093 sort = LS_SORT_BY_SCORE;
1094 flags |= LS_FLAG_ADMISSIBLE_ONLY;
1095 continue;
1096 case 'l':
1097 sort = LS_SORT_BY_LAST_PLAYED;
1098 continue;
1099 case 'n':
1100 sort = LS_SORT_BY_NUM_PLAYED;
1101 continue;
1102 case 'f':
1103 sort = LS_SORT_BY_FREQUENCY;
1104 continue;
1105 case 'c':
1106 sort = LS_SORT_BY_CHANNELS;
1107 continue;
1108 case 'i':
1109 sort = LS_SORT_BY_IMAGE_ID;
1110 continue;
1111 case 'y':
1112 sort = LS_SORT_BY_LYRICS_ID;
1113 continue;
1114 case 'b':
1115 sort = LS_SORT_BY_BITRATE;
1116 continue;
1117 case 'd':
1118 sort = LS_SORT_BY_DURATION;
1119 continue;
1120 case 'a':
1121 sort = LS_SORT_BY_AUDIO_FORMAT;
1122 continue;
1123 default:
1124 return -E_AFT_SYNTAX;
1125 }
1126 }
1127 return -E_AFT_SYNTAX;
1128 }
1129 time(&now);
1130 opts.flags = flags;
1131 opts.sorting = sort;
1132 opts.mode = mode;
1133 opts.num_patterns = argc - i;
1134 ret = send_option_arg_callback_request(&query, opts.num_patterns,
1135 argv + i, com_ls_callback, &ls_output);
1136 if (ret >= 0 && ls_output.data) {
1137 printf("%s\n", (char *)ls_output.data);
1138 free(ls_output.data);
1139 }
1140 return ret;
1141 }
1142
1143 /**
1144 * Call the given function for each file in the audio file table.
1145 *
1146 * \param private_data An arbitrary data pointer, passed to \a func.
1147 * \param func The custom function to be called.
1148 *
1149 * \return The return value of the underlying call to osl_rbtree_loop().
1150 */
1151 int audio_file_loop(void *private_data, osl_rbtree_loop_func *func)
1152 {
1153 return osl_rbtree_loop(audio_file_table, AFTCOL_HASH, private_data,
1154 func);
1155 }
1156
1157 static void *find_hash_sister(HASH_TYPE *hash)
1158 {
1159 const struct osl_object obj = {.data = hash, .size = HASH_SIZE};
1160 struct osl_row *row;
1161
1162 osl_get_row(audio_file_table, AFTCOL_HASH, &obj, &row);
1163 return row;
1164 }
1165
1166 #define AFTROW_HEADER_SIZE 4
1167
1168 enum aft_row_offsets {
1169 AFTROW_AFHI_OFFSET_POS = 0,
1170 AFTROW_CHUNKS_OFFSET_POS = 2,
1171 AFTROW_HASH_OFFSET = AFTROW_HEADER_SIZE,
1172 AFTROW_FLAGS_OFFSET = (AFTROW_HASH_OFFSET + HASH_SIZE),
1173 AFTROW_PATH_OFFSET = (AFTROW_FLAGS_OFFSET + 4)
1174 };
1175
1176 /* never save the afsi, as the server knows it too. Note that afhi might be NULL.
1177 * In this case, afhi won't be stored in the buffer */
1178 static void save_audio_file_info(HASH_TYPE *hash, const char *path,
1179 struct audio_format_info *afhi,
1180 uint32_t flags, struct osl_object *obj)
1181 {
1182 size_t path_len = strlen(path) + 1;
1183 size_t afhi_size = sizeof_afhi_buf(afhi);
1184 size_t size = AFTROW_PATH_OFFSET + path_len + afhi_size
1185 + sizeof_chunk_info_buf(afhi);
1186 char *buf = para_malloc(size);
1187 uint16_t pos;
1188
1189 memcpy(buf + AFTROW_HASH_OFFSET, hash, HASH_SIZE);
1190 write_u32(buf + AFTROW_FLAGS_OFFSET, flags);
1191 strcpy(buf + AFTROW_PATH_OFFSET, path);
1192
1193 pos = AFTROW_PATH_OFFSET + path_len;
1194 PARA_DEBUG_LOG("size: %zu, afhi starts at %d\n", size, pos);
1195 PARA_DEBUG_LOG("last afhi byte: %p, pos %d\n", buf + pos + afhi_size - 1,
1196 pos + afhi_size - 1);
1197 write_u16(buf + AFTROW_AFHI_OFFSET_POS, pos);
1198 save_afhi(afhi, buf + pos);
1199
1200 pos += afhi_size;
1201 PARA_DEBUG_LOG("size: %zu, chunks start at %d\n", size, pos);
1202 write_u16(buf + AFTROW_CHUNKS_OFFSET_POS, pos);
1203 save_chunk_info(afhi, buf + pos);
1204 PARA_DEBUG_LOG("last byte in buf: %p\n", buf + size - 1);
1205 obj->data = buf;
1206 obj->size = size;
1207 }
1208
1209 /*
1210 input:
1211 ~~~~~~
1212 HS: hash sister
1213 PB: path brother
1214 F: force flag given
1215
1216 output:
1217 ~~~~~~~
1218 AFHI: whether afhi and chunk table are computed and sent
1219 ACTION: table modifications to be performed
1220
1221 +---+----+-----+------+---------------------------------------------------+
1222 | HS | PB | F | AFHI | ACTION
1223 +---+----+-----+------+---------------------------------------------------+
1224 | Y | Y | Y | Y | if HS != PB: remove PB. HS: force afhi update,
1225 | | update path, keep afsi
1226 +---+----+-----+------+---------------------------------------------------+
1227 | Y | Y | N | N | if HS == PB: do not send callback request at all.
1228 | | otherwise: remove PB, HS: update path, keep afhi,
1229 | | afsi.
1230 +---+----+-----+------+---------------------------------------------------+
1231 | Y | N | Y | Y | (rename) force afhi update of HS, update path of
1232 | | HS, keep afsi
1233 +---+----+-----+------+---------------------------------------------------+
1234 | Y | N | N | N | (file rename) update path of HS, keep afsi, afhi
1235 +---+----+-----+------+---------------------------------------------------+
1236 | N | Y | Y | Y | (file change) update afhi, hash, of PB, keep afsi
1237 | | (force has no effect)
1238 +---+----+-----+------+---------------------------------------------------+
1239 | N | Y | N | Y | (file change) update afhi, hash of PB, keep afsi
1240 +---+----+-----+------+---------------------------------------------------+
1241 | N | N | Y | Y | (new file) create new entry (force has no effect)
1242 +---+----+-----+------+---------------------------------------------------+
1243 | N | N | N | Y | (new file) create new entry
1244 +---+----+-----+------+---------------------------------------------------+
1245
1246 afhi <=> force or no HS
1247
1248 */
1249
1250
1251 #define ADD_FLAG_LAZY 1
1252 #define ADD_FLAG_FORCE 2
1253 #define ADD_FLAG_VERBOSE 4
1254
1255 static int com_add_callback(const struct osl_object *query,
1256 __a_unused struct osl_object *result)
1257 {
1258 char *buf = query->data, *path;
1259 struct osl_row *pb, *aft_row;
1260 const struct osl_row *hs;
1261 struct osl_object objs[NUM_AFT_COLUMNS];
1262 HASH_TYPE *hash;
1263 char asc[2 * HASH_SIZE + 1];
1264 int ret;
1265 char afsi_buf[AFSI_SIZE];
1266 uint32_t flags = read_u32(buf + AFTROW_FLAGS_OFFSET);
1267
1268 hash = (HASH_TYPE *)buf + AFTROW_HASH_OFFSET;
1269 hash_to_asc(hash, asc);;
1270 objs[AFTCOL_HASH].data = buf + AFTROW_HASH_OFFSET;
1271 objs[AFTCOL_HASH].size = HASH_SIZE;
1272
1273 path = buf + AFTROW_PATH_OFFSET;
1274 objs[AFTCOL_PATH].data = path;
1275 objs[AFTCOL_PATH].size = strlen(path) + 1;
1276
1277 PARA_DEBUG_LOG("request to add %s with hash %s\n", path, asc);
1278 hs = find_hash_sister(hash);
1279 ret = aft_get_row_of_path(path, &pb);
1280 if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
1281 return ret;
1282 if (hs && pb && hs == pb && !(flags & ADD_FLAG_FORCE)) {
1283 if (flags & ADD_FLAG_VERBOSE)
1284 PARA_NOTICE_LOG("ignoring duplicate %p\n", path);
1285 return 1;
1286 }
1287 if (hs && hs != pb) {
1288 struct osl_object obj;
1289 if (pb) { /* hs trumps pb, remove pb */
1290 if (flags & ADD_FLAG_VERBOSE)
1291 PARA_NOTICE_LOG("removing path brother\n");
1292 ret = osl_del_row(audio_file_table, pb);
1293 if (ret < 0)
1294 return ret;
1295 pb = NULL;
1296 }
1297 /* file rename, update hs' path */
1298 ret = osl_get_object(audio_file_table, hs, AFTCOL_PATH, &obj);
1299 if (flags & ADD_FLAG_VERBOSE)
1300 PARA_NOTICE_LOG("rename %s -> %s\n", (char *)obj.data, path);
1301 ret = osl_update_object(audio_file_table, hs, AFTCOL_PATH,
1302 &objs[AFTCOL_PATH]);
1303 if (ret < 0)
1304 return ret;
1305 if (!(flags & ADD_FLAG_FORCE))
1306 return ret;
1307 }
1308 /* no hs or force mode, child must have sent afhi */
1309 uint16_t afhi_offset = read_u16(buf + AFTROW_AFHI_OFFSET_POS);
1310 uint16_t chunks_offset = read_u16(buf + AFTROW_CHUNKS_OFFSET_POS);
1311
1312 objs[AFTCOL_AFHI].data = buf + afhi_offset;
1313 objs[AFTCOL_AFHI].size = chunks_offset - afhi_offset;
1314 if (!objs[AFTCOL_AFHI].size) /* "impossible" */
1315 return -E_NO_AFHI;
1316 objs[AFTCOL_CHUNKS].data = buf + chunks_offset;
1317 objs[AFTCOL_CHUNKS].size = query->size - chunks_offset;
1318 if (pb && !hs) { /* update pb's hash */
1319 char old_asc[2 * HASH_SIZE + 1];
1320 HASH_TYPE *old_hash;
1321 ret = get_hash_of_row(pb, &old_hash);
1322 if (ret < 0)
1323 return ret;
1324 hash_to_asc(old_hash, old_asc);
1325 if (flags & ADD_FLAG_VERBOSE)
1326 PARA_NOTICE_LOG("file change: %s %s -> %s\n", path,
1327 old_asc, asc);
1328 ret = osl_update_object(audio_file_table, pb, AFTCOL_HASH,
1329 &objs[AFTCOL_HASH]);
1330 if (ret < 0)
1331 return ret;
1332 }
1333 if (hs || pb) { /* (hs != NULL and pb != NULL) implies hs == pb */
1334 const void *row = pb? pb : hs;
1335 /* update afhi and chunk_table */
1336 if (flags & ADD_FLAG_VERBOSE)
1337 PARA_NOTICE_LOG("updating audio format handler info (%zd bytes)\n",
1338 objs[AFTCOL_AFHI].size);
1339 ret = osl_update_object(audio_file_table, row, AFTCOL_AFHI,
1340 &objs[AFTCOL_AFHI]);
1341 if (ret < 0)
1342 return ret;
1343 if (flags & ADD_FLAG_VERBOSE)
1344 PARA_NOTICE_LOG("updating chunk table\n");
1345 ret = osl_update_object(audio_file_table, row, AFTCOL_CHUNKS,
1346 &objs[AFTCOL_CHUNKS]);
1347 if (ret < 0)
1348 return ret;
1349 ret = mood_update_audio_file(row, NULL);
1350 if (ret < 0)
1351 return ret;
1352 }
1353 /* new entry, use default afsi */
1354 if (flags & ADD_FLAG_VERBOSE)
1355 PARA_NOTICE_LOG("adding %s\n", path);
1356 objs[AFTCOL_AFSI].data = &afsi_buf;
1357 objs[AFTCOL_AFSI].size = AFSI_SIZE;
1358 save_afsi(NULL, &objs[AFTCOL_AFSI]);
1359 ret = osl_add_and_get_row(audio_file_table, objs, &aft_row);
1360 if (ret < 0)
1361 return ret;
1362 return mood_update_audio_file(aft_row, NULL);
1363 }
1364
1365 struct private_add_data {
1366 int fd;
1367 uint32_t flags;
1368 };
1369
1370 static int add_one_audio_file(const char *arg, const void *private_data)
1371 {
1372 int ret;
1373 const struct private_add_data *pad = private_data;
1374 struct audio_format_info afhi, *afhi_ptr = NULL;
1375 struct osl_row *pb, *hs; /* path brother/hash sister */
1376 struct osl_object map, obj = {.data = NULL};
1377 char *path;
1378 HASH_TYPE hash[HASH_SIZE];
1379
1380 afhi.header_offset = 0;
1381 afhi.header_len = 0;
1382 ret = verify_path(arg, &path);
1383 if (ret < 0)
1384 return ret;
1385 ret = aft_get_row_of_path(path, &pb);
1386 if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
1387 goto out_free;
1388 ret = 1;
1389 if (pb && (pad->flags & ADD_FLAG_LAZY)) { /* lazy is really cheap */
1390 if (pad->flags & ADD_FLAG_VERBOSE)
1391 PARA_NOTICE_LOG("lazy-ignore: %s\n", path);
1392 goto out_free;
1393 }
1394 /* we still want to add this file. Compute its hash and look it up */
1395 ret = mmap_full_file(path, O_RDONLY, &map);
1396 if (ret < 0)
1397 goto out_free;
1398 hash_function(map.data, map.size, hash);
1399 hs = find_hash_sister(hash);
1400 /*
1401 * return success if we're pretty sure that we already know this file
1402 */
1403 ret = 1;
1404 if (pb && hs && hs == pb && (!(pad->flags & ADD_FLAG_FORCE))) {
1405 if (pad->flags & ADD_FLAG_VERBOSE)
1406 PARA_NOTICE_LOG("not forcing update: %s\n", path);
1407 goto out_unmap;
1408 }
1409 /*
1410 * we won't recalculate the audio format info and the chunk table if
1411 * there is a hash sister unless in FORCE mode.
1412 */
1413 if (!hs || (pad->flags & ADD_FLAG_FORCE)) {
1414 ret = mp3_get_file_info(map.data, map.size, &afhi);
1415 if (ret < 0) {
1416 PARA_WARNING_LOG("audio format of %s not recognized, skipping\n", path);
1417 ret = 1;
1418 goto out_unmap;
1419 }
1420 afhi_ptr = &afhi;
1421 }
1422 munmap(map.data, map.size);
1423 save_audio_file_info(hash, path, afhi_ptr, pad->flags, &obj);
1424 /* ask parent to consider this entry for adding */
1425 ret = send_callback_request(com_add_callback, &obj, NULL);
1426 goto out_free;
1427
1428 out_unmap:
1429 munmap(map.data, map.size);
1430 out_free:
1431 free(obj.data);
1432 free(path);
1433 if (afhi_ptr)
1434 free(afhi_ptr->chunk_table);
1435 return ret;
1436 }
1437
1438 int com_add(int fd, int argc, const char **argv)
1439 {
1440 int i, ret;
1441 struct private_add_data pad = {.fd = fd, .flags = 0};
1442 struct stat statbuf;
1443
1444 for (i = 1; i < argc; i++) {
1445 const char *arg = argv[i];
1446 if (arg[0] != '-')
1447 break;
1448 if (!strcmp(arg, "--")) {
1449 i++;
1450 break;
1451 }
1452 if (!strcmp(arg, "-l")) {
1453 pad.flags |= ADD_FLAG_LAZY;
1454 continue;
1455 }
1456 if (!strcmp(arg, "-f")) {
1457 pad.flags |= ADD_FLAG_FORCE;
1458 continue;
1459 }
1460 if (!strcmp(arg, "-v")) {
1461 pad.flags |= ADD_FLAG_VERBOSE;
1462 continue;
1463 }
1464 }
1465 if (argc <= i)
1466 return -E_AFT_SYNTAX;
1467 for (; i < argc; i++) {
1468 ret = stat(argv[i], &statbuf);
1469 if (ret < 0)
1470 return -E_AFS_STAT;
1471 if (S_ISDIR(statbuf.st_mode)) {
1472 ret = for_each_file_in_dir(argv[i],
1473 add_one_audio_file, &pad);
1474 if (ret < 0)
1475 return ret;
1476 continue;
1477 }
1478 ret = add_one_audio_file(argv[i], &pad);
1479 if (ret < 0)
1480 goto out;
1481 }
1482 ret = 1;
1483 out:
1484 return ret;
1485
1486 }
1487
1488 struct com_touch_options {
1489 long num_played;
1490 long last_played;
1491 long lyrics_id;
1492 long image_id;
1493 };
1494
1495 static int com_touch_callback(const struct osl_object *query,
1496 __a_unused struct osl_object *result)
1497 {
1498 struct com_touch_options *cto = query->data;
1499 char *p = (char *)query->data + sizeof(*cto);
1500 size_t len;
1501 int ret, no_options = cto->num_played < 0 && cto->last_played < 0 &&
1502 cto->lyrics_id < 0 && cto->image_id < 0;
1503
1504 for (;p < (char *)query->data + query->size; p += len + 1) {
1505 struct afs_info old_afsi, new_afsi;
1506 struct osl_object obj;
1507 struct osl_row *row;
1508
1509 len = strlen(p);
1510 ret = aft_get_row_of_path(p, &row);
1511 if (ret < 0)
1512 return ret;
1513 ret = get_afsi_object_of_row(row, &obj);
1514 if (ret < 0)
1515 return ret;
1516 ret = load_afsi(&old_afsi, &obj);
1517 if (ret < 0)
1518 return ret;
1519 new_afsi = old_afsi;
1520 if (no_options) {
1521 new_afsi.num_played++;
1522 new_afsi.last_played = time(NULL);
1523 } else {
1524 if (cto->lyrics_id >= 0)
1525 new_afsi.lyrics_id = cto->lyrics_id;
1526 if (cto->image_id >= 0)
1527 new_afsi.image_id = cto->image_id;
1528 if (cto->num_played >= 0)
1529 new_afsi.num_played = cto->num_played;
1530 if (cto->last_played >= 0)
1531 new_afsi.last_played = cto->last_played;
1532 }
1533 save_afsi(&new_afsi, &obj); /* in-place update */
1534 ret = mood_update_audio_file(row, &old_afsi);
1535 if (ret < 0)
1536 return ret;
1537 }
1538 return 1;
1539 }
1540
1541 int com_touch(__a_unused int fd, int argc, const char **argv)
1542 {
1543 struct com_touch_options cto = {
1544 .num_played = -1,
1545 .last_played = -1,
1546 .lyrics_id = -1,
1547 .image_id = -1
1548 };
1549 struct osl_object options = {.data = &cto, .size = sizeof(cto)};
1550 int i, ret;
1551
1552
1553 for (i = 1; i < argc; i++) {
1554 const char *arg = argv[i];
1555 if (arg[0] != '-')
1556 break;
1557 if (!strcmp(arg, "--")) {
1558 i++;
1559 break;
1560 }
1561 if (!strncmp(arg, "-n", 2)) {
1562 ret = para_atol(arg + 2, &cto.num_played);
1563 if (ret < 0)
1564 goto err;
1565 continue;
1566 }
1567 if (!strncmp(arg, "-l", 2)) {
1568 ret = para_atol(arg + 2, &cto.last_played);
1569 if (ret < 0)
1570 goto err;
1571 continue;
1572 }
1573 if (!strncmp(arg, "-y", 2)) {
1574 ret = para_atol(arg + 2, &cto.lyrics_id);
1575 if (ret < 0)
1576 goto err;
1577 continue;
1578 }
1579 if (!strncmp(arg, "-i", 2)) {
1580 ret = para_atol(arg + 2, &cto.image_id);
1581 if (ret < 0)
1582 goto err;
1583 continue;
1584 }
1585 }
1586 ret = -E_AFT_SYNTAX;
1587 if (i >= argc)
1588 goto err;
1589 return send_option_arg_callback_request(&options, argc - i,
1590 argv + i, com_touch_callback, NULL);
1591 err:
1592 return ret;
1593 }
1594
1595 struct com_rm_options {
1596 uint32_t flags;
1597 };
1598
1599 static int com_rm_callback(const struct osl_object *query,
1600 __a_unused struct osl_object *result)
1601 {
1602 struct com_rm_options *cro = query->data;
1603 char *p = (char *)query->data + sizeof(*cro);
1604 size_t len;
1605 int ret;
1606
1607 for (;p < (char *)query->data + query->size; p += len + 1) {
1608 struct osl_row *row;
1609
1610 len = strlen(p);
1611 ret = aft_get_row_of_path(p, &row);
1612 if (ret < 0)
1613 return ret;
1614 ret = mood_delete_audio_file(row);
1615 if (ret < 0)
1616 return ret;
1617 ret = osl_del_row(audio_file_table, row);
1618 if (ret < 0)
1619 return ret;
1620 }
1621 return 1;
1622 }
1623
1624 /*
1625 * TODO options: -v verbose, -f dont stop if file not found
1626 * -h remove by hash, use fnmatch
1627 *
1628 * */
1629
1630 int com_afs_rm(__a_unused int fd, int argc, const char **argv)
1631 {
1632 struct com_rm_options cro = {.flags = 0};
1633 struct osl_object options = {.data = &cro, .size = sizeof(cro)};
1634 int i, ret;
1635
1636 for (i = 1; i < argc; i++) {
1637 const char *arg = argv[i];
1638 if (arg[0] != '-')
1639 break;
1640 if (!strcmp(arg, "--")) {
1641 i++;
1642 break;
1643 }
1644 }
1645 ret = -E_AFT_SYNTAX;
1646 if (i >= argc)
1647 goto err;
1648 return send_option_arg_callback_request(&options, argc - i,
1649 argv + i, com_rm_callback, NULL);
1650 err:
1651 return ret;
1652 }
1653
1654 /**
1655 * Close the audio file table.
1656 *
1657 * \param flags Ususal flags that are passed to osl_close_table().
1658 *
1659 * \sa osl_close_table().
1660 */
1661 void aft_shutdown(enum osl_close_flags flags)
1662 {
1663 osl_close_table(audio_file_table, flags);
1664 }
1665
1666 /**
1667 * Open the audio file table.
1668 *
1669 * \param ti Gets initialized by this function
1670 *
1671 * \return Positive on success, negative on errors.
1672 *
1673 * \sa osl_open_table().
1674 */
1675 int aft_init(struct table_info *ti)
1676 {
1677 int ret;
1678
1679 ti->desc = &audio_file_table_desc;
1680 ret = osl_open_table(ti->desc, &ti->table);
1681 if (ret >= 0) {
1682 unsigned num;
1683 audio_file_table = ti->table;
1684 osl_get_num_rows(audio_file_table, &num);
1685 PARA_INFO_LOG("audio file table contains %d files\n", num);
1686 return ret;
1687 }
1688 audio_file_table = NULL;
1689 return ret == -E_NOENT? 1 : ret;
1690 }