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 sysassert(! pipe(jobpipe) );
234 sysassert(! pipe(donepipe) );
235 resolver_pid= fork();
236 sysassert(resolver_pid!=-1);
238 sysassert( dup2(jobpipe[0],0) ==0 );
239 sysassert(! close(jobpipe[1]) );
240 sysassert(! close(donepipe[0]) );
241 /* we know donepipe[1] is >= 4 and we have dealt with all the others
242 * so we aren't in any danger of overwriting some other fd 4: */
243 sysassert( dup2(donepipe[1],4) ==4 );
244 execlp("./yppsc-ocr-resolver", "yppsc-ocr-resolver",
245 DEBUGP(callout) ? "--debug" : "--noop-arg",
248 sysassert(!"execlp ocr-resolver failed");
250 sysassert(! close(jobpipe[0]) );
251 sysassert(! close(donepipe[1]) );
252 resolver= fdopen(jobpipe[1],"w"); sysassert(resolver);
253 resolver_done= donepipe[0];
255 fprintf(resolver,"%d %d ",unk_l,unk_r);
256 cu_pr_ctxmap(unk_ctxmap);
257 for (i=0, s=rd->results; i<rd->nresults; i++, s++) {
258 if (!strcmp(s->s," ")) continue;
259 fprintf(resolver," %d %d ",s->l,s->r);
260 cu_pr_ctxmap(s->ctxmap);
261 fprintf(resolver," ");
262 for (p=s->s; (c= *p); p++) {
263 if (c=='\\') fprintf(resolver,"\\%c",c);
264 else if (c>=33 && c<=126) fputc(c,resolver);
265 else fprintf(resolver,"\\x%02x",(unsigned char)c);
268 fputc('\n',resolver);
272 "static char *t[] = {\n"
273 "/* columns rows colors chars-per-pixel */\n"
278 for (y=0, pv=1; y<rd->h; y++, pv<<=1) {
281 fputc(cols[x] & pv ? 'o' : ' ', resolver);
282 fputs("\",\n",resolver);
284 fputs("};\n",resolver);
285 sysassert(!ferror(resolver));
286 sysassert(!fflush(resolver));
292 r= read(resolver_done,&cb,1);
293 if (r==-1) { sysassert(errno==EINTR); continue; }
298 waitpid_check_exitstatus(resolver_pid, "character resolver");
300 close(resolver_done);
310 static void add_result(OcrReader *rd, const char *s, int l, int r,
312 if (rd->nresults >= rd->aresults) {
313 rd->aresults++; rd->aresults<<=1;
314 rd->results= mrealloc(rd->results, sizeof(*rd->results)*rd->aresults);
316 rd->results[rd->nresults].s= s;
317 rd->results[rd->nresults].l= l;
318 rd->results[rd->nresults].r= r;
319 rd->results[rd->nresults].ctxmap= ctxmap;
324 const char *ocr_celltype_name(OcrCellType ct) { return ct->name; }
326 OcrResultGlyph *ocr(OcrReader *rd, OcrCellType ct, int w, Pixcol cols[]) {
336 debugf("OCR h=%d w=%d",rd->h,w);
337 for (x=0; x<w; x++) debugf(" %"PSPIXCOL(PRIx),cols[x]);
351 if (nspaces == ct->space_spaces) {
352 debugf("OCR x=%x nspaces=%d space\n",x,nspaces);
353 ctxmap= ct->nextword;
358 /* something here, so we need to add the spaces */
359 if (nspaces >= ct->space_spaces)
360 add_result(rd," ",x-nspaces,x+1,0);
366 DatabaseNode *uniquematch= 0;
367 int uniquematch_rx=-1;
369 debugf("OCR lx=%d ctxmap=%x ",lx,ctxmap);
371 for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
372 DatabaseNode *current= &rd->contexts[ctxi];;
373 DatabaseNode *bestmatch= 0;
377 if (!(ctxmap & (1u << ctxi))) continue;
378 debugf(" || %s",context_names[ctxi]);
385 debugf(" cv=%"PSPIXCOL(PRIx),cv);
386 for (i=0; i<current->nlinks; i++)
387 if (current->links[i].col == cv)
394 current= current->links[i].then;
396 debugf(" \"%s\"%s",current->s,current->endsword?"_":"");
407 if (uniquematch && strcmp(bestmatch->s, uniquematch->s)) {
408 debugf( " ambiguous");
412 uniquematch= bestmatch;
413 uniquematch_rx= bestmatch_rx;
419 add_result(rd, uniquematch->s, lx, uniquematch_rx, ctxmap);
421 if (uniquematch->s[0]) ctxmap= ct->midword;
422 else debugf(" (empty)");
423 if (uniquematch->endsword) {
424 nspaces= ct->space_spaces;
426 ctxmap= ct->nextword;
431 debugf(" || UNKNOWN");
432 for (rx=lx; rx<w && cols[rx]; rx++);
433 debugf(" x=%d ctxmap=%x %d..%d\n",x, ctxmap, lx,rx);
435 callout_unknown(rd, w,cols, lx,rx-1, ctxmap);
439 add_result(rd, 0,-1,-1,0);
440 debugf("OCR finished %d glyphs\n",rd->nresults);
445 OcrReader *ocr_init(int h) {
448 rd= mmalloc(sizeof(*rd));
449 memset(rd,0,sizeof(*rd));