2 * Core OCR algorithm (first exact bitmap match)
5 * This is part of ypp-sc-tools, a set of third-party tools for assisting
6 * players of Yohoho Puzzle Pirates.
8 * Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
10 * This program is free software: you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation, either version 3 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23 * Yohoho and Puzzle Pirates are probably trademarks of Three Rings and
24 * are used without permission. This program is not endorsed or
25 * sponsored by Three Rings.
32 struct DatabaseNode *then;
35 #define MAXGLYPHCHRS 7
37 typedef struct DatabaseNode {
38 char s[MAXGLYPHCHRS+1]; /* null-terminated; "" means no match here */
44 static const char *context_names[]= {
49 struct OcrCellTypeInfo {
50 /* bitmaps of indices into context_names: */
51 unsigned initial, nextword, midword;
55 const struct OcrCellTypeInfo ocr_celltype_number= {
60 const struct OcrCellTypeInfo ocr_celltype_text= {
61 .initial=2, /* Uppercase */
62 .nextword=3, /* Either */
63 .midword=1, /* Lower only */
69 #define NCONTEXTS (sizeof(context_names)/sizeof(context_names[0]))
73 DatabaseNode contexts[NCONTEXTS];
74 OcrResultGlyph *results;
75 int aresults, nresults;
78 static FILE *resolver;
79 static pid_t resolver_pid;
80 static int resolver_done;
82 DEBUG_DEFINE_DEBUGF(ocr)
86 fatal("Error in character set database.\n" \
87 " Requirement not met: %s:%d: %s", __FILE__,__LINE__, #x))
89 static void fgetsline(FILE *f, char *lbuf, size_t lbufsz) {
91 char *s= fgets(lbuf,lbufsz,f);
92 sysassert(!ferror(f));
96 dbassert(l>0); dbassert(lbuf[--l]='\n');
99 #define FGETSLINE(f,buf) (fgetsline(f,buf,sizeof(buf)))
101 static void cleardb_node(DatabaseNode *n) {
104 for (i=0; i<n->nlinks; i++)
105 cleardb_node(n->links[i].then);
108 static void readdb(OcrReader *rd) {
110 DatabaseNode *current, *additional;
111 char chrs[MAXGLYPHCHRS+1];
118 for (ctxi=0; ctxi<NCONTEXTS; ctxi++)
119 cleardb_node(&rd->contexts[ctxi]);
122 asprintf(&dbfname,"%s/charset-%d.txt",get_vardir(),rd->h);
125 db= fopen(dbfname,"r");
128 sysassert(errno==ENOENT);
133 dbassert(!strcmp(lbuf,"# ypp-sc-tools pctb font v1"));
135 r= fscanf(db, "%d", &h);
141 if (!lbuf || lbuf[0]=='#') continue;
142 if (!strcmp(lbuf,".")) break;
144 for (ctxi=0; ctxi<NCONTEXTS; ctxi++)
145 if (!strcmp(lbuf,context_names[ctxi]))
147 /* not found, just skip */
148 for (;;) { FGETSLINE(db,lbuf); if (!lbuf[0]) break; }
153 int c= fgetc(db); sysassert(!ferror(db)); dbassert(c!=EOF);
154 if (c=='\n') { dbassert(nchrs); break; }
155 dbassert(nchrs<MAXGLYPHCHRS);
158 c= fgetc(db); sysassert(!ferror(db)); dbassert(c=='x');
159 r= fscanf(db, "%2x", &cr); sysassert(!ferror(db)); dbassert(r==1);
160 assert(cr>0 && cr<=255);
166 if (nchrs>1 && chrs[nchrs-1]==' ') {
172 current= &rd->contexts[ctxi];
175 if (!lbuf[0]) { dbassert(current != &rd->contexts[ctxi]); break; }
177 cv= strtoul(lbuf,&ep,16); dbassert(!*ep);
178 dbassert(!(cv & ~((1UL << rd->h)-1)));
180 for (j=0; j<current->nlinks; j++)
181 if (current->links[j].col == cv) {
182 current= current->links[j].then;
186 additional= mmalloc(sizeof(*additional));
188 additional->nlinks= additional->alinks= 0;
189 additional->links= 0;
190 if (current->nlinks==current->alinks) {
193 current->links= mrealloc(current->links,
194 sizeof(*current->links) * current->alinks);
196 current->links[current->nlinks].col= cv;
197 current->links[current->nlinks].then= additional;
204 dbassert(!current->s[0]);
205 strcpy(current->s, chrs);
206 current->endsword= endsword;
208 sysassert(!ferror(db));
209 sysassert(!fclose(db));
212 static void cu_pr_ctxmap(unsigned ctxmap) {
213 fprintf(resolver,"{");
216 for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
217 if (!(ctxmap & (1u << ctxi))) continue;
218 fprintf(resolver,"%s%s",spc,context_names[ctxi]);
221 fprintf(resolver,"}");
224 static void callout_unknown(OcrReader *rd, int w, Pixcol cols[],
225 int unk_l, int unk_r, unsigned unk_ctxmap) {
226 int jobpipe[2],donepipe[2], c,i, x,y;
227 const OcrResultGlyph *s;
233 fatal("OCR failed - unrecognised characters or ligatures.\n"
234 "Character set database needs to be updated or augmented.\n"
235 "See README.charset.\n");
238 sysassert(! pipe(jobpipe) );
239 sysassert(! pipe(donepipe) );
240 resolver_pid= fork();
241 sysassert(resolver_pid!=-1);
243 sysassert( dup2(jobpipe[0],0) ==0 );
244 sysassert(! close(jobpipe[1]) );
245 sysassert(! close(donepipe[0]) );
246 /* we know donepipe[1] is >= 4 and we have dealt with all the others
247 * so we aren't in any danger of overwriting some other fd 4: */
248 sysassert( dup2(donepipe[1],4) ==4 );
249 execlp(o_resolver, o_resolver,
250 DEBUGP(callout) ? "--debug" : "--noop-arg",
253 sysassert(!"execlp ocr-resolver failed");
255 sysassert(! close(jobpipe[0]) );
256 sysassert(! close(donepipe[1]) );
257 resolver= fdopen(jobpipe[1],"w"); sysassert(resolver);
258 resolver_done= donepipe[0];
260 fprintf(resolver,"%d %d ",unk_l,unk_r);
261 cu_pr_ctxmap(unk_ctxmap);
262 for (i=0, s=rd->results; i<rd->nresults; i++, s++) {
263 if (!strcmp(s->s," ")) continue;
264 fprintf(resolver," %d %d ",s->l,s->r);
265 cu_pr_ctxmap(s->ctxmap);
266 fprintf(resolver," ");
267 for (p=s->s; (c= *p); p++) {
268 if (c=='\\') fprintf(resolver,"\\%c",c);
269 else if (c>=33 && c<=126) fputc(c,resolver);
270 else fprintf(resolver,"\\x%02x",(unsigned char)c);
273 fputc('\n',resolver);
277 "static char *t[] = {\n"
278 "/* columns rows colors chars-per-pixel */\n"
283 for (y=0, pv=1; y<rd->h; y++, pv<<=1) {
286 fputc(cols[x] & pv ? 'o' : ' ', resolver);
287 fputs("\",\n",resolver);
289 fputs("};\n",resolver);
290 sysassert(!ferror(resolver));
291 sysassert(!fflush(resolver));
297 r= read(resolver_done,&cb,1);
298 if (r==-1) { sysassert(errno==EINTR); continue; }
303 waitpid_check_exitstatus(resolver_pid, "character resolver");
305 close(resolver_done);
315 static void add_result(OcrReader *rd, const char *s, int l, int r,
317 if (rd->nresults >= rd->aresults) {
318 rd->aresults++; rd->aresults<<=1;
319 rd->results= mrealloc(rd->results, sizeof(*rd->results)*rd->aresults);
321 rd->results[rd->nresults].s= s;
322 rd->results[rd->nresults].l= l;
323 rd->results[rd->nresults].r= r;
324 rd->results[rd->nresults].ctxmap= ctxmap;
329 const char *ocr_celltype_name(OcrCellType ct) { return ct->name; }
331 OcrResultGlyph *ocr(OcrReader *rd, OcrCellType ct, int w, Pixcol cols[]) {
341 debugf("OCR h=%d w=%d",rd->h,w);
342 for (x=0; x<w; x++) debugf(" %"PSPIXCOL(PRIx),cols[x]);
356 if (nspaces == ct->space_spaces) {
357 debugf("OCR x=%x nspaces=%d space\n",x,nspaces);
358 ctxmap= ct->nextword;
363 /* something here, so we need to add the spaces */
364 if (nspaces >= ct->space_spaces)
365 add_result(rd," ",x-nspaces,x+1,0);
371 DatabaseNode *uniquematch= 0;
372 int uniquematch_rx=-1;
374 debugf("OCR lx=%d ctxmap=%x ",lx,ctxmap);
376 for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
377 DatabaseNode *current= &rd->contexts[ctxi];;
378 DatabaseNode *bestmatch= 0;
382 if (!(ctxmap & (1u << ctxi))) continue;
383 debugf(" || %s",context_names[ctxi]);
390 debugf(" cv=%"PSPIXCOL(PRIx),cv);
391 for (i=0; i<current->nlinks; i++)
392 if (current->links[i].col == cv)
399 current= current->links[i].then;
401 debugf(" \"%s\"%s",current->s,current->endsword?"_":"");
412 if (uniquematch && strcmp(bestmatch->s, uniquematch->s)) {
413 debugf( " ambiguous");
417 uniquematch= bestmatch;
418 uniquematch_rx= bestmatch_rx;
424 add_result(rd, uniquematch->s, lx, uniquematch_rx, ctxmap);
426 if (uniquematch->s[0]) ctxmap= ct->midword;
427 else debugf(" (empty)");
428 if (uniquematch->endsword) {
429 nspaces= ct->space_spaces;
431 ctxmap= ct->nextword;
436 debugf(" || UNKNOWN");
437 for (rx=lx; rx<w && cols[rx]; rx++);
438 debugf(" x=%d ctxmap=%x %d..%d\n",x, ctxmap, lx,rx);
440 callout_unknown(rd, w,cols, lx,rx-1, ctxmap);
444 add_result(rd, 0,-1,-1,0);
445 debugf("OCR finished %d glyphs\n",rd->nresults);
450 OcrReader *ocr_init(int h) {
453 rd= mmalloc(sizeof(*rd));
454 memset(rd,0,sizeof(*rd));