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