Add -stop-screensaver flag for Windows
[mplayer/kovensky.git] / subreader.c
blobd89e7be826d85760ab7ff22328ec5d51a5c92949
1 /*
2 * Subtitle reader with format autodetection
4 * Written by laaz
5 * Some code cleanup & realloc() by A'rpi/ESP-team
7 */
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <ctype.h>
15 #include <sys/types.h>
16 #include <dirent.h>
18 #include "config.h"
19 #include "mp_msg.h"
20 #include "subreader.h"
21 #include "stream/stream.h"
22 #include "libavutil/common.h"
23 #include "libavutil/avstring.h"
25 #ifdef CONFIG_ENCA
26 #include <enca.h>
27 #endif
29 #define ERR ((void *) -1)
31 #ifdef CONFIG_ICONV
32 #include <iconv.h>
33 char *sub_cp=NULL;
34 #endif
35 #ifdef CONFIG_FRIBIDI
36 #include <fribidi/fribidi.h>
37 char *fribidi_charset = NULL; ///character set that will be passed to FriBiDi
38 int flip_hebrew = 1; ///flip subtitles using fribidi
39 int fribidi_flip_commas = 0; ///flip comma when fribidi is used
40 #endif
42 extern char* dvdsub_lang;
44 /* Maximal length of line of a subtitle */
45 #define LINE_LEN 1000
46 static float mpsub_position=0;
47 static float mpsub_multiplier=1.;
48 static int sub_slacktime = 20000; //20 sec
50 int sub_no_text_pp=0; // 1 => do not apply text post-processing
51 // like {\...} elimination in SSA format.
53 int sub_match_fuzziness=0; // level of sub name matching fuzziness
55 /* Use the SUB_* constant defined in the header file */
56 int sub_format=SUB_INVALID;
57 #ifdef CONFIG_SORTSUB
59 Some subtitling formats, namely AQT and Subrip09, define the end of a
60 subtitle as the beginning of the following. Since currently we read one
61 subtitle at time, for these format we keep two global *subtitle,
62 previous_aqt_sub and previous_subrip09_sub, pointing to previous subtitle,
63 so we can change its end when we read current subtitle starting time.
64 When CONFIG_SORTSUB is defined, we use a single global unsigned long,
65 previous_sub_end, for both (and even future) formats, to store the end of
66 the previous sub: it is initialized to 0 in sub_read_file and eventually
67 modified by sub_read_aqt_line or sub_read_subrip09_line.
69 unsigned long previous_sub_end;
70 #endif
72 static int eol(char p) {
73 return p=='\r' || p=='\n' || p=='\0';
76 /* Remove leading and trailing space */
77 static void trail_space(char *s) {
78 int i = 0;
79 while (isspace(s[i])) ++i;
80 if (i) strcpy(s, s + i);
81 i = strlen(s) - 1;
82 while (i > 0 && isspace(s[i])) s[i--] = '\0';
85 static char *stristr(const char *haystack, const char *needle) {
86 int len = 0;
87 const char *p = haystack;
89 if (!(haystack && needle)) return NULL;
91 len=strlen(needle);
92 while (*p != '\0') {
93 if (strncasecmp(p, needle, len) == 0) return (char*)p;
94 p++;
97 return NULL;
100 static subtitle *sub_read_line_sami(stream_t* st, subtitle *current) {
101 static char line[LINE_LEN+1];
102 static char *s = NULL, *slacktime_s;
103 char text[LINE_LEN+1], *p=NULL, *q;
104 int state;
106 current->lines = current->start = current->end = 0;
107 current->alignment = SUB_ALIGNMENT_BOTTOMCENTER;
108 state = 0;
110 /* read the first line */
111 if (!s)
112 if (!(s = stream_read_line(st, line, LINE_LEN))) return 0;
114 do {
115 switch (state) {
117 case 0: /* find "START=" or "Slacktime:" */
118 slacktime_s = stristr (s, "Slacktime:");
119 if (slacktime_s)
120 sub_slacktime = strtol (slacktime_s+10, NULL, 0) / 10;
122 s = stristr (s, "Start=");
123 if (s) {
124 current->start = strtol (s + 6, &s, 0) / 10;
125 /* eat '>' */
126 for (; *s != '>' && *s != '\0'; s++);
127 s++;
128 state = 1; continue;
130 break;
132 case 1: /* find (optionnal) "<P", skip other TAGs */
133 for (; *s == ' ' || *s == '\t'; s++); /* strip blanks, if any */
134 if (*s == '\0') break;
135 if (*s != '<') { state = 3; p = text; continue; } /* not a TAG */
136 s++;
137 if (*s == 'P' || *s == 'p') { s++; state = 2; continue; } /* found '<P' */
138 for (; *s != '>' && *s != '\0'; s++); /* skip remains of non-<P> TAG */
139 if (s == '\0')
140 break;
141 s++;
142 continue;
144 case 2: /* find ">" */
145 if ((s = strchr (s, '>'))) { s++; state = 3; p = text; continue; }
146 break;
148 case 3: /* get all text until '<' appears */
149 if (*s == '\0') break;
150 else if (!strncasecmp (s, "<br>", 4)) {
151 *p = '\0'; p = text; trail_space (text);
152 if (text[0] != '\0')
153 current->text[current->lines++] = strdup (text);
154 s += 4;
156 else if ((*s == '{') && !sub_no_text_pp) { state = 5; ++s; continue; }
157 else if (*s == '<') { state = 4; }
158 else if (!strncasecmp (s, "&nbsp;", 6)) { *p++ = ' '; s += 6; }
159 else if (*s == '\t') { *p++ = ' '; s++; }
160 else if (*s == '\r' || *s == '\n') { s++; }
161 else *p++ = *s++;
163 /* skip duplicated space */
164 if (p > text + 2) if (*(p-1) == ' ' && *(p-2) == ' ') p--;
166 continue;
168 case 4: /* get current->end or skip <TAG> */
169 q = stristr (s, "Start=");
170 if (q) {
171 current->end = strtol (q + 6, &q, 0) / 10 - 1;
172 *p = '\0'; trail_space (text);
173 if (text[0] != '\0')
174 current->text[current->lines++] = strdup (text);
175 if (current->lines > 0) { state = 99; break; }
176 state = 0; continue;
178 s = strchr (s, '>');
179 if (s) { s++; state = 3; continue; }
180 break;
181 case 5: /* get rid of {...} text, but read the alignment code */
182 if ((*s == '\\') && (*(s + 1) == 'a') && !sub_no_text_pp) {
183 if (stristr(s, "\\a1") != NULL) {
184 current->alignment = SUB_ALIGNMENT_BOTTOMLEFT;
185 s = s + 3;
187 if (stristr(s, "\\a2") != NULL) {
188 current->alignment = SUB_ALIGNMENT_BOTTOMCENTER;
189 s = s + 3;
190 } else if (stristr(s, "\\a3") != NULL) {
191 current->alignment = SUB_ALIGNMENT_BOTTOMRIGHT;
192 s = s + 3;
193 } else if ((stristr(s, "\\a4") != NULL) || (stristr(s, "\\a5") != NULL) || (stristr(s, "\\a8") != NULL)) {
194 current->alignment = SUB_ALIGNMENT_TOPLEFT;
195 s = s + 3;
196 } else if (stristr(s, "\\a6") != NULL) {
197 current->alignment = SUB_ALIGNMENT_TOPCENTER;
198 s = s + 3;
199 } else if (stristr(s, "\\a7") != NULL) {
200 current->alignment = SUB_ALIGNMENT_TOPRIGHT;
201 s = s + 3;
202 } else if (stristr(s, "\\a9") != NULL) {
203 current->alignment = SUB_ALIGNMENT_MIDDLELEFT;
204 s = s + 3;
205 } else if (stristr(s, "\\a10") != NULL) {
206 current->alignment = SUB_ALIGNMENT_MIDDLECENTER;
207 s = s + 4;
208 } else if (stristr(s, "\\a11") != NULL) {
209 current->alignment = SUB_ALIGNMENT_MIDDLERIGHT;
210 s = s + 4;
213 if (*s == '}') state = 3;
214 ++s;
215 continue;
218 /* read next line */
219 if (state != 99 && !(s = stream_read_line (st, line, LINE_LEN))) {
220 if (current->start > 0) {
221 break; // if it is the last subtitle
222 } else {
223 return 0;
227 } while (state != 99);
229 // For the last subtitle
230 if (current->end <= 0) {
231 current->end = current->start + sub_slacktime;
232 *p = '\0'; trail_space (text);
233 if (text[0] != '\0')
234 current->text[current->lines++] = strdup (text);
237 return current;
241 static char *sub_readtext(char *source, char **dest) {
242 int len=0;
243 char *p=source;
245 // printf("src=%p dest=%p \n",source,dest);
247 while ( !eol(*p) && *p!= '|' ) {
248 p++,len++;
251 *dest= malloc (len+1);
252 if (!dest) {return ERR;}
254 strncpy(*dest, source, len);
255 (*dest)[len]=0;
257 while (*p=='\r' || *p=='\n' || *p=='|') p++;
259 if (*p) return p; // not-last text field
260 else return NULL; // last text field
263 static subtitle *sub_read_line_microdvd(stream_t *st,subtitle *current) {
264 char line[LINE_LEN+1];
265 char line2[LINE_LEN+1];
266 char *p, *next;
267 int i;
269 do {
270 if (!stream_read_line (st, line, LINE_LEN)) return NULL;
271 } while ((sscanf (line,
272 "{%ld}{}%[^\r\n]",
273 &(current->start), line2) < 2) &&
274 (sscanf (line,
275 "{%ld}{%ld}%[^\r\n]",
276 &(current->start), &(current->end), line2) < 3));
278 p=line2;
280 next=p, i=0;
281 while ((next =sub_readtext (next, &(current->text[i])))) {
282 if (current->text[i]==ERR) {return ERR;}
283 i++;
284 if (i>=SUB_MAX_TEXT) { mp_msg(MSGT_SUBREADER,MSGL_WARN,"Too many lines in a subtitle\n");current->lines=i;return current;}
286 current->lines= ++i;
288 return current;
291 static subtitle *sub_read_line_mpl2(stream_t *st,subtitle *current) {
292 char line[LINE_LEN+1];
293 char line2[LINE_LEN+1];
294 char *p, *next;
295 int i;
297 do {
298 if (!stream_read_line (st, line, LINE_LEN)) return NULL;
299 } while ((sscanf (line,
300 "[%ld][%ld]%[^\r\n]",
301 &(current->start), &(current->end), line2) < 3));
302 current->start *= 10;
303 current->end *= 10;
304 p=line2;
306 next=p, i=0;
307 while ((next =sub_readtext (next, &(current->text[i])))) {
308 if (current->text[i]==ERR) {return ERR;}
309 i++;
310 if (i>=SUB_MAX_TEXT) { mp_msg(MSGT_SUBREADER,MSGL_WARN,"Too many lines in a subtitle\n");current->lines=i;return current;}
312 current->lines= ++i;
314 return current;
317 static subtitle *sub_read_line_subrip(stream_t* st, subtitle *current) {
318 char line[LINE_LEN+1];
319 int a1,a2,a3,a4,b1,b2,b3,b4;
320 char *p=NULL, *q=NULL;
321 int len;
323 while (1) {
324 if (!stream_read_line (st, line, LINE_LEN)) return NULL;
325 if (sscanf (line, "%d:%d:%d.%d,%d:%d:%d.%d",&a1,&a2,&a3,&a4,&b1,&b2,&b3,&b4) < 8) continue;
326 current->start = a1*360000+a2*6000+a3*100+a4;
327 current->end = b1*360000+b2*6000+b3*100+b4;
329 if (!stream_read_line (st, line, LINE_LEN)) return NULL;
331 p=q=line;
332 for (current->lines=1; current->lines < SUB_MAX_TEXT; current->lines++) {
333 for (q=p,len=0; *p && *p!='\r' && *p!='\n' && *p!='|' && strncmp(p,"[br]",4); p++,len++);
334 current->text[current->lines-1]=malloc (len+1);
335 if (!current->text[current->lines-1]) return ERR;
336 strncpy (current->text[current->lines-1], q, len);
337 current->text[current->lines-1][len]='\0';
338 if (!*p || *p=='\r' || *p=='\n') break;
339 if (*p=='|') p++;
340 else while (*p++!=']');
342 break;
344 return current;
347 static subtitle *sub_read_line_subviewer(stream_t *st,subtitle *current) {
348 char line[LINE_LEN+1];
349 int a1,a2,a3,a4,b1,b2,b3,b4;
350 char *p=NULL;
351 int i,len;
353 while (!current->text[0]) {
354 if (!stream_read_line (st, line, LINE_LEN)) return NULL;
355 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)
356 continue;
357 current->start = a1*360000+a2*6000+a3*100+a4/10;
358 current->end = b1*360000+b2*6000+b3*100+b4/10;
359 for (i=0; i<SUB_MAX_TEXT;) {
360 int blank = 1;
361 if (!stream_read_line (st, line, LINE_LEN)) break;
362 len=0;
363 for (p=line; *p!='\n' && *p!='\r' && *p; p++,len++)
364 if (*p != ' ' && *p != '\t')
365 blank = 0;
366 if (len && !blank) {
367 int j=0,skip=0;
368 char *curptr=current->text[i]=malloc (len+1);
369 if (!current->text[i]) return ERR;
370 //strncpy (current->text[i], line, len); current->text[i][len]='\0';
371 for(; j<len; j++) {
372 /* let's filter html tags ::atmos */
373 if(line[j]=='>') {
374 skip=0;
375 continue;
377 if(line[j]=='<') {
378 skip=1;
379 continue;
381 if(skip) {
382 continue;
384 *curptr=line[j];
385 curptr++;
387 *curptr='\0';
389 i++;
390 } else {
391 break;
394 current->lines=i;
396 return current;
399 static subtitle *sub_read_line_subviewer2(stream_t *st,subtitle *current) {
400 char line[LINE_LEN+1];
401 int a1,a2,a3,a4;
402 char *p=NULL;
403 int i,len;
405 while (!current->text[0]) {
406 if (!stream_read_line (st, line, LINE_LEN)) return NULL;
407 if (line[0]!='{')
408 continue;
409 if ((len=sscanf (line, "{T %d:%d:%d:%d",&a1,&a2,&a3,&a4)) < 4)
410 continue;
411 current->start = a1*360000+a2*6000+a3*100+a4/10;
412 for (i=0; i<SUB_MAX_TEXT;) {
413 if (!stream_read_line (st, line, LINE_LEN)) break;
414 if (line[0]=='}') break;
415 len=0;
416 for (p=line; *p!='\n' && *p!='\r' && *p; ++p,++len);
417 if (len) {
418 current->text[i]=malloc (len+1);
419 if (!current->text[i]) return ERR;
420 strncpy (current->text[i], line, len); current->text[i][len]='\0';
421 ++i;
422 } else {
423 break;
426 current->lines=i;
428 return current;
432 static subtitle *sub_read_line_vplayer(stream_t *st,subtitle *current) {
433 char line[LINE_LEN+1];
434 int a1,a2,a3;
435 char *p=NULL, *next,separator;
436 int i,len,plen;
438 while (!current->text[0]) {
439 if (!stream_read_line (st, line, LINE_LEN)) return NULL;
440 if ((len=sscanf (line, "%d:%d:%d%c%n",&a1,&a2,&a3,&separator,&plen)) < 4)
441 continue;
443 if (!(current->start = a1*360000+a2*6000+a3*100))
444 continue;
445 /* removed by wodzu
446 p=line;
447 // finds the body of the subtitle
448 for (i=0; i<3; i++){
449 p=strchr(p,':');
450 if (p==NULL) break;
451 ++p;
453 if (p==NULL) {
454 printf("SUB: Skipping incorrect subtitle line!\n");
455 continue;
458 // by wodzu: hey! this time we know what length it has! what is
459 // that magic for? it can't deal with space instead of third
460 // colon! look, what simple it can be:
461 p = &line[ plen ];
463 i=0;
464 if (*p!='|') {
466 next = p,i=0;
467 while ((next =sub_readtext (next, &(current->text[i])))) {
468 if (current->text[i]==ERR) {return ERR;}
469 i++;
470 if (i>=SUB_MAX_TEXT) { mp_msg(MSGT_SUBREADER,MSGL_WARN,"Too many lines in a subtitle\n");current->lines=i;return current;}
472 current->lines=i+1;
475 return current;
478 static subtitle *sub_read_line_rt(stream_t *st,subtitle *current) {
479 //TODO: This format uses quite rich (sub/super)set of xhtml
480 // I couldn't check it since DTD is not included.
481 // WARNING: full XML parses can be required for proper parsing
482 char line[LINE_LEN+1];
483 int a1,a2,a3,a4,b1,b2,b3,b4;
484 char *p=NULL,*next=NULL;
485 int i,len,plen;
487 while (!current->text[0]) {
488 if (!stream_read_line (st, line, LINE_LEN)) return NULL;
489 //TODO: it seems that format of time is not easily determined, it may be 1:12, 1:12.0 or 0:1:12.0
490 //to describe the same moment in time. Maybe there are even more formats in use.
491 //if ((len=sscanf (line, "<Time Begin=\"%d:%d:%d.%d\" End=\"%d:%d:%d.%d\"",&a1,&a2,&a3,&a4,&b1,&b2,&b3,&b4)) < 8)
492 plen=a1=a2=a3=a4=b1=b2=b3=b4=0;
493 if (
494 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d.%d\" %*[Ee]nd=\"%d.%d\"%*[^<]<clear/>%n",&a3,&a4,&b3,&b4,&plen)) < 4) &&
495 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d.%d\" %*[Ee]nd=\"%d:%d.%d\"%*[^<]<clear/>%n",&a3,&a4,&b2,&b3,&b4,&plen)) < 5) &&
496 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d:%d\" %*[Ee]nd=\"%d:%d\"%*[^<]<clear/>%n",&a2,&a3,&b2,&b3,&plen)) < 4) &&
497 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d:%d\" %*[Ee]nd=\"%d:%d.%d\"%*[^<]<clear/>%n",&a2,&a3,&b2,&b3,&b4,&plen)) < 5) &&
498 // ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d:%d.%d\" %*[Ee]nd=\"%d:%d\"%*[^<]<clear/>%n",&a2,&a3,&a4,&b2,&b3,&plen)) < 5) &&
499 ((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) &&
500 ((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) &&
501 //now try it without end time
502 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d.%d\"%*[^<]<clear/>%n",&a3,&a4,&plen)) < 2) &&
503 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d:%d\"%*[^<]<clear/>%n",&a2,&a3,&plen)) < 2) &&
504 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d:%d.%d\"%*[^<]<clear/>%n",&a2,&a3,&a4,&plen)) < 3) &&
505 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d:%d:%d.%d\"%*[^<]<clear/>%n",&a1,&a2,&a3,&a4,&plen)) < 4)
507 continue;
508 current->start = a1*360000+a2*6000+a3*100+a4/10;
509 current->end = b1*360000+b2*6000+b3*100+b4/10;
510 if (b1 == 0 && b2 == 0 && b3 == 0 && b4 == 0)
511 current->end = current->start+200;
512 p=line; p+=plen;i=0;
513 // TODO: I don't know what kind of convention is here for marking multiline subs, maybe <br/> like in xml?
514 next = strstr(line,"<clear/>");
515 if(next && strlen(next)>8){
516 next+=8;i=0;
517 while ((next =sub_readtext (next, &(current->text[i])))) {
518 if (current->text[i]==ERR) {return ERR;}
519 i++;
520 if (i>=SUB_MAX_TEXT) { mp_msg(MSGT_SUBREADER,MSGL_WARN,"Too many lines in a subtitle\n");current->lines=i;return current;}
523 current->lines=i+1;
525 return current;
528 static subtitle *sub_read_line_ssa(stream_t *st,subtitle *current) {
530 * Sub Station Alpha v4 (and v2?) scripts have 9 commas before subtitle
531 * other Sub Station Alpha scripts have only 8 commas before subtitle
532 * Reading the "ScriptType:" field is not reliable since many scripts appear
533 * w/o it
535 * http://www.scriptclub.org is a good place to find more examples
536 * http://www.eswat.demon.co.uk is where the SSA specs can be found
538 int comma;
539 static int max_comma = 32; /* let's use 32 for the case that the */
540 /* amount of commas increase with newer SSA versions */
542 int hour1, min1, sec1, hunsec1,
543 hour2, min2, sec2, hunsec2, nothing;
544 int num;
546 char line[LINE_LEN+1],
547 line3[LINE_LEN+1],
548 *line2;
549 char *tmp;
551 do {
552 if (!stream_read_line (st, line, LINE_LEN)) return NULL;
553 } while (sscanf (line, "Dialogue: Marked=%d,%d:%d:%d.%d,%d:%d:%d.%d,"
554 "%[^\n\r]", &nothing,
555 &hour1, &min1, &sec1, &hunsec1,
556 &hour2, &min2, &sec2, &hunsec2,
557 line3) < 9
559 sscanf (line, "Dialogue: %d,%d:%d:%d.%d,%d:%d:%d.%d,"
560 "%[^\n\r]", &nothing,
561 &hour1, &min1, &sec1, &hunsec1,
562 &hour2, &min2, &sec2, &hunsec2,
563 line3) < 9 );
565 line2=strchr(line3, ',');
567 for (comma = 4; comma < max_comma; comma ++)
569 tmp = line2;
570 if(!(tmp=strchr(++tmp, ','))) break;
571 if(*(++tmp) == ' ') break;
572 /* a space after a comma means we're already in a sentence */
573 line2 = tmp;
576 if(comma < max_comma)max_comma = comma;
577 /* eliminate the trailing comma */
578 if(*line2 == ',') line2++;
580 current->lines=0;num=0;
581 current->start = 360000*hour1 + 6000*min1 + 100*sec1 + hunsec1;
582 current->end = 360000*hour2 + 6000*min2 + 100*sec2 + hunsec2;
584 while (((tmp=strstr(line2, "\\n")) != NULL) || ((tmp=strstr(line2, "\\N")) != NULL) ){
585 current->text[num]=malloc(tmp-line2+1);
586 strncpy (current->text[num], line2, tmp-line2);
587 current->text[num][tmp-line2]='\0';
588 line2=tmp+2;
589 num++;
590 current->lines++;
591 if (current->lines >= SUB_MAX_TEXT) return current;
594 current->text[num]=strdup(line2);
595 current->lines++;
597 return current;
600 static void sub_pp_ssa(subtitle *sub) {
601 int l=sub->lines;
602 char *so,*de,*start;
604 while (l){
605 /* eliminate any text enclosed with {}, they are font and color settings */
606 so=de=sub->text[--l];
607 while (*so) {
608 if(*so == '{' && so[1]=='\\') {
609 for (start=so; *so && *so!='}'; so++);
610 if(*so) so++; else so=start;
612 if(*so) {
613 *de=*so;
614 so++; de++;
617 *de=*so;
622 * PJS subtitles reader.
623 * That's the "Phoenix Japanimation Society" format.
624 * I found some of them in http://www.scriptsclub.org/ (used for anime).
625 * The time is in tenths of second.
627 * by set, based on code by szabi (dunnowhat sub format ;-)
629 static subtitle *sub_read_line_pjs(stream_t *st,subtitle *current) {
630 char line[LINE_LEN+1];
631 char text[LINE_LEN+1], *s, *d;
633 if (!stream_read_line (st, line, LINE_LEN))
634 return NULL;
635 /* skip spaces */
636 for (s=line; *s && isspace(*s); s++);
637 /* allow empty lines at the end of the file */
638 if (*s==0)
639 return NULL;
640 /* get the time */
641 if (sscanf (s, "%ld,%ld,", &(current->start),
642 &(current->end)) <2) {
643 return ERR;
645 /* the files I have are in tenths of second */
646 current->start *= 10;
647 current->end *= 10;
648 /* walk to the beggining of the string */
649 for (; *s; s++) if (*s==',') break;
650 if (*s) {
651 for (s++; *s; s++) if (*s==',') break;
652 if (*s) s++;
654 if (*s!='"') {
655 return ERR;
657 /* copy the string to the text buffer */
658 for (s++, d=text; *s && *s!='"'; s++, d++)
659 *d=*s;
660 *d=0;
661 current->text[0] = strdup(text);
662 current->lines = 1;
664 return current;
667 static subtitle *sub_read_line_mpsub(stream_t *st, subtitle *current) {
668 char line[LINE_LEN+1];
669 float a,b;
670 int num=0;
671 char *p, *q;
675 if (!stream_read_line(st, line, LINE_LEN)) return NULL;
676 } while (sscanf (line, "%f %f", &a, &b) !=2);
678 mpsub_position += a*mpsub_multiplier;
679 current->start=(int) mpsub_position;
680 mpsub_position += b*mpsub_multiplier;
681 current->end=(int) mpsub_position;
683 while (num < SUB_MAX_TEXT) {
684 if (!stream_read_line (st, line, LINE_LEN)) {
685 if (num == 0) return NULL;
686 else return current;
688 p=line;
689 while (isspace(*p)) p++;
690 if (eol(*p) && num > 0) return current;
691 if (eol(*p)) return NULL;
693 for (q=p; !eol(*q); q++);
694 *q='\0';
695 if (strlen(p)) {
696 current->text[num]=strdup(p);
697 // printf (">%s<\n",p);
698 current->lines = ++num;
699 } else {
700 if (num) return current;
701 else return NULL;
704 return NULL; // we should have returned before if it's OK
707 #ifndef CONFIG_SORTSUB
708 //we don't need this if we use previous_sub_end
709 subtitle *previous_aqt_sub = NULL;
710 #endif
712 static subtitle *sub_read_line_aqt(stream_t *st,subtitle *current) {
713 char line[LINE_LEN+1];
714 char *next;
715 int i;
717 while (1) {
718 // try to locate next subtitle
719 if (!stream_read_line (st, line, LINE_LEN))
720 return NULL;
721 if (!(sscanf (line, "-->> %ld", &(current->start)) <1))
722 break;
725 #ifdef CONFIG_SORTSUB
726 previous_sub_end = (current->start) ? current->start - 1 : 0;
727 #else
728 if (previous_aqt_sub != NULL)
729 previous_aqt_sub->end = current->start-1;
731 previous_aqt_sub = current;
732 #endif
734 if (!stream_read_line (st, line, LINE_LEN))
735 return NULL;
737 sub_readtext((char *) &line,&current->text[0]);
738 current->lines = 1;
739 current->end = current->start; // will be corrected by next subtitle
741 if (!stream_read_line (st, line, LINE_LEN))
742 return current;
744 next = line,i=1;
745 while ((next =sub_readtext (next, &(current->text[i])))) {
746 if (current->text[i]==ERR) {return ERR;}
747 i++;
748 if (i>=SUB_MAX_TEXT) { mp_msg(MSGT_SUBREADER,MSGL_WARN,"Too many lines in a subtitle\n");current->lines=i;return current;}
750 current->lines=i+1;
752 if (!strlen(current->text[0]) && !strlen(current->text[1])) {
753 #ifdef CONFIG_SORTSUB
754 previous_sub_end = 0;
755 #else
756 // void subtitle -> end of previous marked and exit
757 previous_aqt_sub = NULL;
758 #endif
759 return NULL;
762 return current;
765 #ifndef CONFIG_SORTSUB
766 subtitle *previous_subrip09_sub = NULL;
767 #endif
769 static subtitle *sub_read_line_subrip09(stream_t *st,subtitle *current) {
770 char line[LINE_LEN+1];
771 int a1,a2,a3;
772 char * next=NULL;
773 int i,len;
775 while (1) {
776 // try to locate next subtitle
777 if (!stream_read_line (st, line, LINE_LEN))
778 return NULL;
779 if (!((len=sscanf (line, "[%d:%d:%d]",&a1,&a2,&a3)) < 3))
780 break;
783 current->start = a1*360000+a2*6000+a3*100;
785 #ifdef CONFIG_SORTSUB
786 previous_sub_end = (current->start) ? current->start - 1 : 0;
787 #else
788 if (previous_subrip09_sub != NULL)
789 previous_subrip09_sub->end = current->start-1;
791 previous_subrip09_sub = current;
792 #endif
794 if (!stream_read_line (st, line, LINE_LEN))
795 return NULL;
797 next = line,i=0;
799 current->text[0]=""; // just to be sure that string is clear
801 while ((next =sub_readtext (next, &(current->text[i])))) {
802 if (current->text[i]==ERR) {return ERR;}
803 i++;
804 if (i>=SUB_MAX_TEXT) { mp_msg(MSGT_SUBREADER,MSGL_WARN,"Too many lines in a subtitle\n");current->lines=i;return current;}
806 current->lines=i+1;
808 if (!strlen(current->text[0]) && (i==0)) {
809 #ifdef CONFIG_SORTSUB
810 previous_sub_end = 0;
811 #else
812 // void subtitle -> end of previous marked and exit
813 previous_subrip09_sub = NULL;
814 #endif
815 return NULL;
818 return current;
821 static subtitle *sub_read_line_jacosub(stream_t* st, subtitle * current)
823 char line1[LINE_LEN], line2[LINE_LEN], directive[LINE_LEN], *p, *q;
824 unsigned a1, a2, a3, a4, b1, b2, b3, b4, comment = 0;
825 static unsigned jacoTimeres = 30;
826 static int jacoShift = 0;
828 memset(current, 0, sizeof(subtitle));
829 memset(line1, 0, LINE_LEN);
830 memset(line2, 0, LINE_LEN);
831 memset(directive, 0, LINE_LEN);
832 while (!current->text[0]) {
833 if (!stream_read_line(st, line1, LINE_LEN)) {
834 return NULL;
836 if (sscanf
837 (line1, "%u:%u:%u.%u %u:%u:%u.%u %[^\n\r]", &a1, &a2, &a3, &a4,
838 &b1, &b2, &b3, &b4, line2) < 9) {
839 if (sscanf(line1, "@%u @%u %[^\n\r]", &a4, &b4, line2) < 3) {
840 if (line1[0] == '#') {
841 int hours = 0, minutes = 0, seconds, delta, inverter =
843 unsigned units = jacoShift;
844 switch (toupper(line1[1])) {
845 case 'S':
846 if (isalpha(line1[2])) {
847 delta = 6;
848 } else {
849 delta = 2;
851 if (sscanf(&line1[delta], "%d", &hours)) {
852 if (hours < 0) {
853 hours *= -1;
854 inverter = -1;
856 if (sscanf(&line1[delta], "%*d:%d", &minutes)) {
857 if (sscanf
858 (&line1[delta], "%*d:%*d:%d",
859 &seconds)) {
860 sscanf(&line1[delta], "%*d:%*d:%*d.%d",
861 &units);
862 } else {
863 hours = 0;
864 sscanf(&line1[delta], "%d:%d.%d",
865 &minutes, &seconds, &units);
866 minutes *= inverter;
868 } else {
869 hours = minutes = 0;
870 sscanf(&line1[delta], "%d.%d", &seconds,
871 &units);
872 seconds *= inverter;
874 jacoShift =
875 ((hours * 3600 + minutes * 60 +
876 seconds) * jacoTimeres +
877 units) * inverter;
879 break;
880 case 'T':
881 if (isalpha(line1[2])) {
882 delta = 8;
883 } else {
884 delta = 2;
886 sscanf(&line1[delta], "%u", &jacoTimeres);
887 break;
890 continue;
891 } else {
892 current->start =
893 (unsigned long) ((a4 + jacoShift) * 100.0 /
894 jacoTimeres);
895 current->end =
896 (unsigned long) ((b4 + jacoShift) * 100.0 /
897 jacoTimeres);
899 } else {
900 current->start =
901 (unsigned
902 long) (((a1 * 3600 + a2 * 60 + a3) * jacoTimeres + a4 +
903 jacoShift) * 100.0 / jacoTimeres);
904 current->end =
905 (unsigned
906 long) (((b1 * 3600 + b2 * 60 + b3) * jacoTimeres + b4 +
907 jacoShift) * 100.0 / jacoTimeres);
909 current->lines = 0;
910 p = line2;
911 while ((*p == ' ') || (*p == '\t')) {
912 ++p;
914 if (isalpha(*p)||*p == '[') {
915 int cont, jLength;
917 if (sscanf(p, "%s %[^\n\r]", directive, line1) < 2)
918 return (subtitle *) ERR;
919 jLength = strlen(directive);
920 for (cont = 0; cont < jLength; ++cont) {
921 if (isalpha(*(directive + cont)))
922 *(directive + cont) = toupper(*(directive + cont));
924 if ((strstr(directive, "RDB") != NULL)
925 || (strstr(directive, "RDC") != NULL)
926 || (strstr(directive, "RLB") != NULL)
927 || (strstr(directive, "RLG") != NULL)) {
928 continue;
930 if (strstr(directive, "JL") != NULL) {
931 current->alignment = SUB_ALIGNMENT_BOTTOMLEFT;
932 } else if (strstr(directive, "JR") != NULL) {
933 current->alignment = SUB_ALIGNMENT_BOTTOMRIGHT;
934 } else {
935 current->alignment = SUB_ALIGNMENT_BOTTOMCENTER;
937 strcpy(line2, line1);
938 p = line2;
940 for (q = line1; (!eol(*p)) && (current->lines < SUB_MAX_TEXT); ++p) {
941 switch (*p) {
942 case '{':
943 comment++;
944 break;
945 case '}':
946 if (comment) {
947 --comment;
948 //the next line to get rid of a blank after the comment
949 if ((*(p + 1)) == ' ')
950 p++;
952 break;
953 case '~':
954 if (!comment) {
955 *q = ' ';
956 ++q;
958 break;
959 case ' ':
960 case '\t':
961 if ((*(p + 1) == ' ') || (*(p + 1) == '\t'))
962 break;
963 if (!comment) {
964 *q = ' ';
965 ++q;
967 break;
968 case '\\':
969 if (*(p + 1) == 'n') {
970 *q = '\0';
971 q = line1;
972 current->text[current->lines++] = strdup(line1);
973 ++p;
974 break;
976 if ((toupper(*(p + 1)) == 'C')
977 || (toupper(*(p + 1)) == 'F')) {
978 ++p,++p;
979 break;
981 if ((*(p + 1) == 'B') || (*(p + 1) == 'b') || (*(p + 1) == 'D') || //actually this means "insert current date here"
982 (*(p + 1) == 'I') || (*(p + 1) == 'i') || (*(p + 1) == 'N') || (*(p + 1) == 'T') || //actually this means "insert current time here"
983 (*(p + 1) == 'U') || (*(p + 1) == 'u')) {
984 ++p;
985 break;
987 if ((*(p + 1) == '\\') ||
988 (*(p + 1) == '~') || (*(p + 1) == '{')) {
989 ++p;
990 } else if (eol(*(p + 1))) {
991 if (!stream_read_line(st, directive, LINE_LEN))
992 return NULL;
993 trail_space(directive);
994 av_strlcat(line2, directive, LINE_LEN);
995 break;
997 default:
998 if (!comment) {
999 *q = *p;
1000 ++q;
1002 } //-- switch
1003 } //-- for
1004 *q = '\0';
1005 current->text[current->lines] = strdup(line1);
1006 } //-- while
1007 current->lines++;
1008 return current;
1011 static int sub_autodetect (stream_t* st, int *uses_time) {
1012 char line[LINE_LEN+1];
1013 int i,j=0;
1014 char p;
1016 while (j < 100) {
1017 j++;
1018 if (!stream_read_line (st, line, LINE_LEN))
1019 return SUB_INVALID;
1021 if (sscanf (line, "{%d}{%d}", &i, &i)==2)
1022 {*uses_time=0;return SUB_MICRODVD;}
1023 if (sscanf (line, "{%d}{}", &i)==1)
1024 {*uses_time=0;return SUB_MICRODVD;}
1025 if (sscanf (line, "[%d][%d]", &i, &i)==2)
1026 {*uses_time=1;return SUB_MPL2;}
1027 if (sscanf (line, "%d:%d:%d.%d,%d:%d:%d.%d", &i, &i, &i, &i, &i, &i, &i, &i)==8)
1028 {*uses_time=1;return SUB_SUBRIP;}
1029 if (sscanf (line, "%d:%d:%d%[,.:]%d --> %d:%d:%d%[,.:]%d", &i, &i, &i, (char *)&i, &i, &i, &i, &i, (char *)&i, &i)==10)
1030 {*uses_time=1;return SUB_SUBVIEWER;}
1031 if (sscanf (line, "{T %d:%d:%d:%d",&i, &i, &i, &i)==4)
1032 {*uses_time=1;return SUB_SUBVIEWER2;}
1033 if (strstr (line, "<SAMI>"))
1034 {*uses_time=1; return SUB_SAMI;}
1035 if (sscanf(line, "%d:%d:%d.%d %d:%d:%d.%d", &i, &i, &i, &i, &i, &i, &i, &i) == 8)
1036 {*uses_time = 1; return SUB_JACOSUB;}
1037 if (sscanf(line, "@%d @%d", &i, &i) == 2)
1038 {*uses_time = 1; return SUB_JACOSUB;}
1039 if (sscanf (line, "%d:%d:%d:", &i, &i, &i )==3)
1040 {*uses_time=1;return SUB_VPLAYER;}
1041 if (sscanf (line, "%d:%d:%d ", &i, &i, &i )==3)
1042 {*uses_time=1;return SUB_VPLAYER;}
1043 //TODO: just checking if first line of sub starts with "<" is WAY
1044 // too weak test for RT
1045 // Please someone who knows the format of RT... FIX IT!!!
1046 // It may conflict with other sub formats in the future (actually it doesn't)
1047 if ( *line == '<' )
1048 {*uses_time=1;return SUB_RT;}
1050 if (!memcmp(line, "Dialogue: Marked", 16))
1051 {*uses_time=1; return SUB_SSA;}
1052 if (!memcmp(line, "Dialogue: ", 10))
1053 {*uses_time=1; return SUB_SSA;}
1054 if (sscanf (line, "%d,%d,\"%c", &i, &i, (char *) &i) == 3)
1055 {*uses_time=1;return SUB_PJS;}
1056 if (sscanf (line, "FORMAT=%d", &i) == 1)
1057 {*uses_time=0; return SUB_MPSUB;}
1058 if (sscanf (line, "FORMAT=TIM%c", &p)==1 && p=='E')
1059 {*uses_time=1; return SUB_MPSUB;}
1060 if (strstr (line, "-->>"))
1061 {*uses_time=0; return SUB_AQTITLE;}
1062 if (sscanf (line, "[%d:%d:%d]", &i, &i, &i)==3)
1063 {*uses_time=1;return SUB_SUBRIP09;}
1066 return SUB_INVALID; // too many bad lines
1069 extern int sub_utf8;
1070 int sub_utf8_prev=0;
1072 extern float sub_delay;
1073 extern float sub_fps;
1075 #ifdef CONFIG_ICONV
1076 static iconv_t icdsc = (iconv_t)(-1);
1078 void subcp_open (stream_t *st)
1080 char *tocp = "UTF-8";
1082 if (sub_cp){
1083 const char *cp_tmp = sub_cp;
1084 #ifdef CONFIG_ENCA
1085 char enca_lang[3], enca_fallback[100];
1086 if (sscanf(sub_cp, "enca:%2s:%99s", enca_lang, enca_fallback) == 2
1087 || sscanf(sub_cp, "ENCA:%2s:%99s", enca_lang, enca_fallback) == 2) {
1088 if (st && st->flags & MP_STREAM_SEEK ) {
1089 cp_tmp = guess_cp(st, enca_lang, enca_fallback);
1090 } else {
1091 cp_tmp = enca_fallback;
1092 if (st)
1093 mp_msg(MSGT_SUBREADER,MSGL_WARN,"SUB: enca failed, stream must be seekable.\n");
1096 #endif
1097 if ((icdsc = iconv_open (tocp, cp_tmp)) != (iconv_t)(-1)){
1098 mp_msg(MSGT_SUBREADER,MSGL_V,"SUB: opened iconv descriptor.\n");
1099 sub_utf8 = 2;
1100 } else
1101 mp_msg(MSGT_SUBREADER,MSGL_ERR,"SUB: error opening iconv descriptor.\n");
1105 void subcp_close (void)
1107 if (icdsc != (iconv_t)(-1)){
1108 (void) iconv_close (icdsc);
1109 icdsc = (iconv_t)(-1);
1110 mp_msg(MSGT_SUBREADER,MSGL_V,"SUB: closed iconv descriptor.\n");
1114 subtitle* subcp_recode (subtitle *sub)
1116 int l=sub->lines;
1117 size_t ileft, oleft;
1118 char *op, *ip, *ot;
1119 if(icdsc == (iconv_t)(-1)) return sub;
1121 while (l){
1122 ip = sub->text[--l];
1123 ileft = strlen(ip);
1124 oleft = 4 * ileft;
1126 if (!(ot = malloc(oleft + 1))){
1127 mp_msg(MSGT_SUBREADER,MSGL_WARN,"SUB: error allocating mem.\n");
1128 continue;
1130 op = ot;
1131 if (iconv(icdsc, &ip, &ileft,
1132 &op, &oleft) == (size_t)(-1)) {
1133 mp_msg(MSGT_SUBREADER,MSGL_WARN,"SUB: error recoding line.\n");
1134 free(ot);
1135 continue;
1137 // In some stateful encodings, we must clear the state to handle the last character
1138 if (iconv(icdsc, NULL, NULL,
1139 &op, &oleft) == (size_t)(-1)) {
1140 mp_msg(MSGT_SUBREADER,MSGL_WARN,"SUB: error recoding line, can't clear encoding state.\n");
1142 *op='\0' ;
1143 free (sub->text[l]);
1144 sub->text[l] = ot;
1146 return sub;
1148 #endif
1150 #ifdef CONFIG_FRIBIDI
1152 * Do conversion necessary for right-to-left language support via fribidi.
1153 * @param sub subtitle to convert
1154 * @param sub_utf8 whether the subtitle is encoded in UTF-8
1155 * @param from first new subtitle, all lines before this are assumed to be already converted
1157 static subtitle* sub_fribidi (subtitle *sub, int sub_utf8, int from)
1159 FriBidiChar logical[LINE_LEN+1], visual[LINE_LEN+1]; // Hopefully these two won't smash the stack
1160 char *ip = NULL, *op = NULL;
1161 FriBidiCharType base;
1162 size_t len,orig_len;
1163 int l=sub->lines;
1164 int char_set_num;
1165 fribidi_boolean log2vis;
1166 if (!flip_hebrew)
1167 return sub;
1168 fribidi_set_mirroring(1);
1169 fribidi_set_reorder_nsm(0);
1171 if( sub_utf8 == 0 ) {
1172 char_set_num = fribidi_parse_charset (fribidi_charset?fribidi_charset:"ISO8859-8");
1173 }else {
1174 char_set_num = fribidi_parse_charset ("UTF-8");
1176 while (l > from) {
1177 ip = sub->text[--l];
1178 orig_len = len = strlen( ip ); // We assume that we don't use full unicode, only UTF-8 or ISO8859-x
1179 if(len > LINE_LEN) {
1180 mp_msg(MSGT_SUBREADER,MSGL_WARN,"SUB: sub->text is longer than LINE_LEN.\n");
1181 l++;
1182 break;
1184 len = fribidi_charset_to_unicode (char_set_num, ip, len, logical);
1185 base = fribidi_flip_commas?FRIBIDI_TYPE_ON:FRIBIDI_TYPE_L;
1186 log2vis = fribidi_log2vis (logical, len, &base,
1187 /* output */
1188 visual, NULL, NULL, NULL);
1189 if(log2vis) {
1190 len = fribidi_remove_bidi_marks (visual, len, NULL, NULL,
1191 NULL);
1192 if((op = malloc((FFMAX(2*orig_len,2*len) + 1))) == NULL) {
1193 mp_msg(MSGT_SUBREADER,MSGL_WARN,"SUB: error allocating mem.\n");
1194 l++;
1195 break;
1197 fribidi_unicode_to_charset ( char_set_num, visual, len,op);
1198 free (ip);
1199 sub->text[l] = op;
1202 if (!from && l){
1203 for (l = sub->lines; l;)
1204 free (sub->text[--l]);
1205 return ERR;
1207 return sub;
1210 #endif
1212 static void adjust_subs_time(subtitle* sub, float subtime, float fps, int block,
1213 int sub_num, int sub_uses_time) {
1214 int n,m;
1215 subtitle* nextsub;
1216 int i = sub_num;
1217 unsigned long subfms = (sub_uses_time ? 100 : fps) * subtime;
1218 unsigned long overlap = (sub_uses_time ? 100 : fps) / 5; // 0.2s
1220 n=m=0;
1221 if (i) for (;;){
1222 if (sub->end <= sub->start){
1223 sub->end = sub->start + subfms;
1224 m++;
1225 n++;
1227 if (!--i) break;
1228 nextsub = sub + 1;
1229 if(block){
1230 if ((sub->end > nextsub->start) && (sub->end <= nextsub->start + overlap)) {
1231 // these subtitles overlap for less than 0.2 seconds
1232 // and would result in very short overlapping subtitle
1233 // so let's fix the problem here, before overlapping code
1234 // get its hands on them
1235 unsigned delta = sub->end - nextsub->start, half = delta / 2;
1236 sub->end -= half + 1;
1237 nextsub->start += delta - half;
1239 if (sub->end >= nextsub->start){
1240 sub->end = nextsub->start - 1;
1241 if (sub->end - sub->start > subfms)
1242 sub->end = sub->start + subfms;
1243 if (!m)
1244 n++;
1248 /* Theory:
1249 * Movies are often converted from FILM (24 fps)
1250 * to PAL (25) by simply speeding it up, so we
1251 * to multiply the original timestmaps by
1252 * (Movie's FPS / Subtitle's (guessed) FPS)
1253 * so eg. for 23.98 fps movie and PAL time based
1254 * subtitles we say -subfps 25 and we're fine!
1257 /* timed sub fps correction ::atmos */
1258 /* the frame-based case is handled in mpcommon.c
1259 * where find_sub is called */
1260 if(sub_uses_time && sub_fps) {
1261 sub->start *= sub_fps/fps;
1262 sub->end *= sub_fps/fps;
1265 sub = nextsub;
1266 m = 0;
1268 if (n) mp_msg(MSGT_SUBREADER,MSGL_V,"SUB: Adjusted %d subtitle(s).\n", n);
1271 struct subreader {
1272 subtitle * (*read)(stream_t *st,subtitle *dest);
1273 void (*post)(subtitle *dest);
1274 const char *name;
1277 #ifdef CONFIG_ENCA
1278 const char* guess_buffer_cp(unsigned char* buffer, int buflen, const char *preferred_language, const char *fallback)
1280 const char **languages;
1281 size_t langcnt;
1282 EncaAnalyser analyser;
1283 EncaEncoding encoding;
1284 const char *detected_sub_cp = NULL;
1285 int i;
1287 languages = enca_get_languages(&langcnt);
1288 mp_msg(MSGT_SUBREADER, MSGL_V, "ENCA supported languages: ");
1289 for (i = 0; i < langcnt; i++) {
1290 mp_msg(MSGT_SUBREADER, MSGL_V, "%s ", languages[i]);
1292 mp_msg(MSGT_SUBREADER, MSGL_V, "\n");
1294 for (i = 0; i < langcnt; i++) {
1295 if (strcasecmp(languages[i], preferred_language) != 0) continue;
1296 analyser = enca_analyser_alloc(languages[i]);
1297 encoding = enca_analyse_const(analyser, buffer, buflen);
1298 enca_analyser_free(analyser);
1299 if (encoding.charset != ENCA_CS_UNKNOWN) {
1300 detected_sub_cp = enca_charset_name(encoding.charset, ENCA_NAME_STYLE_ICONV);
1301 break;
1305 free(languages);
1307 if (!detected_sub_cp) {
1308 detected_sub_cp = fallback;
1309 mp_msg(MSGT_SUBREADER, MSGL_INFO, "ENCA detection failed: fallback to %s\n", fallback);
1310 }else{
1311 mp_msg(MSGT_SUBREADER, MSGL_INFO, "ENCA detected charset: %s\n", detected_sub_cp);
1314 return detected_sub_cp;
1317 #define MAX_GUESS_BUFFER_SIZE (256*1024)
1318 const char* guess_cp(stream_t *st, const char *preferred_language, const char *fallback)
1320 size_t buflen;
1321 unsigned char *buffer;
1322 const char *detected_sub_cp = NULL;
1324 buffer = malloc(MAX_GUESS_BUFFER_SIZE);
1325 buflen = stream_read(st,buffer, MAX_GUESS_BUFFER_SIZE);
1327 detected_sub_cp = guess_buffer_cp(buffer, buflen, preferred_language, fallback);
1329 free(buffer);
1330 stream_reset(st);
1331 stream_seek(st,0);
1333 return detected_sub_cp;
1335 #undef MAX_GUESS_BUFFER_SIZE
1336 #endif
1338 sub_data* sub_read_file (char *filename, float fps) {
1339 stream_t* fd;
1340 int n_max, n_first, i, j, sub_first, sub_orig;
1341 subtitle *first, *second, *sub, *return_sub, *alloced_sub = NULL;
1342 sub_data *subt_data;
1343 int uses_time = 0, sub_num = 0, sub_errs = 0;
1344 struct subreader sr[]=
1346 { sub_read_line_microdvd, NULL, "microdvd" },
1347 { sub_read_line_subrip, NULL, "subrip" },
1348 { sub_read_line_subviewer, NULL, "subviewer" },
1349 { sub_read_line_sami, NULL, "sami" },
1350 { sub_read_line_vplayer, NULL, "vplayer" },
1351 { sub_read_line_rt, NULL, "rt" },
1352 { sub_read_line_ssa, sub_pp_ssa, "ssa" },
1353 { sub_read_line_pjs, NULL, "pjs" },
1354 { sub_read_line_mpsub, NULL, "mpsub" },
1355 { sub_read_line_aqt, NULL, "aqt" },
1356 { sub_read_line_subviewer2, NULL, "subviewer 2.0" },
1357 { sub_read_line_subrip09, NULL, "subrip 0.9" },
1358 { sub_read_line_jacosub, NULL, "jacosub" },
1359 { sub_read_line_mpl2, NULL, "mpl2" }
1361 struct subreader *srp;
1363 if(filename==NULL) return NULL; //qnx segfault
1364 i = 0;
1365 fd=open_stream (filename, NULL, &i); if (!fd) return NULL;
1367 sub_format=sub_autodetect (fd, &uses_time);
1368 mpsub_multiplier = (uses_time ? 100.0 : 1.0);
1369 if (sub_format==SUB_INVALID) {mp_msg(MSGT_SUBREADER,MSGL_WARN,"SUB: Could not determine file format\n");return NULL;}
1370 srp=sr+sub_format;
1371 mp_msg(MSGT_SUBREADER, MSGL_V, "SUB: Detected subtitle file format: %s\n", srp->name);
1373 stream_reset(fd);
1374 stream_seek(fd,0);
1376 #ifdef CONFIG_ICONV
1377 sub_utf8_prev=sub_utf8;
1379 int l,k;
1380 k = -1;
1381 if ((l=strlen(filename))>4){
1382 char *exts[] = {".utf", ".utf8", ".utf-8" };
1383 for (k=3;--k>=0;)
1384 if (l >= strlen(exts[k]) && !strcasecmp(filename+(l - strlen(exts[k])), exts[k])){
1385 sub_utf8 = 1;
1386 break;
1389 if (k<0) subcp_open(fd);
1391 #endif
1393 sub_num=0;n_max=32;
1394 first=malloc(n_max*sizeof(subtitle));
1395 if(!first){
1396 #ifdef CONFIG_ICONV
1397 subcp_close();
1398 sub_utf8=sub_utf8_prev;
1399 #endif
1400 return NULL;
1403 #ifdef CONFIG_SORTSUB
1404 alloced_sub =
1405 sub = malloc(sizeof(subtitle));
1406 //This is to deal with those formats (AQT & Subrip) which define the end of a subtitle
1407 //as the beginning of the following
1408 previous_sub_end = 0;
1409 #endif
1410 while(1){
1411 if(sub_num>=n_max){
1412 n_max+=16;
1413 first=realloc(first,n_max*sizeof(subtitle));
1415 #ifndef CONFIG_SORTSUB
1416 sub = &first[sub_num];
1417 #endif
1418 memset(sub, '\0', sizeof(subtitle));
1419 sub=srp->read(fd,sub);
1420 if(!sub) break; // EOF
1421 #ifdef CONFIG_ICONV
1422 if ((sub!=ERR) && (sub_utf8 & 2)) sub=subcp_recode(sub);
1423 #endif
1424 #ifdef CONFIG_FRIBIDI
1425 if (sub!=ERR) sub=sub_fribidi(sub,sub_utf8,0);
1426 #endif
1427 if ( sub == ERR )
1429 #ifdef CONFIG_ICONV
1430 subcp_close();
1431 #endif
1432 if ( first ) free(first);
1433 free(alloced_sub);
1434 return NULL;
1436 // Apply any post processing that needs recoding first
1437 if ((sub!=ERR) && !sub_no_text_pp && srp->post) srp->post(sub);
1438 #ifdef CONFIG_SORTSUB
1439 if(!sub_num || (first[sub_num - 1].start <= sub->start)){
1440 first[sub_num].start = sub->start;
1441 first[sub_num].end = sub->end;
1442 first[sub_num].lines = sub->lines;
1443 first[sub_num].alignment = sub->alignment;
1444 for(i = 0; i < sub->lines; ++i){
1445 first[sub_num].text[i] = sub->text[i];
1447 if (previous_sub_end){
1448 first[sub_num - 1].end = previous_sub_end;
1449 previous_sub_end = 0;
1451 } else {
1452 for(j = sub_num - 1; j >= 0; --j){
1453 first[j + 1].start = first[j].start;
1454 first[j + 1].end = first[j].end;
1455 first[j + 1].lines = first[j].lines;
1456 first[j + 1].alignment = first[j].alignment;
1457 for(i = 0; i < first[j].lines; ++i){
1458 first[j + 1].text[i] = first[j].text[i];
1460 if(!j || (first[j - 1].start <= sub->start)){
1461 first[j].start = sub->start;
1462 first[j].end = sub->end;
1463 first[j].lines = sub->lines;
1464 first[j].alignment = sub->alignment;
1465 for(i = 0; i < SUB_MAX_TEXT; ++i){
1466 first[j].text[i] = sub->text[i];
1468 if (previous_sub_end){
1469 first[j].end = first[j - 1].end;
1470 first[j - 1].end = previous_sub_end;
1471 previous_sub_end = 0;
1473 break;
1477 #endif
1478 if(sub==ERR) ++sub_errs; else ++sub_num; // Error vs. Valid
1481 free_stream(fd);
1483 #ifdef CONFIG_ICONV
1484 subcp_close();
1485 #endif
1486 free(alloced_sub);
1488 // printf ("SUB: Subtitle format %s time.\n", uses_time?"uses":"doesn't use");
1489 mp_msg(MSGT_SUBREADER, MSGL_V,"SUB: Read %i subtitles, %i bad line(s).\n",
1490 sub_num, sub_errs);
1492 if(sub_num<=0){
1493 free(first);
1494 return NULL;
1497 // we do overlap if the user forced it (suboverlap_enable == 2) or
1498 // the user didn't forced no-overlapsub and the format is Jacosub or Ssa.
1499 // this is because usually overlapping subtitles are found in these formats,
1500 // while in others they are probably result of bad timing
1501 if ((suboverlap_enabled == 2) ||
1502 ((suboverlap_enabled) && ((sub_format == SUB_JACOSUB) || (sub_format == SUB_SSA)))) {
1503 adjust_subs_time(first, 6.0, fps, 0, sub_num, uses_time);/*~6 secs AST*/
1504 // here we manage overlapping subtitles
1505 sub_orig = sub_num;
1506 n_first = sub_num;
1507 sub_num = 0;
1508 second = NULL;
1509 // for each subtitle in first[] we deal with its 'block' of
1510 // bonded subtitles
1511 for (sub_first = 0; sub_first < n_first; ++sub_first) {
1512 unsigned long global_start = first[sub_first].start,
1513 global_end = first[sub_first].end, local_start, local_end;
1514 int lines_to_add = first[sub_first].lines, sub_to_add = 0,
1515 **placeholder = NULL, higher_line = 0, counter, start_block_sub = sub_num;
1516 char real_block = 1;
1518 // here we find the number of subtitles inside the 'block'
1519 // and its span interval. this works well only with sorted
1520 // subtitles
1521 while ((sub_first + sub_to_add + 1 < n_first) && (first[sub_first + sub_to_add + 1].start < global_end)) {
1522 ++sub_to_add;
1523 lines_to_add += first[sub_first + sub_to_add].lines;
1524 if (first[sub_first + sub_to_add].start < global_start) {
1525 global_start = first[sub_first + sub_to_add].start;
1527 if (first[sub_first + sub_to_add].end > global_end) {
1528 global_end = first[sub_first + sub_to_add].end;
1532 /* Avoid n^2 memory use for the "placeholder" data structure
1533 * below with subtitles that have a huge number of
1534 * consecutive overlapping lines. */
1535 lines_to_add = FFMIN(lines_to_add, SUB_MAX_TEXT);
1537 // we need a structure to keep trace of the screen lines
1538 // used by the subs, a 'placeholder'
1539 counter = 2 * sub_to_add + 1; // the maximum number of subs derived
1540 // from a block of sub_to_add+1 subs
1541 placeholder = malloc(sizeof(int *) * counter);
1542 for (i = 0; i < counter; ++i) {
1543 placeholder[i] = malloc(sizeof(int) * lines_to_add);
1544 for (j = 0; j < lines_to_add; ++j) {
1545 placeholder[i][j] = -1;
1549 counter = 0;
1550 local_end = global_start - 1;
1551 do {
1552 int ls;
1554 // here we find the beginning and the end of a new
1555 // subtitle in the block
1556 local_start = local_end + 1;
1557 local_end = global_end;
1558 for (j = 0; j <= sub_to_add; ++j) {
1559 if ((first[sub_first + j].start - 1 > local_start) && (first[sub_first + j].start - 1 < local_end)) {
1560 local_end = first[sub_first + j].start - 1;
1561 } else if ((first[sub_first + j].end > local_start) && (first[sub_first + j].end < local_end)) {
1562 local_end = first[sub_first + j].end;
1565 // here we allocate the screen lines to subs we must
1566 // display in current local_start-local_end interval.
1567 // if the subs were yet presents in the previous interval
1568 // they keep the same lines, otherside they get unused lines
1569 for (j = 0; j <= sub_to_add; ++j) {
1570 if ((first[sub_first + j].start <= local_end) && (first[sub_first + j].end > local_start)) {
1571 unsigned long sub_lines = first[sub_first + j].lines, fragment_length = lines_to_add + 1,
1572 tmp = 0;
1573 char boolean = 0;
1574 int fragment_position = -1;
1576 // if this is not the first new sub of the block
1577 // we find if this sub was present in the previous
1578 // new sub
1579 if (counter)
1580 for (i = 0; i < lines_to_add; ++i) {
1581 if (placeholder[counter - 1][i] == sub_first + j) {
1582 placeholder[counter][i] = sub_first + j;
1583 boolean = 1;
1586 if (boolean)
1587 continue;
1589 // we are looking for the shortest among all groups of
1590 // sequential blank lines whose length is greater than or
1591 // equal to sub_lines. we store in fragment_position the
1592 // position of the shortest group, in fragment_length its
1593 // length, and in tmp the length of the group currently
1594 // examinated
1595 for (i = 0; i < lines_to_add; ++i) {
1596 if (placeholder[counter][i] == -1) {
1597 // placeholder[counter][i] is part of the current group
1598 // of blank lines
1599 ++tmp;
1600 } else {
1601 if (tmp == sub_lines) {
1602 // current group's size fits exactly the one we
1603 // need, so we stop looking
1604 fragment_position = i - tmp;
1605 tmp = 0;
1606 break;
1608 if ((tmp) && (tmp > sub_lines) && (tmp < fragment_length)) {
1609 // current group is the best we found till here,
1610 // but is still bigger than the one we are looking
1611 // for, so we keep on looking
1612 fragment_length = tmp;
1613 fragment_position = i - tmp;
1614 tmp = 0;
1615 } else {
1616 // current group doesn't fit at all, so we forget it
1617 tmp = 0;
1621 if (tmp) {
1622 // last screen line is blank, a group ends with it
1623 if ((tmp >= sub_lines) && (tmp < fragment_length)) {
1624 fragment_position = i - tmp;
1627 if (fragment_position == -1) {
1628 // it was not possible to find free screen line(s) for a subtitle,
1629 // usually this means a bug in the code; however we do not overlap
1630 mp_msg(MSGT_SUBREADER, MSGL_WARN, "SUB: we could not find a suitable position for an overlapping subtitle\n");
1631 higher_line = SUB_MAX_TEXT + 1;
1632 break;
1633 } else {
1634 for (tmp = 0; tmp < sub_lines; ++tmp) {
1635 placeholder[counter][fragment_position + tmp] = sub_first + j;
1640 for (j = higher_line + 1; j < lines_to_add; ++j) {
1641 if (placeholder[counter][j] != -1)
1642 higher_line = j;
1643 else
1644 break;
1646 if (higher_line >= SUB_MAX_TEXT) {
1647 // the 'block' has too much lines, so we don't overlap the
1648 // subtitles
1649 second = (subtitle *) realloc(second, (sub_num + sub_to_add + 1) * sizeof(subtitle));
1650 for (j = 0; j <= sub_to_add; ++j) {
1651 int ls;
1652 memset(&second[sub_num + j], '\0', sizeof(subtitle));
1653 second[sub_num + j].start = first[sub_first + j].start;
1654 second[sub_num + j].end = first[sub_first + j].end;
1655 second[sub_num + j].lines = first[sub_first + j].lines;
1656 second[sub_num + j].alignment = first[sub_first + j].alignment;
1657 for (ls = 0; ls < second[sub_num + j].lines; ls++) {
1658 second[sub_num + j].text[ls] = strdup(first[sub_first + j].text[ls]);
1661 sub_num += sub_to_add + 1;
1662 sub_first += sub_to_add;
1663 real_block = 0;
1664 break;
1667 // we read the placeholder structure and create the new
1668 // subs.
1669 second = (subtitle *) realloc(second, (sub_num + 1) * sizeof(subtitle));
1670 memset(&second[sub_num], '\0', sizeof(subtitle));
1671 second[sub_num].start = local_start;
1672 second[sub_num].end = local_end;
1673 second[sub_num].alignment = first[sub_first].alignment;
1674 n_max = (lines_to_add < SUB_MAX_TEXT) ? lines_to_add : SUB_MAX_TEXT;
1675 for (i = 0, j = 0; j < n_max; ++j) {
1676 if (placeholder[counter][j] != -1) {
1677 int lines = first[placeholder[counter][j]].lines;
1678 for (ls = 0; ls < lines; ++ls) {
1679 second[sub_num].text[i++] = strdup(first[placeholder[counter][j]].text[ls]);
1681 j += lines - 1;
1682 } else {
1683 second[sub_num].text[i++] = strdup(" ");
1686 ++sub_num;
1687 ++counter;
1688 } while (local_end < global_end);
1689 if (real_block)
1690 for (i = 0; i < counter; ++i)
1691 second[start_block_sub + i].lines = higher_line + 1;
1693 counter = 2 * sub_to_add + 1;
1694 for (i = 0; i < counter; ++i) {
1695 free(placeholder[i]);
1697 free(placeholder);
1698 sub_first += sub_to_add;
1701 for (j = sub_orig - 1; j >= 0; --j) {
1702 for (i = first[j].lines - 1; i >= 0; --i) {
1703 free(first[j].text[i]);
1706 free(first);
1708 return_sub = second;
1709 } else { //if(suboverlap_enabled)
1710 adjust_subs_time(first, 6.0, fps, 1, sub_num, uses_time);/*~6 secs AST*/
1711 return_sub = first;
1713 if (return_sub == NULL) return NULL;
1714 subt_data = malloc(sizeof(sub_data));
1715 subt_data->filename = strdup(filename);
1716 subt_data->sub_uses_time = uses_time;
1717 subt_data->sub_num = sub_num;
1718 subt_data->sub_errs = sub_errs;
1719 subt_data->subtitles = return_sub;
1720 return subt_data;
1723 #if 0
1724 char * strreplace( char * in,char * what,char * whereof )
1726 int i;
1727 char * tmp;
1729 if ( ( in == NULL )||( what == NULL )||( whereof == NULL )||( ( tmp=strstr( in,what ) ) == NULL ) ) return NULL;
1730 for( i=0;i<strlen( whereof );i++ ) tmp[i]=whereof[i];
1731 if ( strlen( what ) > strlen( whereof ) ) tmp[i]=0;
1732 return in;
1734 #endif
1737 static void strcpy_trim(char *d, char *s)
1739 // skip leading whitespace
1740 while (*s && isspace(*s)) {
1741 s++;
1743 for (;;) {
1744 // copy word
1745 while (*s && !isspace(*s)) {
1746 *d = tolower(*s);
1747 s++; d++;
1749 if (*s == 0) break;
1750 // trim excess whitespace
1751 while (*s && isspace(*s)) {
1752 s++;
1754 if (*s == 0) break;
1755 *d++ = ' ';
1757 *d = 0;
1760 static void strcpy_strip_ext(char *d, char *s)
1762 char *tmp = strrchr(s,'.');
1763 if (!tmp) {
1764 strcpy(d, s);
1765 return;
1766 } else {
1767 strncpy(d, s, tmp-s);
1768 d[tmp-s] = 0;
1770 while (*d) {
1771 *d = tolower(*d);
1772 d++;
1776 static void strcpy_get_ext(char *d, char *s)
1778 char *tmp = strrchr(s,'.');
1779 if (!tmp) {
1780 strcpy(d, "");
1781 return;
1782 } else {
1783 strcpy(d, tmp+1);
1787 static int whiteonly(char *s)
1789 while (*s) {
1790 if (!isspace(*s)) return 0;
1791 s++;
1793 return 1;
1796 typedef struct subfn
1798 int priority;
1799 char *fname;
1800 } subfn;
1802 static int compare_sub_priority(const void *a, const void *b)
1804 if (((const subfn*)a)->priority > ((const subfn*)b)->priority) {
1805 return -1;
1806 } else if (((const subfn*)a)->priority < ((const subfn*)b)->priority) {
1807 return 1;
1808 } else {
1809 return strcoll(((const subfn*)a)->fname, ((const subfn*)b)->fname);
1813 char** sub_filenames(const char* path, char *fname)
1815 char *f_dir, *f_fname, *f_fname_noext, *f_fname_trim, *tmp, *tmp_sub_id;
1816 char *tmp_fname_noext, *tmp_fname_trim, *tmp_fname_ext, *tmpresult;
1818 int len, pos, found, i, j;
1819 char * sub_exts[] = { "utf", "utf8", "utf-8", "sub", "srt", "smi", "rt", "txt", "ssa", "aqt", "jss", "js", "ass", NULL};
1820 subfn *result;
1821 char **result2;
1823 int subcnt;
1825 FILE *f;
1827 DIR *d;
1828 struct dirent *de;
1830 len = (strlen(fname) > 256 ? strlen(fname) : 256)
1831 +(strlen(path) > 256 ? strlen(path) : 256)+2;
1833 f_dir = malloc(len);
1834 f_fname = malloc(len);
1835 f_fname_noext = malloc(len);
1836 f_fname_trim = malloc(len);
1838 tmp_fname_noext = malloc(len);
1839 tmp_fname_trim = malloc(len);
1840 tmp_fname_ext = malloc(len);
1842 tmpresult = malloc(len);
1844 result = malloc(sizeof(subfn)*MAX_SUBTITLE_FILES);
1845 memset(result, 0, sizeof(subfn)*MAX_SUBTITLE_FILES);
1847 subcnt = 0;
1849 tmp = strrchr(fname,'/');
1850 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1851 if(!tmp)tmp = strrchr(fname,'\\');
1852 if(!tmp)tmp = strrchr(fname,':');
1853 #endif
1855 // extract filename & dirname from fname
1856 if (tmp) {
1857 strcpy(f_fname, tmp+1);
1858 pos = tmp - fname;
1859 strncpy(f_dir, fname, pos+1);
1860 f_dir[pos+1] = 0;
1861 } else {
1862 strcpy(f_fname, fname);
1863 strcpy(f_dir, "./");
1866 strcpy_strip_ext(f_fname_noext, f_fname);
1867 strcpy_trim(f_fname_trim, f_fname_noext);
1869 tmp_sub_id = NULL;
1870 if (dvdsub_lang && !whiteonly(dvdsub_lang)) {
1871 tmp_sub_id = malloc(strlen(dvdsub_lang)+1);
1872 strcpy_trim(tmp_sub_id, dvdsub_lang);
1875 // 0 = nothing
1876 // 1 = any subtitle file
1877 // 2 = any sub file containing movie name
1878 // 3 = sub file containing movie name and the lang extension
1879 for (j = 0; j <= 1; j++) {
1880 d = opendir(j == 0 ? f_dir : path);
1881 if (d) {
1882 while ((de = readdir(d))) {
1883 // retrieve various parts of the filename
1884 strcpy_strip_ext(tmp_fname_noext, de->d_name);
1885 strcpy_get_ext(tmp_fname_ext, de->d_name);
1886 strcpy_trim(tmp_fname_trim, tmp_fname_noext);
1888 // does it end with a subtitle extension?
1889 found = 0;
1890 #ifdef CONFIG_ICONV
1891 #ifdef CONFIG_ENCA
1892 for (i = ((sub_cp && strncasecmp(sub_cp, "enca", 4) != 0) ? 3 : 0); sub_exts[i]; i++) {
1893 #else
1894 for (i = (sub_cp ? 3 : 0); sub_exts[i]; i++) {
1895 #endif
1896 #else
1897 for (i = 0; sub_exts[i]; i++) {
1898 #endif
1899 if (strcasecmp(sub_exts[i], tmp_fname_ext) == 0) {
1900 found = 1;
1901 break;
1905 // we have a (likely) subtitle file
1906 if (found) {
1907 int prio = 0;
1908 if (!prio && tmp_sub_id)
1910 sprintf(tmpresult, "%s %s", f_fname_trim, tmp_sub_id);
1911 mp_msg(MSGT_SUBREADER,MSGL_INFO,"dvdsublang...%s\n", tmpresult);
1912 if (strcmp(tmp_fname_trim, tmpresult) == 0 && sub_match_fuzziness >= 1) {
1913 // matches the movie name + lang extension
1914 prio = 5;
1917 if (!prio && strcmp(tmp_fname_trim, f_fname_trim) == 0) {
1918 // matches the movie name
1919 prio = 4;
1921 if (!prio && (tmp = strstr(tmp_fname_trim, f_fname_trim)) && (sub_match_fuzziness >= 1)) {
1922 // contains the movie name
1923 tmp += strlen(f_fname_trim);
1924 if (tmp_sub_id && strstr(tmp, tmp_sub_id)) {
1925 // with sub_id specified prefer localized subtitles
1926 prio = 3;
1927 } else if ((tmp_sub_id == NULL) && whiteonly(tmp)) {
1928 // without sub_id prefer "plain" name
1929 prio = 3;
1930 } else {
1931 // with no localized subs found, try any else instead
1932 prio = 2;
1935 if (!prio) {
1936 // doesn't contain the movie name
1937 // don't try in the mplayer subtitle directory
1938 if ((j == 0) && (sub_match_fuzziness >= 2)) {
1939 prio = 1;
1943 if (prio) {
1944 prio += prio;
1945 #ifdef CONFIG_ICONV
1946 if (i<3){ // prefer UTF-8 coded
1947 prio++;
1949 #endif
1950 sprintf(tmpresult, "%s%s", j == 0 ? f_dir : path, de->d_name);
1951 // fprintf(stderr, "%s priority %d\n", tmpresult, prio);
1952 if ((f = fopen(tmpresult, "rt"))) {
1953 fclose(f);
1954 result[subcnt].priority = prio;
1955 result[subcnt].fname = strdup(tmpresult);
1956 subcnt++;
1961 if (subcnt >= MAX_SUBTITLE_FILES) break;
1963 closedir(d);
1968 if (tmp_sub_id) free(tmp_sub_id);
1970 free(f_dir);
1971 free(f_fname);
1972 free(f_fname_noext);
1973 free(f_fname_trim);
1975 free(tmp_fname_noext);
1976 free(tmp_fname_trim);
1977 free(tmp_fname_ext);
1979 free(tmpresult);
1981 qsort(result, subcnt, sizeof(subfn), compare_sub_priority);
1983 result2 = malloc(sizeof(char*)*(subcnt+1));
1984 memset(result2, 0, sizeof(char*)*(subcnt+1));
1986 for (i = 0; i < subcnt; i++) {
1987 result2[i] = result[i].fname;
1989 result2[subcnt] = NULL;
1991 free(result);
1993 return result2;
1996 void list_sub_file(sub_data* subd){
1997 int i,j;
1998 subtitle *subs = subd->subtitles;
2000 for(j=0; j < subd->sub_num; j++){
2001 subtitle* egysub=&subs[j];
2002 mp_msg(MSGT_SUBREADER,MSGL_INFO,"%i line%c (%li-%li)\n",
2003 egysub->lines,
2004 (1==egysub->lines)?' ':'s',
2005 egysub->start,
2006 egysub->end);
2007 for (i=0; i<egysub->lines; i++) {
2008 mp_msg(MSGT_SUBREADER,MSGL_INFO,"\t\t%d: %s%s", i,egysub->text[i], i==egysub->lines-1?"":" \n ");
2010 mp_msg(MSGT_SUBREADER,MSGL_INFO,"\n");
2013 mp_msg(MSGT_SUBREADER,MSGL_INFO,"Subtitle format %s time.\n",
2014 subd->sub_uses_time ? "uses":"doesn't use");
2015 mp_msg(MSGT_SUBREADER,MSGL_INFO,"Read %i subtitles, %i errors.\n", subd->sub_num, subd->sub_errs);
2018 void dump_srt(sub_data* subd, float fps){
2019 int i,j;
2020 int h,m,s,ms;
2021 FILE * fd;
2022 subtitle * onesub;
2023 unsigned long temp;
2024 subtitle *subs = subd->subtitles;
2026 if (!subd->sub_uses_time && sub_fps == 0)
2027 sub_fps = fps;
2028 fd=fopen("dumpsub.srt","w");
2029 if(!fd)
2031 perror("dump_srt: fopen");
2032 return;
2034 for(i=0; i < subd->sub_num; i++)
2036 onesub=subs+i; //=&subs[i];
2037 fprintf(fd,"%d\n",i+1);//line number
2039 temp=onesub->start;
2040 if (!subd->sub_uses_time)
2041 temp = temp * 100 / sub_fps;
2042 temp -= sub_delay * 100;
2043 h=temp/360000;temp%=360000; //h =1*100*60*60
2044 m=temp/6000; temp%=6000; //m =1*100*60
2045 s=temp/100; temp%=100; //s =1*100
2046 ms=temp*10; //ms=1*10
2047 fprintf(fd,"%02d:%02d:%02d,%03d --> ",h,m,s,ms);
2049 temp=onesub->end;
2050 if (!subd->sub_uses_time)
2051 temp = temp * 100 / sub_fps;
2052 temp -= sub_delay * 100;
2053 h=temp/360000;temp%=360000;
2054 m=temp/6000; temp%=6000;
2055 s=temp/100; temp%=100;
2056 ms=temp*10;
2057 fprintf(fd,"%02d:%02d:%02d,%03d\n",h,m,s,ms);
2059 for(j=0;j<onesub->lines;j++)
2060 fprintf(fd,"%s\n",onesub->text[j]);
2062 fprintf(fd,"\n");
2064 fclose(fd);
2065 mp_msg(MSGT_SUBREADER,MSGL_INFO,"SUB: Subtitles dumped in \'dumpsub.srt\'.\n");
2068 void dump_mpsub(sub_data* subd, float fps){
2069 int i,j;
2070 FILE *fd;
2071 float a,b;
2072 subtitle *subs = subd->subtitles;
2074 mpsub_position = subd->sub_uses_time? (sub_delay*100) : (sub_delay*fps);
2075 if (sub_fps==0) sub_fps=fps;
2077 fd=fopen ("dump.mpsub", "w");
2078 if (!fd) {
2079 perror ("dump_mpsub: fopen");
2080 return;
2084 if (subd->sub_uses_time) fprintf (fd,"FORMAT=TIME\n\n");
2085 else fprintf (fd, "FORMAT=%5.2f\n\n", fps);
2087 for(j=0; j < subd->sub_num; j++){
2088 subtitle* egysub=&subs[j];
2089 if (subd->sub_uses_time) {
2090 a=((egysub->start-mpsub_position)/100.0);
2091 b=((egysub->end-egysub->start)/100.0);
2092 if ( (float)((int)a) == a)
2093 fprintf (fd, "%.0f",a);
2094 else
2095 fprintf (fd, "%.2f",a);
2097 if ( (float)((int)b) == b)
2098 fprintf (fd, " %.0f\n",b);
2099 else
2100 fprintf (fd, " %.2f\n",b);
2101 } else {
2102 fprintf (fd, "%ld %ld\n", (long)((egysub->start*(fps/sub_fps))-((mpsub_position*(fps/sub_fps)))),
2103 (long)(((egysub->end)-(egysub->start))*(fps/sub_fps)));
2106 mpsub_position = egysub->end;
2107 for (i=0; i<egysub->lines; i++) {
2108 fprintf (fd, "%s\n",egysub->text[i]);
2110 fprintf (fd, "\n");
2112 fclose (fd);
2113 mp_msg(MSGT_SUBREADER,MSGL_INFO,"SUB: Subtitles dumped in \'dump.mpsub\'.\n");
2116 void dump_microdvd(sub_data* subd, float fps) {
2117 int i, delay;
2118 FILE *fd;
2119 subtitle *subs = subd->subtitles;
2120 if (sub_fps == 0)
2121 sub_fps = fps;
2122 fd = fopen("dumpsub.sub", "w");
2123 if (!fd) {
2124 perror("dumpsub.sub: fopen");
2125 return;
2127 delay = sub_delay * sub_fps;
2128 for (i = 0; i < subd->sub_num; ++i) {
2129 int j, start, end;
2130 start = subs[i].start;
2131 end = subs[i].end;
2132 if (subd->sub_uses_time) {
2133 start = start * sub_fps / 100 ;
2134 end = end * sub_fps / 100;
2136 else {
2137 start = start * sub_fps / fps;
2138 end = end * sub_fps / fps;
2140 start -= delay;
2141 end -= delay;
2142 fprintf(fd, "{%d}{%d}", start, end);
2143 for (j = 0; j < subs[i].lines; ++j)
2144 fprintf(fd, "%s%s", j ? "|" : "", subs[i].text[j]);
2145 fprintf(fd, "\n");
2147 fclose(fd);
2148 mp_msg(MSGT_SUBREADER,MSGL_INFO,"SUB: Subtitles dumped in \'dumpsub.sub\'.\n");
2151 void dump_jacosub(sub_data* subd, float fps) {
2152 int i,j;
2153 int h,m,s,cs;
2154 FILE * fd;
2155 subtitle * onesub;
2156 unsigned long temp;
2157 subtitle *subs = subd->subtitles;
2159 if (!subd->sub_uses_time && sub_fps == 0)
2160 sub_fps = fps;
2161 fd=fopen("dumpsub.jss","w");
2162 if(!fd)
2164 perror("dump_jacosub: fopen");
2165 return;
2167 fprintf(fd, "#TIMERES %d\n", (subd->sub_uses_time) ? 100 : (int)sub_fps);
2168 for(i=0; i < subd->sub_num; i++)
2170 onesub=subs+i; //=&subs[i];
2172 temp=onesub->start;
2173 if (!subd->sub_uses_time)
2174 temp = temp * 100 / sub_fps;
2175 temp -= sub_delay * 100;
2176 h=temp/360000;temp%=360000; //h =1*100*60*60
2177 m=temp/6000; temp%=6000; //m =1*100*60
2178 s=temp/100; temp%=100; //s =1*100
2179 cs=temp; //cs=1*10
2180 fprintf(fd,"%02d:%02d:%02d.%02d ",h,m,s,cs);
2182 temp=onesub->end;
2183 if (!subd->sub_uses_time)
2184 temp = temp * 100 / sub_fps;
2185 temp -= sub_delay * 100;
2186 h=temp/360000;temp%=360000;
2187 m=temp/6000; temp%=6000;
2188 s=temp/100; temp%=100;
2189 cs=temp;
2190 fprintf(fd,"%02d:%02d:%02d.%02d {~} ",h,m,s,cs);
2192 for(j=0;j<onesub->lines;j++)
2193 fprintf(fd,"%s%s",j ? "\\n" : "", onesub->text[j]);
2195 fprintf(fd,"\n");
2197 fclose(fd);
2198 mp_msg(MSGT_SUBREADER,MSGL_INFO,"SUB: Subtitles dumped in \'dumpsub.js\'.\n");
2201 void dump_sami(sub_data* subd, float fps) {
2202 int i,j;
2203 FILE * fd;
2204 subtitle * onesub;
2205 unsigned long temp;
2206 subtitle *subs = subd->subtitles;
2208 if (!subd->sub_uses_time && sub_fps == 0)
2209 sub_fps = fps;
2210 fd=fopen("dumpsub.smi","w");
2211 if(!fd)
2213 perror("dump_jacosub: fopen");
2214 return;
2216 fprintf(fd, "<SAMI>\n"
2217 "<HEAD>\n"
2218 " <STYLE TYPE=\"Text/css\">\n"
2219 " <!--\n"
2220 " 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"
2221 " .SUBTTL {Name: 'Subtitles'; Lang: en-US; SAMIType: CC;}\n"
2222 " -->\n"
2223 " </STYLE>\n"
2224 "</HEAD>\n"
2225 "<BODY>\n");
2226 for(i=0; i < subd->sub_num; i++)
2228 onesub=subs+i; //=&subs[i];
2230 temp=onesub->start;
2231 if (!subd->sub_uses_time)
2232 temp = temp * 100 / sub_fps;
2233 temp -= sub_delay * 100;
2234 fprintf(fd,"\t<SYNC Start=%lu>\n"
2235 "\t <P>", temp * 10);
2237 for(j=0;j<onesub->lines;j++)
2238 fprintf(fd,"%s%s",j ? "<br>" : "", onesub->text[j]);
2240 fprintf(fd,"\n");
2242 temp=onesub->end;
2243 if (!subd->sub_uses_time)
2244 temp = temp * 100 / sub_fps;
2245 temp -= sub_delay * 100;
2246 fprintf(fd,"\t<SYNC Start=%lu>\n"
2247 "\t <P>&nbsp;\n", temp * 10);
2249 fprintf(fd, "</BODY>\n"
2250 "</SAMI>\n");
2251 fclose(fd);
2252 mp_msg(MSGT_SUBREADER,MSGL_INFO,"SUB: Subtitles dumped in \'dumpsub.smi\'.\n");
2255 void sub_free( sub_data * subd )
2257 int i, j;
2259 if ( !subd ) return;
2261 for (i = 0; i < subd->sub_num; i++)
2262 for (j = 0; j < subd->subtitles[i].lines; j++)
2263 free( subd->subtitles[i].text[j] );
2264 free( subd->subtitles );
2265 free( subd->filename );
2266 free( subd );
2269 #define MAX_SUBLINE 512
2271 * \brief parse text and append it to subtitle in sub
2272 * \param sub subtitle struct to add text to
2273 * \param txt text to parse
2274 * \param len length of text in txt
2275 * \param endpts pts at which this subtitle text should be removed again
2277 * <> and {} are interpreted as comment delimiters, "\n", "\N", '\n', '\r'
2278 * and '\0' are interpreted as newlines, duplicate, leading and trailing
2279 * newlines are ignored.
2281 void sub_add_text(subtitle *sub, const char *txt, int len, double endpts) {
2282 int comment = 0;
2283 int double_newline = 1; // ignore newlines at the beginning
2284 int i, pos;
2285 char *buf;
2286 int orig_lines = sub->lines;
2287 if (sub->lines >= SUB_MAX_TEXT) return;
2288 pos = 0;
2289 buf = malloc(MAX_SUBLINE + 1);
2290 sub->text[sub->lines] = buf;
2291 sub->endpts[sub->lines] = endpts;
2292 for (i = 0; i < len && pos < MAX_SUBLINE; i++) {
2293 char c = txt[i];
2294 if (c == '<') comment |= 1;
2295 if (c == '{') comment |= 2;
2296 if (comment) {
2297 if (c == '}') comment &= ~2;
2298 if (c == '>') comment &= ~1;
2299 continue;
2301 if (pos == MAX_SUBLINE - 1) {
2302 i--;
2303 c = 0;
2305 if (c == '\\' && i + 1 < len) {
2306 c = txt[++i];
2307 if (c == 'n' || c == 'N') c = 0;
2309 if (c == '\n' || c == '\r') c = 0;
2310 if (c) {
2311 double_newline = 0;
2312 buf[pos++] = c;
2313 } else if (!double_newline) {
2314 if (sub->lines >= SUB_MAX_TEXT - 1) {
2315 mp_msg(MSGT_VO, MSGL_WARN, "Too many subtitle lines\n");
2316 break;
2318 double_newline = 1;
2319 buf[pos] = 0;
2320 sub->lines++;
2321 pos = 0;
2322 buf = malloc(MAX_SUBLINE + 1);
2323 sub->text[sub->lines] = buf;
2324 sub->endpts[sub->lines] = endpts;
2327 buf[pos] = 0;
2328 if (sub->lines < SUB_MAX_TEXT &&
2329 strlen(sub->text[sub->lines]))
2330 sub->lines++;
2331 #ifdef CONFIG_FRIBIDI
2332 sub = sub_fribidi(sub, sub_utf8, orig_lines);
2333 #endif
2336 #define MP_NOPTS_VALUE (-1LL<<63)
2338 * \brief remove outdated subtitle lines.
2339 * \param sub subtitle struct to modify
2340 * \param pts current pts. All lines with endpts <= this will be removed.
2341 * Use MP_NOPTS_VALUE to remove all lines
2342 * \return 1 if sub was modified, 0 otherwise.
2344 int sub_clear_text(subtitle *sub, double pts) {
2345 int i = 0;
2346 int changed = 0;
2347 while (i < sub->lines) {
2348 double endpts = sub->endpts[i];
2349 if (pts == MP_NOPTS_VALUE || (endpts != MP_NOPTS_VALUE && pts >= endpts)) {
2350 int j;
2351 free(sub->text[i]);
2352 for (j = i + 1; j < sub->lines; j++) {
2353 sub->text[j - 1] = sub->text[j];
2354 sub->endpts[j - 1] = sub->endpts[j];
2356 sub->lines--;
2357 changed = 1;
2358 } else
2359 i++;
2361 return changed;