move w32-specific resources to a separate file to prevent building them on other...
[Rockbox.git] / apps / tagcache.c
blob1f4521168e28b9c180c423995ac4d5b7d6b1c7ff
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2005 by Miika Pekkarinen
12 * All files in this archive are subject to the GNU General Public License.
13 * See the file COPYING in the source tree root for full license agreement.
15 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
16 * KIND, either express or implied.
18 ****************************************************************************/
21 * TagCache API
23 * ----------x---------x------------------x-----
24 * | | | External
25 * +---------------x-------+ | TagCache | Libraries
26 * | Modification routines | | Core |
27 * +-x---------x-----------+ | |
28 * | (R/W) | | | |
29 * | +------x-------------x-+ +-------------x-----+ |
30 * | | x==x Filters & clauses | |
31 * | | Search routines | +-------------------+ |
32 * | | x============================x DirCache
33 * | +-x--------------------+ | (optional)
34 * | | (R) |
35 * | | +-------------------------------+ +---------+ |
36 * | | | DB Commit (sort,unique,index) | | | |
37 * | | +-x--------------------------x--+ | Control | |
38 * | | | (R/W) | (R) | Thread | |
39 * | | | +----------------------+ | | | |
40 * | | | | TagCache DB Builder | | +---------+ |
41 * | | | +-x-------------x------+ | |
42 * | | | | (R) | (W) | |
43 * | | | | +--x--------x---------+ |
44 * | | | | | Temporary Commit DB | |
45 * | | | | +---------------------+ |
46 * +-x----x-------x--+ |
47 * | TagCache RAM DB x==\(W) +-----------------+ |
48 * +-----------------+ \===x | |
49 * | | | | (R) | Ram DB Loader x============x DirCache
50 * +-x----x---x---x---+ /==x | | (optional)
51 * | Tagcache Disk DB x==/ +-----------------+ |
52 * +------------------+ |
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <ctype.h>
59 #include "config.h"
60 #include "thread.h"
61 #include "kernel.h"
62 #include "system.h"
63 #include "logf.h"
64 #include "string.h"
65 #include "usb.h"
66 #include "metadata.h"
67 #include "id3.h"
68 #include "tagcache.h"
69 #include "buffer.h"
70 #include "crc32.h"
71 #include "misc.h"
72 #include "settings.h"
73 #include "dir.h"
74 #include "structec.h"
75 #ifndef __PCTOOL__
76 #include "atoi.h"
77 #include "splash.h"
78 #include "lang.h"
79 #include "eeprom_settings.h"
80 #endif
82 #ifdef __PCTOOL__
83 #define yield() do { } while(0)
84 #define sim_sleep(timeout) do { } while(0)
85 #define do_timed_yield() do { } while(0)
86 #endif
88 #ifndef __PCTOOL__
89 /* Tag Cache thread. */
90 static struct event_queue tagcache_queue;
91 static long tagcache_stack[(DEFAULT_STACK_SIZE + 0x4000)/sizeof(long)];
92 static const char tagcache_thread_name[] = "tagcache";
93 #endif
95 #define UNTAGGED "<Untagged>"
97 /* Previous path when scanning directory tree recursively. */
98 static char curpath[TAG_MAXLEN+32];
99 static long curpath_size = sizeof(curpath);
101 /* Used when removing duplicates. */
102 static char *tempbuf; /* Allocated when needed. */
103 static long tempbufidx; /* Current location in buffer. */
104 static long tempbuf_size; /* Buffer size (TEMPBUF_SIZE). */
105 static long tempbuf_left; /* Buffer space left. */
106 static long tempbuf_pos;
108 /* Tags we want to get sorted (loaded to the tempbuf). */
109 static const int sorted_tags[] = { tag_artist, tag_album, tag_genre,
110 tag_composer, tag_comment, tag_albumartist, tag_grouping, tag_title };
112 /* Uniqued tags (we can use these tags with filters and conditional clauses). */
113 static const int unique_tags[] = { tag_artist, tag_album, tag_genre,
114 tag_composer, tag_comment, tag_albumartist, tag_grouping };
116 /* Numeric tags (we can use these tags with conditional clauses). */
117 static const int numeric_tags[] = { tag_year, tag_discnumber,
118 tag_tracknumber, tag_length, tag_bitrate, tag_playcount, tag_rating,
119 tag_playtime, tag_lastplayed, tag_commitid, tag_mtime,
120 tag_virt_length_min, tag_virt_length_sec,
121 tag_virt_playtime_min, tag_virt_playtime_sec,
122 tag_virt_entryage, tag_virt_autoscore };
124 /* String presentation of the tags defined in tagcache.h. Must be in correct order! */
125 static const char *tags_str[] = { "artist", "album", "genre", "title",
126 "filename", "composer", "comment", "albumartist", "grouping", "year",
127 "discnumber", "tracknumber", "bitrate", "length", "playcount", "rating",
128 "playtime", "lastplayed", "commitid", "mtime" };
130 /* Status information of the tagcache. */
131 static struct tagcache_stat tc_stat;
133 /* Queue commands. */
134 enum tagcache_queue {
135 Q_STOP_SCAN = 0,
136 Q_START_SCAN,
137 Q_IMPORT_CHANGELOG,
138 Q_UPDATE,
139 Q_REBUILD,
141 /* Internal tagcache command queue. */
142 CMD_UPDATE_MASTER_HEADER,
143 CMD_UPDATE_NUMERIC,
146 struct tagcache_command_entry {
147 long command;
148 long idx_id;
149 long tag;
150 long data;
153 static struct tagcache_command_entry command_queue[TAGCACHE_COMMAND_QUEUE_LENGTH];
154 static volatile int command_queue_widx = 0;
155 static volatile int command_queue_ridx = 0;
156 static struct mutex command_queue_mutex;
157 /* Timestamp of the last added event, so we can wait a bit before committing the
158 * whole queue at once. */
159 static long command_queue_timestamp = 0;
161 /* Tag database structures. */
163 /* Variable-length tag entry in tag files. */
164 struct tagfile_entry {
165 short tag_length; /* Length of the data in bytes including '\0' */
166 short idx_id; /* Corresponding entry location in index file of not unique tags */
167 char tag_data[0]; /* Begin of the tag data */
170 /* Fixed-size tag entry in master db index. */
171 struct index_entry {
172 long tag_seek[TAG_COUNT]; /* Location of tag data or numeric tag data */
173 long flag; /* Status flags */
176 /* Header is the same in every file. */
177 struct tagcache_header {
178 long magic; /* Header version number */
179 long datasize; /* Data size in bytes */
180 long entry_count; /* Number of entries in this file */
183 struct master_header {
184 struct tagcache_header tch;
185 long serial; /* Increasing counting number */
186 long commitid; /* Number of commits so far */
187 long dirty;
190 /* For the endianess correction */
191 static const char *tagfile_entry_ec = "ss";
192 static const char *index_entry_ec = "lllllllllllllllllllll"; /* (1 + TAG_COUNT) * l */
193 static const char *tagcache_header_ec = "lll";
194 static const char *master_header_ec = "llllll";
196 static struct master_header current_tcmh;
198 #ifdef HAVE_TC_RAMCACHE
199 /* Header is created when loading database to ram. */
200 struct ramcache_header {
201 struct master_header h; /* Header from the master index */
202 struct index_entry *indices; /* Master index file content */
203 char *tags[TAG_COUNT]; /* Tag file content (not including filename tag) */
204 int entry_count[TAG_COUNT]; /* Number of entries in the indices. */
207 # ifdef HAVE_EEPROM_SETTINGS
208 struct statefile_header {
209 struct ramcache_header *hdr;
210 struct tagcache_stat tc_stat;
212 # endif
214 /* Pointer to allocated ramcache_header */
215 static struct ramcache_header *hdr;
216 #endif
218 /**
219 * Full tag entries stored in a temporary file waiting
220 * for commit to the cache. */
221 struct temp_file_entry {
222 long tag_offset[TAG_COUNT];
223 short tag_length[TAG_COUNT];
224 long flag;
226 long data_length;
229 struct tempbuf_id_list {
230 long id;
231 struct tempbuf_id_list *next;
234 struct tempbuf_searchidx {
235 long idx_id;
236 char *str;
237 int seek;
238 struct tempbuf_id_list idlist;
241 /* Lookup buffer for fixing messed up index while after sorting. */
242 static long commit_entry_count;
243 static long lookup_buffer_depth;
244 static struct tempbuf_searchidx **lookup;
246 /* Used when building the temporary file. */
247 static int cachefd = -1, filenametag_fd;
248 static int total_entry_count = 0;
249 static int data_size = 0;
250 static int processed_dir_count;
252 /* Thread safe locking */
253 static volatile int write_lock;
254 static volatile int read_lock;
256 static bool delete_entry(long idx_id);
258 const char* tagcache_tag_to_str(int tag)
260 return tags_str[tag];
263 bool tagcache_is_numeric_tag(int type)
265 int i;
267 for (i = 0; i < (int)(sizeof(numeric_tags)/sizeof(numeric_tags[0])); i++)
269 if (type == numeric_tags[i])
270 return true;
273 return false;
276 bool tagcache_is_unique_tag(int type)
278 int i;
280 for (i = 0; i < (int)(sizeof(unique_tags)/sizeof(unique_tags[0])); i++)
282 if (type == unique_tags[i])
283 return true;
286 return false;
289 bool tagcache_is_sorted_tag(int type)
291 int i;
293 for (i = 0; i < (int)(sizeof(sorted_tags)/sizeof(sorted_tags[0])); i++)
295 if (type == sorted_tags[i])
296 return true;
299 return false;
302 static int open_tag_fd(struct tagcache_header *hdr, int tag, bool write)
304 int fd;
305 char buf[MAX_PATH];
306 int rc;
308 if (tagcache_is_numeric_tag(tag) || tag < 0 || tag >= TAG_COUNT)
309 return -1;
311 snprintf(buf, sizeof buf, TAGCACHE_FILE_INDEX, tag);
313 fd = open(buf, write ? O_RDWR : O_RDONLY);
314 if (fd < 0)
316 logf("tag file open failed: tag=%d write=%d file=%s", tag, write, buf);
317 tc_stat.ready = false;
318 return fd;
321 /* Check the header. */
322 rc = ecread(fd, hdr, 1, tagcache_header_ec, tc_stat.econ);
323 if (hdr->magic != TAGCACHE_MAGIC || rc != sizeof(struct tagcache_header))
325 logf("header error");
326 tc_stat.ready = false;
327 close(fd);
328 return -2;
331 return fd;
334 static int open_master_fd(struct master_header *hdr, bool write)
336 int fd;
337 int rc;
339 fd = open(TAGCACHE_FILE_MASTER, write ? O_RDWR : O_RDONLY);
340 if (fd < 0)
342 logf("master file open failed for R/W");
343 tc_stat.ready = false;
344 return fd;
347 tc_stat.econ = false;
349 /* Check the header. */
350 rc = read(fd, hdr, sizeof(struct master_header));
351 if (hdr->tch.magic == TAGCACHE_MAGIC && rc == sizeof(struct master_header))
353 /* Success. */
354 return fd;
357 /* Trying to read again, this time with endianess correction enabled. */
358 lseek(fd, 0, SEEK_SET);
360 rc = ecread(fd, hdr, 1, master_header_ec, true);
361 if (hdr->tch.magic != TAGCACHE_MAGIC || rc != sizeof(struct master_header))
363 logf("header error");
364 tc_stat.ready = false;
365 close(fd);
366 return -2;
369 tc_stat.econ = true;
371 return fd;
374 #ifndef __PCTOOL__
375 static bool do_timed_yield(void)
377 /* Sorting can lock up for quite a while, so yield occasionally */
378 static long wakeup_tick = 0;
379 if (current_tick >= wakeup_tick)
381 wakeup_tick = current_tick + (HZ/4);
382 yield();
383 return true;
385 return false;
387 #endif
389 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
390 static long find_entry_ram(const char *filename,
391 const struct dirent *dc)
393 static long last_pos = 0;
394 int i;
396 /* Check if we tagcache is loaded into ram. */
397 if (!tc_stat.ramcache)
398 return -1;
400 if (dc == NULL)
401 dc = dircache_get_entry_ptr(filename);
403 if (dc == NULL)
405 logf("tagcache: file not found.");
406 return -1;
409 try_again:
411 if (last_pos > 0)
412 i = last_pos;
413 else
414 i = 0;
416 for (; i < hdr->h.tch.entry_count; i++)
418 if (hdr->indices[i].tag_seek[tag_filename] == (long)dc)
420 last_pos = MAX(0, i - 3);
421 return i;
424 do_timed_yield();
427 if (last_pos > 0)
429 last_pos = 0;
430 goto try_again;
433 return -1;
435 #endif
437 static long find_entry_disk(const char *filename)
439 struct tagcache_header tch;
440 static long last_pos = -1;
441 long pos_history[POS_HISTORY_COUNT];
442 long pos_history_idx = 0;
443 bool found = false;
444 struct tagfile_entry tfe;
445 int fd;
446 char buf[TAG_MAXLEN+32];
447 int i;
448 int pos = -1;
450 if (!tc_stat.ready)
451 return -2;
453 fd = filenametag_fd;
454 if (fd < 0)
456 last_pos = -1;
457 if ( (fd = open_tag_fd(&tch, tag_filename, false)) < 0)
458 return -1;
461 check_again:
463 if (last_pos > 0)
464 lseek(fd, last_pos, SEEK_SET);
465 else
466 lseek(fd, sizeof(struct tagcache_header), SEEK_SET);
468 while (true)
470 pos = lseek(fd, 0, SEEK_CUR);
471 for (i = pos_history_idx-1; i >= 0; i--)
472 pos_history[i+1] = pos_history[i];
473 pos_history[0] = pos;
475 if (ecread(fd, &tfe, 1, tagfile_entry_ec, tc_stat.econ)
476 != sizeof(struct tagfile_entry))
478 break ;
481 if (tfe.tag_length >= (long)sizeof(buf))
483 logf("too long tag #1");
484 close(fd);
485 last_pos = -1;
486 return -2;
489 if (read(fd, buf, tfe.tag_length) != tfe.tag_length)
491 logf("read error #2");
492 close(fd);
493 last_pos = -1;
494 return -3;
497 if (!strcasecmp(filename, buf))
499 last_pos = pos_history[pos_history_idx];
500 found = true;
501 break ;
504 if (pos_history_idx < POS_HISTORY_COUNT - 1)
505 pos_history_idx++;
508 /* Not found? */
509 if (!found)
511 if (last_pos > 0)
513 last_pos = -1;
514 logf("seek again");
515 goto check_again;
518 if (fd != filenametag_fd)
519 close(fd);
520 return -4;
523 if (fd != filenametag_fd)
524 close(fd);
526 return tfe.idx_id;
529 static int find_index(const char *filename)
531 long idx_id = -1;
533 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
534 if (tc_stat.ramcache && dircache_is_enabled())
535 idx_id = find_entry_ram(filename, NULL);
536 #endif
538 if (idx_id < 0)
539 idx_id = find_entry_disk(filename);
541 return idx_id;
544 bool tagcache_find_index(struct tagcache_search *tcs, const char *filename)
546 int idx_id;
548 if (!tc_stat.ready)
549 return false;
551 idx_id = find_index(filename);
552 if (idx_id < 0)
553 return false;
555 if (!tagcache_search(tcs, tag_filename))
556 return false;
558 tcs->entry_count = 0;
559 tcs->idx_id = idx_id;
561 return true;
564 static bool get_index(int masterfd, int idxid,
565 struct index_entry *idx, bool use_ram)
567 bool localfd = false;
569 if (idxid < 0)
571 logf("Incorrect idxid: %d", idxid);
572 return false;
575 #ifdef HAVE_TC_RAMCACHE
576 if (tc_stat.ramcache && use_ram)
578 if (hdr->indices[idxid].flag & FLAG_DELETED)
579 return false;
581 memcpy(idx, &hdr->indices[idxid], sizeof(struct index_entry));
582 return true;
584 #else
585 (void)use_ram;
586 #endif
588 if (masterfd < 0)
590 struct master_header tcmh;
592 localfd = true;
593 masterfd = open_master_fd(&tcmh, false);
594 if (masterfd < 0)
595 return false;
598 lseek(masterfd, idxid * sizeof(struct index_entry)
599 + sizeof(struct master_header), SEEK_SET);
600 if (ecread(masterfd, idx, 1, index_entry_ec, tc_stat.econ)
601 != sizeof(struct index_entry))
603 logf("read error #3");
604 if (localfd)
605 close(masterfd);
607 return false;
610 if (localfd)
611 close(masterfd);
613 if (idx->flag & FLAG_DELETED)
614 return false;
616 return true;
619 static bool write_index(int masterfd, int idxid, struct index_entry *idx)
621 /* We need to exclude all memory only flags & tags when writing to disk. */
622 if (idx->flag & FLAG_DIRCACHE)
624 logf("memory only flags!");
625 return false;
628 #ifdef HAVE_TC_RAMCACHE
629 /* Only update numeric data. Writing the whole index to RAM by memcpy
630 * destroys dircache pointers!
632 if (tc_stat.ramcache)
634 int tag;
635 struct index_entry *idx_ram = &hdr->indices[idxid];
637 for (tag = 0; tag < TAG_COUNT; tag++)
639 if (tagcache_is_numeric_tag(tag))
641 idx_ram->tag_seek[tag] = idx->tag_seek[tag];
645 /* Don't touch the dircache flag. */
646 idx_ram->flag = idx->flag | (idx_ram->flag & FLAG_DIRCACHE);
648 #endif
650 lseek(masterfd, idxid * sizeof(struct index_entry)
651 + sizeof(struct master_header), SEEK_SET);
652 if (ecwrite(masterfd, idx, 1, index_entry_ec, tc_stat.econ)
653 != sizeof(struct index_entry))
655 logf("write error #3");
656 logf("idxid: %d", idxid);
657 return false;
660 return true;
663 static bool open_files(struct tagcache_search *tcs, int tag)
665 if (tcs->idxfd[tag] < 0)
667 char fn[MAX_PATH];
669 snprintf(fn, sizeof fn, TAGCACHE_FILE_INDEX, tag);
670 tcs->idxfd[tag] = open(fn, O_RDONLY);
673 if (tcs->idxfd[tag] < 0)
675 logf("File not open!");
676 return false;
679 return true;
682 static bool retrieve(struct tagcache_search *tcs, struct index_entry *idx,
683 int tag, char *buf, long size)
685 struct tagfile_entry tfe;
686 long seek;
688 *buf = '\0';
690 if (tagcache_is_numeric_tag(tag))
691 return false;
693 seek = idx->tag_seek[tag];
694 if (seek < 0)
696 logf("Retrieve failed");
697 return false;
700 #ifdef HAVE_TC_RAMCACHE
701 if (tcs->ramsearch)
703 struct tagfile_entry *ep;
705 # ifdef HAVE_DIRCACHE
706 if (tag == tag_filename && idx->flag & FLAG_DIRCACHE)
708 dircache_copy_path((struct dirent *)seek,
709 buf, size);
710 return true;
712 else
713 # endif
714 if (tag != tag_filename)
716 ep = (struct tagfile_entry *)&hdr->tags[tag][seek];
717 strncpy(buf, ep->tag_data, size-1);
719 return true;
722 #endif
724 if (!open_files(tcs, tag))
725 return false;
727 lseek(tcs->idxfd[tag], seek, SEEK_SET);
728 if (ecread(tcs->idxfd[tag], &tfe, 1, tagfile_entry_ec, tc_stat.econ)
729 != sizeof(struct tagfile_entry))
731 logf("read error #5");
732 return false;
735 if (tfe.tag_length >= size)
737 logf("too small buffer");
738 return false;
741 if (read(tcs->idxfd[tag], buf, tfe.tag_length) !=
742 tfe.tag_length)
744 logf("read error #6");
745 return false;
748 buf[tfe.tag_length] = '\0';
750 return true;
753 static long check_virtual_tags(int tag, const struct index_entry *idx)
755 long data = 0;
757 switch (tag)
759 case tag_virt_length_sec:
760 data = (idx->tag_seek[tag_length]/1000) % 60;
761 break;
763 case tag_virt_length_min:
764 data = (idx->tag_seek[tag_length]/1000) / 60;
765 break;
767 case tag_virt_playtime_sec:
768 data = (idx->tag_seek[tag_playtime]/1000) % 60;
769 break;
771 case tag_virt_playtime_min:
772 data = (idx->tag_seek[tag_playtime]/1000) / 60;
773 break;
775 case tag_virt_autoscore:
776 if (idx->tag_seek[tag_length] == 0
777 || idx->tag_seek[tag_playcount] == 0)
779 data = 0;
781 else
783 data = 100 * idx->tag_seek[tag_playtime]
784 / idx->tag_seek[tag_length]
785 / idx->tag_seek[tag_playcount];
787 break;
789 /* How many commits before the file has been added to the DB. */
790 case tag_virt_entryage:
791 data = current_tcmh.commitid - idx->tag_seek[tag_commitid] - 1;
792 break;
794 default:
795 data = idx->tag_seek[tag];
798 return data;
801 long tagcache_get_numeric(const struct tagcache_search *tcs, int tag)
803 struct index_entry idx;
805 if (!tc_stat.ready)
806 return false;
808 if (!tagcache_is_numeric_tag(tag))
809 return -1;
811 if (!get_index(tcs->masterfd, tcs->idx_id, &idx, true))
812 return -2;
814 return check_virtual_tags(tag, &idx);
817 inline static bool str_ends_with(const char *str1, const char *str2)
819 int str_len = strlen(str1);
820 int clause_len = strlen(str2);
822 if (clause_len > str_len)
823 return false;
825 return !strcasecmp(&str1[str_len - clause_len], str2);
828 inline static bool str_oneof(const char *str, const char *list)
830 const char *sep;
831 int l, len = strlen(str);
833 while (*list)
835 sep = strchr(list, '|');
836 l = sep ? (long)sep - (long)list : (int)strlen(list);
837 if ((l==len) && !strncasecmp(str, list, len))
838 return true;
839 list += sep ? l + 1 : l;
842 return false;
845 static bool check_against_clause(long numeric, const char *str,
846 const struct tagcache_search_clause *clause)
848 if (clause->numeric)
850 switch (clause->type)
852 case clause_is:
853 return numeric == clause->numeric_data;
854 case clause_is_not:
855 return numeric != clause->numeric_data;
856 case clause_gt:
857 return numeric > clause->numeric_data;
858 case clause_gteq:
859 return numeric >= clause->numeric_data;
860 case clause_lt:
861 return numeric < clause->numeric_data;
862 case clause_lteq:
863 return numeric <= clause->numeric_data;
864 default:
865 logf("Incorrect numeric tag: %d", clause->type);
868 else
870 switch (clause->type)
872 case clause_is:
873 return !strcasecmp(clause->str, str);
874 case clause_is_not:
875 return strcasecmp(clause->str, str);
876 case clause_gt:
877 return 0>strcasecmp(clause->str, str);
878 case clause_gteq:
879 return 0>=strcasecmp(clause->str, str);
880 case clause_lt:
881 return 0<strcasecmp(clause->str, str);
882 case clause_lteq:
883 return 0<=strcasecmp(clause->str, str);
884 case clause_contains:
885 return (strcasestr(str, clause->str) != NULL);
886 case clause_not_contains:
887 return (strcasestr(str, clause->str) == NULL);
888 case clause_begins_with:
889 return (strcasestr(str, clause->str) == str);
890 case clause_not_begins_with:
891 return (strcasestr(str, clause->str) != str);
892 case clause_ends_with:
893 return str_ends_with(str, clause->str);
894 case clause_not_ends_with:
895 return !str_ends_with(str, clause->str);
896 case clause_oneof:
897 return str_oneof(str, clause->str);
899 default:
900 logf("Incorrect tag: %d", clause->type);
904 return false;
907 static bool check_clauses(struct tagcache_search *tcs,
908 struct index_entry *idx,
909 struct tagcache_search_clause **clause, int count)
911 int i;
913 #ifdef HAVE_TC_RAMCACHE
914 if (tcs->ramsearch)
916 /* Go through all conditional clauses. */
917 for (i = 0; i < count; i++)
919 struct tagfile_entry *tfe;
920 int seek;
921 char buf[256];
922 char *str = NULL;
924 seek = check_virtual_tags(clause[i]->tag, idx);
926 if (!tagcache_is_numeric_tag(clause[i]->tag))
928 if (clause[i]->tag == tag_filename)
930 retrieve(tcs, idx, tag_filename, buf, sizeof buf);
931 str = buf;
933 else
935 tfe = (struct tagfile_entry *)&hdr->tags[clause[i]->tag][seek];
936 str = tfe->tag_data;
940 if (!check_against_clause(seek, str, clause[i]))
941 return false;
944 else
945 #endif
947 /* Check for conditions. */
948 for (i = 0; i < count; i++)
950 struct tagfile_entry tfe;
951 int seek;
952 char str[256];
954 seek = check_virtual_tags(clause[i]->tag, idx);
956 memset(str, 0, sizeof str);
957 if (!tagcache_is_numeric_tag(clause[i]->tag))
959 int fd = tcs->idxfd[clause[i]->tag];
960 lseek(fd, seek, SEEK_SET);
961 ecread(fd, &tfe, 1, tagfile_entry_ec, tc_stat.econ);
962 if (tfe.tag_length >= (int)sizeof(str))
964 logf("Too long tag read!");
965 break ;
968 read(fd, str, tfe.tag_length);
970 /* Check if entry has been deleted. */
971 if (str[0] == '\0')
972 break;
975 if (!check_against_clause(seek, str, clause[i]))
976 return false;
980 return true;
983 bool tagcache_check_clauses(struct tagcache_search *tcs,
984 struct tagcache_search_clause **clause, int count)
986 struct index_entry idx;
988 if (count == 0)
989 return true;
991 if (!get_index(tcs->masterfd, tcs->idx_id, &idx, true))
992 return false;
994 return check_clauses(tcs, &idx, clause, count);
997 static bool add_uniqbuf(struct tagcache_search *tcs, unsigned long id)
999 int i;
1001 /* If uniq buffer is not defined we must return true for search to work. */
1002 if (tcs->unique_list == NULL
1003 || (!tagcache_is_unique_tag(tcs->type)
1004 && !tagcache_is_numeric_tag(tcs->type)))
1006 return true;
1009 for (i = 0; i < tcs->unique_list_count; i++)
1011 /* Return false if entry is found. */
1012 if (tcs->unique_list[i] == id)
1013 return false;
1016 if (tcs->unique_list_count < tcs->unique_list_capacity)
1018 tcs->unique_list[i] = id;
1019 tcs->unique_list_count++;
1022 return true;
1025 static bool build_lookup_list(struct tagcache_search *tcs)
1027 struct index_entry entry;
1028 int i;
1030 tcs->seek_list_count = 0;
1032 #ifdef HAVE_TC_RAMCACHE
1033 if (tcs->ramsearch)
1035 int j;
1037 for (i = tcs->seek_pos; i < hdr->h.tch.entry_count; i++)
1039 struct index_entry *idx = &hdr->indices[i];
1040 if (tcs->seek_list_count == SEEK_LIST_SIZE)
1041 break ;
1043 /* Skip deleted files. */
1044 if (idx->flag & FLAG_DELETED)
1045 continue;
1047 /* Go through all filters.. */
1048 for (j = 0; j < tcs->filter_count; j++)
1050 if (idx->tag_seek[tcs->filter_tag[j]] != tcs->filter_seek[j])
1052 break ;
1056 if (j < tcs->filter_count)
1057 continue ;
1059 /* Check for conditions. */
1060 if (!check_clauses(tcs, idx, tcs->clause, tcs->clause_count))
1061 continue;
1063 /* Add to the seek list if not already in uniq buffer. */
1064 if (!add_uniqbuf(tcs, idx->tag_seek[tcs->type]))
1065 continue;
1067 /* Lets add it. */
1068 tcs->seek_list[tcs->seek_list_count] = idx->tag_seek[tcs->type];
1069 tcs->seek_flags[tcs->seek_list_count] = idx->flag;
1070 tcs->seek_list_count++;
1073 tcs->seek_pos = i;
1075 return tcs->seek_list_count > 0;
1077 #endif
1079 lseek(tcs->masterfd, tcs->seek_pos * sizeof(struct index_entry) +
1080 sizeof(struct master_header), SEEK_SET);
1082 while (ecread(tcs->masterfd, &entry, 1, index_entry_ec, tc_stat.econ)
1083 == sizeof(struct index_entry))
1085 if (tcs->seek_list_count == SEEK_LIST_SIZE)
1086 break ;
1088 tcs->seek_pos++;
1090 /* Check if entry has been deleted. */
1091 if (entry.flag & FLAG_DELETED)
1092 continue;
1094 /* Go through all filters.. */
1095 for (i = 0; i < tcs->filter_count; i++)
1097 if (entry.tag_seek[tcs->filter_tag[i]] != tcs->filter_seek[i])
1098 break ;
1101 if (i < tcs->filter_count)
1102 continue ;
1104 /* Check for conditions. */
1105 if (!check_clauses(tcs, &entry, tcs->clause, tcs->clause_count))
1106 continue;
1108 /* Add to the seek list if not already in uniq buffer. */
1109 if (!add_uniqbuf(tcs, entry.tag_seek[tcs->type]))
1110 continue;
1112 /* Lets add it. */
1113 tcs->seek_list[tcs->seek_list_count] = entry.tag_seek[tcs->type];
1114 tcs->seek_flags[tcs->seek_list_count] = entry.flag;
1115 tcs->seek_list_count++;
1117 yield();
1120 return tcs->seek_list_count > 0;
1124 static void remove_files(void)
1126 int i;
1127 char buf[MAX_PATH];
1129 tc_stat.ready = false;
1130 tc_stat.ramcache = false;
1131 tc_stat.econ = false;
1132 remove(TAGCACHE_FILE_MASTER);
1133 for (i = 0; i < TAG_COUNT; i++)
1135 if (tagcache_is_numeric_tag(i))
1136 continue;
1138 snprintf(buf, sizeof buf, TAGCACHE_FILE_INDEX, i);
1139 remove(buf);
1144 static bool check_all_headers(void)
1146 struct master_header myhdr;
1147 struct tagcache_header tch;
1148 int tag;
1149 int fd;
1151 if ( (fd = open_master_fd(&myhdr, false)) < 0)
1152 return false;
1154 close(fd);
1155 if (myhdr.dirty)
1157 logf("tagcache is dirty!");
1158 return false;
1161 memcpy(&current_tcmh, &myhdr, sizeof(struct master_header));
1163 for (tag = 0; tag < TAG_COUNT; tag++)
1165 if (tagcache_is_numeric_tag(tag))
1166 continue;
1168 if ( (fd = open_tag_fd(&tch, tag, false)) < 0)
1169 return false;
1171 close(fd);
1174 return true;
1177 bool tagcache_search(struct tagcache_search *tcs, int tag)
1179 struct tagcache_header tag_hdr;
1180 struct master_header master_hdr;
1181 int i;
1183 if (tcs->initialized)
1184 tagcache_search_finish(tcs);
1186 while (read_lock)
1187 sleep(1);
1189 memset(tcs, 0, sizeof(struct tagcache_search));
1190 if (tc_stat.commit_step > 0 || !tc_stat.ready)
1191 return false;
1193 tcs->position = sizeof(struct tagcache_header);
1194 tcs->type = tag;
1195 tcs->seek_pos = 0;
1196 tcs->seek_list_count = 0;
1197 tcs->filter_count = 0;
1198 tcs->masterfd = -1;
1200 for (i = 0; i < TAG_COUNT; i++)
1201 tcs->idxfd[i] = -1;
1203 #ifndef HAVE_TC_RAMCACHE
1204 tcs->ramsearch = false;
1205 #else
1206 tcs->ramsearch = tc_stat.ramcache;
1207 if (tcs->ramsearch)
1209 tcs->entry_count = hdr->entry_count[tcs->type];
1211 else
1212 #endif
1214 if (!tagcache_is_numeric_tag(tcs->type))
1216 tcs->idxfd[tcs->type] = open_tag_fd(&tag_hdr, tcs->type, false);
1217 if (tcs->idxfd[tcs->type] < 0)
1218 return false;
1221 /* Always open as R/W so we can pass tcs to functions that modify data also
1222 * without failing. */
1223 tcs->masterfd = open_master_fd(&master_hdr, true);
1225 if (tcs->masterfd < 0)
1226 return false;
1229 tcs->valid = true;
1230 tcs->initialized = true;
1231 write_lock++;
1233 return true;
1236 void tagcache_search_set_uniqbuf(struct tagcache_search *tcs,
1237 void *buffer, long length)
1239 tcs->unique_list = (unsigned long *)buffer;
1240 tcs->unique_list_capacity = length / sizeof(*tcs->unique_list);
1241 tcs->unique_list_count = 0;
1244 bool tagcache_search_add_filter(struct tagcache_search *tcs,
1245 int tag, int seek)
1247 if (tcs->filter_count == TAGCACHE_MAX_FILTERS)
1248 return false;
1250 if (!tagcache_is_unique_tag(tag) || tagcache_is_numeric_tag(tag))
1251 return false;
1253 tcs->filter_tag[tcs->filter_count] = tag;
1254 tcs->filter_seek[tcs->filter_count] = seek;
1255 tcs->filter_count++;
1257 return true;
1260 bool tagcache_search_add_clause(struct tagcache_search *tcs,
1261 struct tagcache_search_clause *clause)
1263 int i;
1265 if (tcs->clause_count >= TAGCACHE_MAX_CLAUSES)
1267 logf("Too many clauses");
1268 return false;
1271 /* Check if there is already a similar filter in present (filters are
1272 * much faster than clauses).
1274 for (i = 0; i < tcs->filter_count; i++)
1276 if (tcs->filter_tag[i] == clause->tag)
1277 return true;
1280 if (!tagcache_is_numeric_tag(clause->tag) && tcs->idxfd[clause->tag] < 0)
1282 char buf[MAX_PATH];
1284 snprintf(buf, sizeof buf, TAGCACHE_FILE_INDEX, clause->tag);
1285 tcs->idxfd[clause->tag] = open(buf, O_RDONLY);
1288 tcs->clause[tcs->clause_count] = clause;
1289 tcs->clause_count++;
1291 return true;
1294 #define TAG_FILENAME_RAM(tcs) ((tcs->type == tag_filename) \
1295 ? (flag & FLAG_DIRCACHE) : 1)
1297 static bool get_next(struct tagcache_search *tcs)
1299 static char buf[TAG_MAXLEN+32];
1300 struct tagfile_entry entry;
1301 long flag = 0;
1303 if (!tcs->valid || !tc_stat.ready)
1304 return false;
1306 if (tcs->idxfd[tcs->type] < 0 && !tagcache_is_numeric_tag(tcs->type)
1307 #ifdef HAVE_TC_RAMCACHE
1308 && !tcs->ramsearch
1309 #endif
1311 return false;
1313 /* Relative fetch. */
1314 if (tcs->filter_count > 0 || tcs->clause_count > 0
1315 || tagcache_is_numeric_tag(tcs->type))
1317 /* Check for end of list. */
1318 if (tcs->seek_list_count == 0)
1320 /* Try to fetch more. */
1321 if (!build_lookup_list(tcs))
1323 tcs->valid = false;
1324 return false;
1328 tcs->seek_list_count--;
1329 flag = tcs->seek_flags[tcs->seek_list_count];
1331 /* Seek stream to the correct position and continue to direct fetch. */
1332 if ((!tcs->ramsearch || !TAG_FILENAME_RAM(tcs))
1333 && !tagcache_is_numeric_tag(tcs->type))
1335 if (!open_files(tcs, tcs->type))
1336 return false;
1338 lseek(tcs->idxfd[tcs->type], tcs->seek_list[tcs->seek_list_count], SEEK_SET);
1340 else
1341 tcs->position = tcs->seek_list[tcs->seek_list_count];
1344 if (tagcache_is_numeric_tag(tcs->type))
1346 snprintf(buf, sizeof(buf), "%d", tcs->position);
1347 tcs->result_seek = tcs->position;
1348 tcs->result = buf;
1349 tcs->result_len = strlen(buf) + 1;
1350 return true;
1353 /* Direct fetch. */
1354 #ifdef HAVE_TC_RAMCACHE
1355 if (tcs->ramsearch && TAG_FILENAME_RAM(tcs))
1357 struct tagfile_entry *ep;
1359 if (tcs->entry_count == 0)
1361 tcs->valid = false;
1362 return false;
1364 tcs->entry_count--;
1366 tcs->result_seek = tcs->position;
1368 # ifdef HAVE_DIRCACHE
1369 if (tcs->type == tag_filename)
1371 dircache_copy_path((struct dirent *)tcs->position,
1372 buf, sizeof buf);
1373 tcs->result = buf;
1374 tcs->result_len = strlen(buf) + 1;
1375 tcs->idx_id = FLAG_GET_ATTR(flag);
1376 tcs->ramresult = false;
1378 return true;
1380 # endif
1382 ep = (struct tagfile_entry *)&hdr->tags[tcs->type][tcs->position];
1383 tcs->position += sizeof(struct tagfile_entry) + ep->tag_length;
1384 tcs->result = ep->tag_data;
1385 tcs->result_len = strlen(tcs->result) + 1;
1386 tcs->idx_id = ep->idx_id;
1387 tcs->ramresult = true;
1389 return true;
1391 else
1392 #endif
1394 if (!open_files(tcs, tcs->type))
1395 return false;
1397 tcs->result_seek = lseek(tcs->idxfd[tcs->type], 0, SEEK_CUR);
1398 if (ecread(tcs->idxfd[tcs->type], &entry, 1,
1399 tagfile_entry_ec, tc_stat.econ) != sizeof(struct tagfile_entry))
1401 /* End of data. */
1402 tcs->valid = false;
1403 return false;
1407 if (entry.tag_length > (long)sizeof(buf))
1409 tcs->valid = false;
1410 logf("too long tag #2");
1411 return false;
1414 if (read(tcs->idxfd[tcs->type], buf, entry.tag_length) != entry.tag_length)
1416 tcs->valid = false;
1417 logf("read error #4");
1418 return false;
1421 tcs->result = buf;
1422 tcs->result_len = strlen(tcs->result) + 1;
1423 tcs->idx_id = entry.idx_id;
1424 tcs->ramresult = false;
1426 return true;
1429 bool tagcache_get_next(struct tagcache_search *tcs)
1431 while (get_next(tcs))
1433 if (tcs->result_len > 1)
1434 return true;
1437 return false;
1440 bool tagcache_retrieve(struct tagcache_search *tcs, int idxid,
1441 int tag, char *buf, long size)
1443 struct index_entry idx;
1445 *buf = '\0';
1446 if (!get_index(tcs->masterfd, idxid, &idx, true))
1447 return false;
1449 return retrieve(tcs, &idx, tag, buf, size);
1452 static bool update_master_header(void)
1454 struct master_header myhdr;
1455 int fd;
1457 if (!tc_stat.ready)
1458 return false;
1460 if ( (fd = open_master_fd(&myhdr, true)) < 0)
1461 return false;
1463 myhdr.serial = current_tcmh.serial;
1464 myhdr.commitid = current_tcmh.commitid;
1466 /* Write it back */
1467 lseek(fd, 0, SEEK_SET);
1468 ecwrite(fd, &myhdr, 1, master_header_ec, tc_stat.econ);
1469 close(fd);
1471 #ifdef HAVE_TC_RAMCACHE
1472 if (hdr)
1474 hdr->h.serial = current_tcmh.serial;
1475 hdr->h.commitid = current_tcmh.commitid;
1477 #endif
1479 return true;
1482 #if 0
1484 void tagcache_modify(struct tagcache_search *tcs, int type, const char *text)
1486 struct tagentry *entry;
1488 if (tcs->type != tag_title)
1489 return ;
1491 /* We will need reserve buffer for this. */
1492 if (tcs->ramcache)
1494 struct tagfile_entry *ep;
1496 ep = (struct tagfile_entry *)&hdr->tags[tcs->type][tcs->result_seek];
1497 tcs->seek_list[tcs->seek_list_count];
1500 entry = find_entry_ram();
1503 #endif
1505 void tagcache_search_finish(struct tagcache_search *tcs)
1507 int i;
1509 if (!tcs->initialized)
1510 return;
1512 if (tcs->masterfd >= 0)
1514 close(tcs->masterfd);
1515 tcs->masterfd = -1;
1518 for (i = 0; i < TAG_COUNT; i++)
1520 if (tcs->idxfd[i] >= 0)
1522 close(tcs->idxfd[i]);
1523 tcs->idxfd[i] = -1;
1527 tcs->ramsearch = false;
1528 tcs->valid = false;
1529 tcs->initialized = 0;
1530 if (write_lock > 0)
1531 write_lock--;
1534 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1535 static struct tagfile_entry *get_tag(const struct index_entry *entry, int tag)
1537 return (struct tagfile_entry *)&hdr->tags[tag][entry->tag_seek[tag]];
1540 static long get_tag_numeric(const struct index_entry *entry, int tag)
1542 return check_virtual_tags(tag, entry);
1545 static char* get_tag_string(const struct index_entry *entry, int tag)
1547 char* s = get_tag(entry, tag)->tag_data;
1548 return strcmp(s, UNTAGGED) ? s : NULL;
1551 bool tagcache_fill_tags(struct mp3entry *id3, const char *filename)
1553 struct index_entry *entry;
1554 int idx_id;
1556 if (!tc_stat.ready)
1557 return false;
1559 /* Find the corresponding entry in tagcache. */
1560 idx_id = find_entry_ram(filename, NULL);
1561 if (idx_id < 0 || !tc_stat.ramcache)
1562 return false;
1564 entry = &hdr->indices[idx_id];
1566 id3->title = get_tag_string(entry, tag_title);
1567 id3->artist = get_tag_string(entry, tag_artist);
1568 id3->album = get_tag_string(entry, tag_album);
1569 id3->genre_string = get_tag_string(entry, tag_genre);
1570 id3->composer = get_tag_string(entry, tag_composer);
1571 id3->comment = get_tag_string(entry, tag_comment);
1572 id3->albumartist = get_tag_string(entry, tag_albumartist);
1573 id3->grouping = get_tag_string(entry, tag_grouping);
1575 id3->playcount = get_tag_numeric(entry, tag_playcount);
1576 id3->rating = get_tag_numeric(entry, tag_rating);
1577 id3->lastplayed = get_tag_numeric(entry, tag_lastplayed);
1578 id3->score = get_tag_numeric(entry, tag_virt_autoscore) / 10;
1579 id3->year = get_tag_numeric(entry, tag_year);
1581 id3->discnum = get_tag_numeric(entry, tag_discnumber);
1582 id3->tracknum = get_tag_numeric(entry, tag_tracknumber);
1583 id3->bitrate = get_tag_numeric(entry, tag_bitrate);
1584 if (id3->bitrate == 0)
1585 id3->bitrate = 1;
1587 return true;
1589 #endif
1591 static inline void write_item(const char *item)
1593 int len = strlen(item) + 1;
1595 data_size += len;
1596 write(cachefd, item, len);
1599 static int check_if_empty(char **tag)
1601 int length;
1603 if (*tag == NULL || *tag[0] == '\0')
1605 *tag = UNTAGGED;
1606 return sizeof(UNTAGGED); /* Tag length */
1609 length = strlen(*tag);
1610 if (length > TAG_MAXLEN)
1612 logf("over length tag: %s", *tag);
1613 length = TAG_MAXLEN;
1614 *tag[length] = '\0';
1617 return length + 1;
1620 #define ADD_TAG(entry,tag,data) \
1621 /* Adding tag */ \
1622 entry.tag_offset[tag] = offset; \
1623 entry.tag_length[tag] = check_if_empty(data); \
1624 offset += entry.tag_length[tag]
1626 static void add_tagcache(char *path, unsigned long mtime
1627 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1628 ,const struct dirent *dc
1629 #endif
1632 struct mp3entry id3;
1633 struct temp_file_entry entry;
1634 bool ret;
1635 int fd;
1636 int idx_id = -1;
1637 char tracknumfix[3];
1638 int offset = 0;
1639 int path_length = strlen(path);
1640 bool has_albumartist;
1641 bool has_grouping;
1643 if (cachefd < 0)
1644 return ;
1646 /* Check for overlength file path. */
1647 if (path_length > TAG_MAXLEN)
1649 /* Path can't be shortened. */
1650 logf("Too long path: %s", path);
1651 return ;
1654 /* Check if the file is supported. */
1655 if (probe_file_format(path) == AFMT_UNKNOWN)
1656 return ;
1658 /* Check if the file is already cached. */
1659 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
1660 if (tc_stat.ramcache && dircache_is_enabled())
1662 idx_id = find_entry_ram(path, dc);
1664 else
1665 #endif
1667 if (filenametag_fd >= 0)
1669 idx_id = find_entry_disk(path);
1673 /* Check if file has been modified. */
1674 if (idx_id >= 0)
1676 struct index_entry idx;
1678 if (!get_index(-1, idx_id, &idx, true))
1680 logf("failed to retrieve index entry");
1681 return ;
1684 if ((unsigned long)idx.tag_seek[tag_mtime] == mtime)
1686 /* No changes to file. */
1687 return ;
1690 /* Metadata might have been changed. Delete the entry. */
1691 logf("Re-adding: %s", path);
1692 if (!delete_entry(idx_id))
1694 logf("delete_entry failed: %d", idx_id);
1695 return ;
1699 fd = open(path, O_RDONLY);
1700 if (fd < 0)
1702 logf("open fail: %s", path);
1703 return ;
1706 memset(&id3, 0, sizeof(struct mp3entry));
1707 memset(&entry, 0, sizeof(struct temp_file_entry));
1708 memset(&tracknumfix, 0, sizeof(tracknumfix));
1709 ret = get_metadata(&id3, fd, path);
1710 close(fd);
1712 if (!ret)
1713 return ;
1715 logf("-> %s", path);
1717 /* Generate track number if missing. */
1718 if (id3.tracknum <= 0)
1720 const char *p = strrchr(path, '.');
1722 if (p == NULL)
1723 p = &path[strlen(path)-1];
1725 while (*p != '/')
1727 if (isdigit(*p) && isdigit(*(p-1)))
1729 tracknumfix[1] = *p--;
1730 tracknumfix[0] = *p;
1731 break;
1733 p--;
1736 if (tracknumfix[0] != '\0')
1738 id3.tracknum = atoi(tracknumfix);
1739 /* Set a flag to indicate track number has been generated. */
1740 entry.flag |= FLAG_TRKNUMGEN;
1742 else
1744 /* Unable to generate track number. */
1745 id3.tracknum = -1;
1749 /* Numeric tags */
1750 entry.tag_offset[tag_year] = id3.year;
1751 entry.tag_offset[tag_discnumber] = id3.discnum;
1752 entry.tag_offset[tag_tracknumber] = id3.tracknum;
1753 entry.tag_offset[tag_length] = id3.length;
1754 entry.tag_offset[tag_bitrate] = id3.bitrate;
1755 entry.tag_offset[tag_mtime] = mtime;
1757 /* String tags. */
1758 has_albumartist = id3.albumartist != NULL
1759 && strlen(id3.albumartist) > 0;
1760 has_grouping = id3.grouping != NULL
1761 && strlen(id3.grouping) > 0;
1763 ADD_TAG(entry, tag_filename, &path);
1764 ADD_TAG(entry, tag_title, &id3.title);
1765 ADD_TAG(entry, tag_artist, &id3.artist);
1766 ADD_TAG(entry, tag_album, &id3.album);
1767 ADD_TAG(entry, tag_genre, &id3.genre_string);
1768 ADD_TAG(entry, tag_composer, &id3.composer);
1769 ADD_TAG(entry, tag_comment, &id3.comment);
1770 if (has_albumartist)
1772 ADD_TAG(entry, tag_albumartist, &id3.albumartist);
1774 else
1776 ADD_TAG(entry, tag_albumartist, &id3.artist);
1778 if (has_grouping)
1780 ADD_TAG(entry, tag_grouping, &id3.grouping);
1782 else
1784 ADD_TAG(entry, tag_grouping, &id3.title);
1786 entry.data_length = offset;
1788 /* Write the header */
1789 write(cachefd, &entry, sizeof(struct temp_file_entry));
1791 /* And tags also... Correct order is critical */
1792 write_item(path);
1793 write_item(id3.title);
1794 write_item(id3.artist);
1795 write_item(id3.album);
1796 write_item(id3.genre_string);
1797 write_item(id3.composer);
1798 write_item(id3.comment);
1799 if (has_albumartist)
1801 write_item(id3.albumartist);
1803 else
1805 write_item(id3.artist);
1807 if (has_grouping)
1809 write_item(id3.grouping);
1811 else
1813 write_item(id3.title);
1815 total_entry_count++;
1818 static bool tempbuf_insert(char *str, int id, int idx_id, bool unique)
1820 struct tempbuf_searchidx *index = (struct tempbuf_searchidx *)tempbuf;
1821 int len = strlen(str)+1;
1822 int i;
1823 unsigned crc32;
1824 unsigned *crcbuf = (unsigned *)&tempbuf[tempbuf_size-4];
1825 char buf[TAG_MAXLEN+32];
1827 for (i = 0; str[i] != '\0' && i < (int)sizeof(buf)-1; i++)
1828 buf[i] = tolower(str[i]);
1829 buf[i] = '\0';
1831 crc32 = crc_32(buf, i, 0xffffffff);
1833 if (unique)
1835 /* Check if the crc does not exist -> entry does not exist for sure. */
1836 for (i = 0; i < tempbufidx; i++)
1838 if (crcbuf[-i] != crc32)
1839 continue;
1841 if (!strcasecmp(str, index[i].str))
1843 if (id < 0 || id >= lookup_buffer_depth)
1845 logf("lookup buf overf.: %d", id);
1846 return false;
1849 lookup[id] = &index[i];
1850 return true;
1855 /* Insert to CRC buffer. */
1856 crcbuf[-tempbufidx] = crc32;
1857 tempbuf_left -= 4;
1859 /* Insert it to the buffer. */
1860 tempbuf_left -= len;
1861 if (tempbuf_left - 4 < 0 || tempbufidx >= commit_entry_count-1)
1862 return false;
1864 if (id >= lookup_buffer_depth)
1866 logf("lookup buf overf. #2: %d", id);
1867 return false;
1870 if (id >= 0)
1872 lookup[id] = &index[tempbufidx];
1873 index[tempbufidx].idlist.id = id;
1875 else
1876 index[tempbufidx].idlist.id = -1;
1878 index[tempbufidx].idlist.next = NULL;
1879 index[tempbufidx].idx_id = idx_id;
1880 index[tempbufidx].seek = -1;
1881 index[tempbufidx].str = &tempbuf[tempbuf_pos];
1882 memcpy(index[tempbufidx].str, str, len);
1883 tempbuf_pos += len;
1884 tempbufidx++;
1886 return true;
1889 static int compare(const void *p1, const void *p2)
1891 do_timed_yield();
1893 struct tempbuf_searchidx *e1 = (struct tempbuf_searchidx *)p1;
1894 struct tempbuf_searchidx *e2 = (struct tempbuf_searchidx *)p2;
1896 if (strcmp(e1->str, UNTAGGED) == 0)
1898 if (strcmp(e2->str, UNTAGGED) == 0)
1899 return 0;
1900 return -1;
1902 else if (strcmp(e2->str, UNTAGGED) == 0)
1903 return 1;
1905 return strncasecmp(e1->str, e2->str, TAG_MAXLEN);
1908 static int tempbuf_sort(int fd)
1910 struct tempbuf_searchidx *index = (struct tempbuf_searchidx *)tempbuf;
1911 struct tagfile_entry fe;
1912 int i;
1913 int length;
1915 /* Generate reverse lookup entries. */
1916 for (i = 0; i < lookup_buffer_depth; i++)
1918 struct tempbuf_id_list *idlist;
1920 if (!lookup[i])
1921 continue;
1923 if (lookup[i]->idlist.id == i)
1924 continue;
1926 idlist = &lookup[i]->idlist;
1927 while (idlist->next != NULL)
1928 idlist = idlist->next;
1930 tempbuf_left -= sizeof(struct tempbuf_id_list);
1931 if (tempbuf_left - 4 < 0)
1932 return -1;
1934 idlist->next = (struct tempbuf_id_list *)&tempbuf[tempbuf_pos];
1935 if (tempbuf_pos & 0x03)
1937 tempbuf_pos = (tempbuf_pos & ~0x03) + 0x04;
1938 tempbuf_left -= 3;
1939 idlist->next = (struct tempbuf_id_list *)&tempbuf[tempbuf_pos];
1941 tempbuf_pos += sizeof(struct tempbuf_id_list);
1943 idlist = idlist->next;
1944 idlist->id = i;
1945 idlist->next = NULL;
1947 do_timed_yield();
1950 qsort(index, tempbufidx, sizeof(struct tempbuf_searchidx), compare);
1951 memset(lookup, 0, lookup_buffer_depth * sizeof(struct tempbuf_searchidx **));
1953 for (i = 0; i < tempbufidx; i++)
1955 struct tempbuf_id_list *idlist = &index[i].idlist;
1957 /* Fix the lookup list. */
1958 while (idlist != NULL)
1960 if (idlist->id >= 0)
1961 lookup[idlist->id] = &index[i];
1962 idlist = idlist->next;
1965 index[i].seek = lseek(fd, 0, SEEK_CUR);
1966 length = strlen(index[i].str) + 1;
1967 fe.tag_length = length;
1968 fe.idx_id = index[i].idx_id;
1970 /* Check the chunk alignment. */
1971 if ((fe.tag_length + sizeof(struct tagfile_entry))
1972 % TAGFILE_ENTRY_CHUNK_LENGTH)
1974 fe.tag_length += TAGFILE_ENTRY_CHUNK_LENGTH -
1975 ((fe.tag_length + sizeof(struct tagfile_entry))
1976 % TAGFILE_ENTRY_CHUNK_LENGTH);
1979 #ifdef TAGCACHE_STRICT_ALIGN
1980 /* Make sure the entry is long aligned. */
1981 if (index[i].seek & 0x03)
1983 logf("tempbuf_sort: alignment error!");
1984 return -3;
1986 #endif
1988 if (ecwrite(fd, &fe, 1, tagfile_entry_ec, tc_stat.econ) !=
1989 sizeof(struct tagfile_entry))
1991 logf("tempbuf_sort: write error #1");
1992 return -1;
1995 if (write(fd, index[i].str, length) != length)
1997 logf("tempbuf_sort: write error #2");
1998 return -2;
2001 /* Write some padding. */
2002 if (fe.tag_length - length > 0)
2003 write(fd, "XXXXXXXX", fe.tag_length - length);
2006 return i;
2009 inline static struct tempbuf_searchidx* tempbuf_locate(int id)
2011 if (id < 0 || id >= lookup_buffer_depth)
2012 return NULL;
2014 return lookup[id];
2018 inline static int tempbuf_find_location(int id)
2020 struct tempbuf_searchidx *entry;
2022 entry = tempbuf_locate(id);
2023 if (entry == NULL)
2024 return -1;
2026 return entry->seek;
2029 static bool build_numeric_indices(struct tagcache_header *h, int tmpfd)
2031 struct master_header tcmh;
2032 struct index_entry idx;
2033 int masterfd;
2034 int masterfd_pos;
2035 struct temp_file_entry *entrybuf = (struct temp_file_entry *)tempbuf;
2036 int max_entries;
2037 int entries_processed = 0;
2038 int i, j;
2040 max_entries = tempbuf_size / sizeof(struct temp_file_entry) - 1;
2042 logf("Building numeric indices...");
2043 lseek(tmpfd, sizeof(struct tagcache_header), SEEK_SET);
2045 if ( (masterfd = open_master_fd(&tcmh, true)) < 0)
2046 return false;
2048 masterfd_pos = lseek(masterfd, tcmh.tch.entry_count * sizeof(struct index_entry),
2049 SEEK_CUR);
2050 if (masterfd_pos == filesize(masterfd))
2052 logf("we can't append!");
2053 close(masterfd);
2054 return false;
2057 while (entries_processed < h->entry_count)
2059 int count = MIN(h->entry_count - entries_processed, max_entries);
2061 /* Read in as many entries as possible. */
2062 for (i = 0; i < count; i++)
2064 /* Read in numeric data. */
2065 if (read(tmpfd, &entrybuf[i], sizeof(struct temp_file_entry)) !=
2066 sizeof(struct temp_file_entry))
2068 logf("read fail #1");
2069 close(masterfd);
2070 return false;
2073 /* Skip string data. */
2074 lseek(tmpfd, entrybuf[i].data_length, SEEK_CUR);
2077 /* Commit the data to the index. */
2078 for (i = 0; i < count; i++)
2080 int loc = lseek(masterfd, 0, SEEK_CUR);
2082 if (ecread(masterfd, &idx, 1, index_entry_ec, tc_stat.econ)
2083 != sizeof(struct index_entry))
2085 logf("read fail #2");
2086 close(masterfd);
2087 return false;
2090 for (j = 0; j < TAG_COUNT; j++)
2092 if (!tagcache_is_numeric_tag(j))
2093 continue;
2095 idx.tag_seek[j] = entrybuf[i].tag_offset[j];
2097 idx.flag = entrybuf[i].flag;
2099 if (tc_stat.ready && current_tcmh.commitid > 0)
2101 idx.tag_seek[tag_commitid] = current_tcmh.commitid;
2102 idx.flag |= FLAG_DIRTYNUM;
2105 /* Write back the updated index. */
2106 lseek(masterfd, loc, SEEK_SET);
2107 if (ecwrite(masterfd, &idx, 1, index_entry_ec, tc_stat.econ)
2108 != sizeof(struct index_entry))
2110 logf("write fail");
2111 close(masterfd);
2112 return false;
2116 entries_processed += count;
2117 logf("%d/%ld entries processed", entries_processed, h->entry_count);
2120 close(masterfd);
2122 return true;
2126 * Return values:
2127 * > 0 success
2128 * == 0 temporary failure
2129 * < 0 fatal error
2131 static int build_index(int index_type, struct tagcache_header *h, int tmpfd)
2133 int i;
2134 struct tagcache_header tch;
2135 struct master_header tcmh;
2136 struct index_entry idxbuf[IDX_BUF_DEPTH];
2137 int idxbuf_pos;
2138 char buf[TAG_MAXLEN+32];
2139 int fd = -1, masterfd;
2140 bool error = false;
2141 int init;
2142 int masterfd_pos;
2144 logf("Building index: %d", index_type);
2146 /* Check the number of entries we need to allocate ram for. */
2147 commit_entry_count = h->entry_count + 1;
2149 masterfd = open_master_fd(&tcmh, false);
2150 if (masterfd >= 0)
2152 commit_entry_count += tcmh.tch.entry_count;
2153 close(masterfd);
2155 else
2156 remove_files(); /* Just to be sure we are clean. */
2158 /* Open the index file, which contains the tag names. */
2159 fd = open_tag_fd(&tch, index_type, true);
2160 if (fd >= 0)
2162 logf("tch.datasize=%ld", tch.datasize);
2163 lookup_buffer_depth = 1 +
2164 /* First part */ commit_entry_count +
2165 /* Second part */ (tch.datasize / TAGFILE_ENTRY_CHUNK_LENGTH);
2167 else
2169 lookup_buffer_depth = 1 +
2170 /* First part */ commit_entry_count +
2171 /* Second part */ 0;
2174 logf("lookup_buffer_depth=%ld", lookup_buffer_depth);
2175 logf("commit_entry_count=%ld", commit_entry_count);
2177 /* Allocate buffer for all index entries from both old and new
2178 * tag files. */
2179 tempbufidx = 0;
2180 tempbuf_pos = commit_entry_count * sizeof(struct tempbuf_searchidx);
2182 /* Allocate lookup buffer. The first portion of commit_entry_count
2183 * contains the new tags in the temporary file and the second
2184 * part for locating entries already in the db.
2186 * New tags Old tags
2187 * +---------+---------------------------+
2188 * | index | position/ENTRY_CHUNK_SIZE | lookup buffer
2189 * +---------+---------------------------+
2191 * Old tags are inserted to a temporary buffer with position:
2192 * tempbuf_insert(position/ENTRY_CHUNK_SIZE, ...);
2193 * And new tags with index:
2194 * tempbuf_insert(idx, ...);
2196 * The buffer is sorted and written into tag file:
2197 * tempbuf_sort(...);
2198 * leaving master index locations messed up.
2200 * That is fixed using the lookup buffer for old tags:
2201 * new_seek = tempbuf_find_location(old_seek, ...);
2202 * and for new tags:
2203 * new_seek = tempbuf_find_location(idx);
2205 lookup = (struct tempbuf_searchidx **)&tempbuf[tempbuf_pos];
2206 tempbuf_pos += lookup_buffer_depth * sizeof(void **);
2207 memset(lookup, 0, lookup_buffer_depth * sizeof(void **));
2209 /* And calculate the remaining data space used mainly for storing
2210 * tag data (strings). */
2211 tempbuf_left = tempbuf_size - tempbuf_pos - 8;
2212 if (tempbuf_left - TAGFILE_ENTRY_AVG_LENGTH * commit_entry_count < 0)
2214 logf("Buffer way too small!");
2215 return 0;
2218 if (fd >= 0)
2221 * If tag file contains unique tags (sorted index), we will load
2222 * it entirely into memory so we can resort it later for use with
2223 * chunked browsing.
2225 if (tagcache_is_sorted_tag(index_type))
2227 logf("loading tags...");
2228 for (i = 0; i < tch.entry_count; i++)
2230 struct tagfile_entry entry;
2231 int loc = lseek(fd, 0, SEEK_CUR);
2232 bool ret;
2234 if (ecread(fd, &entry, 1, tagfile_entry_ec, tc_stat.econ)
2235 != sizeof(struct tagfile_entry))
2237 logf("read error #7");
2238 close(fd);
2239 return -2;
2242 if (entry.tag_length >= (int)sizeof(buf))
2244 logf("too long tag #3");
2245 close(fd);
2246 return -2;
2249 if (read(fd, buf, entry.tag_length) != entry.tag_length)
2251 logf("read error #8");
2252 close(fd);
2253 return -2;
2256 /* Skip deleted entries. */
2257 if (buf[0] == '\0')
2258 continue;
2261 * Save the tag and tag id in the memory buffer. Tag id
2262 * is saved so we can later reindex the master lookup
2263 * table when the index gets resorted.
2265 ret = tempbuf_insert(buf, loc/TAGFILE_ENTRY_CHUNK_LENGTH
2266 + commit_entry_count, entry.idx_id,
2267 tagcache_is_unique_tag(index_type));
2268 if (!ret)
2270 close(fd);
2271 return -3;
2273 do_timed_yield();
2275 logf("done");
2277 else
2278 tempbufidx = tch.entry_count;
2280 else
2283 * Creating new index file to store the tags. No need to preload
2284 * anything whether the index type is sorted or not.
2286 snprintf(buf, sizeof buf, TAGCACHE_FILE_INDEX, index_type);
2287 fd = open(buf, O_WRONLY | O_CREAT | O_TRUNC);
2288 if (fd < 0)
2290 logf("%s open fail", buf);
2291 return -2;
2294 tch.magic = TAGCACHE_MAGIC;
2295 tch.entry_count = 0;
2296 tch.datasize = 0;
2298 if (ecwrite(fd, &tch, 1, tagcache_header_ec, tc_stat.econ)
2299 != sizeof(struct tagcache_header))
2301 logf("header write failed");
2302 close(fd);
2303 return -2;
2307 /* Loading the tag lookup file as "master file". */
2308 logf("Loading index file");
2309 masterfd = open(TAGCACHE_FILE_MASTER, O_RDWR);
2311 if (masterfd < 0)
2313 logf("Creating new DB");
2314 masterfd = open(TAGCACHE_FILE_MASTER, O_WRONLY | O_CREAT | O_TRUNC);
2316 if (masterfd < 0)
2318 logf("Failure to create index file (%s)", TAGCACHE_FILE_MASTER);
2319 close(fd);
2320 return -2;
2323 /* Write the header (write real values later). */
2324 memset(&tcmh, 0, sizeof(struct master_header));
2325 tcmh.tch = *h;
2326 tcmh.tch.entry_count = 0;
2327 tcmh.tch.datasize = 0;
2328 tcmh.dirty = true;
2329 ecwrite(masterfd, &tcmh, 1, master_header_ec, tc_stat.econ);
2330 init = true;
2331 masterfd_pos = lseek(masterfd, 0, SEEK_CUR);
2333 else
2336 * Master file already exists so we need to process the current
2337 * file first.
2339 init = false;
2341 if (ecread(masterfd, &tcmh, 1, master_header_ec, tc_stat.econ) !=
2342 sizeof(struct master_header) || tcmh.tch.magic != TAGCACHE_MAGIC)
2344 logf("header error");
2345 close(fd);
2346 close(masterfd);
2347 return -2;
2351 * If we reach end of the master file, we need to expand it to
2352 * hold new tags. If the current index is not sorted, we can
2353 * simply append new data to end of the file.
2354 * However, if the index is sorted, we need to update all tag
2355 * pointers in the master file for the current index.
2357 masterfd_pos = lseek(masterfd, tcmh.tch.entry_count * sizeof(struct index_entry),
2358 SEEK_CUR);
2359 if (masterfd_pos == filesize(masterfd))
2361 logf("appending...");
2362 init = true;
2367 * Load new unique tags in memory to be sorted later and added
2368 * to the master lookup file.
2370 if (tagcache_is_sorted_tag(index_type))
2372 lseek(tmpfd, sizeof(struct tagcache_header), SEEK_SET);
2373 /* h is the header of the temporary file containing new tags. */
2374 logf("inserting new tags...");
2375 for (i = 0; i < h->entry_count; i++)
2377 struct temp_file_entry entry;
2379 if (read(tmpfd, &entry, sizeof(struct temp_file_entry)) !=
2380 sizeof(struct temp_file_entry))
2382 logf("read fail #3");
2383 error = true;
2384 goto error_exit;
2387 /* Read data. */
2388 if (entry.tag_length[index_type] >= (long)sizeof(buf))
2390 logf("too long entry!");
2391 error = true;
2392 goto error_exit;
2395 lseek(tmpfd, entry.tag_offset[index_type], SEEK_CUR);
2396 if (read(tmpfd, buf, entry.tag_length[index_type]) !=
2397 entry.tag_length[index_type])
2399 logf("read fail #4");
2400 error = true;
2401 goto error_exit;
2404 if (tagcache_is_unique_tag(index_type))
2405 error = !tempbuf_insert(buf, i, -1, true);
2406 else
2407 error = !tempbuf_insert(buf, i, tcmh.tch.entry_count + i, false);
2409 if (error)
2411 logf("insert error");
2412 goto error_exit;
2415 /* Skip to next. */
2416 lseek(tmpfd, entry.data_length - entry.tag_offset[index_type] -
2417 entry.tag_length[index_type], SEEK_CUR);
2418 do_timed_yield();
2420 logf("done");
2422 /* Sort the buffer data and write it to the index file. */
2423 lseek(fd, sizeof(struct tagcache_header), SEEK_SET);
2424 i = tempbuf_sort(fd);
2425 if (i < 0)
2426 goto error_exit;
2427 logf("sorted %d tags", i);
2430 * Now update all indexes in the master lookup file.
2432 logf("updating indices...");
2433 lseek(masterfd, sizeof(struct master_header), SEEK_SET);
2434 for (i = 0; i < tcmh.tch.entry_count; i += idxbuf_pos)
2436 int j;
2437 int loc = lseek(masterfd, 0, SEEK_CUR);
2439 idxbuf_pos = MIN(tcmh.tch.entry_count - i, IDX_BUF_DEPTH);
2441 if (ecread(masterfd, idxbuf, idxbuf_pos, index_entry_ec, tc_stat.econ)
2442 != (int)sizeof(struct index_entry)*idxbuf_pos)
2444 logf("read fail #5");
2445 error = true;
2446 goto error_exit ;
2448 lseek(masterfd, loc, SEEK_SET);
2450 for (j = 0; j < idxbuf_pos; j++)
2452 if (idxbuf[j].flag & FLAG_DELETED)
2454 /* We can just ignore deleted entries. */
2455 idxbuf[j].tag_seek[index_type] = 0;
2456 continue;
2459 idxbuf[j].tag_seek[index_type] = tempbuf_find_location(
2460 idxbuf[j].tag_seek[index_type]/TAGFILE_ENTRY_CHUNK_LENGTH
2461 + commit_entry_count);
2463 if (idxbuf[j].tag_seek[index_type] < 0)
2465 logf("update error: %d/%ld", i+j, tcmh.tch.entry_count);
2466 error = true;
2467 goto error_exit;
2470 do_timed_yield();
2473 /* Write back the updated index. */
2474 if (ecwrite(masterfd, idxbuf, idxbuf_pos,
2475 index_entry_ec, tc_stat.econ) !=
2476 (int)sizeof(struct index_entry)*idxbuf_pos)
2478 logf("write fail");
2479 error = true;
2480 goto error_exit;
2483 logf("done");
2487 * Walk through the temporary file containing the new tags.
2489 // build_normal_index(h, tmpfd, masterfd, idx);
2490 logf("updating new indices...");
2491 lseek(masterfd, masterfd_pos, SEEK_SET);
2492 lseek(tmpfd, sizeof(struct tagcache_header), SEEK_SET);
2493 lseek(fd, 0, SEEK_END);
2494 for (i = 0; i < h->entry_count; i += idxbuf_pos)
2496 int j;
2498 idxbuf_pos = MIN(h->entry_count - i, IDX_BUF_DEPTH);
2499 if (init)
2501 memset(idxbuf, 0, sizeof(struct index_entry)*IDX_BUF_DEPTH);
2503 else
2505 int loc = lseek(masterfd, 0, SEEK_CUR);
2507 if (ecread(masterfd, idxbuf, idxbuf_pos, index_entry_ec, tc_stat.econ)
2508 != (int)sizeof(struct index_entry)*idxbuf_pos)
2510 logf("read fail #6");
2511 error = true;
2512 break ;
2514 lseek(masterfd, loc, SEEK_SET);
2517 /* Read entry headers. */
2518 for (j = 0; j < idxbuf_pos; j++)
2520 if (!tagcache_is_sorted_tag(index_type))
2522 struct temp_file_entry entry;
2523 struct tagfile_entry fe;
2525 if (read(tmpfd, &entry, sizeof(struct temp_file_entry)) !=
2526 sizeof(struct temp_file_entry))
2528 logf("read fail #7");
2529 error = true;
2530 break ;
2533 /* Read data. */
2534 if (entry.tag_length[index_type] >= (int)sizeof(buf))
2536 logf("too long entry!");
2537 logf("length=%d", entry.tag_length[index_type]);
2538 logf("pos=0x%02lx", lseek(tmpfd, 0, SEEK_CUR));
2539 error = true;
2540 break ;
2543 lseek(tmpfd, entry.tag_offset[index_type], SEEK_CUR);
2544 if (read(tmpfd, buf, entry.tag_length[index_type]) !=
2545 entry.tag_length[index_type])
2547 logf("read fail #8");
2548 logf("offset=0x%02lx", entry.tag_offset[index_type]);
2549 logf("length=0x%02x", entry.tag_length[index_type]);
2550 error = true;
2551 break ;
2554 /* Write to index file. */
2555 idxbuf[j].tag_seek[index_type] = lseek(fd, 0, SEEK_CUR);
2556 fe.tag_length = entry.tag_length[index_type];
2557 fe.idx_id = tcmh.tch.entry_count + i + j;
2558 ecwrite(fd, &fe, 1, tagfile_entry_ec, tc_stat.econ);
2559 write(fd, buf, fe.tag_length);
2560 tempbufidx++;
2562 /* Skip to next. */
2563 lseek(tmpfd, entry.data_length - entry.tag_offset[index_type] -
2564 entry.tag_length[index_type], SEEK_CUR);
2566 else
2568 /* Locate the correct entry from the sorted array. */
2569 idxbuf[j].tag_seek[index_type] = tempbuf_find_location(i + j);
2570 if (idxbuf[j].tag_seek[index_type] < 0)
2572 logf("entry not found (%d)", j);
2573 error = true;
2574 break ;
2579 /* Write index. */
2580 if (ecwrite(masterfd, idxbuf, idxbuf_pos,
2581 index_entry_ec, tc_stat.econ) !=
2582 (int)sizeof(struct index_entry)*idxbuf_pos)
2584 logf("tagcache: write fail #4");
2585 error = true;
2586 break ;
2589 do_timed_yield();
2591 logf("done");
2593 /* Finally write the header. */
2594 tch.magic = TAGCACHE_MAGIC;
2595 tch.entry_count = tempbufidx;
2596 tch.datasize = lseek(fd, 0, SEEK_END) - sizeof(struct tagcache_header);
2597 lseek(fd, 0, SEEK_SET);
2598 ecwrite(fd, &tch, 1, tagcache_header_ec, tc_stat.econ);
2600 if (index_type != tag_filename)
2601 h->datasize += tch.datasize;
2602 logf("s:%d/%ld/%ld", index_type, tch.datasize, h->datasize);
2603 error_exit:
2605 close(fd);
2606 close(masterfd);
2608 if (error)
2609 return -2;
2611 return 1;
2614 static bool commit(void)
2616 struct tagcache_header tch;
2617 struct master_header tcmh;
2618 int i, len, rc;
2619 int tmpfd;
2620 int masterfd;
2621 #ifdef HAVE_DIRCACHE
2622 bool dircache_buffer_stolen = false;
2623 #endif
2624 bool local_allocation = false;
2626 logf("committing tagcache");
2628 while (write_lock)
2629 sleep(1);
2631 tmpfd = open(TAGCACHE_FILE_TEMP, O_RDONLY);
2632 if (tmpfd < 0)
2634 logf("nothing to commit");
2635 return true;
2639 /* Load the header. */
2640 len = sizeof(struct tagcache_header);
2641 rc = read(tmpfd, &tch, len);
2643 if (tch.magic != TAGCACHE_MAGIC || rc != len)
2645 logf("incorrect header");
2646 close(tmpfd);
2647 remove(TAGCACHE_FILE_TEMP);
2648 return false;
2651 if (tch.entry_count == 0)
2653 logf("nothing to commit");
2654 close(tmpfd);
2655 remove(TAGCACHE_FILE_TEMP);
2656 return true;
2659 #ifdef HAVE_EEPROM_SETTINGS
2660 remove(TAGCACHE_STATEFILE);
2661 #endif
2663 /* At first be sure to unload the ramcache! */
2664 #ifdef HAVE_TC_RAMCACHE
2665 tc_stat.ramcache = false;
2666 #endif
2668 read_lock++;
2670 /* Try to steal every buffer we can :) */
2671 if (tempbuf_size == 0)
2672 local_allocation = true;
2674 #ifdef HAVE_DIRCACHE
2675 if (tempbuf_size == 0)
2677 /* Try to steal the dircache buffer. */
2678 tempbuf = dircache_steal_buffer(&tempbuf_size);
2679 tempbuf_size &= ~0x03;
2681 if (tempbuf_size > 0)
2683 dircache_buffer_stolen = true;
2686 #endif
2688 #ifdef HAVE_TC_RAMCACHE
2689 if (tempbuf_size == 0 && tc_stat.ramcache_allocated > 0)
2691 tempbuf = (char *)(hdr + 1);
2692 tempbuf_size = tc_stat.ramcache_allocated - sizeof(struct ramcache_header) - 128;
2693 tempbuf_size &= ~0x03;
2695 #endif
2697 /* And finally fail if there are no buffers available. */
2698 if (tempbuf_size == 0)
2700 logf("delaying commit until next boot");
2701 tc_stat.commit_delayed = true;
2702 close(tmpfd);
2703 read_lock--;
2704 return false;
2707 logf("commit %ld entries...", tch.entry_count);
2709 /* Mark DB dirty so it will stay disabled if commit fails. */
2710 current_tcmh.dirty = true;
2711 update_master_header();
2713 /* Now create the index files. */
2714 tc_stat.commit_step = 0;
2715 tch.datasize = 0;
2716 tc_stat.commit_delayed = false;
2718 for (i = 0; i < TAG_COUNT; i++)
2720 int ret;
2722 if (tagcache_is_numeric_tag(i))
2723 continue;
2725 tc_stat.commit_step++;
2726 ret = build_index(i, &tch, tmpfd);
2727 if (ret <= 0)
2729 close(tmpfd);
2730 logf("tagcache failed init");
2731 if (ret < 0)
2732 remove_files();
2733 else
2734 tc_stat.commit_delayed = true;
2735 tc_stat.commit_step = 0;
2736 read_lock--;
2737 return false;
2741 if (!build_numeric_indices(&tch, tmpfd))
2743 logf("Failure to commit numeric indices");
2744 close(tmpfd);
2745 remove_files();
2746 tc_stat.commit_step = 0;
2747 read_lock--;
2748 return false;
2751 close(tmpfd);
2752 tc_stat.commit_step = 0;
2754 /* Update the master index headers. */
2755 if ( (masterfd = open_master_fd(&tcmh, true)) < 0)
2757 read_lock--;
2758 return false;
2761 tcmh.tch.entry_count += tch.entry_count;
2762 tcmh.tch.datasize = sizeof(struct master_header)
2763 + sizeof(struct index_entry) * tcmh.tch.entry_count
2764 + tch.datasize;
2765 tcmh.dirty = false;
2766 tcmh.commitid++;
2768 lseek(masterfd, 0, SEEK_SET);
2769 ecwrite(masterfd, &tcmh, 1, master_header_ec, tc_stat.econ);
2770 close(masterfd);
2772 logf("tagcache committed");
2773 remove(TAGCACHE_FILE_TEMP);
2774 tc_stat.ready = check_all_headers();
2775 tc_stat.readyvalid = true;
2777 if (local_allocation)
2779 tempbuf = NULL;
2780 tempbuf_size = 0;
2783 #ifdef HAVE_DIRCACHE
2784 /* Rebuild the dircache, if we stole the buffer. */
2785 if (dircache_buffer_stolen)
2786 dircache_build(0);
2787 #endif
2789 #ifdef HAVE_TC_RAMCACHE
2790 /* Reload tagcache. */
2791 if (tc_stat.ramcache_allocated > 0)
2792 tagcache_start_scan();
2793 #endif
2795 read_lock--;
2797 return true;
2800 static void allocate_tempbuf(void)
2802 /* Yeah, malloc would be really nice now :) */
2803 #ifdef __PCTOOL__
2804 tempbuf_size = 32*1024*1024;
2805 tempbuf = malloc(tempbuf_size);
2806 #else
2807 tempbuf = (char *)(((long)audiobuf & ~0x03) + 0x04);
2808 tempbuf_size = (long)audiobufend - (long)audiobuf - 4;
2809 audiobuf += tempbuf_size;
2810 #endif
2813 static void free_tempbuf(void)
2815 if (tempbuf_size == 0)
2816 return ;
2818 #ifdef __PCTOOL__
2819 free(tempbuf);
2820 #else
2821 audiobuf -= tempbuf_size;
2822 #endif
2823 tempbuf = NULL;
2824 tempbuf_size = 0;
2827 static bool modify_numeric_entry(int masterfd, int idx_id, int tag, long data)
2829 struct index_entry idx;
2831 if (!tc_stat.ready)
2832 return false;
2834 if (!tagcache_is_numeric_tag(tag))
2835 return false;
2837 if (!get_index(masterfd, idx_id, &idx, false))
2838 return false;
2840 idx.tag_seek[tag] = data;
2841 idx.flag |= FLAG_DIRTYNUM;
2843 return write_index(masterfd, idx_id, &idx);
2846 #if 0
2847 bool tagcache_modify_numeric_entry(struct tagcache_search *tcs,
2848 int tag, long data)
2850 struct master_header myhdr;
2852 if (tcs->masterfd < 0)
2854 if ( (tcs->masterfd = open_master_fd(&myhdr, true)) < 0)
2855 return false;
2858 return modify_numeric_entry(tcs->masterfd, tcs->idx_id, tag, data);
2860 #endif
2862 #define COMMAND_QUEUE_IS_EMPTY (command_queue_ridx == command_queue_widx)
2864 static bool command_queue_is_full(void)
2866 int next;
2868 next = command_queue_widx + 1;
2869 if (next >= TAGCACHE_COMMAND_QUEUE_LENGTH)
2870 next = 0;
2872 return (next == command_queue_ridx);
2875 void run_command_queue(bool force)
2877 struct master_header myhdr;
2878 int masterfd;
2880 if (COMMAND_QUEUE_IS_EMPTY)
2881 return;
2883 if (!force && !command_queue_is_full()
2884 && current_tick - TAGCACHE_COMMAND_QUEUE_COMMIT_DELAY
2885 < command_queue_timestamp)
2887 return;
2890 mutex_lock(&command_queue_mutex);
2892 if ( (masterfd = open_master_fd(&myhdr, true)) < 0)
2893 return;
2895 while (command_queue_ridx != command_queue_widx)
2897 struct tagcache_command_entry *ce = &command_queue[command_queue_ridx];
2899 switch (ce->command)
2901 case CMD_UPDATE_MASTER_HEADER:
2903 close(masterfd);
2904 update_master_header();
2906 /* Re-open the masterfd. */
2907 if ( (masterfd = open_master_fd(&myhdr, true)) < 0)
2908 return;
2910 break;
2912 case CMD_UPDATE_NUMERIC:
2914 modify_numeric_entry(masterfd, ce->idx_id, ce->tag, ce->data);
2915 break;
2919 if (++command_queue_ridx >= TAGCACHE_COMMAND_QUEUE_LENGTH)
2920 command_queue_ridx = 0;
2923 close(masterfd);
2925 mutex_unlock(&command_queue_mutex);
2928 static void queue_command(int cmd, long idx_id, int tag, long data)
2930 while (1)
2932 int next;
2934 mutex_lock(&command_queue_mutex);
2935 next = command_queue_widx + 1;
2936 if (next >= TAGCACHE_COMMAND_QUEUE_LENGTH)
2937 next = 0;
2939 /* Make sure queue is not full. */
2940 if (next != command_queue_ridx)
2942 struct tagcache_command_entry *ce = &command_queue[command_queue_widx];
2944 ce->command = cmd;
2945 ce->idx_id = idx_id;
2946 ce->tag = tag;
2947 ce->data = data;
2949 command_queue_widx = next;
2950 command_queue_timestamp = current_tick;
2951 mutex_unlock(&command_queue_mutex);
2952 break;
2955 /* Queue is full, try again later... */
2956 mutex_unlock(&command_queue_mutex);
2957 sleep(1);
2961 long tagcache_increase_serial(void)
2963 long old;
2965 if (!tc_stat.ready)
2966 return -2;
2968 while (read_lock)
2969 sleep(1);
2971 old = current_tcmh.serial++;
2972 queue_command(CMD_UPDATE_MASTER_HEADER, 0, 0, 0);
2974 return old;
2977 void tagcache_update_numeric(int idx_id, int tag, long data)
2979 queue_command(CMD_UPDATE_NUMERIC, idx_id, tag, data);
2982 long tagcache_get_serial(void)
2984 return current_tcmh.serial;
2987 long tagcache_get_commitid(void)
2989 return current_tcmh.commitid;
2992 static bool write_tag(int fd, const char *tagstr, const char *datastr)
2994 char buf[512];
2995 int i;
2997 snprintf(buf, sizeof buf, "%s=\"", tagstr);
2998 for (i = strlen(buf); i < (long)sizeof(buf)-3; i++)
3000 if (*datastr == '\0')
3001 break;
3003 if (*datastr == '"')
3005 buf[i] = '\\';
3006 datastr++;
3007 continue;
3010 buf[i] = *(datastr++);
3013 strcpy(&buf[i], "\" ");
3015 write(fd, buf, i + 2);
3017 return true;
3020 static bool read_tag(char *dest, long size,
3021 const char *src, const char *tagstr)
3023 int pos;
3024 char current_tag[32];
3026 while (*src != '\0')
3028 /* Skip all whitespace */
3029 while (*src == ' ')
3030 src++;
3032 if (*src == '\0')
3033 break;
3035 pos = 0;
3036 /* Read in tag name */
3037 while (*src != '=' && *src != ' ')
3039 current_tag[pos] = *src;
3040 src++;
3041 pos++;
3043 if (*src == '\0' || pos >= (long)sizeof(current_tag))
3044 return false;
3046 current_tag[pos] = '\0';
3048 /* Read in tag data */
3050 /* Find the start. */
3051 while (*src != '"' && *src != '\0')
3052 src++;
3054 if (*src == '\0' || *(++src) == '\0')
3055 return false;
3057 /* Read the data. */
3058 for (pos = 0; pos < size; pos++)
3060 if (*src == '\0')
3061 break;
3063 if (*src == '\\' && *(src+1) == '"')
3065 dest[pos] = '"';
3066 src += 2;
3067 continue;
3070 dest[pos] = *src;
3072 if (*src == '"')
3074 src++;
3075 break;
3078 if (*src == '\0')
3079 break;
3081 src++;
3083 dest[pos] = '\0';
3085 if (!strcasecmp(tagstr, current_tag))
3086 return true;
3089 return false;
3092 static int parse_changelog_line(int line_n, const char *buf, void *parameters)
3094 struct index_entry idx;
3095 char tag_data[TAG_MAXLEN+32];
3096 int idx_id;
3097 long masterfd = (long)parameters;
3098 const int import_tags[] = { tag_playcount, tag_rating, tag_playtime, tag_lastplayed,
3099 tag_commitid };
3100 int i;
3101 (void)line_n;
3103 if (*buf == '#')
3104 return 0;
3106 logf("%d/%s", line_n, buf);
3107 if (!read_tag(tag_data, sizeof tag_data, buf, "filename"))
3109 logf("filename missing");
3110 logf("-> %s", buf);
3111 return 0;
3114 idx_id = find_index(tag_data);
3115 if (idx_id < 0)
3117 logf("entry not found");
3118 return 0;
3121 if (!get_index(masterfd, idx_id, &idx, false))
3123 logf("failed to retrieve index entry");
3124 return 0;
3127 /* Stop if tag has already been modified. */
3128 if (idx.flag & FLAG_DIRTYNUM)
3129 return 0;
3131 logf("import: %s", tag_data);
3133 idx.flag |= FLAG_DIRTYNUM;
3134 for (i = 0; i < (long)(sizeof(import_tags)/sizeof(import_tags[0])); i++)
3136 int data;
3138 if (!read_tag(tag_data, sizeof tag_data, buf,
3139 tagcache_tag_to_str(import_tags[i])))
3141 continue;
3144 data = atoi(tag_data);
3145 if (data < 0)
3146 continue;
3148 idx.tag_seek[import_tags[i]] = data;
3150 if (import_tags[i] == tag_lastplayed && data > current_tcmh.serial)
3151 current_tcmh.serial = data;
3152 else if (import_tags[i] == tag_commitid && data >= current_tcmh.commitid)
3153 current_tcmh.commitid = data + 1;
3156 return write_index(masterfd, idx_id, &idx) ? 0 : -5;
3159 #ifndef __PCTOOL__
3160 bool tagcache_import_changelog(void)
3162 struct master_header myhdr;
3163 struct tagcache_header tch;
3164 int clfd;
3165 long masterfd;
3166 char buf[2048];
3168 if (!tc_stat.ready)
3169 return false;
3171 while (read_lock)
3172 sleep(1);
3174 clfd = open(TAGCACHE_FILE_CHANGELOG, O_RDONLY);
3175 if (clfd < 0)
3177 logf("failure to open changelog");
3178 return false;
3181 if ( (masterfd = open_master_fd(&myhdr, true)) < 0)
3183 close(clfd);
3184 return false;
3187 write_lock++;
3189 filenametag_fd = open_tag_fd(&tch, tag_filename, false);
3191 fast_readline(clfd, buf, sizeof buf, (long *)masterfd,
3192 parse_changelog_line);
3194 close(clfd);
3195 close(masterfd);
3197 if (filenametag_fd >= 0)
3198 close(filenametag_fd);
3200 write_lock--;
3202 update_master_header();
3204 return true;
3206 #endif
3208 bool tagcache_create_changelog(struct tagcache_search *tcs)
3210 struct master_header myhdr;
3211 struct index_entry idx;
3212 char buf[TAG_MAXLEN+32];
3213 char temp[32];
3214 int clfd;
3215 int i, j;
3217 if (!tc_stat.ready)
3218 return false;
3220 if (!tagcache_search(tcs, tag_filename))
3221 return false;
3223 /* Initialize the changelog */
3224 clfd = open(TAGCACHE_FILE_CHANGELOG, O_WRONLY | O_CREAT | O_TRUNC);
3225 if (clfd < 0)
3227 logf("failure to open changelog");
3228 return false;
3231 if (tcs->masterfd < 0)
3233 if ( (tcs->masterfd = open_master_fd(&myhdr, false)) < 0)
3234 return false;
3236 else
3238 lseek(tcs->masterfd, 0, SEEK_SET);
3239 ecread(tcs->masterfd, &myhdr, 1, master_header_ec, tc_stat.econ);
3242 write(clfd, "## Changelog version 1\n", 23);
3244 for (i = 0; i < myhdr.tch.entry_count; i++)
3246 if (ecread(tcs->masterfd, &idx, 1, index_entry_ec, tc_stat.econ)
3247 != sizeof(struct index_entry))
3249 logf("read error #9");
3250 tagcache_search_finish(tcs);
3251 close(clfd);
3252 return false;
3255 /* Skip until the entry found has been modified. */
3256 if (! (idx.flag & FLAG_DIRTYNUM) )
3257 continue;
3259 /* Skip deleted entries too. */
3260 if (idx.flag & FLAG_DELETED)
3261 continue;
3263 /* Now retrieve all tags. */
3264 for (j = 0; j < TAG_COUNT; j++)
3266 if (tagcache_is_numeric_tag(j))
3268 snprintf(temp, sizeof temp, "%d", idx.tag_seek[j]);
3269 write_tag(clfd, tagcache_tag_to_str(j), temp);
3270 continue;
3273 tcs->type = j;
3274 tagcache_retrieve(tcs, i, tcs->type, buf, sizeof buf);
3275 write_tag(clfd, tagcache_tag_to_str(j), buf);
3278 write(clfd, "\n", 1);
3279 do_timed_yield();
3282 close(clfd);
3284 tagcache_search_finish(tcs);
3286 return true;
3289 static bool delete_entry(long idx_id)
3291 int fd = -1;
3292 /*int dbdel_fd = -1;*/
3293 int tag, i;
3294 struct index_entry idx, myidx;
3295 struct master_header myhdr;
3296 char buf[TAG_MAXLEN+32];
3297 int in_use[TAG_COUNT];
3299 logf("delete_entry(): %ld", idx_id);
3301 #ifdef HAVE_TC_RAMCACHE
3302 /* At first mark the entry removed from ram cache. */
3303 if (tc_stat.ramcache)
3304 hdr->indices[idx_id].flag |= FLAG_DELETED;
3305 #endif
3307 if ( (fd = open_master_fd(&myhdr, true) ) < 0)
3308 return false;
3311 TODO: Implement soon.
3312 dbdel_fd = open(TAGCACHE_FILE_DELETED, O_RDWR | O_APPEND | O_CREAT);
3313 if (dbdel_fd < 0)
3315 logf("delete_entry(): DBDEL open failed");
3316 goto cleanup;
3318 close(dbdel_fd);
3319 dbdel_fd = -1;
3321 lseek(fd, idx_id * sizeof(struct index_entry), SEEK_CUR);
3322 if (ecread(fd, &myidx, 1, index_entry_ec, tc_stat.econ)
3323 != sizeof(struct index_entry))
3325 logf("delete_entry(): read error");
3326 goto cleanup;
3329 myidx.flag |= FLAG_DELETED;
3330 lseek(fd, -sizeof(struct index_entry), SEEK_CUR);
3331 if (ecwrite(fd, &myidx, 1, index_entry_ec, tc_stat.econ)
3332 != sizeof(struct index_entry))
3334 logf("delete_entry(): write_error");
3335 goto cleanup;
3338 /* Now check which tags are no longer in use (if any) */
3339 for (tag = 0; tag < TAG_COUNT; tag++)
3340 in_use[tag] = 0;
3342 lseek(fd, sizeof(struct master_header), SEEK_SET);
3343 for (i = 0; i < myhdr.tch.entry_count; i++)
3345 struct index_entry *idxp;
3347 #ifdef HAVE_TC_RAMCACHE
3348 /* Use RAM DB if available for greater speed */
3349 if (tc_stat.ramcache)
3350 idxp = &hdr->indices[i];
3351 else
3352 #endif
3354 if (ecread(fd, &idx, 1, index_entry_ec, tc_stat.econ)
3355 != sizeof(struct index_entry))
3357 logf("delete_entry(): read error #2");
3358 goto cleanup;
3360 idxp = &idx;
3363 if (idxp->flag & FLAG_DELETED)
3364 continue;
3366 for (tag = 0; tag < TAG_COUNT; tag++)
3368 if (tagcache_is_numeric_tag(tag))
3369 continue;
3371 if (idxp->tag_seek[tag] == myidx.tag_seek[tag])
3372 in_use[tag]++;
3376 close(fd);
3377 fd = -1;
3379 /* Now delete all tags no longer in use. */
3380 for (tag = 0; tag < TAG_COUNT; tag++)
3382 if (tagcache_is_numeric_tag(tag))
3383 continue;
3385 if (in_use[tag])
3387 logf("in use: %d/%d", tag, in_use[tag]);
3388 continue;
3391 #ifdef HAVE_TC_RAMCACHE
3392 /* Delete from ram. */
3393 if (tc_stat.ramcache && tag != tag_filename)
3395 struct tagfile_entry *tagentry = get_tag(&myidx, tag);
3396 tagentry->tag_data[0] = '\0';
3398 #endif
3400 /* Open the index file, which contains the tag names. */
3401 snprintf(buf, sizeof buf, TAGCACHE_FILE_INDEX, tag);
3402 fd = open(buf, O_RDWR);
3404 if (fd < 0)
3406 logf("open failed");
3407 goto cleanup;
3410 /* Skip the header block */
3411 lseek(fd, myidx.tag_seek[tag] + sizeof(struct tagfile_entry), SEEK_SET);
3413 /* Debug, print 10 first characters of the tag
3414 read(fd, buf, 10);
3415 buf[10]='\0';
3416 logf("TAG:%s", buf);
3417 lseek(fd, -10, SEEK_CUR);
3420 /* Write first data byte in tag as \0 */
3421 write(fd, "", 1);
3423 /* Now tag data has been removed */
3424 close(fd);
3427 return true;
3429 cleanup:
3430 if (fd >= 0)
3431 close(fd);
3432 /* if (dbdel_fd >= 0)
3433 close(dbdel_fd);
3435 return false;
3438 #ifndef __PCTOOL__
3440 * Returns true if there is an event waiting in the queue
3441 * that requires the current operation to be aborted.
3443 static bool check_event_queue(void)
3445 struct queue_event ev;
3447 queue_wait_w_tmo(&tagcache_queue, &ev, 0);
3448 switch (ev.id)
3450 case Q_STOP_SCAN:
3451 case SYS_POWEROFF:
3452 case SYS_USB_CONNECTED:
3453 /* Put the event back into the queue. */
3454 queue_post(&tagcache_queue, ev.id, ev.data);
3455 return true;
3458 return false;
3460 #endif
3462 #ifdef HAVE_TC_RAMCACHE
3463 static bool allocate_tagcache(void)
3465 struct master_header tcmh;
3466 int fd;
3468 /* Load the header. */
3469 if ( (fd = open_master_fd(&tcmh, false)) < 0)
3471 hdr = NULL;
3472 return false;
3475 close(fd);
3477 /**
3478 * Now calculate the required cache size plus
3479 * some extra space for alignment fixes.
3481 tc_stat.ramcache_allocated = tcmh.tch.datasize + 128 + TAGCACHE_RESERVE +
3482 sizeof(struct ramcache_header) + TAG_COUNT*sizeof(void *);
3483 hdr = buffer_alloc(tc_stat.ramcache_allocated + 128);
3484 memset(hdr, 0, sizeof(struct ramcache_header));
3485 memcpy(&hdr->h, &tcmh, sizeof(struct master_header));
3486 hdr->indices = (struct index_entry *)(hdr + 1);
3487 logf("tagcache: %d bytes allocated.", tc_stat.ramcache_allocated);
3489 return true;
3492 # ifdef HAVE_EEPROM_SETTINGS
3493 static bool tagcache_dumpload(void)
3495 struct statefile_header shdr;
3496 int fd, rc;
3497 long offpos;
3498 int i;
3500 fd = open(TAGCACHE_STATEFILE, O_RDONLY);
3501 if (fd < 0)
3503 logf("no tagcache statedump");
3504 return false;
3507 /* Check the statefile memory placement */
3508 hdr = buffer_alloc(0);
3509 rc = read(fd, &shdr, sizeof(struct statefile_header));
3510 if (rc != sizeof(struct statefile_header)
3511 /* || (long)hdr != (long)shdr.hdr */)
3513 logf("incorrect statefile");
3514 hdr = NULL;
3515 close(fd);
3516 return false;
3519 offpos = (long)hdr - (long)shdr.hdr;
3521 /* Lets allocate real memory and load it */
3522 hdr = buffer_alloc(shdr.tc_stat.ramcache_allocated);
3523 rc = read(fd, hdr, shdr.tc_stat.ramcache_allocated);
3524 close(fd);
3526 if (rc != shdr.tc_stat.ramcache_allocated)
3528 logf("read failure!");
3529 hdr = NULL;
3530 return false;
3533 memcpy(&tc_stat, &shdr.tc_stat, sizeof(struct tagcache_stat));
3535 /* Now fix the pointers */
3536 hdr->indices = (struct index_entry *)((long)hdr->indices + offpos);
3537 for (i = 0; i < TAG_COUNT; i++)
3538 hdr->tags[i] += offpos;
3540 return true;
3543 static bool tagcache_dumpsave(void)
3545 struct statefile_header shdr;
3546 int fd;
3548 if (!tc_stat.ramcache)
3549 return false;
3551 fd = open(TAGCACHE_STATEFILE, O_WRONLY | O_CREAT | O_TRUNC);
3552 if (fd < 0)
3554 logf("failed to create a statedump");
3555 return false;
3558 /* Create the header */
3559 shdr.hdr = hdr;
3560 memcpy(&shdr.tc_stat, &tc_stat, sizeof(struct tagcache_stat));
3561 write(fd, &shdr, sizeof(struct statefile_header));
3563 /* And dump the data too */
3564 write(fd, hdr, tc_stat.ramcache_allocated);
3565 close(fd);
3567 return true;
3569 # endif
3571 static bool load_tagcache(void)
3573 struct tagcache_header *tch;
3574 long bytesleft = tc_stat.ramcache_allocated;
3575 struct index_entry *idx;
3576 int rc, fd;
3577 char *p;
3578 int i, tag;
3580 # ifdef HAVE_DIRCACHE
3581 while (dircache_is_initializing())
3582 sleep(1);
3583 # endif
3585 logf("loading tagcache to ram...");
3587 fd = open(TAGCACHE_FILE_MASTER, O_RDONLY);
3588 if (fd < 0)
3590 logf("tagcache open failed");
3591 return false;
3594 if (ecread(fd, &hdr->h, 1, master_header_ec, tc_stat.econ)
3595 != sizeof(struct master_header)
3596 || hdr->h.tch.magic != TAGCACHE_MAGIC)
3598 logf("incorrect header");
3599 return false;
3602 idx = hdr->indices;
3604 /* Load the master index table. */
3605 for (i = 0; i < hdr->h.tch.entry_count; i++)
3607 rc = ecread(fd, idx, 1, index_entry_ec, tc_stat.econ);
3608 if (rc != sizeof(struct index_entry))
3610 logf("read error #10");
3611 close(fd);
3612 return false;
3615 bytesleft -= sizeof(struct index_entry);
3616 if (bytesleft < 0 || ((long)idx - (long)hdr->indices) >= tc_stat.ramcache_allocated)
3618 logf("too big tagcache.");
3619 close(fd);
3620 return false;
3623 idx++;
3626 close(fd);
3628 /* Load the tags. */
3629 p = (char *)idx;
3630 for (tag = 0; tag < TAG_COUNT; tag++)
3632 struct tagfile_entry *fe;
3633 char buf[TAG_MAXLEN+32];
3635 if (tagcache_is_numeric_tag(tag))
3636 continue ;
3638 //p = ((void *)p+1);
3639 p = (char *)((long)p & ~0x03) + 0x04;
3640 hdr->tags[tag] = p;
3642 /* Check the header. */
3643 tch = (struct tagcache_header *)p;
3644 p += sizeof(struct tagcache_header);
3646 if ( (fd = open_tag_fd(tch, tag, false)) < 0)
3647 return false;
3649 for (hdr->entry_count[tag] = 0;
3650 hdr->entry_count[tag] < tch->entry_count;
3651 hdr->entry_count[tag]++)
3653 long pos;
3655 if (do_timed_yield())
3657 /* Abort if we got a critical event in queue */
3658 if (check_event_queue())
3659 return false;
3662 fe = (struct tagfile_entry *)p;
3663 pos = lseek(fd, 0, SEEK_CUR);
3664 rc = ecread(fd, fe, 1, tagfile_entry_ec, tc_stat.econ);
3665 if (rc != sizeof(struct tagfile_entry))
3667 /* End of lookup table. */
3668 logf("read error #11");
3669 close(fd);
3670 return false;
3673 /* We have a special handling for the filename tags. */
3674 if (tag == tag_filename)
3676 # ifdef HAVE_DIRCACHE
3677 const struct dirent *dc;
3678 # endif
3680 // FIXME: This is wrong!
3681 // idx = &hdr->indices[hdr->entry_count[i]];
3682 idx = &hdr->indices[fe->idx_id];
3684 if (fe->tag_length >= (long)sizeof(buf)-1)
3686 read(fd, buf, 10);
3687 buf[10] = '\0';
3688 logf("TAG:%s", buf);
3689 logf("too long filename");
3690 close(fd);
3691 return false;
3694 rc = read(fd, buf, fe->tag_length);
3695 if (rc != fe->tag_length)
3697 logf("read error #12");
3698 close(fd);
3699 return false;
3702 /* Check if the entry has already been removed */
3703 if (idx->flag & FLAG_DELETED)
3704 continue;
3706 /* This flag must not be used yet. */
3707 if (idx->flag & FLAG_DIRCACHE)
3709 logf("internal error!");
3710 close(fd);
3711 return false;
3714 if (idx->tag_seek[tag] != pos)
3716 logf("corrupt data structures!");
3717 close(fd);
3718 return false;
3721 # ifdef HAVE_DIRCACHE
3722 if (dircache_is_enabled())
3724 dc = dircache_get_entry_ptr(buf);
3725 if (dc == NULL)
3727 logf("Entry no longer valid.");
3728 logf("-> %s", buf);
3729 delete_entry(fe->idx_id);
3730 continue ;
3733 idx->flag |= FLAG_DIRCACHE;
3734 FLAG_SET_ATTR(idx->flag, fe->idx_id);
3735 idx->tag_seek[tag_filename] = (long)dc;
3737 else
3738 # endif
3741 /* Enabled for flash based targets. Too slow otherwise. */
3742 # ifdef HAVE_FLASH_STORAGE
3743 /* Check if entry has been removed. */
3744 if (global_settings.tagcache_autoupdate)
3746 int testfd;
3748 testfd = open(buf, O_RDONLY);
3749 if (testfd < 0)
3751 logf("Entry no longer valid.");
3752 logf("-> %s", buf);
3753 delete_entry(fe->idx_id);
3754 continue;
3756 close(testfd);
3758 # endif
3761 continue ;
3764 bytesleft -= sizeof(struct tagfile_entry) + fe->tag_length;
3765 if (bytesleft < 0)
3767 logf("too big tagcache #2");
3768 logf("tl: %d", fe->tag_length);
3769 logf("bl: %ld", bytesleft);
3770 close(fd);
3771 return false;
3774 p = fe->tag_data;
3775 rc = read(fd, fe->tag_data, fe->tag_length);
3776 p += rc;
3778 if (rc != fe->tag_length)
3780 logf("read error #13");
3781 logf("rc=0x%04x", rc); // 0x431
3782 logf("len=0x%04x", fe->tag_length); // 0x4000
3783 logf("pos=0x%04lx", lseek(fd, 0, SEEK_CUR)); // 0x433
3784 logf("tag=0x%02x", tag); // 0x00
3785 close(fd);
3786 return false;
3789 close(fd);
3792 tc_stat.ramcache_used = tc_stat.ramcache_allocated - bytesleft;
3793 logf("tagcache loaded into ram!");
3795 return true;
3797 #endif /* HAVE_TC_RAMCACHE */
3799 static bool check_deleted_files(void)
3801 int fd, testfd;
3802 char buf[TAG_MAXLEN+32];
3803 struct tagfile_entry tfe;
3805 logf("reverse scan...");
3806 snprintf(buf, sizeof buf, TAGCACHE_FILE_INDEX, tag_filename);
3807 fd = open(buf, O_RDONLY);
3809 if (fd < 0)
3811 logf("%s open fail", buf);
3812 return false;
3815 lseek(fd, sizeof(struct tagcache_header), SEEK_SET);
3816 while (ecread(fd, &tfe, 1, tagfile_entry_ec, tc_stat.econ)
3817 == sizeof(struct tagfile_entry)
3818 #ifndef __PCTOOL__
3819 && !check_event_queue()
3820 #endif
3823 if (tfe.tag_length >= (long)sizeof(buf)-1)
3825 logf("too long tag");
3826 close(fd);
3827 return false;
3830 if (read(fd, buf, tfe.tag_length) != tfe.tag_length)
3832 logf("read error #14");
3833 close(fd);
3834 return false;
3837 /* Check if the file has already deleted from the db. */
3838 if (*buf == '\0')
3839 continue;
3841 /* Now check if the file exists. */
3842 testfd = open(buf, O_RDONLY);
3843 if (testfd < 0)
3845 logf("Entry no longer valid.");
3846 logf("-> %s / %d", buf, tfe.tag_length);
3847 delete_entry(tfe.idx_id);
3849 close(testfd);
3852 close(fd);
3854 logf("done");
3856 return true;
3859 static bool check_dir(const char *dirname)
3861 DIR *dir;
3862 int len;
3863 int success = false;
3864 char newpath[MAX_PATH];
3866 dir = opendir(dirname);
3867 if (!dir)
3869 logf("tagcache: opendir() failed");
3870 return false;
3873 /* check for a database.ignore file */
3874 snprintf(newpath, MAX_PATH, "%s/database.ignore", dirname);
3875 if (file_exists(newpath))
3877 closedir(dir);
3878 return false;
3881 /* Recursively scan the dir. */
3882 #ifdef __PCTOOL__
3883 while (1)
3884 #else
3885 while (!check_event_queue())
3886 #endif
3888 struct dirent *entry;
3890 entry = readdir(dir);
3892 if (entry == NULL)
3894 success = true;
3895 break ;
3898 if (!strcmp((char *)entry->d_name, ".") ||
3899 !strcmp((char *)entry->d_name, ".."))
3900 continue;
3902 yield();
3904 len = strlen(curpath);
3905 snprintf(&curpath[len], curpath_size - len, "/%s",
3906 entry->d_name);
3908 processed_dir_count++;
3909 if (entry->attribute & ATTR_DIRECTORY)
3910 check_dir(curpath);
3911 else
3913 tc_stat.curentry = curpath;
3915 /* Add a new entry to the temporary db file. */
3916 add_tagcache(curpath, (entry->wrtdate << 16) | entry->wrttime
3917 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
3918 , dir->internal_entry
3919 #endif
3922 /* Wait until current path for debug screen is read and unset. */
3923 while (tc_stat.syncscreen && tc_stat.curentry != NULL)
3924 yield();
3926 tc_stat.curentry = NULL;
3929 curpath[len] = '\0';
3932 closedir(dir);
3934 return success;
3937 void tagcache_screensync_event(void)
3939 tc_stat.curentry = NULL;
3942 void tagcache_screensync_enable(bool state)
3944 tc_stat.syncscreen = state;
3947 void build_tagcache(const char *path)
3949 struct tagcache_header header;
3950 bool ret;
3952 curpath[0] = '\0';
3953 data_size = 0;
3954 total_entry_count = 0;
3955 processed_dir_count = 0;
3957 #ifdef HAVE_DIRCACHE
3958 while (dircache_is_initializing())
3959 sleep(1);
3960 #endif
3962 logf("updating tagcache");
3964 cachefd = open(TAGCACHE_FILE_TEMP, O_RDONLY);
3965 if (cachefd >= 0)
3967 logf("skipping, cache already waiting for commit");
3968 close(cachefd);
3969 return ;
3972 cachefd = open(TAGCACHE_FILE_TEMP, O_RDWR | O_CREAT | O_TRUNC);
3973 if (cachefd < 0)
3975 logf("master file open failed: %s", TAGCACHE_FILE_TEMP);
3976 return ;
3979 filenametag_fd = open_tag_fd(&header, tag_filename, false);
3981 cpu_boost(true);
3983 logf("Scanning files...");
3984 /* Scan for new files. */
3985 memset(&header, 0, sizeof(struct tagcache_header));
3986 write(cachefd, &header, sizeof(struct tagcache_header));
3988 if (strcmp("/", path) != 0)
3989 strcpy(curpath, path);
3990 ret = check_dir(path);
3992 /* Write the header. */
3993 header.magic = TAGCACHE_MAGIC;
3994 header.datasize = data_size;
3995 header.entry_count = total_entry_count;
3996 lseek(cachefd, 0, SEEK_SET);
3997 write(cachefd, &header, sizeof(struct tagcache_header));
3998 close(cachefd);
4000 if (filenametag_fd >= 0)
4002 close(filenametag_fd);
4003 filenametag_fd = -1;
4006 if (!ret)
4008 logf("Aborted.");
4009 cpu_boost(false);
4010 return ;
4013 /* Commit changes to the database. */
4014 #ifdef __PCTOOL__
4015 allocate_tempbuf();
4016 #endif
4017 if (commit())
4019 remove(TAGCACHE_FILE_TEMP);
4020 logf("tagcache built!");
4022 #ifdef __PCTOOL__
4023 free_tempbuf();
4024 #endif
4026 #ifdef HAVE_TC_RAMCACHE
4027 if (hdr)
4029 /* Import runtime statistics if we just initialized the db. */
4030 if (hdr->h.serial == 0)
4031 queue_post(&tagcache_queue, Q_IMPORT_CHANGELOG, 0);
4033 #endif
4035 cpu_boost(false);
4038 #ifdef HAVE_TC_RAMCACHE
4039 static void load_ramcache(void)
4041 if (!hdr)
4042 return ;
4044 cpu_boost(true);
4046 /* At first we should load the cache (if exists). */
4047 tc_stat.ramcache = load_tagcache();
4049 if (!tc_stat.ramcache)
4051 /* If loading failed, it must indicate some problem with the db
4052 * so disable it entirely to prevent further issues. */
4053 tc_stat.ready = false;
4054 hdr = NULL;
4057 cpu_boost(false);
4060 void tagcache_unload_ramcache(void)
4062 tc_stat.ramcache = false;
4063 /* Just to make sure there is no statefile present. */
4064 // remove(TAGCACHE_STATEFILE);
4066 #endif
4068 #ifndef __PCTOOL__
4069 static void tagcache_thread(void)
4071 struct queue_event ev;
4072 bool check_done = false;
4074 /* If the previous cache build/update was interrupted, commit
4075 * the changes first in foreground. */
4076 cpu_boost(true);
4077 allocate_tempbuf();
4078 commit();
4079 free_tempbuf();
4081 #ifdef HAVE_TC_RAMCACHE
4082 # ifdef HAVE_EEPROM_SETTINGS
4083 if (firmware_settings.initialized && firmware_settings.disk_clean)
4084 check_done = tagcache_dumpload();
4086 remove(TAGCACHE_STATEFILE);
4087 # endif
4089 /* Allocate space for the tagcache if found on disk. */
4090 if (global_settings.tagcache_ram && !tc_stat.ramcache)
4091 allocate_tagcache();
4092 #endif
4094 cpu_boost(false);
4095 tc_stat.initialized = true;
4097 /* Don't delay bootup with the header check but do it on background. */
4098 sleep(HZ);
4099 tc_stat.ready = check_all_headers();
4100 tc_stat.readyvalid = true;
4102 while (1)
4104 run_command_queue(false);
4106 queue_wait_w_tmo(&tagcache_queue, &ev, HZ);
4108 switch (ev.id)
4110 case Q_IMPORT_CHANGELOG:
4111 tagcache_import_changelog();
4112 break;
4114 case Q_REBUILD:
4115 remove_files();
4116 build_tagcache("/");
4117 break;
4119 case Q_UPDATE:
4120 build_tagcache("/");
4121 #ifdef HAVE_TC_RAMCACHE
4122 load_ramcache();
4123 #endif
4124 check_deleted_files();
4125 break ;
4127 case Q_START_SCAN:
4128 check_done = false;
4129 case SYS_TIMEOUT:
4130 if (check_done || !tc_stat.ready)
4131 break ;
4133 #ifdef HAVE_TC_RAMCACHE
4134 if (!tc_stat.ramcache && global_settings.tagcache_ram)
4136 load_ramcache();
4137 if (tc_stat.ramcache && global_settings.tagcache_autoupdate)
4138 build_tagcache("/");
4140 else
4141 #endif
4142 if (global_settings.tagcache_autoupdate)
4144 build_tagcache("/");
4145 /* Don't do auto removal without dircache or flash
4146 * storage (very slow). */
4147 #ifdef HAVE_FLASH_STORAGE
4148 check_deleted_files();
4149 #else
4150 # ifdef HAVE_DIRCACHE
4151 if (dircache_is_enabled())
4152 check_deleted_files();
4153 # endif
4154 #endif
4157 logf("tagcache check done");
4159 check_done = true;
4160 break ;
4162 case Q_STOP_SCAN:
4163 break ;
4165 case SYS_POWEROFF:
4166 break ;
4168 #ifndef SIMULATOR
4169 case SYS_USB_CONNECTED:
4170 logf("USB: TagCache");
4171 usb_acknowledge(SYS_USB_CONNECTED_ACK);
4172 usb_wait_for_disconnect(&tagcache_queue);
4173 break ;
4174 #endif
4179 bool tagcache_prepare_shutdown(void)
4181 if (tagcache_get_commit_step() > 0)
4182 return false;
4184 tagcache_stop_scan();
4185 while (read_lock || write_lock)
4186 sleep(1);
4188 return true;
4191 void tagcache_shutdown(void)
4193 /* Flush the command queue. */
4194 run_command_queue(true);
4196 #ifdef HAVE_EEPROM_SETTINGS
4197 if (tc_stat.ramcache)
4198 tagcache_dumpsave();
4199 #endif
4202 static int get_progress(void)
4204 int total_count = -1;
4206 #ifdef HAVE_DIRCACHE
4207 if (dircache_is_enabled())
4209 total_count = dircache_get_entry_count();
4211 else
4212 #endif
4213 #ifdef HAVE_TC_RAMCACHE
4215 if (hdr && tc_stat.ramcache)
4216 total_count = hdr->h.tch.entry_count;
4218 #endif
4220 if (total_count < 0)
4221 return -1;
4223 return processed_dir_count * 100 / total_count;
4226 struct tagcache_stat* tagcache_get_stat(void)
4228 tc_stat.progress = get_progress();
4229 tc_stat.processed_entries = processed_dir_count;
4231 return &tc_stat;
4234 void tagcache_start_scan(void)
4236 queue_post(&tagcache_queue, Q_START_SCAN, 0);
4239 bool tagcache_update(void)
4241 if (!tc_stat.ready)
4242 return false;
4244 queue_post(&tagcache_queue, Q_UPDATE, 0);
4245 return false;
4248 bool tagcache_rebuild()
4250 queue_post(&tagcache_queue, Q_REBUILD, 0);
4251 return false;
4254 void tagcache_stop_scan(void)
4256 queue_post(&tagcache_queue, Q_STOP_SCAN, 0);
4259 #ifdef HAVE_TC_RAMCACHE
4260 bool tagcache_is_ramcache(void)
4262 return tc_stat.ramcache;
4264 #endif
4266 #endif /* !__PCTOOL__ */
4269 void tagcache_init(void)
4271 memset(&tc_stat, 0, sizeof(struct tagcache_stat));
4272 memset(&current_tcmh, 0, sizeof(struct master_header));
4273 filenametag_fd = -1;
4274 write_lock = read_lock = 0;
4276 #ifndef __PCTOOL__
4277 mutex_init(&command_queue_mutex);
4278 queue_init(&tagcache_queue, true);
4279 create_thread(tagcache_thread, tagcache_stack,
4280 sizeof(tagcache_stack), 0, tagcache_thread_name
4281 IF_PRIO(, PRIORITY_BACKGROUND)
4282 IF_COP(, CPU));
4283 #else
4284 tc_stat.initialized = true;
4285 allocate_tempbuf();
4286 commit();
4287 free_tempbuf();
4288 tc_stat.ready = check_all_headers();
4289 #endif
4292 #ifdef __PCTOOL__
4293 void tagcache_reverse_scan(void)
4295 logf("Checking for deleted files");
4296 check_deleted_files();
4298 #endif
4300 bool tagcache_is_initialized(void)
4302 return tc_stat.initialized;
4304 bool tagcache_is_usable(void)
4306 return tc_stat.initialized && tc_stat.ready;
4308 int tagcache_get_commit_step(void)
4310 return tc_stat.commit_step;
4312 int tagcache_get_max_commit_step(void)
4314 return (int)(sizeof(sorted_tags)/sizeof(sorted_tags[0]))+1;