vo_corevideo: Avoid some code duplication.
[mplayer/glamo.git] / subreader.c
blob772d58c79c101ba0cfc4d23b0ca0532ffbc889c3
1 /*
2 * Subtitle reader with format autodetection
4 * Copyright (c) 2001 laaz
5 * Some code cleanup & realloc() by A'rpi/ESP-team
7 * This file is part of MPlayer.
9 * MPlayer is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * MPlayer is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with MPlayer; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <ctype.h>
29 #include <sys/types.h>
30 #include <dirent.h>
32 #include "config.h"
33 #include "mp_msg.h"
34 #include "subreader.h"
35 #include "stream/stream.h"
36 #include "libavutil/common.h"
37 #include "libavutil/avstring.h"
39 #ifdef CONFIG_ENCA
40 #include <enca.h>
41 #endif
43 #define ERR ((void *) -1)
45 #ifdef CONFIG_ICONV
46 #include <iconv.h>
47 char *sub_cp=NULL;
48 #endif
49 #ifdef CONFIG_FRIBIDI
50 #include <fribidi/fribidi.h>
51 char *fribidi_charset = NULL; ///character set that will be passed to FriBiDi
52 int flip_hebrew = 1; ///flip subtitles using fribidi
53 int fribidi_flip_commas = 0; ///flip comma when fribidi is used
54 #endif
56 /* Maximal length of line of a subtitle */
57 #define LINE_LEN 1000
58 static float mpsub_position=0;
59 static float mpsub_multiplier=1.;
60 static int sub_slacktime = 20000; //20 sec
62 int sub_no_text_pp=0; // 1 => do not apply text post-processing
63 // like {\...} elimination in SSA format.
65 int sub_match_fuzziness=0; // level of sub name matching fuzziness
67 /* Use the SUB_* constant defined in the header file */
68 int sub_format=SUB_INVALID;
69 #ifdef CONFIG_SORTSUB
71 Some subtitling formats, namely AQT and Subrip09, define the end of a
72 subtitle as the beginning of the following. Since currently we read one
73 subtitle at time, for these format we keep two global *subtitle,
74 previous_aqt_sub and previous_subrip09_sub, pointing to previous subtitle,
75 so we can change its end when we read current subtitle starting time.
76 When CONFIG_SORTSUB is defined, we use a single global unsigned long,
77 previous_sub_end, for both (and even future) formats, to store the end of
78 the previous sub: it is initialized to 0 in sub_read_file and eventually
79 modified by sub_read_aqt_line or sub_read_subrip09_line.
81 unsigned long previous_sub_end;
82 #endif
84 static int eol(char p) {
85 return p=='\r' || p=='\n' || p=='\0';
88 /* Remove leading and trailing space */
89 static void trail_space(char *s) {
90 int i = 0;
91 while (isspace(s[i])) ++i;
92 if (i) strcpy(s, s + i);
93 i = strlen(s) - 1;
94 while (i > 0 && isspace(s[i])) s[i--] = '\0';
97 static char *stristr(const char *haystack, const char *needle) {
98 int len = 0;
99 const char *p = haystack;
101 if (!(haystack && needle)) return NULL;
103 len=strlen(needle);
104 while (*p != '\0') {
105 if (strncasecmp(p, needle, len) == 0) return (char*)p;
106 p++;
109 return NULL;
112 static void sami_add_line(subtitle *current, char *buffer, char **pos) {
113 char *p = *pos;
114 *p = 0;
115 trail_space(buffer);
116 if (*buffer && current->lines < SUB_MAX_TEXT)
117 current->text[current->lines++] = strdup(buffer);
118 *pos = buffer;
121 static subtitle *sub_read_line_sami(stream_t* st, subtitle *current, int utf16) {
122 static char line[LINE_LEN+1];
123 static char *s = NULL, *slacktime_s;
124 char text[LINE_LEN+1], *p=NULL, *q;
125 int state;
127 current->lines = current->start = current->end = 0;
128 current->alignment = SUB_ALIGNMENT_BOTTOMCENTER;
129 state = 0;
131 /* read the first line */
132 if (!s)
133 if (!(s = stream_read_line(st, line, LINE_LEN, utf16))) return 0;
135 do {
136 switch (state) {
138 case 0: /* find "START=" or "Slacktime:" */
139 slacktime_s = stristr (s, "Slacktime:");
140 if (slacktime_s)
141 sub_slacktime = strtol (slacktime_s+10, NULL, 0) / 10;
143 s = stristr (s, "Start=");
144 if (s) {
145 current->start = strtol (s + 6, &s, 0) / 10;
146 /* eat '>' */
147 for (; *s != '>' && *s != '\0'; s++);
148 s++;
149 state = 1; continue;
151 break;
153 case 1: /* find (optional) "<P", skip other TAGs */
154 for (; *s == ' ' || *s == '\t'; s++); /* strip blanks, if any */
155 if (*s == '\0') break;
156 if (*s != '<') { state = 3; p = text; continue; } /* not a TAG */
157 s++;
158 if (*s == 'P' || *s == 'p') { s++; state = 2; continue; } /* found '<P' */
159 for (; *s != '>' && *s != '\0'; s++); /* skip remains of non-<P> TAG */
160 if (s == '\0')
161 break;
162 s++;
163 continue;
165 case 2: /* find ">" */
166 if ((s = strchr (s, '>'))) { s++; state = 3; p = text; continue; }
167 break;
169 case 3: /* get all text until '<' appears */
170 if (*s == '\0') break;
171 else if (!strncasecmp (s, "<br>", 4)) {
172 sami_add_line(current, text, &p);
173 s += 4;
175 else if ((*s == '{') && !sub_no_text_pp) { state = 5; ++s; continue; }
176 else if (*s == '<') { state = 4; }
177 else if (!strncasecmp (s, "&nbsp;", 6)) { *p++ = ' '; s += 6; }
178 else if (*s == '\t') { *p++ = ' '; s++; }
179 else if (*s == '\r' || *s == '\n') { s++; }
180 else *p++ = *s++;
182 /* skip duplicated space */
183 if (p > text + 2) if (*(p-1) == ' ' && *(p-2) == ' ') p--;
185 continue;
187 case 4: /* get current->end or skip <TAG> */
188 q = stristr (s, "Start=");
189 if (q) {
190 current->end = strtol (q + 6, &q, 0) / 10 - 1;
191 *p = '\0'; trail_space (text);
192 if (text[0] != '\0')
193 current->text[current->lines++] = strdup (text);
194 if (current->lines > 0) { state = 99; break; }
195 state = 0; continue;
197 s = strchr (s, '>');
198 if (s) { s++; state = 3; continue; }
199 break;
200 case 5: /* get rid of {...} text, but read the alignment code */
201 if ((*s == '\\') && (*(s + 1) == 'a') && !sub_no_text_pp) {
202 if (stristr(s, "\\a1") != NULL) {
203 current->alignment = SUB_ALIGNMENT_BOTTOMLEFT;
204 s = s + 3;
206 if (stristr(s, "\\a2") != NULL) {
207 current->alignment = SUB_ALIGNMENT_BOTTOMCENTER;
208 s = s + 3;
209 } else if (stristr(s, "\\a3") != NULL) {
210 current->alignment = SUB_ALIGNMENT_BOTTOMRIGHT;
211 s = s + 3;
212 } else if ((stristr(s, "\\a4") != NULL) || (stristr(s, "\\a5") != NULL) || (stristr(s, "\\a8") != NULL)) {
213 current->alignment = SUB_ALIGNMENT_TOPLEFT;
214 s = s + 3;
215 } else if (stristr(s, "\\a6") != NULL) {
216 current->alignment = SUB_ALIGNMENT_TOPCENTER;
217 s = s + 3;
218 } else if (stristr(s, "\\a7") != NULL) {
219 current->alignment = SUB_ALIGNMENT_TOPRIGHT;
220 s = s + 3;
221 } else if (stristr(s, "\\a9") != NULL) {
222 current->alignment = SUB_ALIGNMENT_MIDDLELEFT;
223 s = s + 3;
224 } else if (stristr(s, "\\a10") != NULL) {
225 current->alignment = SUB_ALIGNMENT_MIDDLECENTER;
226 s = s + 4;
227 } else if (stristr(s, "\\a11") != NULL) {
228 current->alignment = SUB_ALIGNMENT_MIDDLERIGHT;
229 s = s + 4;
232 if (*s == '}') state = 3;
233 ++s;
234 continue;
237 /* read next line */
238 if (state != 99 && !(s = stream_read_line (st, line, LINE_LEN, utf16))) {
239 if (current->start > 0) {
240 break; // if it is the last subtitle
241 } else {
242 return 0;
246 } while (state != 99);
248 // For the last subtitle
249 if (current->end <= 0) {
250 current->end = current->start + sub_slacktime;
251 sami_add_line(current, text, &p);
254 return current;
258 static char *sub_readtext(char *source, char **dest) {
259 int len=0;
260 char *p=source;
262 // printf("src=%p dest=%p \n",source,dest);
264 while ( !eol(*p) && *p!= '|' ) {
265 p++,len++;
268 *dest= malloc (len+1);
269 if (!dest) {return ERR;}
271 strncpy(*dest, source, len);
272 (*dest)[len]=0;
274 while (*p=='\r' || *p=='\n' || *p=='|') p++;
276 if (*p) return p; // not-last text field
277 else return NULL; // last text field
280 static subtitle *sub_read_line_microdvd(stream_t *st,subtitle *current, int utf16) {
281 char line[LINE_LEN+1];
282 char line2[LINE_LEN+1];
283 char *p, *next;
284 int i;
286 do {
287 if (!stream_read_line (st, line, LINE_LEN, utf16)) return NULL;
288 } while ((sscanf (line,
289 "{%ld}{}%[^\r\n]",
290 &(current->start), line2) < 2) &&
291 (sscanf (line,
292 "{%ld}{%ld}%[^\r\n]",
293 &(current->start), &(current->end), line2) < 3));
295 p=line2;
297 next=p, i=0;
298 while ((next =sub_readtext (next, &(current->text[i])))) {
299 if (current->text[i]==ERR) {return ERR;}
300 i++;
301 if (i>=SUB_MAX_TEXT) { mp_msg(MSGT_SUBREADER,MSGL_WARN,"Too many lines in a subtitle\n");current->lines=i;return current;}
303 current->lines= ++i;
305 return current;
308 static subtitle *sub_read_line_mpl2(stream_t *st,subtitle *current, int utf16) {
309 char line[LINE_LEN+1];
310 char line2[LINE_LEN+1];
311 char *p, *next;
312 int i;
314 do {
315 if (!stream_read_line (st, line, LINE_LEN, utf16)) return NULL;
316 } while ((sscanf (line,
317 "[%ld][%ld]%[^\r\n]",
318 &(current->start), &(current->end), line2) < 3));
319 current->start *= 10;
320 current->end *= 10;
321 p=line2;
323 next=p, i=0;
324 while ((next =sub_readtext (next, &(current->text[i])))) {
325 if (current->text[i]==ERR) {return ERR;}
326 i++;
327 if (i>=SUB_MAX_TEXT) { mp_msg(MSGT_SUBREADER,MSGL_WARN,"Too many lines in a subtitle\n");current->lines=i;return current;}
329 current->lines= ++i;
331 return current;
334 static subtitle *sub_read_line_subrip(stream_t* st, subtitle *current, int utf16) {
335 char line[LINE_LEN+1];
336 int a1,a2,a3,a4,b1,b2,b3,b4;
337 char *p=NULL, *q=NULL;
338 int len;
340 while (1) {
341 if (!stream_read_line (st, line, LINE_LEN, utf16)) return NULL;
342 if (sscanf (line, "%d:%d:%d.%d,%d:%d:%d.%d",&a1,&a2,&a3,&a4,&b1,&b2,&b3,&b4) < 8) continue;
343 current->start = a1*360000+a2*6000+a3*100+a4;
344 current->end = b1*360000+b2*6000+b3*100+b4;
346 if (!stream_read_line (st, line, LINE_LEN, utf16)) return NULL;
348 p=q=line;
349 for (current->lines=1; current->lines < SUB_MAX_TEXT; current->lines++) {
350 for (q=p,len=0; *p && *p!='\r' && *p!='\n' && *p!='|' && strncmp(p,"[br]",4); p++,len++);
351 current->text[current->lines-1]=malloc (len+1);
352 if (!current->text[current->lines-1]) return ERR;
353 strncpy (current->text[current->lines-1], q, len);
354 current->text[current->lines-1][len]='\0';
355 if (!*p || *p=='\r' || *p=='\n') break;
356 if (*p=='|') p++;
357 else while (*p++!=']');
359 break;
361 return current;
364 static subtitle *sub_read_line_subviewer(stream_t *st,subtitle *current, int utf16) {
365 char line[LINE_LEN+1];
366 int a1,a2,a3,a4,b1,b2,b3,b4;
367 char *p=NULL;
368 int i,len;
370 while (!current->text[0]) {
371 if (!stream_read_line (st, line, LINE_LEN, utf16)) return NULL;
372 if ((len=sscanf (line, "%d:%d:%d%[,.:]%d --> %d:%d:%d%[,.:]%d",&a1,&a2,&a3,(char *)&i,&a4,&b1,&b2,&b3,(char *)&i,&b4)) < 10)
373 continue;
374 current->start = a1*360000+a2*6000+a3*100+a4/10;
375 current->end = b1*360000+b2*6000+b3*100+b4/10;
376 for (i=0; i<SUB_MAX_TEXT;) {
377 int blank = 1;
378 if (!stream_read_line (st, line, LINE_LEN, utf16)) break;
379 len=0;
380 for (p=line; *p!='\n' && *p!='\r' && *p; p++,len++)
381 if (*p != ' ' && *p != '\t')
382 blank = 0;
383 if (len && !blank) {
384 int j=0,skip=0;
385 char *curptr=current->text[i]=malloc (len+1);
386 if (!current->text[i]) return ERR;
387 //strncpy (current->text[i], line, len); current->text[i][len]='\0';
388 for(; j<len; j++) {
389 /* let's filter html tags ::atmos */
390 if(line[j]=='>') {
391 skip=0;
392 continue;
394 if(line[j]=='<') {
395 skip=1;
396 continue;
398 if(skip) {
399 continue;
401 *curptr=line[j];
402 curptr++;
404 *curptr='\0';
406 i++;
407 } else {
408 break;
411 current->lines=i;
413 return current;
416 static subtitle *sub_read_line_subviewer2(stream_t *st,subtitle *current, int utf16) {
417 char line[LINE_LEN+1];
418 int a1,a2,a3,a4;
419 char *p=NULL;
420 int i,len;
422 while (!current->text[0]) {
423 if (!stream_read_line (st, line, LINE_LEN, utf16)) return NULL;
424 if (line[0]!='{')
425 continue;
426 if ((len=sscanf (line, "{T %d:%d:%d:%d",&a1,&a2,&a3,&a4)) < 4)
427 continue;
428 current->start = a1*360000+a2*6000+a3*100+a4/10;
429 for (i=0; i<SUB_MAX_TEXT;) {
430 if (!stream_read_line (st, line, LINE_LEN, utf16)) break;
431 if (line[0]=='}') break;
432 len=0;
433 for (p=line; *p!='\n' && *p!='\r' && *p; ++p,++len);
434 if (len) {
435 current->text[i]=malloc (len+1);
436 if (!current->text[i]) return ERR;
437 strncpy (current->text[i], line, len); current->text[i][len]='\0';
438 ++i;
439 } else {
440 break;
443 current->lines=i;
445 return current;
449 static subtitle *sub_read_line_vplayer(stream_t *st,subtitle *current, int utf16) {
450 char line[LINE_LEN+1];
451 int a1,a2,a3;
452 char *p=NULL, *next,separator;
453 int i,len,plen;
455 while (!current->text[0]) {
456 if (!stream_read_line (st, line, LINE_LEN, utf16)) return NULL;
457 if ((len=sscanf (line, "%d:%d:%d%c%n",&a1,&a2,&a3,&separator,&plen)) < 4)
458 continue;
460 if (!(current->start = a1*360000+a2*6000+a3*100))
461 continue;
462 /* removed by wodzu
463 p=line;
464 // finds the body of the subtitle
465 for (i=0; i<3; i++){
466 p=strchr(p,':');
467 if (p==NULL) break;
468 ++p;
470 if (p==NULL) {
471 printf("SUB: Skipping incorrect subtitle line!\n");
472 continue;
475 // by wodzu: hey! this time we know what length it has! what is
476 // that magic for? it can't deal with space instead of third
477 // colon! look, what simple it can be:
478 p = &line[ plen ];
480 i=0;
481 if (*p!='|') {
483 next = p,i=0;
484 while ((next =sub_readtext (next, &(current->text[i])))) {
485 if (current->text[i]==ERR) {return ERR;}
486 i++;
487 if (i>=SUB_MAX_TEXT) { mp_msg(MSGT_SUBREADER,MSGL_WARN,"Too many lines in a subtitle\n");current->lines=i;return current;}
489 current->lines=i+1;
492 return current;
495 static subtitle *sub_read_line_rt(stream_t *st,subtitle *current, int utf16) {
496 //TODO: This format uses quite rich (sub/super)set of xhtml
497 // I couldn't check it since DTD is not included.
498 // WARNING: full XML parses can be required for proper parsing
499 char line[LINE_LEN+1];
500 int a1,a2,a3,a4,b1,b2,b3,b4;
501 char *p=NULL,*next=NULL;
502 int i,len,plen;
504 while (!current->text[0]) {
505 if (!stream_read_line (st, line, LINE_LEN, utf16)) return NULL;
506 //TODO: it seems that format of time is not easily determined, it may be 1:12, 1:12.0 or 0:1:12.0
507 //to describe the same moment in time. Maybe there are even more formats in use.
508 //if ((len=sscanf (line, "<Time Begin=\"%d:%d:%d.%d\" End=\"%d:%d:%d.%d\"",&a1,&a2,&a3,&a4,&b1,&b2,&b3,&b4)) < 8)
509 plen=a1=a2=a3=a4=b1=b2=b3=b4=0;
510 if (
511 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d.%d\" %*[Ee]nd=\"%d.%d\"%*[^<]<clear/>%n",&a3,&a4,&b3,&b4,&plen)) < 4) &&
512 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d.%d\" %*[Ee]nd=\"%d:%d.%d\"%*[^<]<clear/>%n",&a3,&a4,&b2,&b3,&b4,&plen)) < 5) &&
513 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d:%d\" %*[Ee]nd=\"%d:%d\"%*[^<]<clear/>%n",&a2,&a3,&b2,&b3,&plen)) < 4) &&
514 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d:%d\" %*[Ee]nd=\"%d:%d.%d\"%*[^<]<clear/>%n",&a2,&a3,&b2,&b3,&b4,&plen)) < 5) &&
515 // ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d:%d.%d\" %*[Ee]nd=\"%d:%d\"%*[^<]<clear/>%n",&a2,&a3,&a4,&b2,&b3,&plen)) < 5) &&
516 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d:%d.%d\" %*[Ee]nd=\"%d:%d.%d\"%*[^<]<clear/>%n",&a2,&a3,&a4,&b2,&b3,&b4,&plen)) < 6) &&
517 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d:%d:%d.%d\" %*[Ee]nd=\"%d:%d:%d.%d\"%*[^<]<clear/>%n",&a1,&a2,&a3,&a4,&b1,&b2,&b3,&b4,&plen)) < 8) &&
518 //now try it without end time
519 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d.%d\"%*[^<]<clear/>%n",&a3,&a4,&plen)) < 2) &&
520 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d:%d\"%*[^<]<clear/>%n",&a2,&a3,&plen)) < 2) &&
521 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d:%d.%d\"%*[^<]<clear/>%n",&a2,&a3,&a4,&plen)) < 3) &&
522 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d:%d:%d.%d\"%*[^<]<clear/>%n",&a1,&a2,&a3,&a4,&plen)) < 4)
524 continue;
525 current->start = a1*360000+a2*6000+a3*100+a4/10;
526 current->end = b1*360000+b2*6000+b3*100+b4/10;
527 if (b1 == 0 && b2 == 0 && b3 == 0 && b4 == 0)
528 current->end = current->start+200;
529 p=line; p+=plen;i=0;
530 // TODO: I don't know what kind of convention is here for marking multiline subs, maybe <br/> like in xml?
531 next = strstr(line,"<clear/>");
532 if(next && strlen(next)>8){
533 next+=8;i=0;
534 while ((next =sub_readtext (next, &(current->text[i])))) {
535 if (current->text[i]==ERR) {return ERR;}
536 i++;
537 if (i>=SUB_MAX_TEXT) { mp_msg(MSGT_SUBREADER,MSGL_WARN,"Too many lines in a subtitle\n");current->lines=i;return current;}
540 current->lines=i+1;
542 return current;
545 static subtitle *sub_read_line_ssa(stream_t *st,subtitle *current, int utf16) {
547 * Sub Station Alpha v4 (and v2?) scripts have 9 commas before subtitle
548 * other Sub Station Alpha scripts have only 8 commas before subtitle
549 * Reading the "ScriptType:" field is not reliable since many scripts appear
550 * w/o it
552 * http://www.scriptclub.org is a good place to find more examples
553 * http://www.eswat.demon.co.uk is where the SSA specs can be found
555 int comma;
556 static int max_comma = 32; /* let's use 32 for the case that the */
557 /* amount of commas increase with newer SSA versions */
559 int hour1, min1, sec1, hunsec1,
560 hour2, min2, sec2, hunsec2, nothing;
561 int num;
563 char line[LINE_LEN+1],
564 line3[LINE_LEN+1],
565 *line2;
566 char *tmp;
568 do {
569 if (!stream_read_line (st, line, LINE_LEN, utf16)) return NULL;
570 } while (sscanf (line, "Dialogue: Marked=%d,%d:%d:%d.%d,%d:%d:%d.%d,"
571 "%[^\n\r]", &nothing,
572 &hour1, &min1, &sec1, &hunsec1,
573 &hour2, &min2, &sec2, &hunsec2,
574 line3) < 9
576 sscanf (line, "Dialogue: %d,%d:%d:%d.%d,%d:%d:%d.%d,"
577 "%[^\n\r]", &nothing,
578 &hour1, &min1, &sec1, &hunsec1,
579 &hour2, &min2, &sec2, &hunsec2,
580 line3) < 9 );
582 line2=strchr(line3, ',');
584 for (comma = 4; comma < max_comma; comma ++)
586 tmp = line2;
587 if(!(tmp=strchr(++tmp, ','))) break;
588 if(*(++tmp) == ' ') break;
589 /* a space after a comma means we're already in a sentence */
590 line2 = tmp;
593 if(comma < max_comma)max_comma = comma;
594 /* eliminate the trailing comma */
595 if(*line2 == ',') line2++;
597 current->lines=0;num=0;
598 current->start = 360000*hour1 + 6000*min1 + 100*sec1 + hunsec1;
599 current->end = 360000*hour2 + 6000*min2 + 100*sec2 + hunsec2;
601 while (((tmp=strstr(line2, "\\n")) != NULL) || ((tmp=strstr(line2, "\\N")) != NULL) ){
602 current->text[num]=malloc(tmp-line2+1);
603 strncpy (current->text[num], line2, tmp-line2);
604 current->text[num][tmp-line2]='\0';
605 line2=tmp+2;
606 num++;
607 current->lines++;
608 if (current->lines >= SUB_MAX_TEXT) return current;
611 current->text[num]=strdup(line2);
612 current->lines++;
614 return current;
617 static void sub_pp_ssa(subtitle *sub) {
618 int l=sub->lines;
619 char *so,*de,*start;
621 while (l){
622 /* eliminate any text enclosed with {}, they are font and color settings */
623 so=de=sub->text[--l];
624 while (*so) {
625 if(*so == '{' && so[1]=='\\') {
626 for (start=so; *so && *so!='}'; so++);
627 if(*so) so++; else so=start;
629 if(*so) {
630 *de=*so;
631 so++; de++;
634 *de=*so;
639 * PJS subtitles reader.
640 * That's the "Phoenix Japanimation Society" format.
641 * I found some of them in http://www.scriptsclub.org/ (used for anime).
642 * The time is in tenths of second.
644 * by set, based on code by szabi (dunnowhat sub format ;-)
646 static subtitle *sub_read_line_pjs(stream_t *st,subtitle *current, int utf16) {
647 char line[LINE_LEN+1];
648 char text[LINE_LEN+1], *s, *d;
650 if (!stream_read_line (st, line, LINE_LEN, utf16))
651 return NULL;
652 /* skip spaces */
653 for (s=line; *s && isspace(*s); s++);
654 /* allow empty lines at the end of the file */
655 if (*s==0)
656 return NULL;
657 /* get the time */
658 if (sscanf (s, "%ld,%ld,", &(current->start),
659 &(current->end)) <2) {
660 return ERR;
662 /* the files I have are in tenths of second */
663 current->start *= 10;
664 current->end *= 10;
665 /* walk to the beggining of the string */
666 for (; *s; s++) if (*s==',') break;
667 if (*s) {
668 for (s++; *s; s++) if (*s==',') break;
669 if (*s) s++;
671 if (*s!='"') {
672 return ERR;
674 /* copy the string to the text buffer */
675 for (s++, d=text; *s && *s!='"'; s++, d++)
676 *d=*s;
677 *d=0;
678 current->text[0] = strdup(text);
679 current->lines = 1;
681 return current;
684 static subtitle *sub_read_line_mpsub(stream_t *st, subtitle *current, int utf16) {
685 char line[LINE_LEN+1];
686 float a,b;
687 int num=0;
688 char *p, *q;
692 if (!stream_read_line(st, line, LINE_LEN, utf16)) return NULL;
693 } while (sscanf (line, "%f %f", &a, &b) !=2);
695 mpsub_position += a*mpsub_multiplier;
696 current->start=(int) mpsub_position;
697 mpsub_position += b*mpsub_multiplier;
698 current->end=(int) mpsub_position;
700 while (num < SUB_MAX_TEXT) {
701 if (!stream_read_line (st, line, LINE_LEN, utf16)) {
702 if (num == 0) return NULL;
703 else return current;
705 p=line;
706 while (isspace(*p)) p++;
707 if (eol(*p) && num > 0) return current;
708 if (eol(*p)) return NULL;
710 for (q=p; !eol(*q); q++);
711 *q='\0';
712 if (strlen(p)) {
713 current->text[num]=strdup(p);
714 // printf (">%s<\n",p);
715 current->lines = ++num;
716 } else {
717 if (num) return current;
718 else return NULL;
721 return NULL; // we should have returned before if it's OK
724 #ifndef CONFIG_SORTSUB
725 //we don't need this if we use previous_sub_end
726 subtitle *previous_aqt_sub = NULL;
727 #endif
729 static subtitle *sub_read_line_aqt(stream_t *st,subtitle *current, int utf16) {
730 char line[LINE_LEN+1];
731 char *next;
732 int i;
734 while (1) {
735 // try to locate next subtitle
736 if (!stream_read_line (st, line, LINE_LEN, utf16))
737 return NULL;
738 if (!(sscanf (line, "-->> %ld", &(current->start)) <1))
739 break;
742 #ifdef CONFIG_SORTSUB
743 previous_sub_end = (current->start) ? current->start - 1 : 0;
744 #else
745 if (previous_aqt_sub != NULL)
746 previous_aqt_sub->end = current->start-1;
748 previous_aqt_sub = current;
749 #endif
751 if (!stream_read_line (st, line, LINE_LEN, utf16))
752 return NULL;
754 sub_readtext((char *) &line,&current->text[0]);
755 current->lines = 1;
756 current->end = current->start; // will be corrected by next subtitle
758 if (!stream_read_line (st, line, LINE_LEN, utf16))
759 return current;
761 next = line,i=1;
762 while ((next =sub_readtext (next, &(current->text[i])))) {
763 if (current->text[i]==ERR) {return ERR;}
764 i++;
765 if (i>=SUB_MAX_TEXT) { mp_msg(MSGT_SUBREADER,MSGL_WARN,"Too many lines in a subtitle\n");current->lines=i;return current;}
767 current->lines=i+1;
769 if (!strlen(current->text[0]) && !strlen(current->text[1])) {
770 #ifdef CONFIG_SORTSUB
771 previous_sub_end = 0;
772 #else
773 // void subtitle -> end of previous marked and exit
774 previous_aqt_sub = NULL;
775 #endif
776 return NULL;
779 return current;
782 #ifndef CONFIG_SORTSUB
783 subtitle *previous_subrip09_sub = NULL;
784 #endif
786 static subtitle *sub_read_line_subrip09(stream_t *st,subtitle *current, int utf16) {
787 char line[LINE_LEN+1];
788 int a1,a2,a3;
789 char * next=NULL;
790 int i,len;
792 while (1) {
793 // try to locate next subtitle
794 if (!stream_read_line (st, line, LINE_LEN, utf16))
795 return NULL;
796 if (!((len=sscanf (line, "[%d:%d:%d]",&a1,&a2,&a3)) < 3))
797 break;
800 current->start = a1*360000+a2*6000+a3*100;
802 #ifdef CONFIG_SORTSUB
803 previous_sub_end = (current->start) ? current->start - 1 : 0;
804 #else
805 if (previous_subrip09_sub != NULL)
806 previous_subrip09_sub->end = current->start-1;
808 previous_subrip09_sub = current;
809 #endif
811 if (!stream_read_line (st, line, LINE_LEN, utf16))
812 return NULL;
814 next = line,i=0;
816 current->text[0]=""; // just to be sure that string is clear
818 while ((next =sub_readtext (next, &(current->text[i])))) {
819 if (current->text[i]==ERR) {return ERR;}
820 i++;
821 if (i>=SUB_MAX_TEXT) { mp_msg(MSGT_SUBREADER,MSGL_WARN,"Too many lines in a subtitle\n");current->lines=i;return current;}
823 current->lines=i+1;
825 if (!strlen(current->text[0]) && (i==0)) {
826 #ifdef CONFIG_SORTSUB
827 previous_sub_end = 0;
828 #else
829 // void subtitle -> end of previous marked and exit
830 previous_subrip09_sub = NULL;
831 #endif
832 return NULL;
835 return current;
838 static subtitle *sub_read_line_jacosub(stream_t* st, subtitle * current, int utf16)
840 char line1[LINE_LEN], line2[LINE_LEN], directive[LINE_LEN], *p, *q;
841 unsigned a1, a2, a3, a4, b1, b2, b3, b4, comment = 0;
842 static unsigned jacoTimeres = 30;
843 static int jacoShift = 0;
845 memset(current, 0, sizeof(subtitle));
846 memset(line1, 0, LINE_LEN);
847 memset(line2, 0, LINE_LEN);
848 memset(directive, 0, LINE_LEN);
849 while (!current->text[0]) {
850 if (!stream_read_line(st, line1, LINE_LEN, utf16)) {
851 return NULL;
853 if (sscanf
854 (line1, "%u:%u:%u.%u %u:%u:%u.%u %[^\n\r]", &a1, &a2, &a3, &a4,
855 &b1, &b2, &b3, &b4, line2) < 9) {
856 if (sscanf(line1, "@%u @%u %[^\n\r]", &a4, &b4, line2) < 3) {
857 if (line1[0] == '#') {
858 int hours = 0, minutes = 0, seconds, delta, inverter =
860 unsigned units = jacoShift;
861 switch (toupper(line1[1])) {
862 case 'S':
863 if (isalpha(line1[2])) {
864 delta = 6;
865 } else {
866 delta = 2;
868 if (sscanf(&line1[delta], "%d", &hours)) {
869 if (hours < 0) {
870 hours *= -1;
871 inverter = -1;
873 if (sscanf(&line1[delta], "%*d:%d", &minutes)) {
874 if (sscanf
875 (&line1[delta], "%*d:%*d:%d",
876 &seconds)) {
877 sscanf(&line1[delta], "%*d:%*d:%*d.%d",
878 &units);
879 } else {
880 hours = 0;
881 sscanf(&line1[delta], "%d:%d.%d",
882 &minutes, &seconds, &units);
883 minutes *= inverter;
885 } else {
886 hours = minutes = 0;
887 sscanf(&line1[delta], "%d.%d", &seconds,
888 &units);
889 seconds *= inverter;
891 jacoShift =
892 ((hours * 3600 + minutes * 60 +
893 seconds) * jacoTimeres +
894 units) * inverter;
896 break;
897 case 'T':
898 if (isalpha(line1[2])) {
899 delta = 8;
900 } else {
901 delta = 2;
903 sscanf(&line1[delta], "%u", &jacoTimeres);
904 break;
907 continue;
908 } else {
909 current->start =
910 (unsigned long) ((a4 + jacoShift) * 100.0 /
911 jacoTimeres);
912 current->end =
913 (unsigned long) ((b4 + jacoShift) * 100.0 /
914 jacoTimeres);
916 } else {
917 current->start =
918 (unsigned
919 long) (((a1 * 3600 + a2 * 60 + a3) * jacoTimeres + a4 +
920 jacoShift) * 100.0 / jacoTimeres);
921 current->end =
922 (unsigned
923 long) (((b1 * 3600 + b2 * 60 + b3) * jacoTimeres + b4 +
924 jacoShift) * 100.0 / jacoTimeres);
926 current->lines = 0;
927 p = line2;
928 while ((*p == ' ') || (*p == '\t')) {
929 ++p;
931 if (isalpha(*p)||*p == '[') {
932 int cont, jLength;
934 if (sscanf(p, "%s %[^\n\r]", directive, line1) < 2)
935 return (subtitle *) ERR;
936 jLength = strlen(directive);
937 for (cont = 0; cont < jLength; ++cont) {
938 if (isalpha(*(directive + cont)))
939 *(directive + cont) = toupper(*(directive + cont));
941 if ((strstr(directive, "RDB") != NULL)
942 || (strstr(directive, "RDC") != NULL)
943 || (strstr(directive, "RLB") != NULL)
944 || (strstr(directive, "RLG") != NULL)) {
945 continue;
947 if (strstr(directive, "JL") != NULL) {
948 current->alignment = SUB_ALIGNMENT_BOTTOMLEFT;
949 } else if (strstr(directive, "JR") != NULL) {
950 current->alignment = SUB_ALIGNMENT_BOTTOMRIGHT;
951 } else {
952 current->alignment = SUB_ALIGNMENT_BOTTOMCENTER;
954 strcpy(line2, line1);
955 p = line2;
957 for (q = line1; (!eol(*p)) && (current->lines < SUB_MAX_TEXT); ++p) {
958 switch (*p) {
959 case '{':
960 comment++;
961 break;
962 case '}':
963 if (comment) {
964 --comment;
965 //the next line to get rid of a blank after the comment
966 if ((*(p + 1)) == ' ')
967 p++;
969 break;
970 case '~':
971 if (!comment) {
972 *q = ' ';
973 ++q;
975 break;
976 case ' ':
977 case '\t':
978 if ((*(p + 1) == ' ') || (*(p + 1) == '\t'))
979 break;
980 if (!comment) {
981 *q = ' ';
982 ++q;
984 break;
985 case '\\':
986 if (*(p + 1) == 'n') {
987 *q = '\0';
988 q = line1;
989 current->text[current->lines++] = strdup(line1);
990 ++p;
991 break;
993 if ((toupper(*(p + 1)) == 'C')
994 || (toupper(*(p + 1)) == 'F')) {
995 ++p,++p;
996 break;
998 if ((*(p + 1) == 'B') || (*(p + 1) == 'b') || (*(p + 1) == 'D') || //actually this means "insert current date here"
999 (*(p + 1) == 'I') || (*(p + 1) == 'i') || (*(p + 1) == 'N') || (*(p + 1) == 'T') || //actually this means "insert current time here"
1000 (*(p + 1) == 'U') || (*(p + 1) == 'u')) {
1001 ++p;
1002 break;
1004 if ((*(p + 1) == '\\') ||
1005 (*(p + 1) == '~') || (*(p + 1) == '{')) {
1006 ++p;
1007 } else if (eol(*(p + 1))) {
1008 if (!stream_read_line(st, directive, LINE_LEN, utf16))
1009 return NULL;
1010 trail_space(directive);
1011 av_strlcat(line2, directive, LINE_LEN);
1012 break;
1014 default:
1015 if (!comment) {
1016 *q = *p;
1017 ++q;
1019 } //-- switch
1020 } //-- for
1021 *q = '\0';
1022 current->text[current->lines] = strdup(line1);
1023 } //-- while
1024 current->lines++;
1025 return current;
1028 static int sub_autodetect (stream_t* st, int *uses_time, int utf16) {
1029 char line[LINE_LEN+1];
1030 int i,j=0;
1031 char p;
1033 while (j < 100) {
1034 j++;
1035 if (!stream_read_line (st, line, LINE_LEN, utf16))
1036 return SUB_INVALID;
1038 if (sscanf (line, "{%d}{%d}", &i, &i)==2)
1039 {*uses_time=0;return SUB_MICRODVD;}
1040 if (sscanf (line, "{%d}{}", &i)==1)
1041 {*uses_time=0;return SUB_MICRODVD;}
1042 if (sscanf (line, "[%d][%d]", &i, &i)==2)
1043 {*uses_time=1;return SUB_MPL2;}
1044 if (sscanf (line, "%d:%d:%d.%d,%d:%d:%d.%d", &i, &i, &i, &i, &i, &i, &i, &i)==8)
1045 {*uses_time=1;return SUB_SUBRIP;}
1046 if (sscanf (line, "%d:%d:%d%[,.:]%d --> %d:%d:%d%[,.:]%d", &i, &i, &i, (char *)&i, &i, &i, &i, &i, (char *)&i, &i)==10)
1047 {*uses_time=1;return SUB_SUBVIEWER;}
1048 if (sscanf (line, "{T %d:%d:%d:%d",&i, &i, &i, &i)==4)
1049 {*uses_time=1;return SUB_SUBVIEWER2;}
1050 if (strstr (line, "<SAMI>"))
1051 {*uses_time=1; return SUB_SAMI;}
1052 if (sscanf(line, "%d:%d:%d.%d %d:%d:%d.%d", &i, &i, &i, &i, &i, &i, &i, &i) == 8)
1053 {*uses_time = 1; return SUB_JACOSUB;}
1054 if (sscanf(line, "@%d @%d", &i, &i) == 2)
1055 {*uses_time = 1; return SUB_JACOSUB;}
1056 if (sscanf (line, "%d:%d:%d:", &i, &i, &i )==3)
1057 {*uses_time=1;return SUB_VPLAYER;}
1058 if (sscanf (line, "%d:%d:%d ", &i, &i, &i )==3)
1059 {*uses_time=1;return SUB_VPLAYER;}
1060 //TODO: just checking if first line of sub starts with "<" is WAY
1061 // too weak test for RT
1062 // Please someone who knows the format of RT... FIX IT!!!
1063 // It may conflict with other sub formats in the future (actually it doesn't)
1064 if ( *line == '<' )
1065 {*uses_time=1;return SUB_RT;}
1067 if (!memcmp(line, "Dialogue: Marked", 16))
1068 {*uses_time=1; return SUB_SSA;}
1069 if (!memcmp(line, "Dialogue: ", 10))
1070 {*uses_time=1; return SUB_SSA;}
1071 if (sscanf (line, "%d,%d,\"%c", &i, &i, (char *) &i) == 3)
1072 {*uses_time=1;return SUB_PJS;}
1073 if (sscanf (line, "FORMAT=%d", &i) == 1)
1074 {*uses_time=0; return SUB_MPSUB;}
1075 if (sscanf (line, "FORMAT=TIM%c", &p)==1 && p=='E')
1076 {*uses_time=1; return SUB_MPSUB;}
1077 if (strstr (line, "-->>"))
1078 {*uses_time=0; return SUB_AQTITLE;}
1079 if (sscanf (line, "[%d:%d:%d]", &i, &i, &i)==3)
1080 {*uses_time=1;return SUB_SUBRIP09;}
1083 return SUB_INVALID; // too many bad lines
1086 extern int sub_utf8;
1087 int sub_utf8_prev=0;
1089 extern float sub_delay;
1090 extern float sub_fps;
1092 #ifdef CONFIG_ICONV
1093 static iconv_t icdsc = (iconv_t)(-1);
1095 void subcp_open (stream_t *st)
1097 char *tocp = "UTF-8";
1099 if (sub_cp){
1100 const char *cp_tmp = sub_cp;
1101 #ifdef CONFIG_ENCA
1102 char enca_lang[3], enca_fallback[100];
1103 if (sscanf(sub_cp, "enca:%2s:%99s", enca_lang, enca_fallback) == 2
1104 || sscanf(sub_cp, "ENCA:%2s:%99s", enca_lang, enca_fallback) == 2) {
1105 if (st && st->flags & MP_STREAM_SEEK ) {
1106 cp_tmp = guess_cp(st, enca_lang, enca_fallback);
1107 } else {
1108 cp_tmp = enca_fallback;
1109 if (st)
1110 mp_msg(MSGT_SUBREADER,MSGL_WARN,"SUB: enca failed, stream must be seekable.\n");
1113 #endif
1114 if ((icdsc = iconv_open (tocp, cp_tmp)) != (iconv_t)(-1)){
1115 mp_msg(MSGT_SUBREADER,MSGL_V,"SUB: opened iconv descriptor.\n");
1116 sub_utf8 = 2;
1117 } else
1118 mp_msg(MSGT_SUBREADER,MSGL_ERR,"SUB: error opening iconv descriptor.\n");
1122 void subcp_close (void)
1124 if (icdsc != (iconv_t)(-1)){
1125 (void) iconv_close (icdsc);
1126 icdsc = (iconv_t)(-1);
1127 mp_msg(MSGT_SUBREADER,MSGL_V,"SUB: closed iconv descriptor.\n");
1131 subtitle* subcp_recode (subtitle *sub)
1133 int l=sub->lines;
1134 size_t ileft, oleft;
1135 char *op, *ip, *ot;
1136 if(icdsc == (iconv_t)(-1)) return sub;
1138 while (l){
1139 ip = sub->text[--l];
1140 ileft = strlen(ip);
1141 oleft = 4 * ileft;
1143 if (!(ot = malloc(oleft + 1))){
1144 mp_msg(MSGT_SUBREADER,MSGL_WARN,"SUB: error allocating mem.\n");
1145 continue;
1147 op = ot;
1148 if (iconv(icdsc, &ip, &ileft,
1149 &op, &oleft) == (size_t)(-1)) {
1150 mp_msg(MSGT_SUBREADER,MSGL_WARN,"SUB: error recoding line.\n");
1151 free(ot);
1152 continue;
1154 // In some stateful encodings, we must clear the state to handle the last character
1155 if (iconv(icdsc, NULL, NULL,
1156 &op, &oleft) == (size_t)(-1)) {
1157 mp_msg(MSGT_SUBREADER,MSGL_WARN,"SUB: error recoding line, can't clear encoding state.\n");
1159 *op='\0' ;
1160 free (sub->text[l]);
1161 sub->text[l] = ot;
1163 return sub;
1165 #endif
1167 #ifdef CONFIG_FRIBIDI
1169 * Do conversion necessary for right-to-left language support via fribidi.
1170 * @param sub subtitle to convert
1171 * @param sub_utf8 whether the subtitle is encoded in UTF-8
1172 * @param from first new subtitle, all lines before this are assumed to be already converted
1174 static subtitle* sub_fribidi (subtitle *sub, int sub_utf8, int from)
1176 FriBidiChar logical[LINE_LEN+1], visual[LINE_LEN+1]; // Hopefully these two won't smash the stack
1177 char *ip = NULL, *op = NULL;
1178 size_t len,orig_len;
1179 int l=sub->lines;
1180 int char_set_num;
1181 fribidi_boolean log2vis;
1182 if (!flip_hebrew)
1183 return sub;
1184 fribidi_set_mirroring(1);
1185 fribidi_set_reorder_nsm(0);
1187 if( sub_utf8 == 0 ) {
1188 char_set_num = fribidi_parse_charset (fribidi_charset?fribidi_charset:"ISO8859-8");
1189 }else {
1190 char_set_num = fribidi_parse_charset ("UTF-8");
1192 while (l > from) {
1193 ip = sub->text[--l];
1194 orig_len = len = strlen( ip ); // We assume that we don't use full unicode, only UTF-8 or ISO8859-x
1195 if(len > LINE_LEN) {
1196 mp_msg(MSGT_SUBREADER,MSGL_WARN,"SUB: sub->text is longer than LINE_LEN.\n");
1197 l++;
1198 break;
1200 len = fribidi_charset_to_unicode (char_set_num, ip, len, logical);
1201 #if FRIBIDI_INTERFACE_VERSION < 3
1202 FriBidiCharType base = fribidi_flip_commas?FRIBIDI_TYPE_ON:FRIBIDI_TYPE_L;
1203 #else
1204 FriBidiParType base = fribidi_flip_commas?FRIBIDI_TYPE_ON:FRIBIDI_TYPE_L;
1205 #endif
1206 log2vis = fribidi_log2vis (logical, len, &base,
1207 /* output */
1208 visual, NULL, NULL, NULL);
1209 if(log2vis) {
1210 len = fribidi_remove_bidi_marks (visual, len, NULL, NULL,
1211 NULL);
1212 if((op = malloc((FFMAX(2*orig_len,2*len) + 1))) == NULL) {
1213 mp_msg(MSGT_SUBREADER,MSGL_WARN,"SUB: error allocating mem.\n");
1214 l++;
1215 break;
1217 fribidi_unicode_to_charset ( char_set_num, visual, len,op);
1218 free (ip);
1219 sub->text[l] = op;
1222 if (!from && l){
1223 for (l = sub->lines; l;)
1224 free (sub->text[--l]);
1225 return ERR;
1227 return sub;
1230 #endif
1232 static void adjust_subs_time(subtitle* sub, float subtime, float fps, int block,
1233 int sub_num, int sub_uses_time) {
1234 int n,m;
1235 subtitle* nextsub;
1236 int i = sub_num;
1237 unsigned long subfms = (sub_uses_time ? 100 : fps) * subtime;
1238 unsigned long overlap = (sub_uses_time ? 100 : fps) / 5; // 0.2s
1240 n=m=0;
1241 if (i) for (;;){
1242 if (sub->end <= sub->start){
1243 sub->end = sub->start + subfms;
1244 m++;
1245 n++;
1247 if (!--i) break;
1248 nextsub = sub + 1;
1249 if(block){
1250 if ((sub->end > nextsub->start) && (sub->end <= nextsub->start + overlap)) {
1251 // these subtitles overlap for less than 0.2 seconds
1252 // and would result in very short overlapping subtitle
1253 // so let's fix the problem here, before overlapping code
1254 // get its hands on them
1255 unsigned delta = sub->end - nextsub->start, half = delta / 2;
1256 sub->end -= half + 1;
1257 nextsub->start += delta - half;
1259 if (sub->end >= nextsub->start){
1260 sub->end = nextsub->start - 1;
1261 if (sub->end - sub->start > subfms)
1262 sub->end = sub->start + subfms;
1263 if (!m)
1264 n++;
1268 /* Theory:
1269 * Movies are often converted from FILM (24 fps)
1270 * to PAL (25) by simply speeding it up, so we
1271 * to multiply the original timestmaps by
1272 * (Movie's FPS / Subtitle's (guessed) FPS)
1273 * so eg. for 23.98 fps movie and PAL time based
1274 * subtitles we say -subfps 25 and we're fine!
1277 /* timed sub fps correction ::atmos */
1278 /* the frame-based case is handled in mpcommon.c
1279 * where find_sub is called */
1280 if(sub_uses_time && sub_fps) {
1281 sub->start *= sub_fps/fps;
1282 sub->end *= sub_fps/fps;
1285 sub = nextsub;
1286 m = 0;
1288 if (n) mp_msg(MSGT_SUBREADER,MSGL_V,"SUB: Adjusted %d subtitle(s).\n", n);
1291 struct subreader {
1292 subtitle * (*read)(stream_t *st,subtitle *dest,int utf16);
1293 void (*post)(subtitle *dest);
1294 const char *name;
1297 #ifdef CONFIG_ENCA
1298 const char* guess_buffer_cp(unsigned char* buffer, int buflen, const char *preferred_language, const char *fallback)
1300 const char **languages;
1301 size_t langcnt;
1302 EncaAnalyser analyser;
1303 EncaEncoding encoding;
1304 const char *detected_sub_cp = NULL;
1305 int i;
1307 languages = enca_get_languages(&langcnt);
1308 mp_msg(MSGT_SUBREADER, MSGL_V, "ENCA supported languages: ");
1309 for (i = 0; i < langcnt; i++) {
1310 mp_msg(MSGT_SUBREADER, MSGL_V, "%s ", languages[i]);
1312 mp_msg(MSGT_SUBREADER, MSGL_V, "\n");
1314 for (i = 0; i < langcnt; i++) {
1315 if (strcasecmp(languages[i], preferred_language) != 0) continue;
1316 analyser = enca_analyser_alloc(languages[i]);
1317 encoding = enca_analyse_const(analyser, buffer, buflen);
1318 enca_analyser_free(analyser);
1319 if (encoding.charset != ENCA_CS_UNKNOWN) {
1320 detected_sub_cp = enca_charset_name(encoding.charset, ENCA_NAME_STYLE_ICONV);
1321 break;
1325 free(languages);
1327 if (!detected_sub_cp) {
1328 detected_sub_cp = fallback;
1329 mp_msg(MSGT_SUBREADER, MSGL_INFO, "ENCA detection failed: fallback to %s\n", fallback);
1330 }else{
1331 mp_msg(MSGT_SUBREADER, MSGL_INFO, "ENCA detected charset: %s\n", detected_sub_cp);
1334 return detected_sub_cp;
1337 #define MAX_GUESS_BUFFER_SIZE (256*1024)
1338 const char* guess_cp(stream_t *st, const char *preferred_language, const char *fallback)
1340 size_t buflen;
1341 unsigned char *buffer;
1342 const char *detected_sub_cp = NULL;
1344 buffer = malloc(MAX_GUESS_BUFFER_SIZE);
1345 buflen = stream_read(st,buffer, MAX_GUESS_BUFFER_SIZE);
1347 detected_sub_cp = guess_buffer_cp(buffer, buflen, preferred_language, fallback);
1349 free(buffer);
1350 stream_reset(st);
1351 stream_seek(st,0);
1353 return detected_sub_cp;
1355 #undef MAX_GUESS_BUFFER_SIZE
1356 #endif
1358 sub_data* sub_read_file (char *filename, float fps) {
1359 int utf16;
1360 stream_t* fd;
1361 int n_max, n_first, i, j, sub_first, sub_orig;
1362 subtitle *first, *second, *sub, *return_sub, *alloced_sub = NULL;
1363 sub_data *subt_data;
1364 int uses_time = 0, sub_num = 0, sub_errs = 0;
1365 static const struct subreader sr[]=
1367 { sub_read_line_microdvd, NULL, "microdvd" },
1368 { sub_read_line_subrip, NULL, "subrip" },
1369 { sub_read_line_subviewer, NULL, "subviewer" },
1370 { sub_read_line_sami, NULL, "sami" },
1371 { sub_read_line_vplayer, NULL, "vplayer" },
1372 { sub_read_line_rt, NULL, "rt" },
1373 { sub_read_line_ssa, sub_pp_ssa, "ssa" },
1374 { sub_read_line_pjs, NULL, "pjs" },
1375 { sub_read_line_mpsub, NULL, "mpsub" },
1376 { sub_read_line_aqt, NULL, "aqt" },
1377 { sub_read_line_subviewer2, NULL, "subviewer 2.0" },
1378 { sub_read_line_subrip09, NULL, "subrip 0.9" },
1379 { sub_read_line_jacosub, NULL, "jacosub" },
1380 { sub_read_line_mpl2, NULL, "mpl2" }
1382 const struct subreader *srp;
1384 if(filename==NULL) return NULL; //qnx segfault
1385 i = 0;
1386 fd=open_stream (filename, NULL, &i); if (!fd) return NULL;
1388 sub_format = SUB_INVALID;
1389 for (utf16 = 0; sub_format == SUB_INVALID && utf16 < 3; utf16++) {
1390 sub_format=sub_autodetect (fd, &uses_time, utf16);
1391 stream_reset(fd);
1392 stream_seek(fd,0);
1394 utf16--;
1396 mpsub_multiplier = (uses_time ? 100.0 : 1.0);
1397 if (sub_format==SUB_INVALID) {mp_msg(MSGT_SUBREADER,MSGL_WARN,"SUB: Could not determine file format\n");return NULL;}
1398 srp=sr+sub_format;
1399 mp_msg(MSGT_SUBREADER, MSGL_V, "SUB: Detected subtitle file format: %s\n", srp->name);
1401 #ifdef CONFIG_ICONV
1402 sub_utf8_prev=sub_utf8;
1404 int l,k;
1405 k = -1;
1406 if ((l=strlen(filename))>4){
1407 char *exts[] = {".utf", ".utf8", ".utf-8" };
1408 for (k=3;--k>=0;)
1409 if (l >= strlen(exts[k]) && !strcasecmp(filename+(l - strlen(exts[k])), exts[k])){
1410 sub_utf8 = 1;
1411 break;
1414 if (k<0) subcp_open(fd);
1416 #endif
1418 sub_num=0;n_max=32;
1419 first=malloc(n_max*sizeof(subtitle));
1420 if(!first){
1421 #ifdef CONFIG_ICONV
1422 subcp_close();
1423 sub_utf8=sub_utf8_prev;
1424 #endif
1425 return NULL;
1428 #ifdef CONFIG_SORTSUB
1429 alloced_sub =
1430 sub = malloc(sizeof(subtitle));
1431 //This is to deal with those formats (AQT & Subrip) which define the end of a subtitle
1432 //as the beginning of the following
1433 previous_sub_end = 0;
1434 #endif
1435 while(1){
1436 if(sub_num>=n_max){
1437 n_max+=16;
1438 first=realloc(first,n_max*sizeof(subtitle));
1440 #ifndef CONFIG_SORTSUB
1441 sub = &first[sub_num];
1442 #endif
1443 memset(sub, '\0', sizeof(subtitle));
1444 sub=srp->read(fd,sub,utf16);
1445 if(!sub) break; // EOF
1446 #ifdef CONFIG_ICONV
1447 if ((sub!=ERR) && sub_utf8 == 2) sub=subcp_recode(sub);
1448 #endif
1449 #ifdef CONFIG_FRIBIDI
1450 if (sub!=ERR) sub=sub_fribidi(sub,sub_utf8,0);
1451 #endif
1452 if ( sub == ERR )
1454 #ifdef CONFIG_ICONV
1455 subcp_close();
1456 #endif
1457 if ( first ) free(first);
1458 free(alloced_sub);
1459 return NULL;
1461 // Apply any post processing that needs recoding first
1462 if ((sub!=ERR) && !sub_no_text_pp && srp->post) srp->post(sub);
1463 #ifdef CONFIG_SORTSUB
1464 if(!sub_num || (first[sub_num - 1].start <= sub->start)){
1465 first[sub_num].start = sub->start;
1466 first[sub_num].end = sub->end;
1467 first[sub_num].lines = sub->lines;
1468 first[sub_num].alignment = sub->alignment;
1469 for(i = 0; i < sub->lines; ++i){
1470 first[sub_num].text[i] = sub->text[i];
1472 if (previous_sub_end){
1473 first[sub_num - 1].end = previous_sub_end;
1474 previous_sub_end = 0;
1476 } else {
1477 for(j = sub_num - 1; j >= 0; --j){
1478 first[j + 1].start = first[j].start;
1479 first[j + 1].end = first[j].end;
1480 first[j + 1].lines = first[j].lines;
1481 first[j + 1].alignment = first[j].alignment;
1482 for(i = 0; i < first[j].lines; ++i){
1483 first[j + 1].text[i] = first[j].text[i];
1485 if(!j || (first[j - 1].start <= sub->start)){
1486 first[j].start = sub->start;
1487 first[j].end = sub->end;
1488 first[j].lines = sub->lines;
1489 first[j].alignment = sub->alignment;
1490 for(i = 0; i < SUB_MAX_TEXT; ++i){
1491 first[j].text[i] = sub->text[i];
1493 if (previous_sub_end){
1494 first[j].end = first[j - 1].end;
1495 first[j - 1].end = previous_sub_end;
1496 previous_sub_end = 0;
1498 break;
1502 #endif
1503 if(sub==ERR) ++sub_errs; else ++sub_num; // Error vs. Valid
1506 free_stream(fd);
1508 #ifdef CONFIG_ICONV
1509 subcp_close();
1510 #endif
1511 free(alloced_sub);
1513 // printf ("SUB: Subtitle format %s time.\n", uses_time?"uses":"doesn't use");
1514 mp_msg(MSGT_SUBREADER, MSGL_V,"SUB: Read %i subtitles, %i bad line(s).\n",
1515 sub_num, sub_errs);
1517 if(sub_num<=0){
1518 free(first);
1519 return NULL;
1522 // we do overlap if the user forced it (suboverlap_enable == 2) or
1523 // the user didn't forced no-overlapsub and the format is Jacosub or Ssa.
1524 // this is because usually overlapping subtitles are found in these formats,
1525 // while in others they are probably result of bad timing
1526 if ((suboverlap_enabled == 2) ||
1527 ((suboverlap_enabled) && ((sub_format == SUB_JACOSUB) || (sub_format == SUB_SSA)))) {
1528 adjust_subs_time(first, 6.0, fps, 0, sub_num, uses_time);/*~6 secs AST*/
1529 // here we manage overlapping subtitles
1530 sub_orig = sub_num;
1531 n_first = sub_num;
1532 sub_num = 0;
1533 second = NULL;
1534 // for each subtitle in first[] we deal with its 'block' of
1535 // bonded subtitles
1536 for (sub_first = 0; sub_first < n_first; ++sub_first) {
1537 unsigned long global_start = first[sub_first].start,
1538 global_end = first[sub_first].end, local_start, local_end;
1539 int lines_to_add = first[sub_first].lines, sub_to_add = 0,
1540 **placeholder = NULL, higher_line = 0, counter, start_block_sub = sub_num;
1541 char real_block = 1;
1543 // here we find the number of subtitles inside the 'block'
1544 // and its span interval. this works well only with sorted
1545 // subtitles
1546 while ((sub_first + sub_to_add + 1 < n_first) && (first[sub_first + sub_to_add + 1].start < global_end)) {
1547 ++sub_to_add;
1548 lines_to_add += first[sub_first + sub_to_add].lines;
1549 if (first[sub_first + sub_to_add].start < global_start) {
1550 global_start = first[sub_first + sub_to_add].start;
1552 if (first[sub_first + sub_to_add].end > global_end) {
1553 global_end = first[sub_first + sub_to_add].end;
1557 /* Avoid n^2 memory use for the "placeholder" data structure
1558 * below with subtitles that have a huge number of
1559 * consecutive overlapping lines. */
1560 lines_to_add = FFMIN(lines_to_add, SUB_MAX_TEXT);
1562 // we need a structure to keep trace of the screen lines
1563 // used by the subs, a 'placeholder'
1564 counter = 2 * sub_to_add + 1; // the maximum number of subs derived
1565 // from a block of sub_to_add+1 subs
1566 placeholder = malloc(sizeof(int *) * counter);
1567 for (i = 0; i < counter; ++i) {
1568 placeholder[i] = malloc(sizeof(int) * lines_to_add);
1569 for (j = 0; j < lines_to_add; ++j) {
1570 placeholder[i][j] = -1;
1574 counter = 0;
1575 local_end = global_start - 1;
1576 do {
1577 int ls;
1579 // here we find the beginning and the end of a new
1580 // subtitle in the block
1581 local_start = local_end + 1;
1582 local_end = global_end;
1583 for (j = 0; j <= sub_to_add; ++j) {
1584 if ((first[sub_first + j].start - 1 > local_start) && (first[sub_first + j].start - 1 < local_end)) {
1585 local_end = first[sub_first + j].start - 1;
1586 } else if ((first[sub_first + j].end > local_start) && (first[sub_first + j].end < local_end)) {
1587 local_end = first[sub_first + j].end;
1590 // here we allocate the screen lines to subs we must
1591 // display in current local_start-local_end interval.
1592 // if the subs were yet presents in the previous interval
1593 // they keep the same lines, otherside they get unused lines
1594 for (j = 0; j <= sub_to_add; ++j) {
1595 if ((first[sub_first + j].start <= local_end) && (first[sub_first + j].end > local_start)) {
1596 unsigned long sub_lines = first[sub_first + j].lines, fragment_length = lines_to_add + 1,
1597 tmp = 0;
1598 char boolean = 0;
1599 int fragment_position = -1;
1601 // if this is not the first new sub of the block
1602 // we find if this sub was present in the previous
1603 // new sub
1604 if (counter)
1605 for (i = 0; i < lines_to_add; ++i) {
1606 if (placeholder[counter - 1][i] == sub_first + j) {
1607 placeholder[counter][i] = sub_first + j;
1608 boolean = 1;
1611 if (boolean)
1612 continue;
1614 // we are looking for the shortest among all groups of
1615 // sequential blank lines whose length is greater than or
1616 // equal to sub_lines. we store in fragment_position the
1617 // position of the shortest group, in fragment_length its
1618 // length, and in tmp the length of the group currently
1619 // examinated
1620 for (i = 0; i < lines_to_add; ++i) {
1621 if (placeholder[counter][i] == -1) {
1622 // placeholder[counter][i] is part of the current group
1623 // of blank lines
1624 ++tmp;
1625 } else {
1626 if (tmp == sub_lines) {
1627 // current group's size fits exactly the one we
1628 // need, so we stop looking
1629 fragment_position = i - tmp;
1630 tmp = 0;
1631 break;
1633 if ((tmp) && (tmp > sub_lines) && (tmp < fragment_length)) {
1634 // current group is the best we found till here,
1635 // but is still bigger than the one we are looking
1636 // for, so we keep on looking
1637 fragment_length = tmp;
1638 fragment_position = i - tmp;
1639 tmp = 0;
1640 } else {
1641 // current group doesn't fit at all, so we forget it
1642 tmp = 0;
1646 if (tmp) {
1647 // last screen line is blank, a group ends with it
1648 if ((tmp >= sub_lines) && (tmp < fragment_length)) {
1649 fragment_position = i - tmp;
1652 if (fragment_position == -1) {
1653 // it was not possible to find free screen line(s) for a subtitle,
1654 // usually this means a bug in the code; however we do not overlap
1655 mp_msg(MSGT_SUBREADER, MSGL_WARN, "SUB: we could not find a suitable position for an overlapping subtitle\n");
1656 higher_line = SUB_MAX_TEXT + 1;
1657 break;
1658 } else {
1659 for (tmp = 0; tmp < sub_lines; ++tmp) {
1660 placeholder[counter][fragment_position + tmp] = sub_first + j;
1665 for (j = higher_line + 1; j < lines_to_add; ++j) {
1666 if (placeholder[counter][j] != -1)
1667 higher_line = j;
1668 else
1669 break;
1671 if (higher_line >= SUB_MAX_TEXT) {
1672 // the 'block' has too much lines, so we don't overlap the
1673 // subtitles
1674 second = realloc(second, (sub_num + sub_to_add + 1) * sizeof(subtitle));
1675 for (j = 0; j <= sub_to_add; ++j) {
1676 int ls;
1677 memset(&second[sub_num + j], '\0', sizeof(subtitle));
1678 second[sub_num + j].start = first[sub_first + j].start;
1679 second[sub_num + j].end = first[sub_first + j].end;
1680 second[sub_num + j].lines = first[sub_first + j].lines;
1681 second[sub_num + j].alignment = first[sub_first + j].alignment;
1682 for (ls = 0; ls < second[sub_num + j].lines; ls++) {
1683 second[sub_num + j].text[ls] = strdup(first[sub_first + j].text[ls]);
1686 sub_num += sub_to_add + 1;
1687 sub_first += sub_to_add;
1688 real_block = 0;
1689 break;
1692 // we read the placeholder structure and create the new
1693 // subs.
1694 second = realloc(second, (sub_num + 1) * sizeof(subtitle));
1695 memset(&second[sub_num], '\0', sizeof(subtitle));
1696 second[sub_num].start = local_start;
1697 second[sub_num].end = local_end;
1698 second[sub_num].alignment = first[sub_first].alignment;
1699 n_max = (lines_to_add < SUB_MAX_TEXT) ? lines_to_add : SUB_MAX_TEXT;
1700 for (i = 0, j = 0; j < n_max; ++j) {
1701 if (placeholder[counter][j] != -1) {
1702 int lines = first[placeholder[counter][j]].lines;
1703 for (ls = 0; ls < lines; ++ls) {
1704 second[sub_num].text[i++] = strdup(first[placeholder[counter][j]].text[ls]);
1706 j += lines - 1;
1707 } else {
1708 second[sub_num].text[i++] = strdup(" ");
1711 ++sub_num;
1712 ++counter;
1713 } while (local_end < global_end);
1714 if (real_block)
1715 for (i = 0; i < counter; ++i)
1716 second[start_block_sub + i].lines = higher_line + 1;
1718 counter = 2 * sub_to_add + 1;
1719 for (i = 0; i < counter; ++i) {
1720 free(placeholder[i]);
1722 free(placeholder);
1723 sub_first += sub_to_add;
1726 for (j = sub_orig - 1; j >= 0; --j) {
1727 for (i = first[j].lines - 1; i >= 0; --i) {
1728 free(first[j].text[i]);
1731 free(first);
1733 return_sub = second;
1734 } else { //if(suboverlap_enabled)
1735 adjust_subs_time(first, 6.0, fps, 1, sub_num, uses_time);/*~6 secs AST*/
1736 return_sub = first;
1738 if (return_sub == NULL) return NULL;
1739 subt_data = malloc(sizeof(sub_data));
1740 subt_data->filename = strdup(filename);
1741 subt_data->sub_uses_time = uses_time;
1742 subt_data->sub_num = sub_num;
1743 subt_data->sub_errs = sub_errs;
1744 subt_data->subtitles = return_sub;
1745 return subt_data;
1748 #if 0
1749 char * strreplace( char * in,char * what,char * whereof )
1751 int i;
1752 char * tmp;
1754 if ( ( in == NULL )||( what == NULL )||( whereof == NULL )||( ( tmp=strstr( in,what ) ) == NULL ) ) return NULL;
1755 for( i=0;i<strlen( whereof );i++ ) tmp[i]=whereof[i];
1756 if ( strlen( what ) > strlen( whereof ) ) tmp[i]=0;
1757 return in;
1759 #endif
1762 static void strcpy_trim(char *d, char *s)
1764 // skip leading whitespace
1765 while (*s && isspace(*s)) {
1766 s++;
1768 for (;;) {
1769 // copy word
1770 while (*s && !isspace(*s)) {
1771 *d = tolower(*s);
1772 s++; d++;
1774 if (*s == 0) break;
1775 // trim excess whitespace
1776 while (*s && isspace(*s)) {
1777 s++;
1779 if (*s == 0) break;
1780 *d++ = ' ';
1782 *d = 0;
1785 static void strcpy_strip_ext(char *d, char *s)
1787 char *tmp = strrchr(s,'.');
1788 if (!tmp) {
1789 strcpy(d, s);
1790 return;
1791 } else {
1792 strncpy(d, s, tmp-s);
1793 d[tmp-s] = 0;
1795 while (*d) {
1796 *d = tolower(*d);
1797 d++;
1801 static void strcpy_get_ext(char *d, char *s)
1803 char *tmp = strrchr(s,'.');
1804 if (!tmp) {
1805 strcpy(d, "");
1806 return;
1807 } else {
1808 strcpy(d, tmp+1);
1812 static int whiteonly(char *s)
1814 while (*s) {
1815 if (!isspace(*s)) return 0;
1816 s++;
1818 return 1;
1821 typedef struct subfn
1823 int priority;
1824 char *fname;
1825 } subfn;
1827 static int compare_sub_priority(const void *a, const void *b)
1829 if (((const subfn*)a)->priority > ((const subfn*)b)->priority) {
1830 return -1;
1831 } else if (((const subfn*)a)->priority < ((const subfn*)b)->priority) {
1832 return 1;
1833 } else {
1834 return strcoll(((const subfn*)a)->fname, ((const subfn*)b)->fname);
1838 char** sub_filenames(const char* path, char *fname)
1840 char *f_dir, *f_fname, *f_fname_noext, *f_fname_trim, *tmp, *tmp_sub_id;
1841 char *tmp_fname_noext, *tmp_fname_trim, *tmp_fname_ext, *tmpresult;
1843 int len, pos, found, i, j;
1844 char * sub_exts[] = { "utf", "utf8", "utf-8", "sub", "srt", "smi", "rt", "txt", "ssa", "aqt", "jss", "js", "ass", NULL};
1845 subfn *result;
1846 char **result2;
1848 int subcnt;
1850 FILE *f;
1852 DIR *d;
1853 struct dirent *de;
1855 len = (strlen(fname) > 256 ? strlen(fname) : 256)
1856 +(strlen(path) > 256 ? strlen(path) : 256)+2;
1858 f_dir = malloc(len);
1859 f_fname = malloc(len);
1860 f_fname_noext = malloc(len);
1861 f_fname_trim = malloc(len);
1863 tmp_fname_noext = malloc(len);
1864 tmp_fname_trim = malloc(len);
1865 tmp_fname_ext = malloc(len);
1867 tmpresult = malloc(len);
1869 result = malloc(sizeof(subfn)*MAX_SUBTITLE_FILES);
1870 memset(result, 0, sizeof(subfn)*MAX_SUBTITLE_FILES);
1872 subcnt = 0;
1874 tmp = strrchr(fname,'/');
1875 #if HAVE_DOS_PATHS
1876 if(!tmp)tmp = strrchr(fname,'\\');
1877 if(!tmp)tmp = strrchr(fname,':');
1878 #endif
1880 // extract filename & dirname from fname
1881 if (tmp) {
1882 strcpy(f_fname, tmp+1);
1883 pos = tmp - fname;
1884 strncpy(f_dir, fname, pos+1);
1885 f_dir[pos+1] = 0;
1886 } else {
1887 strcpy(f_fname, fname);
1888 strcpy(f_dir, "./");
1891 strcpy_strip_ext(f_fname_noext, f_fname);
1892 strcpy_trim(f_fname_trim, f_fname_noext);
1894 /* The code using sub language here is broken - it assumes strict
1895 * "videoname languagename" syntax for the subtitle file, which is
1896 * very unlikely to match especially if language name uses "en,de"
1897 * syntax... */
1898 tmp_sub_id = NULL;
1899 #if 0
1900 if (dvdsub_lang && !whiteonly(dvdsub_lang)) {
1901 tmp_sub_id = malloc(strlen(dvdsub_lang)+1);
1902 strcpy_trim(tmp_sub_id, dvdsub_lang);
1904 #endif
1906 // 0 = nothing
1907 // 1 = any subtitle file
1908 // 2 = any sub file containing movie name
1909 // 3 = sub file containing movie name and the lang extension
1910 for (j = 0; j <= 1; j++) {
1911 d = opendir(j == 0 ? f_dir : path);
1912 if (d) {
1913 while ((de = readdir(d))) {
1914 // retrieve various parts of the filename
1915 strcpy_strip_ext(tmp_fname_noext, de->d_name);
1916 strcpy_get_ext(tmp_fname_ext, de->d_name);
1917 strcpy_trim(tmp_fname_trim, tmp_fname_noext);
1919 // does it end with a subtitle extension?
1920 found = 0;
1921 #ifdef CONFIG_ICONV
1922 #ifdef CONFIG_ENCA
1923 for (i = ((sub_cp && strncasecmp(sub_cp, "enca", 4) != 0) ? 3 : 0); sub_exts[i]; i++) {
1924 #else
1925 for (i = (sub_cp ? 3 : 0); sub_exts[i]; i++) {
1926 #endif
1927 #else
1928 for (i = 0; sub_exts[i]; i++) {
1929 #endif
1930 if (strcasecmp(sub_exts[i], tmp_fname_ext) == 0) {
1931 found = 1;
1932 break;
1936 // we have a (likely) subtitle file
1937 if (found) {
1938 int prio = 0;
1939 if (!prio && tmp_sub_id)
1941 sprintf(tmpresult, "%s %s", f_fname_trim, tmp_sub_id);
1942 if (strcmp(tmp_fname_trim, tmpresult) == 0 && sub_match_fuzziness >= 1) {
1943 // matches the movie name + lang extension
1944 prio = 5;
1947 if (!prio && strcmp(tmp_fname_trim, f_fname_trim) == 0) {
1948 // matches the movie name
1949 prio = 4;
1951 if (!prio && (tmp = strstr(tmp_fname_trim, f_fname_trim)) && (sub_match_fuzziness >= 1)) {
1952 // contains the movie name
1953 tmp += strlen(f_fname_trim);
1954 if (tmp_sub_id && strstr(tmp, tmp_sub_id)) {
1955 // with sub_id specified prefer localized subtitles
1956 prio = 3;
1957 } else if ((tmp_sub_id == NULL) && whiteonly(tmp)) {
1958 // without sub_id prefer "plain" name
1959 prio = 3;
1960 } else {
1961 // with no localized subs found, try any else instead
1962 prio = 2;
1965 if (!prio) {
1966 // doesn't contain the movie name
1967 // don't try in the mplayer subtitle directory
1968 if ((j == 0) && (sub_match_fuzziness >= 2)) {
1969 prio = 1;
1973 mp_msg(MSGT_SUBREADER, MSGL_DBG2, "Potential sub file: "
1974 "\"%s\" Priority: %d\n", de->d_name, prio);
1975 if (prio) {
1976 prio += prio;
1977 #ifdef CONFIG_ICONV
1978 if (i<3){ // prefer UTF-8 coded
1979 prio++;
1981 #endif
1982 sprintf(tmpresult, "%s%s", j == 0 ? f_dir : path, de->d_name);
1983 // fprintf(stderr, "%s priority %d\n", tmpresult, prio);
1984 if ((f = fopen(tmpresult, "rt"))) {
1985 fclose(f);
1986 result[subcnt].priority = prio;
1987 result[subcnt].fname = strdup(tmpresult);
1988 subcnt++;
1993 if (subcnt >= MAX_SUBTITLE_FILES) break;
1995 closedir(d);
2000 if (tmp_sub_id) free(tmp_sub_id);
2002 free(f_dir);
2003 free(f_fname);
2004 free(f_fname_noext);
2005 free(f_fname_trim);
2007 free(tmp_fname_noext);
2008 free(tmp_fname_trim);
2009 free(tmp_fname_ext);
2011 free(tmpresult);
2013 qsort(result, subcnt, sizeof(subfn), compare_sub_priority);
2015 result2 = malloc(sizeof(char*)*(subcnt+1));
2016 memset(result2, 0, sizeof(char*)*(subcnt+1));
2018 for (i = 0; i < subcnt; i++) {
2019 result2[i] = result[i].fname;
2021 result2[subcnt] = NULL;
2023 free(result);
2025 return result2;
2028 void list_sub_file(sub_data* subd){
2029 int i,j;
2030 subtitle *subs = subd->subtitles;
2032 for(j=0; j < subd->sub_num; j++){
2033 subtitle* egysub=&subs[j];
2034 mp_msg(MSGT_SUBREADER,MSGL_INFO,"%i line%c (%li-%li)\n",
2035 egysub->lines,
2036 (1==egysub->lines)?' ':'s',
2037 egysub->start,
2038 egysub->end);
2039 for (i=0; i<egysub->lines; i++) {
2040 mp_msg(MSGT_SUBREADER,MSGL_INFO,"\t\t%d: %s%s", i,egysub->text[i], i==egysub->lines-1?"":" \n ");
2042 mp_msg(MSGT_SUBREADER,MSGL_INFO,"\n");
2045 mp_msg(MSGT_SUBREADER,MSGL_INFO,"Subtitle format %s time.\n",
2046 subd->sub_uses_time ? "uses":"doesn't use");
2047 mp_msg(MSGT_SUBREADER,MSGL_INFO,"Read %i subtitles, %i errors.\n", subd->sub_num, subd->sub_errs);
2050 void dump_srt(sub_data* subd, float fps){
2051 int i,j;
2052 int h,m,s,ms;
2053 FILE * fd;
2054 subtitle * onesub;
2055 unsigned long temp;
2056 subtitle *subs = subd->subtitles;
2058 if (!subd->sub_uses_time && sub_fps == 0)
2059 sub_fps = fps;
2060 fd=fopen("dumpsub.srt","w");
2061 if(!fd)
2063 perror("dump_srt: fopen");
2064 return;
2066 for(i=0; i < subd->sub_num; i++)
2068 onesub=subs+i; //=&subs[i];
2069 fprintf(fd,"%d\n",i+1);//line number
2071 temp=onesub->start;
2072 if (!subd->sub_uses_time)
2073 temp = temp * 100 / sub_fps;
2074 temp -= sub_delay * 100;
2075 h=temp/360000;temp%=360000; //h =1*100*60*60
2076 m=temp/6000; temp%=6000; //m =1*100*60
2077 s=temp/100; temp%=100; //s =1*100
2078 ms=temp*10; //ms=1*10
2079 fprintf(fd,"%02d:%02d:%02d,%03d --> ",h,m,s,ms);
2081 temp=onesub->end;
2082 if (!subd->sub_uses_time)
2083 temp = temp * 100 / sub_fps;
2084 temp -= sub_delay * 100;
2085 h=temp/360000;temp%=360000;
2086 m=temp/6000; temp%=6000;
2087 s=temp/100; temp%=100;
2088 ms=temp*10;
2089 fprintf(fd,"%02d:%02d:%02d,%03d\n",h,m,s,ms);
2091 for(j=0;j<onesub->lines;j++)
2092 fprintf(fd,"%s\n",onesub->text[j]);
2094 fprintf(fd,"\n");
2096 fclose(fd);
2097 mp_msg(MSGT_SUBREADER,MSGL_INFO,"SUB: Subtitles dumped in \'dumpsub.srt\'.\n");
2100 void dump_mpsub(sub_data* subd, float fps){
2101 int i,j;
2102 FILE *fd;
2103 float a,b;
2104 subtitle *subs = subd->subtitles;
2106 mpsub_position = subd->sub_uses_time? (sub_delay*100) : (sub_delay*fps);
2107 if (sub_fps==0) sub_fps=fps;
2109 fd=fopen ("dump.mpsub", "w");
2110 if (!fd) {
2111 perror ("dump_mpsub: fopen");
2112 return;
2116 if (subd->sub_uses_time) fprintf (fd,"FORMAT=TIME\n\n");
2117 else fprintf (fd, "FORMAT=%5.2f\n\n", fps);
2119 for(j=0; j < subd->sub_num; j++){
2120 subtitle* egysub=&subs[j];
2121 if (subd->sub_uses_time) {
2122 a=((egysub->start-mpsub_position)/100.0);
2123 b=((egysub->end-egysub->start)/100.0);
2124 if ( (float)((int)a) == a)
2125 fprintf (fd, "%.0f",a);
2126 else
2127 fprintf (fd, "%.2f",a);
2129 if ( (float)((int)b) == b)
2130 fprintf (fd, " %.0f\n",b);
2131 else
2132 fprintf (fd, " %.2f\n",b);
2133 } else {
2134 fprintf (fd, "%ld %ld\n", (long)((egysub->start*(fps/sub_fps))-((mpsub_position*(fps/sub_fps)))),
2135 (long)(((egysub->end)-(egysub->start))*(fps/sub_fps)));
2138 mpsub_position = egysub->end;
2139 for (i=0; i<egysub->lines; i++) {
2140 fprintf (fd, "%s\n",egysub->text[i]);
2142 fprintf (fd, "\n");
2144 fclose (fd);
2145 mp_msg(MSGT_SUBREADER,MSGL_INFO,"SUB: Subtitles dumped in \'dump.mpsub\'.\n");
2148 void dump_microdvd(sub_data* subd, float fps) {
2149 int i, delay;
2150 FILE *fd;
2151 subtitle *subs = subd->subtitles;
2152 if (sub_fps == 0)
2153 sub_fps = fps;
2154 fd = fopen("dumpsub.sub", "w");
2155 if (!fd) {
2156 perror("dumpsub.sub: fopen");
2157 return;
2159 delay = sub_delay * sub_fps;
2160 for (i = 0; i < subd->sub_num; ++i) {
2161 int j, start, end;
2162 start = subs[i].start;
2163 end = subs[i].end;
2164 if (subd->sub_uses_time) {
2165 start = start * sub_fps / 100 ;
2166 end = end * sub_fps / 100;
2168 else {
2169 start = start * sub_fps / fps;
2170 end = end * sub_fps / fps;
2172 start -= delay;
2173 end -= delay;
2174 fprintf(fd, "{%d}{%d}", start, end);
2175 for (j = 0; j < subs[i].lines; ++j)
2176 fprintf(fd, "%s%s", j ? "|" : "", subs[i].text[j]);
2177 fprintf(fd, "\n");
2179 fclose(fd);
2180 mp_msg(MSGT_SUBREADER,MSGL_INFO,"SUB: Subtitles dumped in \'dumpsub.sub\'.\n");
2183 void dump_jacosub(sub_data* subd, float fps) {
2184 int i,j;
2185 int h,m,s,cs;
2186 FILE * fd;
2187 subtitle * onesub;
2188 unsigned long temp;
2189 subtitle *subs = subd->subtitles;
2191 if (!subd->sub_uses_time && sub_fps == 0)
2192 sub_fps = fps;
2193 fd=fopen("dumpsub.jss","w");
2194 if(!fd)
2196 perror("dump_jacosub: fopen");
2197 return;
2199 fprintf(fd, "#TIMERES %d\n", (subd->sub_uses_time) ? 100 : (int)sub_fps);
2200 for(i=0; i < subd->sub_num; i++)
2202 onesub=subs+i; //=&subs[i];
2204 temp=onesub->start;
2205 if (!subd->sub_uses_time)
2206 temp = temp * 100 / sub_fps;
2207 temp -= sub_delay * 100;
2208 h=temp/360000;temp%=360000; //h =1*100*60*60
2209 m=temp/6000; temp%=6000; //m =1*100*60
2210 s=temp/100; temp%=100; //s =1*100
2211 cs=temp; //cs=1*10
2212 fprintf(fd,"%02d:%02d:%02d.%02d ",h,m,s,cs);
2214 temp=onesub->end;
2215 if (!subd->sub_uses_time)
2216 temp = temp * 100 / sub_fps;
2217 temp -= sub_delay * 100;
2218 h=temp/360000;temp%=360000;
2219 m=temp/6000; temp%=6000;
2220 s=temp/100; temp%=100;
2221 cs=temp;
2222 fprintf(fd,"%02d:%02d:%02d.%02d {~} ",h,m,s,cs);
2224 for(j=0;j<onesub->lines;j++)
2225 fprintf(fd,"%s%s",j ? "\\n" : "", onesub->text[j]);
2227 fprintf(fd,"\n");
2229 fclose(fd);
2230 mp_msg(MSGT_SUBREADER,MSGL_INFO,"SUB: Subtitles dumped in \'dumpsub.js\'.\n");
2233 void dump_sami(sub_data* subd, float fps) {
2234 int i,j;
2235 FILE * fd;
2236 subtitle * onesub;
2237 unsigned long temp;
2238 subtitle *subs = subd->subtitles;
2240 if (!subd->sub_uses_time && sub_fps == 0)
2241 sub_fps = fps;
2242 fd=fopen("dumpsub.smi","w");
2243 if(!fd)
2245 perror("dump_jacosub: fopen");
2246 return;
2248 fprintf(fd, "<SAMI>\n"
2249 "<HEAD>\n"
2250 " <STYLE TYPE=\"Text/css\">\n"
2251 " <!--\n"
2252 " P {margin-left: 29pt; margin-right: 29pt; font-size: 24pt; text-align: center; font-family: Tahoma; font-weight: bold; color: #FCDD03; background-color: #000000;}\n"
2253 " .SUBTTL {Name: 'Subtitles'; Lang: en-US; SAMIType: CC;}\n"
2254 " -->\n"
2255 " </STYLE>\n"
2256 "</HEAD>\n"
2257 "<BODY>\n");
2258 for(i=0; i < subd->sub_num; i++)
2260 onesub=subs+i; //=&subs[i];
2262 temp=onesub->start;
2263 if (!subd->sub_uses_time)
2264 temp = temp * 100 / sub_fps;
2265 temp -= sub_delay * 100;
2266 fprintf(fd,"\t<SYNC Start=%lu>\n"
2267 "\t <P>", temp * 10);
2269 for(j=0;j<onesub->lines;j++)
2270 fprintf(fd,"%s%s",j ? "<br>" : "", onesub->text[j]);
2272 fprintf(fd,"\n");
2274 temp=onesub->end;
2275 if (!subd->sub_uses_time)
2276 temp = temp * 100 / sub_fps;
2277 temp -= sub_delay * 100;
2278 fprintf(fd,"\t<SYNC Start=%lu>\n"
2279 "\t <P>&nbsp;\n", temp * 10);
2281 fprintf(fd, "</BODY>\n"
2282 "</SAMI>\n");
2283 fclose(fd);
2284 mp_msg(MSGT_SUBREADER,MSGL_INFO,"SUB: Subtitles dumped in \'dumpsub.smi\'.\n");
2287 void sub_free( sub_data * subd )
2289 int i, j;
2291 if ( !subd ) return;
2293 for (i = 0; i < subd->sub_num; i++)
2294 for (j = 0; j < subd->subtitles[i].lines; j++)
2295 free( subd->subtitles[i].text[j] );
2296 free( subd->subtitles );
2297 free( subd->filename );
2298 free( subd );
2301 #define MAX_SUBLINE 512
2303 * \brief parse text and append it to subtitle in sub
2304 * \param sub subtitle struct to add text to
2305 * \param txt text to parse
2306 * \param len length of text in txt
2307 * \param endpts pts at which this subtitle text should be removed again
2309 * <> and {} are interpreted as comment delimiters, "\n", "\N", '\n', '\r'
2310 * and '\0' are interpreted as newlines, duplicate, leading and trailing
2311 * newlines are ignored.
2313 void sub_add_text(subtitle *sub, const char *txt, int len, double endpts) {
2314 int comment = 0;
2315 int double_newline = 1; // ignore newlines at the beginning
2316 int i, pos;
2317 char *buf;
2318 #ifdef CONFIG_FRIBIDI
2319 int orig_lines = sub->lines;
2320 #endif
2321 if (sub->lines >= SUB_MAX_TEXT) return;
2322 pos = 0;
2323 buf = malloc(MAX_SUBLINE + 1);
2324 sub->text[sub->lines] = buf;
2325 sub->endpts[sub->lines] = endpts;
2326 for (i = 0; i < len && pos < MAX_SUBLINE; i++) {
2327 char c = txt[i];
2328 if (c == '<') comment |= 1;
2329 if (c == '{') comment |= 2;
2330 if (comment) {
2331 if (c == '}') comment &= ~2;
2332 if (c == '>') comment &= ~1;
2333 continue;
2335 if (pos == MAX_SUBLINE - 1) {
2336 i--;
2337 c = 0;
2339 if (c == '\\' && i + 1 < len) {
2340 c = txt[++i];
2341 if (c == 'n' || c == 'N') c = 0;
2343 if (c == '\n' || c == '\r') c = 0;
2344 if (c) {
2345 double_newline = 0;
2346 buf[pos++] = c;
2347 } else if (!double_newline) {
2348 if (sub->lines >= SUB_MAX_TEXT - 1) {
2349 mp_msg(MSGT_VO, MSGL_WARN, "Too many subtitle lines\n");
2350 break;
2352 double_newline = 1;
2353 buf[pos] = 0;
2354 sub->lines++;
2355 pos = 0;
2356 buf = malloc(MAX_SUBLINE + 1);
2357 sub->text[sub->lines] = buf;
2358 sub->endpts[sub->lines] = endpts;
2361 buf[pos] = 0;
2362 if (sub->lines < SUB_MAX_TEXT &&
2363 strlen(sub->text[sub->lines]))
2364 sub->lines++;
2365 #ifdef CONFIG_FRIBIDI
2366 sub = sub_fribidi(sub, sub_utf8, orig_lines);
2367 #endif
2370 #define MP_NOPTS_VALUE (-1LL<<63)
2372 * \brief remove outdated subtitle lines.
2373 * \param sub subtitle struct to modify
2374 * \param pts current pts. All lines with endpts <= this will be removed.
2375 * Use MP_NOPTS_VALUE to remove all lines
2376 * \return 1 if sub was modified, 0 otherwise.
2378 int sub_clear_text(subtitle *sub, double pts) {
2379 int i = 0;
2380 int changed = 0;
2381 while (i < sub->lines) {
2382 double endpts = sub->endpts[i];
2383 if (pts == MP_NOPTS_VALUE || (endpts != MP_NOPTS_VALUE && pts >= endpts)) {
2384 int j;
2385 free(sub->text[i]);
2386 for (j = i + 1; j < sub->lines; j++) {
2387 sub->text[j - 1] = sub->text[j];
2388 sub->endpts[j - 1] = sub->endpts[j];
2390 sub->lines--;
2391 changed = 1;
2392 } else
2393 i++;
2395 return changed;