Add explanatory comments to #endif preprocessor directives.
[mplayer/greg.git] / subreader.c
blob2381b76d1a6845909e29ad81342d5a2fb914dd43
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"
23 #ifdef HAVE_ENCA
24 #include <enca.h>
25 #endif
27 #define ERR ((void *) -1)
29 #ifdef USE_ICONV
30 #include <iconv.h>
31 char *sub_cp=NULL;
32 #endif
33 #ifdef USE_FRIBIDI
34 #include <fribidi/fribidi.h>
35 char *fribidi_charset = NULL; ///character set that will be passed to FriBiDi
36 int flip_hebrew = 1; ///flip subtitles using fribidi
37 int fribidi_flip_commas = 0; ///flip comma when fribidi is used
38 #endif
40 extern char* dvdsub_lang;
42 /* Maximal length of line of a subtitle */
43 #define LINE_LEN 1000
44 static float mpsub_position=0;
45 static float mpsub_multiplier=1.;
46 static int sub_slacktime = 20000; //20 sec
48 int sub_no_text_pp=0; // 1 => do not apply text post-processing
49 // like {\...} elimination in SSA format.
51 int sub_match_fuzziness=0; // level of sub name matching fuzziness
53 /* Use the SUB_* constant defined in the header file */
54 int sub_format=SUB_INVALID;
55 #ifdef USE_SORTSUB
56 /*
57 Some subtitling formats, namely AQT and Subrip09, define the end of a
58 subtitle as the beginning of the following. Since currently we read one
59 subtitle at time, for these format we keep two global *subtitle,
60 previous_aqt_sub and previous_subrip09_sub, pointing to previous subtitle,
61 so we can change its end when we read current subtitle starting time.
62 When USE_SORTSUB is defined, we use a single global unsigned long,
63 previous_sub_end, for both (and even future) formats, to store the end of
64 the previous sub: it is initialized to 0 in sub_read_file and eventually
65 modified by sub_read_aqt_line or sub_read_subrip09_line.
67 unsigned long previous_sub_end;
68 #endif
70 static int eol(char p) {
71 return (p=='\r' || p=='\n' || p=='\0');
74 /* Remove leading and trailing space */
75 static void trail_space(char *s) {
76 int i = 0;
77 while (isspace(s[i])) ++i;
78 if (i) strcpy(s, s + i);
79 i = strlen(s) - 1;
80 while (i > 0 && isspace(s[i])) s[i--] = '\0';
83 static char *stristr(const char *haystack, const char *needle) {
84 int len = 0;
85 const char *p = haystack;
87 if (!(haystack && needle)) return NULL;
89 len=strlen(needle);
90 while (*p != '\0') {
91 if (strncasecmp(p, needle, len) == 0) return (char*)p;
92 p++;
95 return NULL;
98 static subtitle *sub_read_line_sami(stream_t* st, subtitle *current) {
99 static char line[LINE_LEN+1];
100 static char *s = NULL, *slacktime_s;
101 char text[LINE_LEN+1], *p=NULL, *q;
102 int state;
104 current->lines = current->start = current->end = 0;
105 current->alignment = SUB_ALIGNMENT_BOTTOMCENTER;
106 state = 0;
108 /* read the first line */
109 if (!s)
110 if (!(s = stream_read_line(st, line, LINE_LEN))) return 0;
112 do {
113 switch (state) {
115 case 0: /* find "START=" or "Slacktime:" */
116 slacktime_s = stristr (s, "Slacktime:");
117 if (slacktime_s)
118 sub_slacktime = strtol (slacktime_s+10, NULL, 0) / 10;
120 s = stristr (s, "Start=");
121 if (s) {
122 current->start = strtol (s + 6, &s, 0) / 10;
123 /* eat '>' */
124 for (; *s != '>' && *s != '\0'; s++);
125 s++;
126 state = 1; continue;
128 break;
130 case 1: /* find (optionnal) "<P", skip other TAGs */
131 for (; *s == ' ' || *s == '\t'; s++); /* strip blanks, if any */
132 if (*s == '\0') break;
133 if (*s != '<') { state = 3; p = text; continue; } /* not a TAG */
134 s++;
135 if (*s == 'P' || *s == 'p') { s++; state = 2; continue; } /* found '<P' */
136 for (; *s != '>' && *s != '\0'; s++); /* skip remains of non-<P> TAG */
137 if (s == '\0')
138 break;
139 s++;
140 continue;
142 case 2: /* find ">" */
143 if ((s = strchr (s, '>'))) { s++; state = 3; p = text; continue; }
144 break;
146 case 3: /* get all text until '<' appears */
147 if (*s == '\0') break;
148 else if (!strncasecmp (s, "<br>", 4)) {
149 *p = '\0'; p = text; trail_space (text);
150 if (text[0] != '\0')
151 current->text[current->lines++] = strdup (text);
152 s += 4;
154 else if ((*s == '{') && !sub_no_text_pp) { state = 5; ++s; continue; }
155 else if (*s == '<') { state = 4; }
156 else if (!strncasecmp (s, "&nbsp;", 6)) { *p++ = ' '; s += 6; }
157 else if (*s == '\t') { *p++ = ' '; s++; }
158 else if (*s == '\r' || *s == '\n') { s++; }
159 else *p++ = *s++;
161 /* skip duplicated space */
162 if (p > text + 2) if (*(p-1) == ' ' && *(p-2) == ' ') p--;
164 continue;
166 case 4: /* get current->end or skip <TAG> */
167 q = stristr (s, "Start=");
168 if (q) {
169 current->end = strtol (q + 6, &q, 0) / 10 - 1;
170 *p = '\0'; trail_space (text);
171 if (text[0] != '\0')
172 current->text[current->lines++] = strdup (text);
173 if (current->lines > 0) { state = 99; break; }
174 state = 0; continue;
176 s = strchr (s, '>');
177 if (s) { s++; state = 3; continue; }
178 break;
179 case 5: /* get rid of {...} text, but read the alignment code */
180 if ((*s == '\\') && (*(s + 1) == 'a') && !sub_no_text_pp) {
181 if (stristr(s, "\\a1") != NULL) {
182 current->alignment = SUB_ALIGNMENT_BOTTOMLEFT;
183 s = s + 3;
185 if (stristr(s, "\\a2") != NULL) {
186 current->alignment = SUB_ALIGNMENT_BOTTOMCENTER;
187 s = s + 3;
188 } else if (stristr(s, "\\a3") != NULL) {
189 current->alignment = SUB_ALIGNMENT_BOTTOMRIGHT;
190 s = s + 3;
191 } else if ((stristr(s, "\\a4") != NULL) || (stristr(s, "\\a5") != NULL) || (stristr(s, "\\a8") != NULL)) {
192 current->alignment = SUB_ALIGNMENT_TOPLEFT;
193 s = s + 3;
194 } else if (stristr(s, "\\a6") != NULL) {
195 current->alignment = SUB_ALIGNMENT_TOPCENTER;
196 s = s + 3;
197 } else if (stristr(s, "\\a7") != NULL) {
198 current->alignment = SUB_ALIGNMENT_TOPRIGHT;
199 s = s + 3;
200 } else if (stristr(s, "\\a9") != NULL) {
201 current->alignment = SUB_ALIGNMENT_MIDDLELEFT;
202 s = s + 3;
203 } else if (stristr(s, "\\a10") != NULL) {
204 current->alignment = SUB_ALIGNMENT_MIDDLECENTER;
205 s = s + 4;
206 } else if (stristr(s, "\\a11") != NULL) {
207 current->alignment = SUB_ALIGNMENT_MIDDLERIGHT;
208 s = s + 4;
211 if (*s == '}') state = 3;
212 ++s;
213 continue;
216 /* read next line */
217 if (state != 99 && !(s = stream_read_line (st, line, LINE_LEN))) {
218 if (current->start > 0) {
219 break; // if it is the last subtitle
220 } else {
221 return 0;
225 } while (state != 99);
227 // For the last subtitle
228 if (current->end <= 0) {
229 current->end = current->start + sub_slacktime;
230 *p = '\0'; trail_space (text);
231 if (text[0] != '\0')
232 current->text[current->lines++] = strdup (text);
235 return current;
239 static char *sub_readtext(char *source, char **dest) {
240 int len=0;
241 char *p=source;
243 // printf("src=%p dest=%p \n",source,dest);
245 while ( !eol(*p) && *p!= '|' ) {
246 p++,len++;
249 *dest= malloc (len+1);
250 if (!dest) {return ERR;}
252 strncpy(*dest, source, len);
253 (*dest)[len]=0;
255 while (*p=='\r' || *p=='\n' || *p=='|') p++;
257 if (*p) return p; // not-last text field
258 else return NULL; // last text field
261 static subtitle *sub_read_line_microdvd(stream_t *st,subtitle *current) {
262 char line[LINE_LEN+1];
263 char line2[LINE_LEN+1];
264 char *p, *next;
265 int i;
267 do {
268 if (!stream_read_line (st, line, LINE_LEN)) return NULL;
269 } while ((sscanf (line,
270 "{%ld}{}%[^\r\n]",
271 &(current->start), line2) < 2) &&
272 (sscanf (line,
273 "{%ld}{%ld}%[^\r\n]",
274 &(current->start), &(current->end), line2) < 3));
276 p=line2;
278 next=p, i=0;
279 while ((next =sub_readtext (next, &(current->text[i])))) {
280 if (current->text[i]==ERR) {return ERR;}
281 i++;
282 if (i>=SUB_MAX_TEXT) { mp_msg(MSGT_SUBREADER,MSGL_WARN,"Too many lines in a subtitle\n");current->lines=i;return current;}
284 current->lines= ++i;
286 return current;
289 static subtitle *sub_read_line_mpl2(stream_t *st,subtitle *current) {
290 char line[LINE_LEN+1];
291 char line2[LINE_LEN+1];
292 char *p, *next;
293 int i;
295 do {
296 if (!stream_read_line (st, line, LINE_LEN)) return NULL;
297 } while ((sscanf (line,
298 "[%ld][%ld]%[^\r\n]",
299 &(current->start), &(current->end), line2) < 3));
300 current->start *= 10;
301 current->end *= 10;
302 p=line2;
304 next=p, i=0;
305 while ((next =sub_readtext (next, &(current->text[i])))) {
306 if (current->text[i]==ERR) {return ERR;}
307 i++;
308 if (i>=SUB_MAX_TEXT) { mp_msg(MSGT_SUBREADER,MSGL_WARN,"Too many lines in a subtitle\n");current->lines=i;return current;}
310 current->lines= ++i;
312 return current;
315 static subtitle *sub_read_line_subrip(stream_t* st, subtitle *current) {
316 char line[LINE_LEN+1];
317 int a1,a2,a3,a4,b1,b2,b3,b4;
318 char *p=NULL, *q=NULL;
319 int len;
321 while (1) {
322 if (!stream_read_line (st, line, LINE_LEN)) return NULL;
323 if (sscanf (line, "%d:%d:%d.%d,%d:%d:%d.%d",&a1,&a2,&a3,&a4,&b1,&b2,&b3,&b4) < 8) continue;
324 current->start = a1*360000+a2*6000+a3*100+a4;
325 current->end = b1*360000+b2*6000+b3*100+b4;
327 if (!stream_read_line (st, line, LINE_LEN)) return NULL;
329 p=q=line;
330 for (current->lines=1; current->lines < SUB_MAX_TEXT; current->lines++) {
331 for (q=p,len=0; *p && *p!='\r' && *p!='\n' && *p!='|' && strncmp(p,"[br]",4); p++,len++);
332 current->text[current->lines-1]=malloc (len+1);
333 if (!current->text[current->lines-1]) return ERR;
334 strncpy (current->text[current->lines-1], q, len);
335 current->text[current->lines-1][len]='\0';
336 if (!*p || *p=='\r' || *p=='\n') break;
337 if (*p=='|') p++;
338 else while (*p++!=']');
340 break;
342 return current;
345 static subtitle *sub_read_line_subviewer(stream_t *st,subtitle *current) {
346 char line[LINE_LEN+1];
347 int a1,a2,a3,a4,b1,b2,b3,b4;
348 char *p=NULL;
349 int i,len;
351 while (!current->text[0]) {
352 if (!stream_read_line (st, line, LINE_LEN)) return NULL;
353 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)
354 continue;
355 current->start = a1*360000+a2*6000+a3*100+a4/10;
356 current->end = b1*360000+b2*6000+b3*100+b4/10;
357 for (i=0; i<SUB_MAX_TEXT;) {
358 int blank = 1;
359 if (!stream_read_line (st, line, LINE_LEN)) break;
360 len=0;
361 for (p=line; *p!='\n' && *p!='\r' && *p; p++,len++)
362 if (*p != ' ' && *p != '\t')
363 blank = 0;
364 if (len && !blank) {
365 int j=0,skip=0;
366 char *curptr=current->text[i]=malloc (len+1);
367 if (!current->text[i]) return ERR;
368 //strncpy (current->text[i], line, len); current->text[i][len]='\0';
369 for(; j<len; j++) {
370 /* let's filter html tags ::atmos */
371 if(line[j]=='>') {
372 skip=0;
373 continue;
375 if(line[j]=='<') {
376 skip=1;
377 continue;
379 if(skip) {
380 continue;
382 *curptr=line[j];
383 curptr++;
385 *curptr='\0';
387 i++;
388 } else {
389 break;
392 current->lines=i;
394 return current;
397 static subtitle *sub_read_line_subviewer2(stream_t *st,subtitle *current) {
398 char line[LINE_LEN+1];
399 int a1,a2,a3,a4;
400 char *p=NULL;
401 int i,len;
403 while (!current->text[0]) {
404 if (!stream_read_line (st, line, LINE_LEN)) return NULL;
405 if (line[0]!='{')
406 continue;
407 if ((len=sscanf (line, "{T %d:%d:%d:%d",&a1,&a2,&a3,&a4)) < 4)
408 continue;
409 current->start = a1*360000+a2*6000+a3*100+a4/10;
410 for (i=0; i<SUB_MAX_TEXT;) {
411 if (!stream_read_line (st, line, LINE_LEN)) break;
412 if (line[0]=='}') break;
413 len=0;
414 for (p=line; *p!='\n' && *p!='\r' && *p; ++p,++len);
415 if (len) {
416 current->text[i]=malloc (len+1);
417 if (!current->text[i]) return ERR;
418 strncpy (current->text[i], line, len); current->text[i][len]='\0';
419 ++i;
420 } else {
421 break;
424 current->lines=i;
426 return current;
430 static subtitle *sub_read_line_vplayer(stream_t *st,subtitle *current) {
431 char line[LINE_LEN+1];
432 int a1,a2,a3;
433 char *p=NULL, *next,separator;
434 int i,len,plen;
436 while (!current->text[0]) {
437 if (!stream_read_line (st, line, LINE_LEN)) return NULL;
438 if ((len=sscanf (line, "%d:%d:%d%c%n",&a1,&a2,&a3,&separator,&plen)) < 4)
439 continue;
441 if (!(current->start = a1*360000+a2*6000+a3*100))
442 continue;
443 /* removed by wodzu
444 p=line;
445 // finds the body of the subtitle
446 for (i=0; i<3; i++){
447 p=strchr(p,':');
448 if (p==NULL) break;
449 ++p;
451 if (p==NULL) {
452 printf("SUB: Skipping incorrect subtitle line!\n");
453 continue;
456 // by wodzu: hey! this time we know what length it has! what is
457 // that magic for? it can't deal with space instead of third
458 // colon! look, what simple it can be:
459 p = &line[ plen ];
461 i=0;
462 if (*p!='|') {
464 next = p,i=0;
465 while ((next =sub_readtext (next, &(current->text[i])))) {
466 if (current->text[i]==ERR) {return ERR;}
467 i++;
468 if (i>=SUB_MAX_TEXT) { mp_msg(MSGT_SUBREADER,MSGL_WARN,"Too many lines in a subtitle\n");current->lines=i;return current;}
470 current->lines=i+1;
473 return current;
476 static subtitle *sub_read_line_rt(stream_t *st,subtitle *current) {
477 //TODO: This format uses quite rich (sub/super)set of xhtml
478 // I couldn't check it since DTD is not included.
479 // WARNING: full XML parses can be required for proper parsing
480 char line[LINE_LEN+1];
481 int a1,a2,a3,a4,b1,b2,b3,b4;
482 char *p=NULL,*next=NULL;
483 int i,len,plen;
485 while (!current->text[0]) {
486 if (!stream_read_line (st, line, LINE_LEN)) return NULL;
487 //TODO: it seems that format of time is not easily determined, it may be 1:12, 1:12.0 or 0:1:12.0
488 //to describe the same moment in time. Maybe there are even more formats in use.
489 //if ((len=sscanf (line, "<Time Begin=\"%d:%d:%d.%d\" End=\"%d:%d:%d.%d\"",&a1,&a2,&a3,&a4,&b1,&b2,&b3,&b4)) < 8)
490 plen=a1=a2=a3=a4=b1=b2=b3=b4=0;
491 if (
492 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d.%d\" %*[Ee]nd=\"%d.%d\"%*[^<]<clear/>%n",&a3,&a4,&b3,&b4,&plen)) < 4) &&
493 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d.%d\" %*[Ee]nd=\"%d:%d.%d\"%*[^<]<clear/>%n",&a3,&a4,&b2,&b3,&b4,&plen)) < 5) &&
494 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d:%d\" %*[Ee]nd=\"%d:%d\"%*[^<]<clear/>%n",&a2,&a3,&b2,&b3,&plen)) < 4) &&
495 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d:%d\" %*[Ee]nd=\"%d:%d.%d\"%*[^<]<clear/>%n",&a2,&a3,&b2,&b3,&b4,&plen)) < 5) &&
496 // ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d:%d.%d\" %*[Ee]nd=\"%d:%d\"%*[^<]<clear/>%n",&a2,&a3,&a4,&b2,&b3,&plen)) < 5) &&
497 ((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) &&
498 ((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) &&
499 //now try it without end time
500 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d.%d\"%*[^<]<clear/>%n",&a3,&a4,&plen)) < 2) &&
501 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d:%d\"%*[^<]<clear/>%n",&a2,&a3,&plen)) < 2) &&
502 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d:%d.%d\"%*[^<]<clear/>%n",&a2,&a3,&a4,&plen)) < 3) &&
503 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d:%d:%d.%d\"%*[^<]<clear/>%n",&a1,&a2,&a3,&a4,&plen)) < 4)
505 continue;
506 current->start = a1*360000+a2*6000+a3*100+a4/10;
507 current->end = b1*360000+b2*6000+b3*100+b4/10;
508 if (b1 == 0 && b2 == 0 && b3 == 0 && b4 == 0)
509 current->end = current->start+200;
510 p=line; p+=plen;i=0;
511 // TODO: I don't know what kind of convention is here for marking multiline subs, maybe <br/> like in xml?
512 next = strstr(line,"<clear/>");
513 if(next && strlen(next)>8){
514 next+=8;i=0;
515 while ((next =sub_readtext (next, &(current->text[i])))) {
516 if (current->text[i]==ERR) {return ERR;}
517 i++;
518 if (i>=SUB_MAX_TEXT) { mp_msg(MSGT_SUBREADER,MSGL_WARN,"Too many lines in a subtitle\n");current->lines=i;return current;}
521 current->lines=i+1;
523 return current;
526 static subtitle *sub_read_line_ssa(stream_t *st,subtitle *current) {
528 * Sub Station Alpha v4 (and v2?) scripts have 9 commas before subtitle
529 * other Sub Station Alpha scripts have only 8 commas before subtitle
530 * Reading the "ScriptType:" field is not reliable since many scripts appear
531 * w/o it
533 * http://www.scriptclub.org is a good place to find more examples
534 * http://www.eswat.demon.co.uk is where the SSA specs can be found
536 int comma;
537 static int max_comma = 32; /* let's use 32 for the case that the */
538 /* amount of commas increase with newer SSA versions */
540 int hour1, min1, sec1, hunsec1,
541 hour2, min2, sec2, hunsec2, nothing;
542 int num;
544 char line[LINE_LEN+1],
545 line3[LINE_LEN+1],
546 *line2;
547 char *tmp;
549 do {
550 if (!stream_read_line (st, line, LINE_LEN)) return NULL;
551 } while (sscanf (line, "Dialogue: Marked=%d,%d:%d:%d.%d,%d:%d:%d.%d,"
552 "%[^\n\r]", &nothing,
553 &hour1, &min1, &sec1, &hunsec1,
554 &hour2, &min2, &sec2, &hunsec2,
555 line3) < 9
557 sscanf (line, "Dialogue: %d,%d:%d:%d.%d,%d:%d:%d.%d,"
558 "%[^\n\r]", &nothing,
559 &hour1, &min1, &sec1, &hunsec1,
560 &hour2, &min2, &sec2, &hunsec2,
561 line3) < 9 );
563 line2=strchr(line3, ',');
565 for (comma = 4; comma < max_comma; comma ++)
567 tmp = line2;
568 if(!(tmp=strchr(++tmp, ','))) break;
569 if(*(++tmp) == ' ') break;
570 /* a space after a comma means we're already in a sentence */
571 line2 = tmp;
574 if(comma < max_comma)max_comma = comma;
575 /* eliminate the trailing comma */
576 if(*line2 == ',') line2++;
578 current->lines=0;num=0;
579 current->start = 360000*hour1 + 6000*min1 + 100*sec1 + hunsec1;
580 current->end = 360000*hour2 + 6000*min2 + 100*sec2 + hunsec2;
582 while (((tmp=strstr(line2, "\\n")) != NULL) || ((tmp=strstr(line2, "\\N")) != NULL) ){
583 current->text[num]=malloc(tmp-line2+1);
584 strncpy (current->text[num], line2, tmp-line2);
585 current->text[num][tmp-line2]='\0';
586 line2=tmp+2;
587 num++;
588 current->lines++;
589 if (current->lines >= SUB_MAX_TEXT) return current;
592 current->text[num]=strdup(line2);
593 current->lines++;
595 return current;
598 static void sub_pp_ssa(subtitle *sub) {
599 int l=sub->lines;
600 char *so,*de,*start;
602 while (l){
603 /* eliminate any text enclosed with {}, they are font and color settings */
604 so=de=sub->text[--l];
605 while (*so) {
606 if(*so == '{' && so[1]=='\\') {
607 for (start=so; *so && *so!='}'; so++);
608 if(*so) so++; else so=start;
610 if(*so) {
611 *de=*so;
612 so++; de++;
615 *de=*so;
620 * PJS subtitles reader.
621 * That's the "Phoenix Japanimation Society" format.
622 * I found some of them in http://www.scriptsclub.org/ (used for anime).
623 * The time is in tenths of second.
625 * by set, based on code by szabi (dunnowhat sub format ;-)
627 static subtitle *sub_read_line_pjs(stream_t *st,subtitle *current) {
628 char line[LINE_LEN+1];
629 char text[LINE_LEN+1], *s, *d;
631 if (!stream_read_line (st, line, LINE_LEN))
632 return NULL;
633 /* skip spaces */
634 for (s=line; *s && isspace(*s); s++);
635 /* allow empty lines at the end of the file */
636 if (*s==0)
637 return NULL;
638 /* get the time */
639 if (sscanf (s, "%ld,%ld,", &(current->start),
640 &(current->end)) <2) {
641 return ERR;
643 /* the files I have are in tenths of second */
644 current->start *= 10;
645 current->end *= 10;
646 /* walk to the beggining of the string */
647 for (; *s; s++) if (*s==',') break;
648 if (*s) {
649 for (s++; *s; s++) if (*s==',') break;
650 if (*s) s++;
652 if (*s!='"') {
653 return ERR;
655 /* copy the string to the text buffer */
656 for (s++, d=text; *s && *s!='"'; s++, d++)
657 *d=*s;
658 *d=0;
659 current->text[0] = strdup(text);
660 current->lines = 1;
662 return current;
665 static subtitle *sub_read_line_mpsub(stream_t *st, subtitle *current) {
666 char line[LINE_LEN+1];
667 float a,b;
668 int num=0;
669 char *p, *q;
673 if (!stream_read_line(st, line, LINE_LEN)) return NULL;
674 } while (sscanf (line, "%f %f", &a, &b) !=2);
676 mpsub_position += a*mpsub_multiplier;
677 current->start=(int) mpsub_position;
678 mpsub_position += b*mpsub_multiplier;
679 current->end=(int) mpsub_position;
681 while (num < SUB_MAX_TEXT) {
682 if (!stream_read_line (st, line, LINE_LEN)) {
683 if (num == 0) return NULL;
684 else return current;
686 p=line;
687 while (isspace(*p)) p++;
688 if (eol(*p) && num > 0) return current;
689 if (eol(*p)) return NULL;
691 for (q=p; !eol(*q); q++);
692 *q='\0';
693 if (strlen(p)) {
694 current->text[num]=strdup(p);
695 // printf (">%s<\n",p);
696 current->lines = ++num;
697 } else {
698 if (num) return current;
699 else return NULL;
702 return NULL; // we should have returned before if it's OK
705 #ifndef USE_SORTSUB
706 //we don't need this if we use previous_sub_end
707 subtitle *previous_aqt_sub = NULL;
708 #endif
710 static subtitle *sub_read_line_aqt(stream_t *st,subtitle *current) {
711 char line[LINE_LEN+1];
712 char *next;
713 int i;
715 while (1) {
716 // try to locate next subtitle
717 if (!stream_read_line (st, line, LINE_LEN))
718 return NULL;
719 if (!(sscanf (line, "-->> %ld", &(current->start)) <1))
720 break;
723 #ifdef USE_SORTSUB
724 previous_sub_end = (current->start) ? current->start - 1 : 0;
725 #else
726 if (previous_aqt_sub != NULL)
727 previous_aqt_sub->end = current->start-1;
729 previous_aqt_sub = current;
730 #endif
732 if (!stream_read_line (st, line, LINE_LEN))
733 return NULL;
735 sub_readtext((char *) &line,&current->text[0]);
736 current->lines = 1;
737 current->end = current->start; // will be corrected by next subtitle
739 if (!stream_read_line (st, line, LINE_LEN))
740 return current;
742 next = line,i=1;
743 while ((next =sub_readtext (next, &(current->text[i])))) {
744 if (current->text[i]==ERR) {return ERR;}
745 i++;
746 if (i>=SUB_MAX_TEXT) { mp_msg(MSGT_SUBREADER,MSGL_WARN,"Too many lines in a subtitle\n");current->lines=i;return current;}
748 current->lines=i+1;
750 if (!strlen(current->text[0]) && !strlen(current->text[1])) {
751 #ifdef USE_SORTSUB
752 previous_sub_end = 0;
753 #else
754 // void subtitle -> end of previous marked and exit
755 previous_aqt_sub = NULL;
756 #endif
757 return NULL;
760 return current;
763 #ifndef USE_SORTSUB
764 subtitle *previous_subrip09_sub = NULL;
765 #endif
767 static subtitle *sub_read_line_subrip09(stream_t *st,subtitle *current) {
768 char line[LINE_LEN+1];
769 int a1,a2,a3;
770 char * next=NULL;
771 int i,len;
773 while (1) {
774 // try to locate next subtitle
775 if (!stream_read_line (st, line, LINE_LEN))
776 return NULL;
777 if (!((len=sscanf (line, "[%d:%d:%d]",&a1,&a2,&a3)) < 3))
778 break;
781 current->start = a1*360000+a2*6000+a3*100;
783 #ifdef USE_SORTSUB
784 previous_sub_end = (current->start) ? current->start - 1 : 0;
785 #else
786 if (previous_subrip09_sub != NULL)
787 previous_subrip09_sub->end = current->start-1;
789 previous_subrip09_sub = current;
790 #endif
792 if (!stream_read_line (st, line, LINE_LEN))
793 return NULL;
795 next = line,i=0;
797 current->text[0]=""; // just to be sure that string is clear
799 while ((next =sub_readtext (next, &(current->text[i])))) {
800 if (current->text[i]==ERR) {return ERR;}
801 i++;
802 if (i>=SUB_MAX_TEXT) { mp_msg(MSGT_SUBREADER,MSGL_WARN,"Too many lines in a subtitle\n");current->lines=i;return current;}
804 current->lines=i+1;
806 if (!strlen(current->text[0]) && (i==0)) {
807 #ifdef USE_SORTSUB
808 previous_sub_end = 0;
809 #else
810 // void subtitle -> end of previous marked and exit
811 previous_subrip09_sub = NULL;
812 #endif
813 return NULL;
816 return current;
819 static subtitle *sub_read_line_jacosub(stream_t* st, subtitle * current)
821 char line1[LINE_LEN], line2[LINE_LEN], directive[LINE_LEN], *p, *q;
822 unsigned a1, a2, a3, a4, b1, b2, b3, b4, comment = 0;
823 static unsigned jacoTimeres = 30;
824 static int jacoShift = 0;
826 memset(current, 0, sizeof(subtitle));
827 memset(line1, 0, LINE_LEN);
828 memset(line2, 0, LINE_LEN);
829 memset(directive, 0, LINE_LEN);
830 while (!current->text[0]) {
831 if (!stream_read_line(st, line1, LINE_LEN)) {
832 return NULL;
834 if (sscanf
835 (line1, "%u:%u:%u.%u %u:%u:%u.%u %[^\n\r]", &a1, &a2, &a3, &a4,
836 &b1, &b2, &b3, &b4, line2) < 9) {
837 if (sscanf(line1, "@%u @%u %[^\n\r]", &a4, &b4, line2) < 3) {
838 if (line1[0] == '#') {
839 int hours = 0, minutes = 0, seconds, delta, inverter =
841 unsigned units = jacoShift;
842 switch (toupper(line1[1])) {
843 case 'S':
844 if (isalpha(line1[2])) {
845 delta = 6;
846 } else {
847 delta = 2;
849 if (sscanf(&line1[delta], "%d", &hours)) {
850 if (hours < 0) {
851 hours *= -1;
852 inverter = -1;
854 if (sscanf(&line1[delta], "%*d:%d", &minutes)) {
855 if (sscanf
856 (&line1[delta], "%*d:%*d:%d",
857 &seconds)) {
858 sscanf(&line1[delta], "%*d:%*d:%*d.%d",
859 &units);
860 } else {
861 hours = 0;
862 sscanf(&line1[delta], "%d:%d.%d",
863 &minutes, &seconds, &units);
864 minutes *= inverter;
866 } else {
867 hours = minutes = 0;
868 sscanf(&line1[delta], "%d.%d", &seconds,
869 &units);
870 seconds *= inverter;
872 jacoShift =
873 ((hours * 3600 + minutes * 60 +
874 seconds) * jacoTimeres +
875 units) * inverter;
877 break;
878 case 'T':
879 if (isalpha(line1[2])) {
880 delta = 8;
881 } else {
882 delta = 2;
884 sscanf(&line1[delta], "%u", &jacoTimeres);
885 break;
888 continue;
889 } else {
890 current->start =
891 (unsigned long) ((a4 + jacoShift) * 100.0 /
892 jacoTimeres);
893 current->end =
894 (unsigned long) ((b4 + jacoShift) * 100.0 /
895 jacoTimeres);
897 } else {
898 current->start =
899 (unsigned
900 long) (((a1 * 3600 + a2 * 60 + a3) * jacoTimeres + a4 +
901 jacoShift) * 100.0 / jacoTimeres);
902 current->end =
903 (unsigned
904 long) (((b1 * 3600 + b2 * 60 + b3) * jacoTimeres + b4 +
905 jacoShift) * 100.0 / jacoTimeres);
907 current->lines = 0;
908 p = line2;
909 while ((*p == ' ') || (*p == '\t')) {
910 ++p;
912 if (isalpha(*p)||*p == '[') {
913 int cont, jLength;
915 if (sscanf(p, "%s %[^\n\r]", directive, line1) < 2)
916 return (subtitle *) ERR;
917 jLength = strlen(directive);
918 for (cont = 0; cont < jLength; ++cont) {
919 if (isalpha(*(directive + cont)))
920 *(directive + cont) = toupper(*(directive + cont));
922 if ((strstr(directive, "RDB") != NULL)
923 || (strstr(directive, "RDC") != NULL)
924 || (strstr(directive, "RLB") != NULL)
925 || (strstr(directive, "RLG") != NULL)) {
926 continue;
928 if (strstr(directive, "JL") != NULL) {
929 current->alignment = SUB_ALIGNMENT_BOTTOMLEFT;
930 } else if (strstr(directive, "JR") != NULL) {
931 current->alignment = SUB_ALIGNMENT_BOTTOMRIGHT;
932 } else {
933 current->alignment = SUB_ALIGNMENT_BOTTOMCENTER;
935 strcpy(line2, line1);
936 p = line2;
938 for (q = line1; (!eol(*p)) && (current->lines < SUB_MAX_TEXT); ++p) {
939 switch (*p) {
940 case '{':
941 comment++;
942 break;
943 case '}':
944 if (comment) {
945 --comment;
946 //the next line to get rid of a blank after the comment
947 if ((*(p + 1)) == ' ')
948 p++;
950 break;
951 case '~':
952 if (!comment) {
953 *q = ' ';
954 ++q;
956 break;
957 case ' ':
958 case '\t':
959 if ((*(p + 1) == ' ') || (*(p + 1) == '\t'))
960 break;
961 if (!comment) {
962 *q = ' ';
963 ++q;
965 break;
966 case '\\':
967 if (*(p + 1) == 'n') {
968 *q = '\0';
969 q = line1;
970 current->text[current->lines++] = strdup(line1);
971 ++p;
972 break;
974 if ((toupper(*(p + 1)) == 'C')
975 || (toupper(*(p + 1)) == 'F')) {
976 ++p,++p;
977 break;
979 if ((*(p + 1) == 'B') || (*(p + 1) == 'b') || (*(p + 1) == 'D') || //actually this means "insert current date here"
980 (*(p + 1) == 'I') || (*(p + 1) == 'i') || (*(p + 1) == 'N') || (*(p + 1) == 'T') || //actually this means "insert current time here"
981 (*(p + 1) == 'U') || (*(p + 1) == 'u')) {
982 ++p;
983 break;
985 if ((*(p + 1) == '\\') ||
986 (*(p + 1) == '~') || (*(p + 1) == '{')) {
987 ++p;
988 } else if (eol(*(p + 1))) {
989 if (!stream_read_line(st, directive, LINE_LEN))
990 return NULL;
991 trail_space(directive);
992 strncat(line2, directive,
993 (LINE_LEN > 511) ? LINE_LEN : 511);
994 break;
996 default:
997 if (!comment) {
998 *q = *p;
999 ++q;
1001 } //-- switch
1002 } //-- for
1003 *q = '\0';
1004 current->text[current->lines] = strdup(line1);
1005 } //-- while
1006 current->lines++;
1007 return current;
1010 static int sub_autodetect (stream_t* st, int *uses_time) {
1011 char line[LINE_LEN+1];
1012 int i,j=0;
1013 char p;
1015 while (j < 100) {
1016 j++;
1017 if (!stream_read_line (st, line, LINE_LEN))
1018 return SUB_INVALID;
1020 if (sscanf (line, "{%d}{%d}", &i, &i)==2)
1021 {*uses_time=0;return SUB_MICRODVD;}
1022 if (sscanf (line, "{%d}{}", &i)==1)
1023 {*uses_time=0;return SUB_MICRODVD;}
1024 if (sscanf (line, "[%d][%d]", &i, &i)==2)
1025 {*uses_time=1;return SUB_MPL2;}
1026 if (sscanf (line, "%d:%d:%d.%d,%d:%d:%d.%d", &i, &i, &i, &i, &i, &i, &i, &i)==8)
1027 {*uses_time=1;return SUB_SUBRIP;}
1028 if (sscanf (line, "%d:%d:%d%[,.:]%d --> %d:%d:%d%[,.:]%d", &i, &i, &i, (char *)&i, &i, &i, &i, &i, (char *)&i, &i)==10)
1029 {*uses_time=1;return SUB_SUBVIEWER;}
1030 if (sscanf (line, "{T %d:%d:%d:%d",&i, &i, &i, &i)==4)
1031 {*uses_time=1;return SUB_SUBVIEWER2;}
1032 if (strstr (line, "<SAMI>"))
1033 {*uses_time=1; return SUB_SAMI;}
1034 if (sscanf(line, "%d:%d:%d.%d %d:%d:%d.%d", &i, &i, &i, &i, &i, &i, &i, &i) == 8)
1035 {*uses_time = 1; return SUB_JACOSUB;}
1036 if (sscanf(line, "@%d @%d", &i, &i) == 2)
1037 {*uses_time = 1; return SUB_JACOSUB;}
1038 if (sscanf (line, "%d:%d:%d:", &i, &i, &i )==3)
1039 {*uses_time=1;return SUB_VPLAYER;}
1040 if (sscanf (line, "%d:%d:%d ", &i, &i, &i )==3)
1041 {*uses_time=1;return SUB_VPLAYER;}
1042 //TODO: just checking if first line of sub starts with "<" is WAY
1043 // too weak test for RT
1044 // Please someone who knows the format of RT... FIX IT!!!
1045 // It may conflict with other sub formats in the future (actually it doesn't)
1046 if ( *line == '<' )
1047 {*uses_time=1;return SUB_RT;}
1049 if (!memcmp(line, "Dialogue: Marked", 16))
1050 {*uses_time=1; return SUB_SSA;}
1051 if (!memcmp(line, "Dialogue: ", 10))
1052 {*uses_time=1; return SUB_SSA;}
1053 if (sscanf (line, "%d,%d,\"%c", &i, &i, (char *) &i) == 3)
1054 {*uses_time=1;return SUB_PJS;}
1055 if (sscanf (line, "FORMAT=%d", &i) == 1)
1056 {*uses_time=0; return SUB_MPSUB;}
1057 if (sscanf (line, "FORMAT=TIM%c", &p)==1 && p=='E')
1058 {*uses_time=1; return SUB_MPSUB;}
1059 if (strstr (line, "-->>"))
1060 {*uses_time=0; return SUB_AQTITLE;}
1061 if (sscanf (line, "[%d:%d:%d]", &i, &i, &i)==3)
1062 {*uses_time=1;return SUB_SUBRIP09;}
1065 return SUB_INVALID; // too many bad lines
1068 #ifdef DUMPSUBS
1069 int sub_utf8=0;
1070 #else
1071 extern int sub_utf8;
1072 int sub_utf8_prev=0;
1073 #endif
1075 extern float sub_delay;
1076 extern float sub_fps;
1078 #ifdef USE_ICONV
1079 static iconv_t icdsc = (iconv_t)(-1);
1081 void subcp_open (stream_t *st)
1083 char *tocp = "UTF-8";
1085 if (sub_cp){
1086 const char *cp_tmp = sub_cp;
1087 #ifdef HAVE_ENCA
1088 char enca_lang[3], enca_fallback[100];
1089 if (sscanf(sub_cp, "enca:%2s:%99s", enca_lang, enca_fallback) == 2
1090 || sscanf(sub_cp, "ENCA:%2s:%99s", enca_lang, enca_fallback) == 2) {
1091 if (st && st->flags & STREAM_SEEK ) {
1092 cp_tmp = guess_cp(st, enca_lang, enca_fallback);
1093 } else {
1094 cp_tmp = enca_fallback;
1095 if (st)
1096 mp_msg(MSGT_SUBREADER,MSGL_WARN,"SUB: enca failed, stream must be seekable.\n");
1099 #endif
1100 if ((icdsc = iconv_open (tocp, cp_tmp)) != (iconv_t)(-1)){
1101 mp_msg(MSGT_SUBREADER,MSGL_V,"SUB: opened iconv descriptor.\n");
1102 sub_utf8 = 2;
1103 } else
1104 mp_msg(MSGT_SUBREADER,MSGL_ERR,"SUB: error opening iconv descriptor.\n");
1108 void subcp_close (void)
1110 if (icdsc != (iconv_t)(-1)){
1111 (void) iconv_close (icdsc);
1112 icdsc = (iconv_t)(-1);
1113 mp_msg(MSGT_SUBREADER,MSGL_V,"SUB: closed iconv descriptor.\n");
1117 subtitle* subcp_recode (subtitle *sub)
1119 int l=sub->lines;
1120 size_t ileft, oleft;
1121 char *op, *ip, *ot;
1122 if(icdsc == (iconv_t)(-1)) return sub;
1124 while (l){
1125 ip = sub->text[--l];
1126 ileft = strlen(ip);
1127 oleft = 4 * ileft;
1129 if (!(ot = malloc(oleft + 1))){
1130 mp_msg(MSGT_SUBREADER,MSGL_WARN,"SUB: error allocating mem.\n");
1131 continue;
1133 op = ot;
1134 if (iconv(icdsc, &ip, &ileft,
1135 &op, &oleft) == (size_t)(-1)) {
1136 mp_msg(MSGT_SUBREADER,MSGL_WARN,"SUB: error recoding line.\n");
1137 free(ot);
1138 continue;
1140 *op='\0' ;
1141 free (sub->text[l]);
1142 sub->text[l] = ot;
1144 return sub;
1146 #endif
1148 #ifdef USE_FRIBIDI
1149 #ifndef max
1150 #define max(a,b) (((a)>(b))?(a):(b))
1151 #endif
1152 subtitle* sub_fribidi (subtitle *sub, int sub_utf8)
1154 FriBidiChar logical[LINE_LEN+1], visual[LINE_LEN+1]; // Hopefully these two won't smash the stack
1155 char *ip = NULL, *op = NULL;
1156 FriBidiCharType base;
1157 size_t len,orig_len;
1158 int l=sub->lines;
1159 int char_set_num;
1160 fribidi_boolean log2vis;
1161 if(flip_hebrew) { // Please fix the indentation someday
1162 fribidi_set_mirroring(1);
1163 fribidi_set_reorder_nsm(0);
1165 if( sub_utf8 == 0 ) {
1166 char_set_num = fribidi_parse_charset (fribidi_charset?fribidi_charset:"ISO8859-8");
1167 }else {
1168 char_set_num = fribidi_parse_charset ("UTF-8");
1170 while (l) {
1171 ip = sub->text[--l];
1172 orig_len = len = strlen( ip ); // We assume that we don't use full unicode, only UTF-8 or ISO8859-x
1173 if(len > LINE_LEN) {
1174 mp_msg(MSGT_SUBREADER,MSGL_WARN,"SUB: sub->text is longer than LINE_LEN.\n");
1175 l++;
1176 break;
1178 len = fribidi_charset_to_unicode (char_set_num, ip, len, logical);
1179 base = fribidi_flip_commas?FRIBIDI_TYPE_ON:FRIBIDI_TYPE_L;
1180 log2vis = fribidi_log2vis (logical, len, &base,
1181 /* output */
1182 visual, NULL, NULL, NULL);
1183 if(log2vis) {
1184 len = fribidi_remove_bidi_marks (visual, len, NULL, NULL,
1185 NULL);
1186 if((op = malloc((max(2*orig_len,2*len) + 1))) == NULL) {
1187 mp_msg(MSGT_SUBREADER,MSGL_WARN,"SUB: error allocating mem.\n");
1188 l++;
1189 break;
1191 fribidi_unicode_to_charset ( char_set_num, visual, len,op);
1192 free (ip);
1193 sub->text[l] = op;
1196 if (l){
1197 for (l = sub->lines; l;)
1198 free (sub->text[--l]);
1199 return ERR;
1202 return sub;
1205 #endif
1207 static void adjust_subs_time(subtitle* sub, float subtime, float fps, int block,
1208 int sub_num, int sub_uses_time) {
1209 int n,m;
1210 subtitle* nextsub;
1211 int i = sub_num;
1212 unsigned long subfms = (sub_uses_time ? 100 : fps) * subtime;
1213 unsigned long overlap = (sub_uses_time ? 100 : fps) / 5; // 0.2s
1215 n=m=0;
1216 if (i) for (;;){
1217 if (sub->end <= sub->start){
1218 sub->end = sub->start + subfms;
1219 m++;
1220 n++;
1222 if (!--i) break;
1223 nextsub = sub + 1;
1224 if(block){
1225 if ((sub->end > nextsub->start) && (sub->end <= nextsub->start + overlap)) {
1226 // these subtitles overlap for less than 0.2 seconds
1227 // and would result in very short overlapping subtitle
1228 // so let's fix the problem here, before overlapping code
1229 // get its hands on them
1230 unsigned delta = sub->end - nextsub->start, half = delta / 2;
1231 sub->end -= half + 1;
1232 nextsub->start += delta - half;
1234 if (sub->end >= nextsub->start){
1235 sub->end = nextsub->start - 1;
1236 if (sub->end - sub->start > subfms)
1237 sub->end = sub->start + subfms;
1238 if (!m)
1239 n++;
1243 /* Theory:
1244 * Movies are often converted from FILM (24 fps)
1245 * to PAL (25) by simply speeding it up, so we
1246 * to multiply the original timestmaps by
1247 * (Movie's FPS / Subtitle's (guessed) FPS)
1248 * so eg. for 23.98 fps movie and PAL time based
1249 * subtitles we say -subfps 25 and we're fine!
1252 /* timed sub fps correction ::atmos */
1253 /* the frame-based case is handled in mpcommon.c
1254 * where find_sub is called */
1255 if(sub_uses_time && sub_fps) {
1256 sub->start *= sub_fps/fps;
1257 sub->end *= sub_fps/fps;
1260 sub = nextsub;
1261 m = 0;
1263 if (n) mp_msg(MSGT_SUBREADER,MSGL_INFO,"SUB: Adjusted %d subtitle(s).\n", n);
1266 struct subreader {
1267 subtitle * (*read)(stream_t *st,subtitle *dest);
1268 void (*post)(subtitle *dest);
1269 const char *name;
1272 #ifdef HAVE_ENCA
1273 const char* guess_buffer_cp(unsigned char* buffer, int buflen, const char *preferred_language, const char *fallback)
1275 const char **languages;
1276 size_t langcnt;
1277 EncaAnalyser analyser;
1278 EncaEncoding encoding;
1279 const char *detected_sub_cp = NULL;
1280 int i;
1282 languages = enca_get_languages(&langcnt);
1283 mp_msg(MSGT_SUBREADER, MSGL_V, "ENCA supported languages: ");
1284 for (i = 0; i < langcnt; i++) {
1285 mp_msg(MSGT_SUBREADER, MSGL_V, "%s ", languages[i]);
1287 mp_msg(MSGT_SUBREADER, MSGL_V, "\n");
1289 for (i = 0; i < langcnt; i++) {
1290 if (strcasecmp(languages[i], preferred_language) != 0) continue;
1291 analyser = enca_analyser_alloc(languages[i]);
1292 encoding = enca_analyse_const(analyser, buffer, buflen);
1293 enca_analyser_free(analyser);
1294 if (encoding.charset != ENCA_CS_UNKNOWN) {
1295 detected_sub_cp = enca_charset_name(encoding.charset, ENCA_NAME_STYLE_ICONV);
1296 break;
1300 free(languages);
1302 if (!detected_sub_cp) {
1303 detected_sub_cp = fallback;
1304 mp_msg(MSGT_SUBREADER, MSGL_INFO, "ENCA detection failed: fallback to %s\n", fallback);
1305 }else{
1306 mp_msg(MSGT_SUBREADER, MSGL_INFO, "ENCA detected charset: %s\n", detected_sub_cp);
1309 return detected_sub_cp;
1312 #define MAX_GUESS_BUFFER_SIZE (256*1024)
1313 const char* guess_cp(stream_t *st, const char *preferred_language, const char *fallback)
1315 size_t buflen;
1316 unsigned char *buffer;
1317 const char *detected_sub_cp = NULL;
1319 buffer = malloc(MAX_GUESS_BUFFER_SIZE);
1320 buflen = stream_read(st,buffer, MAX_GUESS_BUFFER_SIZE);
1322 detected_sub_cp = guess_buffer_cp(buffer, buflen, preferred_language, fallback);
1324 free(buffer);
1325 stream_reset(st);
1326 stream_seek(st,0);
1328 return detected_sub_cp;
1330 #undef MAX_GUESS_BUFFER_SIZE
1331 #endif
1333 sub_data* sub_read_file (char *filename, float fps) {
1334 stream_t* fd;
1335 int n_max, n_first, i, j, sub_first, sub_orig;
1336 subtitle *first, *second, *sub, *return_sub;
1337 sub_data *subt_data;
1338 int uses_time = 0, sub_num = 0, sub_errs = 0;
1339 struct subreader sr[]=
1341 { sub_read_line_microdvd, NULL, "microdvd" },
1342 { sub_read_line_subrip, NULL, "subrip" },
1343 { sub_read_line_subviewer, NULL, "subviewer" },
1344 { sub_read_line_sami, NULL, "sami" },
1345 { sub_read_line_vplayer, NULL, "vplayer" },
1346 { sub_read_line_rt, NULL, "rt" },
1347 { sub_read_line_ssa, sub_pp_ssa, "ssa" },
1348 { sub_read_line_pjs, NULL, "pjs" },
1349 { sub_read_line_mpsub, NULL, "mpsub" },
1350 { sub_read_line_aqt, NULL, "aqt" },
1351 { sub_read_line_subviewer2, NULL, "subviewer 2.0" },
1352 { sub_read_line_subrip09, NULL, "subrip 0.9" },
1353 { sub_read_line_jacosub, NULL, "jacosub" },
1354 { sub_read_line_mpl2, NULL, "mpl2" }
1356 struct subreader *srp;
1358 if(filename==NULL) return NULL; //qnx segfault
1359 i = 0;
1360 fd=open_stream (filename, NULL, &i); if (!fd) return NULL;
1362 sub_format=sub_autodetect (fd, &uses_time);
1363 mpsub_multiplier = (uses_time ? 100.0 : 1.0);
1364 if (sub_format==SUB_INVALID) {mp_msg(MSGT_SUBREADER,MSGL_WARN,"SUB: Could not determine file format\n");return NULL;}
1365 srp=sr+sub_format;
1366 mp_msg(MSGT_SUBREADER,MSGL_INFO,"SUB: Detected subtitle file format: %s\n", srp->name);
1368 stream_reset(fd);
1369 stream_seek(fd,0);
1371 #ifdef USE_ICONV
1372 sub_utf8_prev=sub_utf8;
1374 int l,k;
1375 k = -1;
1376 if ((l=strlen(filename))>4){
1377 char *exts[] = {".utf", ".utf8", ".utf-8" };
1378 for (k=3;--k>=0;)
1379 if (l >= strlen(exts[k]) && !strcasecmp(filename+(l - strlen(exts[k])), exts[k])){
1380 sub_utf8 = 1;
1381 break;
1384 if (k<0) subcp_open(fd);
1386 #endif
1388 sub_num=0;n_max=32;
1389 first=malloc(n_max*sizeof(subtitle));
1390 if(!first){
1391 #ifdef USE_ICONV
1392 subcp_close();
1393 sub_utf8=sub_utf8_prev;
1394 #endif
1395 return NULL;
1398 #ifdef USE_SORTSUB
1399 sub = malloc(sizeof(subtitle));
1400 //This is to deal with those formats (AQT & Subrip) which define the end of a subtitle
1401 //as the beginning of the following
1402 previous_sub_end = 0;
1403 #endif
1404 while(1){
1405 if(sub_num>=n_max){
1406 n_max+=16;
1407 first=realloc(first,n_max*sizeof(subtitle));
1409 #ifndef USE_SORTSUB
1410 sub = &first[sub_num];
1411 #endif
1412 memset(sub, '\0', sizeof(subtitle));
1413 sub=srp->read(fd,sub);
1414 if(!sub) break; // EOF
1415 #ifdef USE_ICONV
1416 if ((sub!=ERR) && (sub_utf8 & 2)) sub=subcp_recode(sub);
1417 #endif
1418 #ifdef USE_FRIBIDI
1419 if (sub!=ERR) sub=sub_fribidi(sub,sub_utf8);
1420 #endif
1421 if ( sub == ERR )
1423 #ifdef USE_ICONV
1424 subcp_close();
1425 #endif
1426 if ( first ) free(first);
1427 return NULL;
1429 // Apply any post processing that needs recoding first
1430 if ((sub!=ERR) && !sub_no_text_pp && srp->post) srp->post(sub);
1431 #ifdef USE_SORTSUB
1432 if(!sub_num || (first[sub_num - 1].start <= sub->start)){
1433 first[sub_num].start = sub->start;
1434 first[sub_num].end = sub->end;
1435 first[sub_num].lines = sub->lines;
1436 first[sub_num].alignment = sub->alignment;
1437 for(i = 0; i < sub->lines; ++i){
1438 first[sub_num].text[i] = sub->text[i];
1440 if (previous_sub_end){
1441 first[sub_num - 1].end = previous_sub_end;
1442 previous_sub_end = 0;
1444 } else {
1445 for(j = sub_num - 1; j >= 0; --j){
1446 first[j + 1].start = first[j].start;
1447 first[j + 1].end = first[j].end;
1448 first[j + 1].lines = first[j].lines;
1449 first[j + 1].alignment = first[j].alignment;
1450 for(i = 0; i < first[j].lines; ++i){
1451 first[j + 1].text[i] = first[j].text[i];
1453 if(!j || (first[j - 1].start <= sub->start)){
1454 first[j].start = sub->start;
1455 first[j].end = sub->end;
1456 first[j].lines = sub->lines;
1457 first[j].alignment = sub->alignment;
1458 for(i = 0; i < SUB_MAX_TEXT; ++i){
1459 first[j].text[i] = sub->text[i];
1461 if (previous_sub_end){
1462 first[j].end = first[j - 1].end;
1463 first[j - 1].end = previous_sub_end;
1464 previous_sub_end = 0;
1466 break;
1470 #endif
1471 if(sub==ERR) ++sub_errs; else ++sub_num; // Error vs. Valid
1474 free_stream(fd);
1476 #ifdef USE_ICONV
1477 subcp_close();
1478 #endif
1480 // printf ("SUB: Subtitle format %s time.\n", uses_time?"uses":"doesn't use");
1481 mp_msg(MSGT_SUBREADER,MSGL_INFO,"SUB: Read %i subtitles", sub_num);
1482 if (sub_errs) mp_msg(MSGT_SUBREADER,MSGL_INFO,", %i bad line(s).\n", sub_errs);
1483 else mp_msg(MSGT_SUBREADER,MSGL_INFO,".\n");
1485 if(sub_num<=0){
1486 free(first);
1487 return NULL;
1490 // we do overlap if the user forced it (suboverlap_enable == 2) or
1491 // the user didn't forced no-overlapsub and the format is Jacosub or Ssa.
1492 // this is because usually overlapping subtitles are found in these formats,
1493 // while in others they are probably result of bad timing
1494 if ((suboverlap_enabled == 2) ||
1495 ((suboverlap_enabled) && ((sub_format == SUB_JACOSUB) || (sub_format == SUB_SSA)))) {
1496 adjust_subs_time(first, 6.0, fps, 0, sub_num, uses_time);/*~6 secs AST*/
1497 // here we manage overlapping subtitles
1498 sub_orig = sub_num;
1499 n_first = sub_num;
1500 sub_num = 0;
1501 second = NULL;
1502 // for each subtitle in first[] we deal with its 'block' of
1503 // bonded subtitles
1504 for (sub_first = 0; sub_first < n_first; ++sub_first) {
1505 unsigned long global_start = first[sub_first].start,
1506 global_end = first[sub_first].end, local_start, local_end;
1507 int lines_to_add = first[sub_first].lines, sub_to_add = 0,
1508 **placeholder = NULL, higher_line = 0, counter, start_block_sub = sub_num;
1509 char real_block = 1;
1511 // here we find the number of subtitles inside the 'block'
1512 // and its span interval. this works well only with sorted
1513 // subtitles
1514 while ((sub_first + sub_to_add + 1 < n_first) && (first[sub_first + sub_to_add + 1].start < global_end)) {
1515 ++sub_to_add;
1516 lines_to_add += first[sub_first + sub_to_add].lines;
1517 if (first[sub_first + sub_to_add].start < global_start) {
1518 global_start = first[sub_first + sub_to_add].start;
1520 if (first[sub_first + sub_to_add].end > global_end) {
1521 global_end = first[sub_first + sub_to_add].end;
1525 // we need a structure to keep trace of the screen lines
1526 // used by the subs, a 'placeholder'
1527 counter = 2 * sub_to_add + 1; // the maximum number of subs derived
1528 // from a block of sub_to_add+1 subs
1529 placeholder = malloc(sizeof(int *) * counter);
1530 for (i = 0; i < counter; ++i) {
1531 placeholder[i] = malloc(sizeof(int) * lines_to_add);
1532 for (j = 0; j < lines_to_add; ++j) {
1533 placeholder[i][j] = -1;
1537 counter = 0;
1538 local_end = global_start - 1;
1539 do {
1540 int ls;
1542 // here we find the beginning and the end of a new
1543 // subtitle in the block
1544 local_start = local_end + 1;
1545 local_end = global_end;
1546 for (j = 0; j <= sub_to_add; ++j) {
1547 if ((first[sub_first + j].start - 1 > local_start) && (first[sub_first + j].start - 1 < local_end)) {
1548 local_end = first[sub_first + j].start - 1;
1549 } else if ((first[sub_first + j].end > local_start) && (first[sub_first + j].end < local_end)) {
1550 local_end = first[sub_first + j].end;
1553 // here we allocate the screen lines to subs we must
1554 // display in current local_start-local_end interval.
1555 // if the subs were yet presents in the previous interval
1556 // they keep the same lines, otherside they get unused lines
1557 for (j = 0; j <= sub_to_add; ++j) {
1558 if ((first[sub_first + j].start <= local_end) && (first[sub_first + j].end > local_start)) {
1559 unsigned long sub_lines = first[sub_first + j].lines, fragment_length = lines_to_add + 1,
1560 tmp = 0;
1561 char boolean = 0;
1562 int fragment_position = -1;
1564 // if this is not the first new sub of the block
1565 // we find if this sub was present in the previous
1566 // new sub
1567 if (counter)
1568 for (i = 0; i < lines_to_add; ++i) {
1569 if (placeholder[counter - 1][i] == sub_first + j) {
1570 placeholder[counter][i] = sub_first + j;
1571 boolean = 1;
1574 if (boolean)
1575 continue;
1577 // we are looking for the shortest among all groups of
1578 // sequential blank lines whose length is greater than or
1579 // equal to sub_lines. we store in fragment_position the
1580 // position of the shortest group, in fragment_length its
1581 // length, and in tmp the length of the group currently
1582 // examinated
1583 for (i = 0; i < lines_to_add; ++i) {
1584 if (placeholder[counter][i] == -1) {
1585 // placeholder[counter][i] is part of the current group
1586 // of blank lines
1587 ++tmp;
1588 } else {
1589 if (tmp == sub_lines) {
1590 // current group's size fits exactly the one we
1591 // need, so we stop looking
1592 fragment_position = i - tmp;
1593 tmp = 0;
1594 break;
1596 if ((tmp) && (tmp > sub_lines) && (tmp < fragment_length)) {
1597 // current group is the best we found till here,
1598 // but is still bigger than the one we are looking
1599 // for, so we keep on looking
1600 fragment_length = tmp;
1601 fragment_position = i - tmp;
1602 tmp = 0;
1603 } else {
1604 // current group doesn't fit at all, so we forget it
1605 tmp = 0;
1609 if (tmp) {
1610 // last screen line is blank, a group ends with it
1611 if ((tmp >= sub_lines) && (tmp < fragment_length)) {
1612 fragment_position = i - tmp;
1615 if (fragment_position == -1) {
1616 // it was not possible to find free screen line(s) for a subtitle,
1617 // usually this means a bug in the code; however we do not overlap
1618 mp_msg(MSGT_SUBREADER, MSGL_WARN, "SUB: we could not find a suitable position for an overlapping subtitle\n");
1619 higher_line = SUB_MAX_TEXT + 1;
1620 break;
1621 } else {
1622 for (tmp = 0; tmp < sub_lines; ++tmp) {
1623 placeholder[counter][fragment_position + tmp] = sub_first + j;
1628 for (j = higher_line + 1; j < lines_to_add; ++j) {
1629 if (placeholder[counter][j] != -1)
1630 higher_line = j;
1631 else
1632 break;
1634 if (higher_line >= SUB_MAX_TEXT) {
1635 // the 'block' has too much lines, so we don't overlap the
1636 // subtitles
1637 second = (subtitle *) realloc(second, (sub_num + sub_to_add + 1) * sizeof(subtitle));
1638 for (j = 0; j <= sub_to_add; ++j) {
1639 int ls;
1640 memset(&second[sub_num + j], '\0', sizeof(subtitle));
1641 second[sub_num + j].start = first[sub_first + j].start;
1642 second[sub_num + j].end = first[sub_first + j].end;
1643 second[sub_num + j].lines = first[sub_first + j].lines;
1644 second[sub_num + j].alignment = first[sub_first + j].alignment;
1645 for (ls = 0; ls < second[sub_num + j].lines; ls++) {
1646 second[sub_num + j].text[ls] = strdup(first[sub_first + j].text[ls]);
1649 sub_num += sub_to_add + 1;
1650 sub_first += sub_to_add;
1651 real_block = 0;
1652 break;
1655 // we read the placeholder structure and create the new
1656 // subs.
1657 second = (subtitle *) realloc(second, (sub_num + 1) * sizeof(subtitle));
1658 memset(&second[sub_num], '\0', sizeof(subtitle));
1659 second[sub_num].start = local_start;
1660 second[sub_num].end = local_end;
1661 second[sub_num].alignment = first[sub_first].alignment;
1662 n_max = (lines_to_add < SUB_MAX_TEXT) ? lines_to_add : SUB_MAX_TEXT;
1663 for (i = 0, j = 0; j < n_max; ++j) {
1664 if (placeholder[counter][j] != -1) {
1665 int lines = first[placeholder[counter][j]].lines;
1666 for (ls = 0; ls < lines; ++ls) {
1667 second[sub_num].text[i++] = strdup(first[placeholder[counter][j]].text[ls]);
1669 j += lines - 1;
1670 } else {
1671 second[sub_num].text[i++] = strdup(" ");
1674 ++sub_num;
1675 ++counter;
1676 } while (local_end < global_end);
1677 if (real_block)
1678 for (i = 0; i < counter; ++i)
1679 second[start_block_sub + i].lines = higher_line + 1;
1681 counter = 2 * sub_to_add + 1;
1682 for (i = 0; i < counter; ++i) {
1683 free(placeholder[i]);
1685 free(placeholder);
1686 sub_first += sub_to_add;
1689 for (j = sub_orig - 1; j >= 0; --j) {
1690 for (i = first[j].lines - 1; i >= 0; --i) {
1691 free(first[j].text[i]);
1694 free(first);
1696 return_sub = second;
1697 } else { //if(suboverlap_enabled)
1698 adjust_subs_time(first, 6.0, fps, 1, sub_num, uses_time);/*~6 secs AST*/
1699 return_sub = first;
1701 if (return_sub == NULL) return NULL;
1702 subt_data = malloc(sizeof(sub_data));
1703 subt_data->filename = strdup(filename);
1704 subt_data->sub_uses_time = uses_time;
1705 subt_data->sub_num = sub_num;
1706 subt_data->sub_errs = sub_errs;
1707 subt_data->subtitles = return_sub;
1708 return subt_data;
1711 #if 0
1712 char * strreplace( char * in,char * what,char * whereof )
1714 int i;
1715 char * tmp;
1717 if ( ( in == NULL )||( what == NULL )||( whereof == NULL )||( ( tmp=strstr( in,what ) ) == NULL ) ) return NULL;
1718 for( i=0;i<strlen( whereof );i++ ) tmp[i]=whereof[i];
1719 if ( strlen( what ) > strlen( whereof ) ) tmp[i]=0;
1720 return in;
1722 #endif
1725 static void strcpy_trim(char *d, char *s)
1727 // skip leading whitespace
1728 while (*s && !isalnum(*s)) {
1729 s++;
1731 for (;;) {
1732 // copy word
1733 while (*s && isalnum(*s)) {
1734 *d = tolower(*s);
1735 s++; d++;
1737 if (*s == 0) break;
1738 // trim excess whitespace
1739 while (*s && !isalnum(*s)) {
1740 s++;
1742 if (*s == 0) break;
1743 *d++ = ' ';
1745 *d = 0;
1748 static void strcpy_strip_ext(char *d, char *s)
1750 char *tmp = strrchr(s,'.');
1751 if (!tmp) {
1752 strcpy(d, s);
1753 return;
1754 } else {
1755 strncpy(d, s, tmp-s);
1756 d[tmp-s] = 0;
1758 while (*d) {
1759 *d = tolower(*d);
1760 d++;
1764 static void strcpy_get_ext(char *d, char *s)
1766 char *tmp = strrchr(s,'.');
1767 if (!tmp) {
1768 strcpy(d, "");
1769 return;
1770 } else {
1771 strcpy(d, tmp+1);
1775 static int whiteonly(char *s)
1777 while (*s) {
1778 if (isalnum(*s)) return 0;
1779 s++;
1781 return 1;
1784 typedef struct _subfn
1786 int priority;
1787 char *fname;
1788 } subfn;
1790 static int compare_sub_priority(const void *a, const void *b)
1792 if (((const subfn*)a)->priority > ((const subfn*)b)->priority) {
1793 return -1;
1794 } else if (((const subfn*)a)->priority < ((const subfn*)b)->priority) {
1795 return 1;
1796 } else {
1797 return strcoll(((const subfn*)a)->fname, ((const subfn*)b)->fname);
1801 char** sub_filenames(const char* path, char *fname)
1803 char *f_dir, *f_fname, *f_fname_noext, *f_fname_trim, *tmp, *tmp_sub_id;
1804 char *tmp_fname_noext, *tmp_fname_trim, *tmp_fname_ext, *tmpresult;
1806 int len, pos, found, i, j;
1807 char * sub_exts[] = { "utf", "utf8", "utf-8", "sub", "srt", "smi", "rt", "txt", "ssa", "aqt", "jss", "js", "ass", NULL};
1808 subfn *result;
1809 char **result2;
1811 int subcnt;
1813 FILE *f;
1815 DIR *d;
1816 struct dirent *de;
1818 len = (strlen(fname) > 256 ? strlen(fname) : 256)
1819 +(strlen(path) > 256 ? strlen(path) : 256)+2;
1821 f_dir = malloc(len);
1822 f_fname = malloc(len);
1823 f_fname_noext = malloc(len);
1824 f_fname_trim = malloc(len);
1826 tmp_fname_noext = malloc(len);
1827 tmp_fname_trim = malloc(len);
1828 tmp_fname_ext = malloc(len);
1830 tmpresult = malloc(len);
1832 result = malloc(sizeof(subfn)*MAX_SUBTITLE_FILES);
1833 memset(result, 0, sizeof(subfn)*MAX_SUBTITLE_FILES);
1835 subcnt = 0;
1837 tmp = strrchr(fname,'/');
1838 #ifdef WIN32
1839 if(!tmp)tmp = strrchr(fname,'\\');
1840 #endif
1842 // extract filename & dirname from fname
1843 if (tmp) {
1844 strcpy(f_fname, tmp+1);
1845 pos = tmp - fname;
1846 strncpy(f_dir, fname, pos+1);
1847 f_dir[pos+1] = 0;
1848 } else {
1849 strcpy(f_fname, fname);
1850 strcpy(f_dir, "./");
1853 strcpy_strip_ext(f_fname_noext, f_fname);
1854 strcpy_trim(f_fname_trim, f_fname_noext);
1856 tmp_sub_id = NULL;
1857 if (dvdsub_lang && !whiteonly(dvdsub_lang)) {
1858 tmp_sub_id = malloc(strlen(dvdsub_lang)+1);
1859 strcpy_trim(tmp_sub_id, dvdsub_lang);
1862 // 0 = nothing
1863 // 1 = any subtitle file
1864 // 2 = any sub file containing movie name
1865 // 3 = sub file containing movie name and the lang extension
1866 for (j = 0; j <= 1; j++) {
1867 d = opendir(j == 0 ? f_dir : path);
1868 if (d) {
1869 while ((de = readdir(d))) {
1870 // retrieve various parts of the filename
1871 strcpy_strip_ext(tmp_fname_noext, de->d_name);
1872 strcpy_get_ext(tmp_fname_ext, de->d_name);
1873 strcpy_trim(tmp_fname_trim, tmp_fname_noext);
1875 // does it end with a subtitle extension?
1876 found = 0;
1877 #ifdef USE_ICONV
1878 #ifdef HAVE_ENCA
1879 for (i = ((sub_cp && strncasecmp(sub_cp, "enca", 4) != 0) ? 3 : 0); sub_exts[i]; i++) {
1880 #else
1881 for (i = (sub_cp ? 3 : 0); sub_exts[i]; i++) {
1882 #endif
1883 #else
1884 for (i = 0; sub_exts[i]; i++) {
1885 #endif
1886 if (strcasecmp(sub_exts[i], tmp_fname_ext) == 0) {
1887 found = 1;
1888 break;
1892 // we have a (likely) subtitle file
1893 if (found) {
1894 int prio = 0;
1895 if (!prio && tmp_sub_id)
1897 sprintf(tmpresult, "%s %s", f_fname_trim, tmp_sub_id);
1898 mp_msg(MSGT_SUBREADER,MSGL_INFO,"dvdsublang...%s\n", tmpresult);
1899 if (strcmp(tmp_fname_trim, tmpresult) == 0 && sub_match_fuzziness >= 1) {
1900 // matches the movie name + lang extension
1901 prio = 5;
1904 if (!prio && strcmp(tmp_fname_trim, f_fname_trim) == 0) {
1905 // matches the movie name
1906 prio = 4;
1908 if (!prio && (tmp = strstr(tmp_fname_trim, f_fname_trim)) && (sub_match_fuzziness >= 1)) {
1909 // contains the movie name
1910 tmp += strlen(f_fname_trim);
1911 if (tmp_sub_id && strstr(tmp, tmp_sub_id)) {
1912 // with sub_id specified prefer localized subtitles
1913 prio = 3;
1914 } else if ((tmp_sub_id == NULL) && whiteonly(tmp)) {
1915 // without sub_id prefer "plain" name
1916 prio = 3;
1917 } else {
1918 // with no localized subs found, try any else instead
1919 prio = 2;
1922 if (!prio) {
1923 // doesn't contain the movie name
1924 // don't try in the mplayer subtitle directory
1925 if ((j == 0) && (sub_match_fuzziness >= 2)) {
1926 prio = 1;
1930 if (prio) {
1931 prio += prio;
1932 #ifdef USE_ICONV
1933 if (i<3){ // prefer UTF-8 coded
1934 prio++;
1936 #endif
1937 sprintf(tmpresult, "%s%s", j == 0 ? f_dir : path, de->d_name);
1938 // fprintf(stderr, "%s priority %d\n", tmpresult, prio);
1939 if ((f = fopen(tmpresult, "rt"))) {
1940 fclose(f);
1941 result[subcnt].priority = prio;
1942 result[subcnt].fname = strdup(tmpresult);
1943 subcnt++;
1948 if (subcnt >= MAX_SUBTITLE_FILES) break;
1950 closedir(d);
1955 if (tmp_sub_id) free(tmp_sub_id);
1957 free(f_dir);
1958 free(f_fname);
1959 free(f_fname_noext);
1960 free(f_fname_trim);
1962 free(tmp_fname_noext);
1963 free(tmp_fname_trim);
1964 free(tmp_fname_ext);
1966 free(tmpresult);
1968 qsort(result, subcnt, sizeof(subfn), compare_sub_priority);
1970 result2 = malloc(sizeof(char*)*(subcnt+1));
1971 memset(result2, 0, sizeof(char*)*(subcnt+1));
1973 for (i = 0; i < subcnt; i++) {
1974 result2[i] = result[i].fname;
1976 result2[subcnt] = NULL;
1978 free(result);
1980 return result2;
1983 void list_sub_file(sub_data* subd){
1984 int i,j;
1985 subtitle *subs = subd->subtitles;
1987 for(j=0; j < subd->sub_num; j++){
1988 subtitle* egysub=&subs[j];
1989 mp_msg(MSGT_SUBREADER,MSGL_INFO,"%i line%c (%li-%li)\n",
1990 egysub->lines,
1991 (1==egysub->lines)?' ':'s',
1992 egysub->start,
1993 egysub->end);
1994 for (i=0; i<egysub->lines; i++) {
1995 mp_msg(MSGT_SUBREADER,MSGL_INFO,"\t\t%d: %s%s", i,egysub->text[i], i==egysub->lines-1?"":" \n ");
1997 mp_msg(MSGT_SUBREADER,MSGL_INFO,"\n");
2000 mp_msg(MSGT_SUBREADER,MSGL_INFO,"Subtitle format %s time.\n",
2001 subd->sub_uses_time ? "uses":"doesn't use");
2002 mp_msg(MSGT_SUBREADER,MSGL_INFO,"Read %i subtitles, %i errors.\n", subd->sub_num, subd->sub_errs);
2005 void dump_srt(sub_data* subd, float fps){
2006 int i,j;
2007 int h,m,s,ms;
2008 FILE * fd;
2009 subtitle * onesub;
2010 unsigned long temp;
2011 subtitle *subs = subd->subtitles;
2013 if (!subd->sub_uses_time && sub_fps == 0)
2014 sub_fps = fps;
2015 fd=fopen("dumpsub.srt","w");
2016 if(!fd)
2018 perror("dump_srt: fopen");
2019 return;
2021 for(i=0; i < subd->sub_num; i++)
2023 onesub=subs+i; //=&subs[i];
2024 fprintf(fd,"%d\n",i+1);//line number
2026 temp=onesub->start;
2027 if (!subd->sub_uses_time)
2028 temp = temp * 100 / sub_fps;
2029 temp -= sub_delay * 100;
2030 h=temp/360000;temp%=360000; //h =1*100*60*60
2031 m=temp/6000; temp%=6000; //m =1*100*60
2032 s=temp/100; temp%=100; //s =1*100
2033 ms=temp*10; //ms=1*10
2034 fprintf(fd,"%02d:%02d:%02d,%03d --> ",h,m,s,ms);
2036 temp=onesub->end;
2037 if (!subd->sub_uses_time)
2038 temp = temp * 100 / sub_fps;
2039 temp -= sub_delay * 100;
2040 h=temp/360000;temp%=360000;
2041 m=temp/6000; temp%=6000;
2042 s=temp/100; temp%=100;
2043 ms=temp*10;
2044 fprintf(fd,"%02d:%02d:%02d,%03d\n",h,m,s,ms);
2046 for(j=0;j<onesub->lines;j++)
2047 fprintf(fd,"%s\n",onesub->text[j]);
2049 fprintf(fd,"\n");
2051 fclose(fd);
2052 mp_msg(MSGT_SUBREADER,MSGL_INFO,"SUB: Subtitles dumped in \'dumpsub.srt\'.\n");
2055 void dump_mpsub(sub_data* subd, float fps){
2056 int i,j;
2057 FILE *fd;
2058 float a,b;
2059 subtitle *subs = subd->subtitles;
2061 mpsub_position = subd->sub_uses_time? (sub_delay*100) : (sub_delay*fps);
2062 if (sub_fps==0) sub_fps=fps;
2064 fd=fopen ("dump.mpsub", "w");
2065 if (!fd) {
2066 perror ("dump_mpsub: fopen");
2067 return;
2071 if (subd->sub_uses_time) fprintf (fd,"FORMAT=TIME\n\n");
2072 else fprintf (fd, "FORMAT=%5.2f\n\n", fps);
2074 for(j=0; j < subd->sub_num; j++){
2075 subtitle* egysub=&subs[j];
2076 if (subd->sub_uses_time) {
2077 a=((egysub->start-mpsub_position)/100.0);
2078 b=((egysub->end-egysub->start)/100.0);
2079 if ( (float)((int)a) == a)
2080 fprintf (fd, "%.0f",a);
2081 else
2082 fprintf (fd, "%.2f",a);
2084 if ( (float)((int)b) == b)
2085 fprintf (fd, " %.0f\n",b);
2086 else
2087 fprintf (fd, " %.2f\n",b);
2088 } else {
2089 fprintf (fd, "%ld %ld\n", (long)((egysub->start*(fps/sub_fps))-((mpsub_position*(fps/sub_fps)))),
2090 (long)(((egysub->end)-(egysub->start))*(fps/sub_fps)));
2093 mpsub_position = egysub->end;
2094 for (i=0; i<egysub->lines; i++) {
2095 fprintf (fd, "%s\n",egysub->text[i]);
2097 fprintf (fd, "\n");
2099 fclose (fd);
2100 mp_msg(MSGT_SUBREADER,MSGL_INFO,"SUB: Subtitles dumped in \'dump.mpsub\'.\n");
2103 void dump_microdvd(sub_data* subd, float fps) {
2104 int i, delay;
2105 FILE *fd;
2106 subtitle *subs = subd->subtitles;
2107 if (sub_fps == 0)
2108 sub_fps = fps;
2109 fd = fopen("dumpsub.sub", "w");
2110 if (!fd) {
2111 perror("dumpsub.sub: fopen");
2112 return;
2114 delay = sub_delay * sub_fps;
2115 for (i = 0; i < subd->sub_num; ++i) {
2116 int j, start, end;
2117 start = subs[i].start;
2118 end = subs[i].end;
2119 if (subd->sub_uses_time) {
2120 start = start * sub_fps / 100 ;
2121 end = end * sub_fps / 100;
2123 else {
2124 start = start * sub_fps / fps;
2125 end = end * sub_fps / fps;
2127 start -= delay;
2128 end -= delay;
2129 fprintf(fd, "{%d}{%d}", start, end);
2130 for (j = 0; j < subs[i].lines; ++j)
2131 fprintf(fd, "%s%s", j ? "|" : "", subs[i].text[j]);
2132 fprintf(fd, "\n");
2134 fclose(fd);
2135 mp_msg(MSGT_SUBREADER,MSGL_INFO,"SUB: Subtitles dumped in \'dumpsub.sub\'.\n");
2138 void dump_jacosub(sub_data* subd, float fps) {
2139 int i,j;
2140 int h,m,s,cs;
2141 FILE * fd;
2142 subtitle * onesub;
2143 unsigned long temp;
2144 subtitle *subs = subd->subtitles;
2146 if (!subd->sub_uses_time && sub_fps == 0)
2147 sub_fps = fps;
2148 fd=fopen("dumpsub.jss","w");
2149 if(!fd)
2151 perror("dump_jacosub: fopen");
2152 return;
2154 fprintf(fd, "#TIMERES %d\n", (subd->sub_uses_time) ? 100 : (int)sub_fps);
2155 for(i=0; i < subd->sub_num; i++)
2157 onesub=subs+i; //=&subs[i];
2159 temp=onesub->start;
2160 if (!subd->sub_uses_time)
2161 temp = temp * 100 / sub_fps;
2162 temp -= sub_delay * 100;
2163 h=temp/360000;temp%=360000; //h =1*100*60*60
2164 m=temp/6000; temp%=6000; //m =1*100*60
2165 s=temp/100; temp%=100; //s =1*100
2166 cs=temp; //cs=1*10
2167 fprintf(fd,"%02d:%02d:%02d.%02d ",h,m,s,cs);
2169 temp=onesub->end;
2170 if (!subd->sub_uses_time)
2171 temp = temp * 100 / sub_fps;
2172 temp -= sub_delay * 100;
2173 h=temp/360000;temp%=360000;
2174 m=temp/6000; temp%=6000;
2175 s=temp/100; temp%=100;
2176 cs=temp;
2177 fprintf(fd,"%02d:%02d:%02d.%02d {~} ",h,m,s,cs);
2179 for(j=0;j<onesub->lines;j++)
2180 fprintf(fd,"%s%s",j ? "\\n" : "", onesub->text[j]);
2182 fprintf(fd,"\n");
2184 fclose(fd);
2185 mp_msg(MSGT_SUBREADER,MSGL_INFO,"SUB: Subtitles dumped in \'dumpsub.js\'.\n");
2188 void dump_sami(sub_data* subd, float fps) {
2189 int i,j;
2190 FILE * fd;
2191 subtitle * onesub;
2192 unsigned long temp;
2193 subtitle *subs = subd->subtitles;
2195 if (!subd->sub_uses_time && sub_fps == 0)
2196 sub_fps = fps;
2197 fd=fopen("dumpsub.smi","w");
2198 if(!fd)
2200 perror("dump_jacosub: fopen");
2201 return;
2203 fprintf(fd, "<SAMI>\n"
2204 "<HEAD>\n"
2205 " <STYLE TYPE=\"Text/css\">\n"
2206 " <!--\n"
2207 " 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"
2208 " .SUBTTL {Name: 'Subtitles'; Lang: en-US; SAMIType: CC;}\n"
2209 " -->\n"
2210 " </STYLE>\n"
2211 "</HEAD>\n"
2212 "<BODY>\n");
2213 for(i=0; i < subd->sub_num; i++)
2215 onesub=subs+i; //=&subs[i];
2217 temp=onesub->start;
2218 if (!subd->sub_uses_time)
2219 temp = temp * 100 / sub_fps;
2220 temp -= sub_delay * 100;
2221 fprintf(fd,"\t<SYNC Start=%lu>\n"
2222 "\t <P>", temp * 10);
2224 for(j=0;j<onesub->lines;j++)
2225 fprintf(fd,"%s%s",j ? "<br>" : "", onesub->text[j]);
2227 fprintf(fd,"\n");
2229 temp=onesub->end;
2230 if (!subd->sub_uses_time)
2231 temp = temp * 100 / sub_fps;
2232 temp -= sub_delay * 100;
2233 fprintf(fd,"\t<SYNC Start=%lu>\n"
2234 "\t <P>&nbsp;\n", temp * 10);
2236 fprintf(fd, "</BODY>\n"
2237 "</SAMI>\n");
2238 fclose(fd);
2239 mp_msg(MSGT_SUBREADER,MSGL_INFO,"SUB: Subtitles dumped in \'dumpsub.smi\'.\n");
2242 void sub_free( sub_data * subd )
2244 int i;
2246 if ( !subd ) return;
2248 if (subd->subtitles) {
2249 for (i=0; i < subd->subtitles->lines; i++) free( subd->subtitles->text[i] );
2250 free( subd->subtitles );
2252 if (subd->filename) free( subd->filename );
2253 free( subd );
2256 #define MAX_SUBLINE 512
2258 * \brief parse text and append it to subtitle in sub
2259 * \param sub subtitle struct to add text to
2260 * \param txt text to parse
2261 * \param len length of text in txt
2262 * \param endpts pts at which this subtitle text should be removed again
2264 * <> and {} are interpreted as comment delimiters, "\n", "\N", '\n', '\r'
2265 * and '\0' are interpreted as newlines, duplicate, leading and trailing
2266 * newlines are ignored.
2268 void sub_add_text(subtitle *sub, const char *txt, int len, double endpts) {
2269 int comment = 0;
2270 int double_newline = 1; // ignore newlines at the beginning
2271 int i, pos;
2272 char *buf;
2273 if (sub->lines >= SUB_MAX_TEXT) return;
2274 pos = 0;
2275 buf = malloc(MAX_SUBLINE + 1);
2276 sub->text[sub->lines] = buf;
2277 sub->endpts[sub->lines] = endpts;
2278 for (i = 0; i < len && pos < MAX_SUBLINE; i++) {
2279 char c = txt[i];
2280 if (c == '<') comment |= 1;
2281 if (c == '{') comment |= 2;
2282 if (comment) {
2283 if (c == '}') comment &= ~2;
2284 if (c == '>') comment &= ~1;
2285 continue;
2287 if (pos == MAX_SUBLINE - 1) {
2288 i--;
2289 c = 0;
2291 if (c == '\\' && i + 1 < len) {
2292 c = txt[++i];
2293 if (c == 'n' || c == 'N') c = 0;
2295 if (c == '\n' || c == '\r') c = 0;
2296 if (c) {
2297 double_newline = 0;
2298 buf[pos++] = c;
2299 } else if (!double_newline) {
2300 if (sub->lines >= SUB_MAX_TEXT - 1) {
2301 mp_msg(MSGT_VO, MSGL_WARN, "Too many subtitle lines\n");
2302 break;
2304 double_newline = 1;
2305 buf[pos] = 0;
2306 sub->lines++;
2307 pos = 0;
2308 buf = malloc(MAX_SUBLINE + 1);
2309 sub->text[sub->lines] = buf;
2310 sub->endpts[sub->lines] = endpts;
2313 buf[pos] = 0;
2314 if (sub->lines < SUB_MAX_TEXT &&
2315 strlen(sub->text[sub->lines]))
2316 sub->lines++;
2319 #define MP_NOPTS_VALUE (-1LL<<63)
2321 * \brief remove outdated subtitle lines.
2322 * \param sub subtitle struct to modify
2323 * \param pts current pts. All lines with endpts <= this will be removed.
2324 * Use MP_NOPTS_VALUE to remove all lines
2325 * \return 1 if sub was modified, 0 otherwise.
2327 int sub_clear_text(subtitle *sub, double pts) {
2328 int i = 0;
2329 int changed = 0;
2330 while (i < sub->lines) {
2331 double endpts = sub->endpts[i];
2332 if (pts == MP_NOPTS_VALUE || (endpts != MP_NOPTS_VALUE && pts >= endpts)) {
2333 int j;
2334 free(sub->text[i]);
2335 for (j = i + 1; j < sub->lines; j++) {
2336 sub->text[j - 1] = sub->text[j];
2337 sub->endpts[j - 1] = sub->endpts[j];
2339 sub->lines--;
2340 changed = 1;
2341 } else
2342 i++;
2344 return changed;
2347 #ifdef DUMPSUBS
2348 int main(int argc, char **argv) { // for testing
2349 sub_data *subd;
2351 if(argc<2){
2352 printf("\nUsage: subreader filename.sub\n\n");
2353 exit(1);
2355 sub_cp = argv[2];
2356 subd = sub_read_file(argv[1]);
2357 if(!subd){
2358 printf("Couldn't load file.\n");
2359 exit(1);
2362 list_sub_file(subd);
2364 return 0;
2366 #endif