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