mime type [video/x-ms-wmv] is not an ASF redirector.
[mplayer/glamo.git] / subreader.c
blob0776ea2b1752b6990015fc7c41f73916d5579577
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"
24 #ifdef CONFIG_ENCA
25 #include <enca.h>
26 #endif
28 #define ERR ((void *) -1)
30 #ifdef CONFIG_ICONV
31 #include <iconv.h>
32 char *sub_cp=NULL;
33 #endif
34 #ifdef CONFIG_FRIBIDI
35 #include <fribidi/fribidi.h>
36 char *fribidi_charset = NULL; ///character set that will be passed to FriBiDi
37 int flip_hebrew = 1; ///flip subtitles using fribidi
38 int fribidi_flip_commas = 0; ///flip comma when fribidi is used
39 #endif
41 extern char* dvdsub_lang;
43 /* Maximal length of line of a subtitle */
44 #define LINE_LEN 1000
45 static float mpsub_position=0;
46 static float mpsub_multiplier=1.;
47 static int sub_slacktime = 20000; //20 sec
49 int sub_no_text_pp=0; // 1 => do not apply text post-processing
50 // like {\...} elimination in SSA format.
52 int sub_match_fuzziness=0; // level of sub name matching fuzziness
54 /* Use the SUB_* constant defined in the header file */
55 int sub_format=SUB_INVALID;
56 #ifdef CONFIG_SORTSUB
58 Some subtitling formats, namely AQT and Subrip09, define the end of a
59 subtitle as the beginning of the following. Since currently we read one
60 subtitle at time, for these format we keep two global *subtitle,
61 previous_aqt_sub and previous_subrip09_sub, pointing to previous subtitle,
62 so we can change its end when we read current subtitle starting time.
63 When CONFIG_SORTSUB is defined, we use a single global unsigned long,
64 previous_sub_end, for both (and even future) formats, to store the end of
65 the previous sub: it is initialized to 0 in sub_read_file and eventually
66 modified by sub_read_aqt_line or sub_read_subrip09_line.
68 unsigned long previous_sub_end;
69 #endif
71 static int eol(char p) {
72 return p=='\r' || p=='\n' || p=='\0';
75 /* Remove leading and trailing space */
76 static void trail_space(char *s) {
77 int i = 0;
78 while (isspace(s[i])) ++i;
79 if (i) strcpy(s, s + i);
80 i = strlen(s) - 1;
81 while (i > 0 && isspace(s[i])) s[i--] = '\0';
84 static char *stristr(const char *haystack, const char *needle) {
85 int len = 0;
86 const char *p = haystack;
88 if (!(haystack && needle)) return NULL;
90 len=strlen(needle);
91 while (*p != '\0') {
92 if (strncasecmp(p, needle, len) == 0) return (char*)p;
93 p++;
96 return NULL;
99 static subtitle *sub_read_line_sami(stream_t* st, subtitle *current) {
100 static char line[LINE_LEN+1];
101 static char *s = NULL, *slacktime_s;
102 char text[LINE_LEN+1], *p=NULL, *q;
103 int state;
105 current->lines = current->start = current->end = 0;
106 current->alignment = SUB_ALIGNMENT_BOTTOMCENTER;
107 state = 0;
109 /* read the first line */
110 if (!s)
111 if (!(s = stream_read_line(st, line, LINE_LEN))) return 0;
113 do {
114 switch (state) {
116 case 0: /* find "START=" or "Slacktime:" */
117 slacktime_s = stristr (s, "Slacktime:");
118 if (slacktime_s)
119 sub_slacktime = strtol (slacktime_s+10, NULL, 0) / 10;
121 s = stristr (s, "Start=");
122 if (s) {
123 current->start = strtol (s + 6, &s, 0) / 10;
124 /* eat '>' */
125 for (; *s != '>' && *s != '\0'; s++);
126 s++;
127 state = 1; continue;
129 break;
131 case 1: /* find (optionnal) "<P", skip other TAGs */
132 for (; *s == ' ' || *s == '\t'; s++); /* strip blanks, if any */
133 if (*s == '\0') break;
134 if (*s != '<') { state = 3; p = text; continue; } /* not a TAG */
135 s++;
136 if (*s == 'P' || *s == 'p') { s++; state = 2; continue; } /* found '<P' */
137 for (; *s != '>' && *s != '\0'; s++); /* skip remains of non-<P> TAG */
138 if (s == '\0')
139 break;
140 s++;
141 continue;
143 case 2: /* find ">" */
144 if ((s = strchr (s, '>'))) { s++; state = 3; p = text; continue; }
145 break;
147 case 3: /* get all text until '<' appears */
148 if (*s == '\0') break;
149 else if (!strncasecmp (s, "<br>", 4)) {
150 *p = '\0'; p = text; trail_space (text);
151 if (text[0] != '\0')
152 current->text[current->lines++] = strdup (text);
153 s += 4;
155 else if ((*s == '{') && !sub_no_text_pp) { state = 5; ++s; continue; }
156 else if (*s == '<') { state = 4; }
157 else if (!strncasecmp (s, "&nbsp;", 6)) { *p++ = ' '; s += 6; }
158 else if (*s == '\t') { *p++ = ' '; s++; }
159 else if (*s == '\r' || *s == '\n') { s++; }
160 else *p++ = *s++;
162 /* skip duplicated space */
163 if (p > text + 2) if (*(p-1) == ' ' && *(p-2) == ' ') p--;
165 continue;
167 case 4: /* get current->end or skip <TAG> */
168 q = stristr (s, "Start=");
169 if (q) {
170 current->end = strtol (q + 6, &q, 0) / 10 - 1;
171 *p = '\0'; trail_space (text);
172 if (text[0] != '\0')
173 current->text[current->lines++] = strdup (text);
174 if (current->lines > 0) { state = 99; break; }
175 state = 0; continue;
177 s = strchr (s, '>');
178 if (s) { s++; state = 3; continue; }
179 break;
180 case 5: /* get rid of {...} text, but read the alignment code */
181 if ((*s == '\\') && (*(s + 1) == 'a') && !sub_no_text_pp) {
182 if (stristr(s, "\\a1") != NULL) {
183 current->alignment = SUB_ALIGNMENT_BOTTOMLEFT;
184 s = s + 3;
186 if (stristr(s, "\\a2") != NULL) {
187 current->alignment = SUB_ALIGNMENT_BOTTOMCENTER;
188 s = s + 3;
189 } else if (stristr(s, "\\a3") != NULL) {
190 current->alignment = SUB_ALIGNMENT_BOTTOMRIGHT;
191 s = s + 3;
192 } else if ((stristr(s, "\\a4") != NULL) || (stristr(s, "\\a5") != NULL) || (stristr(s, "\\a8") != NULL)) {
193 current->alignment = SUB_ALIGNMENT_TOPLEFT;
194 s = s + 3;
195 } else if (stristr(s, "\\a6") != NULL) {
196 current->alignment = SUB_ALIGNMENT_TOPCENTER;
197 s = s + 3;
198 } else if (stristr(s, "\\a7") != NULL) {
199 current->alignment = SUB_ALIGNMENT_TOPRIGHT;
200 s = s + 3;
201 } else if (stristr(s, "\\a9") != NULL) {
202 current->alignment = SUB_ALIGNMENT_MIDDLELEFT;
203 s = s + 3;
204 } else if (stristr(s, "\\a10") != NULL) {
205 current->alignment = SUB_ALIGNMENT_MIDDLECENTER;
206 s = s + 4;
207 } else if (stristr(s, "\\a11") != NULL) {
208 current->alignment = SUB_ALIGNMENT_MIDDLERIGHT;
209 s = s + 4;
212 if (*s == '}') state = 3;
213 ++s;
214 continue;
217 /* read next line */
218 if (state != 99 && !(s = stream_read_line (st, line, LINE_LEN))) {
219 if (current->start > 0) {
220 break; // if it is the last subtitle
221 } else {
222 return 0;
226 } while (state != 99);
228 // For the last subtitle
229 if (current->end <= 0) {
230 current->end = current->start + sub_slacktime;
231 *p = '\0'; trail_space (text);
232 if (text[0] != '\0')
233 current->text[current->lines++] = strdup (text);
236 return current;
240 static char *sub_readtext(char *source, char **dest) {
241 int len=0;
242 char *p=source;
244 // printf("src=%p dest=%p \n",source,dest);
246 while ( !eol(*p) && *p!= '|' ) {
247 p++,len++;
250 *dest= malloc (len+1);
251 if (!dest) {return ERR;}
253 strncpy(*dest, source, len);
254 (*dest)[len]=0;
256 while (*p=='\r' || *p=='\n' || *p=='|') p++;
258 if (*p) return p; // not-last text field
259 else return NULL; // last text field
262 static subtitle *sub_read_line_microdvd(stream_t *st,subtitle *current) {
263 char line[LINE_LEN+1];
264 char line2[LINE_LEN+1];
265 char *p, *next;
266 int i;
268 do {
269 if (!stream_read_line (st, line, LINE_LEN)) return NULL;
270 } while ((sscanf (line,
271 "{%ld}{}%[^\r\n]",
272 &(current->start), line2) < 2) &&
273 (sscanf (line,
274 "{%ld}{%ld}%[^\r\n]",
275 &(current->start), &(current->end), line2) < 3));
277 p=line2;
279 next=p, i=0;
280 while ((next =sub_readtext (next, &(current->text[i])))) {
281 if (current->text[i]==ERR) {return ERR;}
282 i++;
283 if (i>=SUB_MAX_TEXT) { mp_msg(MSGT_SUBREADER,MSGL_WARN,"Too many lines in a subtitle\n");current->lines=i;return current;}
285 current->lines= ++i;
287 return current;
290 static subtitle *sub_read_line_mpl2(stream_t *st,subtitle *current) {
291 char line[LINE_LEN+1];
292 char line2[LINE_LEN+1];
293 char *p, *next;
294 int i;
296 do {
297 if (!stream_read_line (st, line, LINE_LEN)) return NULL;
298 } while ((sscanf (line,
299 "[%ld][%ld]%[^\r\n]",
300 &(current->start), &(current->end), line2) < 3));
301 current->start *= 10;
302 current->end *= 10;
303 p=line2;
305 next=p, i=0;
306 while ((next =sub_readtext (next, &(current->text[i])))) {
307 if (current->text[i]==ERR) {return ERR;}
308 i++;
309 if (i>=SUB_MAX_TEXT) { mp_msg(MSGT_SUBREADER,MSGL_WARN,"Too many lines in a subtitle\n");current->lines=i;return current;}
311 current->lines= ++i;
313 return current;
316 static subtitle *sub_read_line_subrip(stream_t* st, subtitle *current) {
317 char line[LINE_LEN+1];
318 int a1,a2,a3,a4,b1,b2,b3,b4;
319 char *p=NULL, *q=NULL;
320 int len;
322 while (1) {
323 if (!stream_read_line (st, line, LINE_LEN)) return NULL;
324 if (sscanf (line, "%d:%d:%d.%d,%d:%d:%d.%d",&a1,&a2,&a3,&a4,&b1,&b2,&b3,&b4) < 8) continue;
325 current->start = a1*360000+a2*6000+a3*100+a4;
326 current->end = b1*360000+b2*6000+b3*100+b4;
328 if (!stream_read_line (st, line, LINE_LEN)) return NULL;
330 p=q=line;
331 for (current->lines=1; current->lines < SUB_MAX_TEXT; current->lines++) {
332 for (q=p,len=0; *p && *p!='\r' && *p!='\n' && *p!='|' && strncmp(p,"[br]",4); p++,len++);
333 current->text[current->lines-1]=malloc (len+1);
334 if (!current->text[current->lines-1]) return ERR;
335 strncpy (current->text[current->lines-1], q, len);
336 current->text[current->lines-1][len]='\0';
337 if (!*p || *p=='\r' || *p=='\n') break;
338 if (*p=='|') p++;
339 else while (*p++!=']');
341 break;
343 return current;
346 static subtitle *sub_read_line_subviewer(stream_t *st,subtitle *current) {
347 char line[LINE_LEN+1];
348 int a1,a2,a3,a4,b1,b2,b3,b4;
349 char *p=NULL;
350 int i,len;
352 while (!current->text[0]) {
353 if (!stream_read_line (st, line, LINE_LEN)) return NULL;
354 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)
355 continue;
356 current->start = a1*360000+a2*6000+a3*100+a4/10;
357 current->end = b1*360000+b2*6000+b3*100+b4/10;
358 for (i=0; i<SUB_MAX_TEXT;) {
359 int blank = 1;
360 if (!stream_read_line (st, line, LINE_LEN)) break;
361 len=0;
362 for (p=line; *p!='\n' && *p!='\r' && *p; p++,len++)
363 if (*p != ' ' && *p != '\t')
364 blank = 0;
365 if (len && !blank) {
366 int j=0,skip=0;
367 char *curptr=current->text[i]=malloc (len+1);
368 if (!current->text[i]) return ERR;
369 //strncpy (current->text[i], line, len); current->text[i][len]='\0';
370 for(; j<len; j++) {
371 /* let's filter html tags ::atmos */
372 if(line[j]=='>') {
373 skip=0;
374 continue;
376 if(line[j]=='<') {
377 skip=1;
378 continue;
380 if(skip) {
381 continue;
383 *curptr=line[j];
384 curptr++;
386 *curptr='\0';
388 i++;
389 } else {
390 break;
393 current->lines=i;
395 return current;
398 static subtitle *sub_read_line_subviewer2(stream_t *st,subtitle *current) {
399 char line[LINE_LEN+1];
400 int a1,a2,a3,a4;
401 char *p=NULL;
402 int i,len;
404 while (!current->text[0]) {
405 if (!stream_read_line (st, line, LINE_LEN)) return NULL;
406 if (line[0]!='{')
407 continue;
408 if ((len=sscanf (line, "{T %d:%d:%d:%d",&a1,&a2,&a3,&a4)) < 4)
409 continue;
410 current->start = a1*360000+a2*6000+a3*100+a4/10;
411 for (i=0; i<SUB_MAX_TEXT;) {
412 if (!stream_read_line (st, line, LINE_LEN)) break;
413 if (line[0]=='}') break;
414 len=0;
415 for (p=line; *p!='\n' && *p!='\r' && *p; ++p,++len);
416 if (len) {
417 current->text[i]=malloc (len+1);
418 if (!current->text[i]) return ERR;
419 strncpy (current->text[i], line, len); current->text[i][len]='\0';
420 ++i;
421 } else {
422 break;
425 current->lines=i;
427 return current;
431 static subtitle *sub_read_line_vplayer(stream_t *st,subtitle *current) {
432 char line[LINE_LEN+1];
433 int a1,a2,a3;
434 char *p=NULL, *next,separator;
435 int i,len,plen;
437 while (!current->text[0]) {
438 if (!stream_read_line (st, line, LINE_LEN)) return NULL;
439 if ((len=sscanf (line, "%d:%d:%d%c%n",&a1,&a2,&a3,&separator,&plen)) < 4)
440 continue;
442 if (!(current->start = a1*360000+a2*6000+a3*100))
443 continue;
444 /* removed by wodzu
445 p=line;
446 // finds the body of the subtitle
447 for (i=0; i<3; i++){
448 p=strchr(p,':');
449 if (p==NULL) break;
450 ++p;
452 if (p==NULL) {
453 printf("SUB: Skipping incorrect subtitle line!\n");
454 continue;
457 // by wodzu: hey! this time we know what length it has! what is
458 // that magic for? it can't deal with space instead of third
459 // colon! look, what simple it can be:
460 p = &line[ plen ];
462 i=0;
463 if (*p!='|') {
465 next = p,i=0;
466 while ((next =sub_readtext (next, &(current->text[i])))) {
467 if (current->text[i]==ERR) {return ERR;}
468 i++;
469 if (i>=SUB_MAX_TEXT) { mp_msg(MSGT_SUBREADER,MSGL_WARN,"Too many lines in a subtitle\n");current->lines=i;return current;}
471 current->lines=i+1;
474 return current;
477 static subtitle *sub_read_line_rt(stream_t *st,subtitle *current) {
478 //TODO: This format uses quite rich (sub/super)set of xhtml
479 // I couldn't check it since DTD is not included.
480 // WARNING: full XML parses can be required for proper parsing
481 char line[LINE_LEN+1];
482 int a1,a2,a3,a4,b1,b2,b3,b4;
483 char *p=NULL,*next=NULL;
484 int i,len,plen;
486 while (!current->text[0]) {
487 if (!stream_read_line (st, line, LINE_LEN)) return NULL;
488 //TODO: it seems that format of time is not easily determined, it may be 1:12, 1:12.0 or 0:1:12.0
489 //to describe the same moment in time. Maybe there are even more formats in use.
490 //if ((len=sscanf (line, "<Time Begin=\"%d:%d:%d.%d\" End=\"%d:%d:%d.%d\"",&a1,&a2,&a3,&a4,&b1,&b2,&b3,&b4)) < 8)
491 plen=a1=a2=a3=a4=b1=b2=b3=b4=0;
492 if (
493 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d.%d\" %*[Ee]nd=\"%d.%d\"%*[^<]<clear/>%n",&a3,&a4,&b3,&b4,&plen)) < 4) &&
494 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d.%d\" %*[Ee]nd=\"%d:%d.%d\"%*[^<]<clear/>%n",&a3,&a4,&b2,&b3,&b4,&plen)) < 5) &&
495 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d:%d\" %*[Ee]nd=\"%d:%d\"%*[^<]<clear/>%n",&a2,&a3,&b2,&b3,&plen)) < 4) &&
496 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d:%d\" %*[Ee]nd=\"%d:%d.%d\"%*[^<]<clear/>%n",&a2,&a3,&b2,&b3,&b4,&plen)) < 5) &&
497 // ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d:%d.%d\" %*[Ee]nd=\"%d:%d\"%*[^<]<clear/>%n",&a2,&a3,&a4,&b2,&b3,&plen)) < 5) &&
498 ((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) &&
499 ((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) &&
500 //now try it without end time
501 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d.%d\"%*[^<]<clear/>%n",&a3,&a4,&plen)) < 2) &&
502 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d:%d\"%*[^<]<clear/>%n",&a2,&a3,&plen)) < 2) &&
503 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d:%d.%d\"%*[^<]<clear/>%n",&a2,&a3,&a4,&plen)) < 3) &&
504 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d:%d:%d.%d\"%*[^<]<clear/>%n",&a1,&a2,&a3,&a4,&plen)) < 4)
506 continue;
507 current->start = a1*360000+a2*6000+a3*100+a4/10;
508 current->end = b1*360000+b2*6000+b3*100+b4/10;
509 if (b1 == 0 && b2 == 0 && b3 == 0 && b4 == 0)
510 current->end = current->start+200;
511 p=line; p+=plen;i=0;
512 // TODO: I don't know what kind of convention is here for marking multiline subs, maybe <br/> like in xml?
513 next = strstr(line,"<clear/>");
514 if(next && strlen(next)>8){
515 next+=8;i=0;
516 while ((next =sub_readtext (next, &(current->text[i])))) {
517 if (current->text[i]==ERR) {return ERR;}
518 i++;
519 if (i>=SUB_MAX_TEXT) { mp_msg(MSGT_SUBREADER,MSGL_WARN,"Too many lines in a subtitle\n");current->lines=i;return current;}
522 current->lines=i+1;
524 return current;
527 static subtitle *sub_read_line_ssa(stream_t *st,subtitle *current) {
529 * Sub Station Alpha v4 (and v2?) scripts have 9 commas before subtitle
530 * other Sub Station Alpha scripts have only 8 commas before subtitle
531 * Reading the "ScriptType:" field is not reliable since many scripts appear
532 * w/o it
534 * http://www.scriptclub.org is a good place to find more examples
535 * http://www.eswat.demon.co.uk is where the SSA specs can be found
537 int comma;
538 static int max_comma = 32; /* let's use 32 for the case that the */
539 /* amount of commas increase with newer SSA versions */
541 int hour1, min1, sec1, hunsec1,
542 hour2, min2, sec2, hunsec2, nothing;
543 int num;
545 char line[LINE_LEN+1],
546 line3[LINE_LEN+1],
547 *line2;
548 char *tmp;
550 do {
551 if (!stream_read_line (st, line, LINE_LEN)) return NULL;
552 } while (sscanf (line, "Dialogue: Marked=%d,%d:%d:%d.%d,%d:%d:%d.%d,"
553 "%[^\n\r]", &nothing,
554 &hour1, &min1, &sec1, &hunsec1,
555 &hour2, &min2, &sec2, &hunsec2,
556 line3) < 9
558 sscanf (line, "Dialogue: %d,%d:%d:%d.%d,%d:%d:%d.%d,"
559 "%[^\n\r]", &nothing,
560 &hour1, &min1, &sec1, &hunsec1,
561 &hour2, &min2, &sec2, &hunsec2,
562 line3) < 9 );
564 line2=strchr(line3, ',');
566 for (comma = 4; comma < max_comma; comma ++)
568 tmp = line2;
569 if(!(tmp=strchr(++tmp, ','))) break;
570 if(*(++tmp) == ' ') break;
571 /* a space after a comma means we're already in a sentence */
572 line2 = tmp;
575 if(comma < max_comma)max_comma = comma;
576 /* eliminate the trailing comma */
577 if(*line2 == ',') line2++;
579 current->lines=0;num=0;
580 current->start = 360000*hour1 + 6000*min1 + 100*sec1 + hunsec1;
581 current->end = 360000*hour2 + 6000*min2 + 100*sec2 + hunsec2;
583 while (((tmp=strstr(line2, "\\n")) != NULL) || ((tmp=strstr(line2, "\\N")) != NULL) ){
584 current->text[num]=malloc(tmp-line2+1);
585 strncpy (current->text[num], line2, tmp-line2);
586 current->text[num][tmp-line2]='\0';
587 line2=tmp+2;
588 num++;
589 current->lines++;
590 if (current->lines >= SUB_MAX_TEXT) return current;
593 current->text[num]=strdup(line2);
594 current->lines++;
596 return current;
599 static void sub_pp_ssa(subtitle *sub) {
600 int l=sub->lines;
601 char *so,*de,*start;
603 while (l){
604 /* eliminate any text enclosed with {}, they are font and color settings */
605 so=de=sub->text[--l];
606 while (*so) {
607 if(*so == '{' && so[1]=='\\') {
608 for (start=so; *so && *so!='}'; so++);
609 if(*so) so++; else so=start;
611 if(*so) {
612 *de=*so;
613 so++; de++;
616 *de=*so;
621 * PJS subtitles reader.
622 * That's the "Phoenix Japanimation Society" format.
623 * I found some of them in http://www.scriptsclub.org/ (used for anime).
624 * The time is in tenths of second.
626 * by set, based on code by szabi (dunnowhat sub format ;-)
628 static subtitle *sub_read_line_pjs(stream_t *st,subtitle *current) {
629 char line[LINE_LEN+1];
630 char text[LINE_LEN+1], *s, *d;
632 if (!stream_read_line (st, line, LINE_LEN))
633 return NULL;
634 /* skip spaces */
635 for (s=line; *s && isspace(*s); s++);
636 /* allow empty lines at the end of the file */
637 if (*s==0)
638 return NULL;
639 /* get the time */
640 if (sscanf (s, "%ld,%ld,", &(current->start),
641 &(current->end)) <2) {
642 return ERR;
644 /* the files I have are in tenths of second */
645 current->start *= 10;
646 current->end *= 10;
647 /* walk to the beggining of the string */
648 for (; *s; s++) if (*s==',') break;
649 if (*s) {
650 for (s++; *s; s++) if (*s==',') break;
651 if (*s) s++;
653 if (*s!='"') {
654 return ERR;
656 /* copy the string to the text buffer */
657 for (s++, d=text; *s && *s!='"'; s++, d++)
658 *d=*s;
659 *d=0;
660 current->text[0] = strdup(text);
661 current->lines = 1;
663 return current;
666 static subtitle *sub_read_line_mpsub(stream_t *st, subtitle *current) {
667 char line[LINE_LEN+1];
668 float a,b;
669 int num=0;
670 char *p, *q;
674 if (!stream_read_line(st, line, LINE_LEN)) return NULL;
675 } while (sscanf (line, "%f %f", &a, &b) !=2);
677 mpsub_position += a*mpsub_multiplier;
678 current->start=(int) mpsub_position;
679 mpsub_position += b*mpsub_multiplier;
680 current->end=(int) mpsub_position;
682 while (num < SUB_MAX_TEXT) {
683 if (!stream_read_line (st, line, LINE_LEN)) {
684 if (num == 0) return NULL;
685 else return current;
687 p=line;
688 while (isspace(*p)) p++;
689 if (eol(*p) && num > 0) return current;
690 if (eol(*p)) return NULL;
692 for (q=p; !eol(*q); q++);
693 *q='\0';
694 if (strlen(p)) {
695 current->text[num]=strdup(p);
696 // printf (">%s<\n",p);
697 current->lines = ++num;
698 } else {
699 if (num) return current;
700 else return NULL;
703 return NULL; // we should have returned before if it's OK
706 #ifndef CONFIG_SORTSUB
707 //we don't need this if we use previous_sub_end
708 subtitle *previous_aqt_sub = NULL;
709 #endif
711 static subtitle *sub_read_line_aqt(stream_t *st,subtitle *current) {
712 char line[LINE_LEN+1];
713 char *next;
714 int i;
716 while (1) {
717 // try to locate next subtitle
718 if (!stream_read_line (st, line, LINE_LEN))
719 return NULL;
720 if (!(sscanf (line, "-->> %ld", &(current->start)) <1))
721 break;
724 #ifdef CONFIG_SORTSUB
725 previous_sub_end = (current->start) ? current->start - 1 : 0;
726 #else
727 if (previous_aqt_sub != NULL)
728 previous_aqt_sub->end = current->start-1;
730 previous_aqt_sub = current;
731 #endif
733 if (!stream_read_line (st, line, LINE_LEN))
734 return NULL;
736 sub_readtext((char *) &line,&current->text[0]);
737 current->lines = 1;
738 current->end = current->start; // will be corrected by next subtitle
740 if (!stream_read_line (st, line, LINE_LEN))
741 return current;
743 next = line,i=1;
744 while ((next =sub_readtext (next, &(current->text[i])))) {
745 if (current->text[i]==ERR) {return ERR;}
746 i++;
747 if (i>=SUB_MAX_TEXT) { mp_msg(MSGT_SUBREADER,MSGL_WARN,"Too many lines in a subtitle\n");current->lines=i;return current;}
749 current->lines=i+1;
751 if (!strlen(current->text[0]) && !strlen(current->text[1])) {
752 #ifdef CONFIG_SORTSUB
753 previous_sub_end = 0;
754 #else
755 // void subtitle -> end of previous marked and exit
756 previous_aqt_sub = NULL;
757 #endif
758 return NULL;
761 return current;
764 #ifndef CONFIG_SORTSUB
765 subtitle *previous_subrip09_sub = NULL;
766 #endif
768 static subtitle *sub_read_line_subrip09(stream_t *st,subtitle *current) {
769 char line[LINE_LEN+1];
770 int a1,a2,a3;
771 char * next=NULL;
772 int i,len;
774 while (1) {
775 // try to locate next subtitle
776 if (!stream_read_line (st, line, LINE_LEN))
777 return NULL;
778 if (!((len=sscanf (line, "[%d:%d:%d]",&a1,&a2,&a3)) < 3))
779 break;
782 current->start = a1*360000+a2*6000+a3*100;
784 #ifdef CONFIG_SORTSUB
785 previous_sub_end = (current->start) ? current->start - 1 : 0;
786 #else
787 if (previous_subrip09_sub != NULL)
788 previous_subrip09_sub->end = current->start-1;
790 previous_subrip09_sub = current;
791 #endif
793 if (!stream_read_line (st, line, LINE_LEN))
794 return NULL;
796 next = line,i=0;
798 current->text[0]=""; // just to be sure that string is clear
800 while ((next =sub_readtext (next, &(current->text[i])))) {
801 if (current->text[i]==ERR) {return ERR;}
802 i++;
803 if (i>=SUB_MAX_TEXT) { mp_msg(MSGT_SUBREADER,MSGL_WARN,"Too many lines in a subtitle\n");current->lines=i;return current;}
805 current->lines=i+1;
807 if (!strlen(current->text[0]) && (i==0)) {
808 #ifdef CONFIG_SORTSUB
809 previous_sub_end = 0;
810 #else
811 // void subtitle -> end of previous marked and exit
812 previous_subrip09_sub = NULL;
813 #endif
814 return NULL;
817 return current;
820 static subtitle *sub_read_line_jacosub(stream_t* st, subtitle * current)
822 char line1[LINE_LEN], line2[LINE_LEN], directive[LINE_LEN], *p, *q;
823 unsigned a1, a2, a3, a4, b1, b2, b3, b4, comment = 0;
824 static unsigned jacoTimeres = 30;
825 static int jacoShift = 0;
827 memset(current, 0, sizeof(subtitle));
828 memset(line1, 0, LINE_LEN);
829 memset(line2, 0, LINE_LEN);
830 memset(directive, 0, LINE_LEN);
831 while (!current->text[0]) {
832 if (!stream_read_line(st, line1, LINE_LEN)) {
833 return NULL;
835 if (sscanf
836 (line1, "%u:%u:%u.%u %u:%u:%u.%u %[^\n\r]", &a1, &a2, &a3, &a4,
837 &b1, &b2, &b3, &b4, line2) < 9) {
838 if (sscanf(line1, "@%u @%u %[^\n\r]", &a4, &b4, line2) < 3) {
839 if (line1[0] == '#') {
840 int hours = 0, minutes = 0, seconds, delta, inverter =
842 unsigned units = jacoShift;
843 switch (toupper(line1[1])) {
844 case 'S':
845 if (isalpha(line1[2])) {
846 delta = 6;
847 } else {
848 delta = 2;
850 if (sscanf(&line1[delta], "%d", &hours)) {
851 if (hours < 0) {
852 hours *= -1;
853 inverter = -1;
855 if (sscanf(&line1[delta], "%*d:%d", &minutes)) {
856 if (sscanf
857 (&line1[delta], "%*d:%*d:%d",
858 &seconds)) {
859 sscanf(&line1[delta], "%*d:%*d:%*d.%d",
860 &units);
861 } else {
862 hours = 0;
863 sscanf(&line1[delta], "%d:%d.%d",
864 &minutes, &seconds, &units);
865 minutes *= inverter;
867 } else {
868 hours = minutes = 0;
869 sscanf(&line1[delta], "%d.%d", &seconds,
870 &units);
871 seconds *= inverter;
873 jacoShift =
874 ((hours * 3600 + minutes * 60 +
875 seconds) * jacoTimeres +
876 units) * inverter;
878 break;
879 case 'T':
880 if (isalpha(line1[2])) {
881 delta = 8;
882 } else {
883 delta = 2;
885 sscanf(&line1[delta], "%u", &jacoTimeres);
886 break;
889 continue;
890 } else {
891 current->start =
892 (unsigned long) ((a4 + jacoShift) * 100.0 /
893 jacoTimeres);
894 current->end =
895 (unsigned long) ((b4 + jacoShift) * 100.0 /
896 jacoTimeres);
898 } else {
899 current->start =
900 (unsigned
901 long) (((a1 * 3600 + a2 * 60 + a3) * jacoTimeres + a4 +
902 jacoShift) * 100.0 / jacoTimeres);
903 current->end =
904 (unsigned
905 long) (((b1 * 3600 + b2 * 60 + b3) * jacoTimeres + b4 +
906 jacoShift) * 100.0 / jacoTimeres);
908 current->lines = 0;
909 p = line2;
910 while ((*p == ' ') || (*p == '\t')) {
911 ++p;
913 if (isalpha(*p)||*p == '[') {
914 int cont, jLength;
916 if (sscanf(p, "%s %[^\n\r]", directive, line1) < 2)
917 return (subtitle *) ERR;
918 jLength = strlen(directive);
919 for (cont = 0; cont < jLength; ++cont) {
920 if (isalpha(*(directive + cont)))
921 *(directive + cont) = toupper(*(directive + cont));
923 if ((strstr(directive, "RDB") != NULL)
924 || (strstr(directive, "RDC") != NULL)
925 || (strstr(directive, "RLB") != NULL)
926 || (strstr(directive, "RLG") != NULL)) {
927 continue;
929 if (strstr(directive, "JL") != NULL) {
930 current->alignment = SUB_ALIGNMENT_BOTTOMLEFT;
931 } else if (strstr(directive, "JR") != NULL) {
932 current->alignment = SUB_ALIGNMENT_BOTTOMRIGHT;
933 } else {
934 current->alignment = SUB_ALIGNMENT_BOTTOMCENTER;
936 strcpy(line2, line1);
937 p = line2;
939 for (q = line1; (!eol(*p)) && (current->lines < SUB_MAX_TEXT); ++p) {
940 switch (*p) {
941 case '{':
942 comment++;
943 break;
944 case '}':
945 if (comment) {
946 --comment;
947 //the next line to get rid of a blank after the comment
948 if ((*(p + 1)) == ' ')
949 p++;
951 break;
952 case '~':
953 if (!comment) {
954 *q = ' ';
955 ++q;
957 break;
958 case ' ':
959 case '\t':
960 if ((*(p + 1) == ' ') || (*(p + 1) == '\t'))
961 break;
962 if (!comment) {
963 *q = ' ';
964 ++q;
966 break;
967 case '\\':
968 if (*(p + 1) == 'n') {
969 *q = '\0';
970 q = line1;
971 current->text[current->lines++] = strdup(line1);
972 ++p;
973 break;
975 if ((toupper(*(p + 1)) == 'C')
976 || (toupper(*(p + 1)) == 'F')) {
977 ++p,++p;
978 break;
980 if ((*(p + 1) == 'B') || (*(p + 1) == 'b') || (*(p + 1) == 'D') || //actually this means "insert current date here"
981 (*(p + 1) == 'I') || (*(p + 1) == 'i') || (*(p + 1) == 'N') || (*(p + 1) == 'T') || //actually this means "insert current time here"
982 (*(p + 1) == 'U') || (*(p + 1) == 'u')) {
983 ++p;
984 break;
986 if ((*(p + 1) == '\\') ||
987 (*(p + 1) == '~') || (*(p + 1) == '{')) {
988 ++p;
989 } else if (eol(*(p + 1))) {
990 if (!stream_read_line(st, directive, LINE_LEN))
991 return NULL;
992 trail_space(directive);
993 strncat(line2, directive,
994 (LINE_LEN > 511) ? LINE_LEN : 511);
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;
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 sub = malloc(sizeof(subtitle));
1405 //This is to deal with those formats (AQT & Subrip) which define the end of a subtitle
1406 //as the beginning of the following
1407 previous_sub_end = 0;
1408 #endif
1409 while(1){
1410 if(sub_num>=n_max){
1411 n_max+=16;
1412 first=realloc(first,n_max*sizeof(subtitle));
1414 #ifndef CONFIG_SORTSUB
1415 sub = &first[sub_num];
1416 #endif
1417 memset(sub, '\0', sizeof(subtitle));
1418 sub=srp->read(fd,sub);
1419 if(!sub) break; // EOF
1420 #ifdef CONFIG_ICONV
1421 if ((sub!=ERR) && (sub_utf8 & 2)) sub=subcp_recode(sub);
1422 #endif
1423 #ifdef CONFIG_FRIBIDI
1424 if (sub!=ERR) sub=sub_fribidi(sub,sub_utf8,0);
1425 #endif
1426 if ( sub == ERR )
1428 #ifdef CONFIG_ICONV
1429 subcp_close();
1430 #endif
1431 if ( first ) free(first);
1432 return NULL;
1434 // Apply any post processing that needs recoding first
1435 if ((sub!=ERR) && !sub_no_text_pp && srp->post) srp->post(sub);
1436 #ifdef CONFIG_SORTSUB
1437 if(!sub_num || (first[sub_num - 1].start <= sub->start)){
1438 first[sub_num].start = sub->start;
1439 first[sub_num].end = sub->end;
1440 first[sub_num].lines = sub->lines;
1441 first[sub_num].alignment = sub->alignment;
1442 for(i = 0; i < sub->lines; ++i){
1443 first[sub_num].text[i] = sub->text[i];
1445 if (previous_sub_end){
1446 first[sub_num - 1].end = previous_sub_end;
1447 previous_sub_end = 0;
1449 } else {
1450 for(j = sub_num - 1; j >= 0; --j){
1451 first[j + 1].start = first[j].start;
1452 first[j + 1].end = first[j].end;
1453 first[j + 1].lines = first[j].lines;
1454 first[j + 1].alignment = first[j].alignment;
1455 for(i = 0; i < first[j].lines; ++i){
1456 first[j + 1].text[i] = first[j].text[i];
1458 if(!j || (first[j - 1].start <= sub->start)){
1459 first[j].start = sub->start;
1460 first[j].end = sub->end;
1461 first[j].lines = sub->lines;
1462 first[j].alignment = sub->alignment;
1463 for(i = 0; i < SUB_MAX_TEXT; ++i){
1464 first[j].text[i] = sub->text[i];
1466 if (previous_sub_end){
1467 first[j].end = first[j - 1].end;
1468 first[j - 1].end = previous_sub_end;
1469 previous_sub_end = 0;
1471 break;
1475 #endif
1476 if(sub==ERR) ++sub_errs; else ++sub_num; // Error vs. Valid
1479 free_stream(fd);
1481 #ifdef CONFIG_ICONV
1482 subcp_close();
1483 #endif
1485 // printf ("SUB: Subtitle format %s time.\n", uses_time?"uses":"doesn't use");
1486 mp_msg(MSGT_SUBREADER, MSGL_V,"SUB: Read %i subtitles, %i bad line(s).\n",
1487 sub_num, sub_errs);
1489 if(sub_num<=0){
1490 free(first);
1491 return NULL;
1494 // we do overlap if the user forced it (suboverlap_enable == 2) or
1495 // the user didn't forced no-overlapsub and the format is Jacosub or Ssa.
1496 // this is because usually overlapping subtitles are found in these formats,
1497 // while in others they are probably result of bad timing
1498 if ((suboverlap_enabled == 2) ||
1499 ((suboverlap_enabled) && ((sub_format == SUB_JACOSUB) || (sub_format == SUB_SSA)))) {
1500 adjust_subs_time(first, 6.0, fps, 0, sub_num, uses_time);/*~6 secs AST*/
1501 // here we manage overlapping subtitles
1502 sub_orig = sub_num;
1503 n_first = sub_num;
1504 sub_num = 0;
1505 second = NULL;
1506 // for each subtitle in first[] we deal with its 'block' of
1507 // bonded subtitles
1508 for (sub_first = 0; sub_first < n_first; ++sub_first) {
1509 unsigned long global_start = first[sub_first].start,
1510 global_end = first[sub_first].end, local_start, local_end;
1511 int lines_to_add = first[sub_first].lines, sub_to_add = 0,
1512 **placeholder = NULL, higher_line = 0, counter, start_block_sub = sub_num;
1513 char real_block = 1;
1515 // here we find the number of subtitles inside the 'block'
1516 // and its span interval. this works well only with sorted
1517 // subtitles
1518 while ((sub_first + sub_to_add + 1 < n_first) && (first[sub_first + sub_to_add + 1].start < global_end)) {
1519 ++sub_to_add;
1520 lines_to_add += first[sub_first + sub_to_add].lines;
1521 if (first[sub_first + sub_to_add].start < global_start) {
1522 global_start = first[sub_first + sub_to_add].start;
1524 if (first[sub_first + sub_to_add].end > global_end) {
1525 global_end = first[sub_first + sub_to_add].end;
1529 // we need a structure to keep trace of the screen lines
1530 // used by the subs, a 'placeholder'
1531 counter = 2 * sub_to_add + 1; // the maximum number of subs derived
1532 // from a block of sub_to_add+1 subs
1533 placeholder = malloc(sizeof(int *) * counter);
1534 for (i = 0; i < counter; ++i) {
1535 placeholder[i] = malloc(sizeof(int) * lines_to_add);
1536 for (j = 0; j < lines_to_add; ++j) {
1537 placeholder[i][j] = -1;
1541 counter = 0;
1542 local_end = global_start - 1;
1543 do {
1544 int ls;
1546 // here we find the beginning and the end of a new
1547 // subtitle in the block
1548 local_start = local_end + 1;
1549 local_end = global_end;
1550 for (j = 0; j <= sub_to_add; ++j) {
1551 if ((first[sub_first + j].start - 1 > local_start) && (first[sub_first + j].start - 1 < local_end)) {
1552 local_end = first[sub_first + j].start - 1;
1553 } else if ((first[sub_first + j].end > local_start) && (first[sub_first + j].end < local_end)) {
1554 local_end = first[sub_first + j].end;
1557 // here we allocate the screen lines to subs we must
1558 // display in current local_start-local_end interval.
1559 // if the subs were yet presents in the previous interval
1560 // they keep the same lines, otherside they get unused lines
1561 for (j = 0; j <= sub_to_add; ++j) {
1562 if ((first[sub_first + j].start <= local_end) && (first[sub_first + j].end > local_start)) {
1563 unsigned long sub_lines = first[sub_first + j].lines, fragment_length = lines_to_add + 1,
1564 tmp = 0;
1565 char boolean = 0;
1566 int fragment_position = -1;
1568 // if this is not the first new sub of the block
1569 // we find if this sub was present in the previous
1570 // new sub
1571 if (counter)
1572 for (i = 0; i < lines_to_add; ++i) {
1573 if (placeholder[counter - 1][i] == sub_first + j) {
1574 placeholder[counter][i] = sub_first + j;
1575 boolean = 1;
1578 if (boolean)
1579 continue;
1581 // we are looking for the shortest among all groups of
1582 // sequential blank lines whose length is greater than or
1583 // equal to sub_lines. we store in fragment_position the
1584 // position of the shortest group, in fragment_length its
1585 // length, and in tmp the length of the group currently
1586 // examinated
1587 for (i = 0; i < lines_to_add; ++i) {
1588 if (placeholder[counter][i] == -1) {
1589 // placeholder[counter][i] is part of the current group
1590 // of blank lines
1591 ++tmp;
1592 } else {
1593 if (tmp == sub_lines) {
1594 // current group's size fits exactly the one we
1595 // need, so we stop looking
1596 fragment_position = i - tmp;
1597 tmp = 0;
1598 break;
1600 if ((tmp) && (tmp > sub_lines) && (tmp < fragment_length)) {
1601 // current group is the best we found till here,
1602 // but is still bigger than the one we are looking
1603 // for, so we keep on looking
1604 fragment_length = tmp;
1605 fragment_position = i - tmp;
1606 tmp = 0;
1607 } else {
1608 // current group doesn't fit at all, so we forget it
1609 tmp = 0;
1613 if (tmp) {
1614 // last screen line is blank, a group ends with it
1615 if ((tmp >= sub_lines) && (tmp < fragment_length)) {
1616 fragment_position = i - tmp;
1619 if (fragment_position == -1) {
1620 // it was not possible to find free screen line(s) for a subtitle,
1621 // usually this means a bug in the code; however we do not overlap
1622 mp_msg(MSGT_SUBREADER, MSGL_WARN, "SUB: we could not find a suitable position for an overlapping subtitle\n");
1623 higher_line = SUB_MAX_TEXT + 1;
1624 break;
1625 } else {
1626 for (tmp = 0; tmp < sub_lines; ++tmp) {
1627 placeholder[counter][fragment_position + tmp] = sub_first + j;
1632 for (j = higher_line + 1; j < lines_to_add; ++j) {
1633 if (placeholder[counter][j] != -1)
1634 higher_line = j;
1635 else
1636 break;
1638 if (higher_line >= SUB_MAX_TEXT) {
1639 // the 'block' has too much lines, so we don't overlap the
1640 // subtitles
1641 second = (subtitle *) realloc(second, (sub_num + sub_to_add + 1) * sizeof(subtitle));
1642 for (j = 0; j <= sub_to_add; ++j) {
1643 int ls;
1644 memset(&second[sub_num + j], '\0', sizeof(subtitle));
1645 second[sub_num + j].start = first[sub_first + j].start;
1646 second[sub_num + j].end = first[sub_first + j].end;
1647 second[sub_num + j].lines = first[sub_first + j].lines;
1648 second[sub_num + j].alignment = first[sub_first + j].alignment;
1649 for (ls = 0; ls < second[sub_num + j].lines; ls++) {
1650 second[sub_num + j].text[ls] = strdup(first[sub_first + j].text[ls]);
1653 sub_num += sub_to_add + 1;
1654 sub_first += sub_to_add;
1655 real_block = 0;
1656 break;
1659 // we read the placeholder structure and create the new
1660 // subs.
1661 second = (subtitle *) realloc(second, (sub_num + 1) * sizeof(subtitle));
1662 memset(&second[sub_num], '\0', sizeof(subtitle));
1663 second[sub_num].start = local_start;
1664 second[sub_num].end = local_end;
1665 second[sub_num].alignment = first[sub_first].alignment;
1666 n_max = (lines_to_add < SUB_MAX_TEXT) ? lines_to_add : SUB_MAX_TEXT;
1667 for (i = 0, j = 0; j < n_max; ++j) {
1668 if (placeholder[counter][j] != -1) {
1669 int lines = first[placeholder[counter][j]].lines;
1670 for (ls = 0; ls < lines; ++ls) {
1671 second[sub_num].text[i++] = strdup(first[placeholder[counter][j]].text[ls]);
1673 j += lines - 1;
1674 } else {
1675 second[sub_num].text[i++] = strdup(" ");
1678 ++sub_num;
1679 ++counter;
1680 } while (local_end < global_end);
1681 if (real_block)
1682 for (i = 0; i < counter; ++i)
1683 second[start_block_sub + i].lines = higher_line + 1;
1685 counter = 2 * sub_to_add + 1;
1686 for (i = 0; i < counter; ++i) {
1687 free(placeholder[i]);
1689 free(placeholder);
1690 sub_first += sub_to_add;
1693 for (j = sub_orig - 1; j >= 0; --j) {
1694 for (i = first[j].lines - 1; i >= 0; --i) {
1695 free(first[j].text[i]);
1698 free(first);
1700 return_sub = second;
1701 } else { //if(suboverlap_enabled)
1702 adjust_subs_time(first, 6.0, fps, 1, sub_num, uses_time);/*~6 secs AST*/
1703 return_sub = first;
1705 if (return_sub == NULL) return NULL;
1706 subt_data = malloc(sizeof(sub_data));
1707 subt_data->filename = strdup(filename);
1708 subt_data->sub_uses_time = uses_time;
1709 subt_data->sub_num = sub_num;
1710 subt_data->sub_errs = sub_errs;
1711 subt_data->subtitles = return_sub;
1712 return subt_data;
1715 #if 0
1716 char * strreplace( char * in,char * what,char * whereof )
1718 int i;
1719 char * tmp;
1721 if ( ( in == NULL )||( what == NULL )||( whereof == NULL )||( ( tmp=strstr( in,what ) ) == NULL ) ) return NULL;
1722 for( i=0;i<strlen( whereof );i++ ) tmp[i]=whereof[i];
1723 if ( strlen( what ) > strlen( whereof ) ) tmp[i]=0;
1724 return in;
1726 #endif
1729 static void strcpy_trim(char *d, char *s)
1731 // skip leading whitespace
1732 while (*s && !isalnum(*s)) {
1733 s++;
1735 for (;;) {
1736 // copy word
1737 while (*s && isalnum(*s)) {
1738 *d = tolower(*s);
1739 s++; d++;
1741 if (*s == 0) break;
1742 // trim excess whitespace
1743 while (*s && !isalnum(*s)) {
1744 s++;
1746 if (*s == 0) break;
1747 *d++ = ' ';
1749 *d = 0;
1752 static void strcpy_strip_ext(char *d, char *s)
1754 char *tmp = strrchr(s,'.');
1755 if (!tmp) {
1756 strcpy(d, s);
1757 return;
1758 } else {
1759 strncpy(d, s, tmp-s);
1760 d[tmp-s] = 0;
1762 while (*d) {
1763 *d = tolower(*d);
1764 d++;
1768 static void strcpy_get_ext(char *d, char *s)
1770 char *tmp = strrchr(s,'.');
1771 if (!tmp) {
1772 strcpy(d, "");
1773 return;
1774 } else {
1775 strcpy(d, tmp+1);
1779 static int whiteonly(char *s)
1781 while (*s) {
1782 if (isalnum(*s)) return 0;
1783 s++;
1785 return 1;
1788 typedef struct subfn
1790 int priority;
1791 char *fname;
1792 } subfn;
1794 static int compare_sub_priority(const void *a, const void *b)
1796 if (((const subfn*)a)->priority > ((const subfn*)b)->priority) {
1797 return -1;
1798 } else if (((const subfn*)a)->priority < ((const subfn*)b)->priority) {
1799 return 1;
1800 } else {
1801 return strcoll(((const subfn*)a)->fname, ((const subfn*)b)->fname);
1805 char** sub_filenames(const char* path, char *fname)
1807 char *f_dir, *f_fname, *f_fname_noext, *f_fname_trim, *tmp, *tmp_sub_id;
1808 char *tmp_fname_noext, *tmp_fname_trim, *tmp_fname_ext, *tmpresult;
1810 int len, pos, found, i, j;
1811 char * sub_exts[] = { "utf", "utf8", "utf-8", "sub", "srt", "smi", "rt", "txt", "ssa", "aqt", "jss", "js", "ass", NULL};
1812 subfn *result;
1813 char **result2;
1815 int subcnt;
1817 FILE *f;
1819 DIR *d;
1820 struct dirent *de;
1822 len = (strlen(fname) > 256 ? strlen(fname) : 256)
1823 +(strlen(path) > 256 ? strlen(path) : 256)+2;
1825 f_dir = malloc(len);
1826 f_fname = malloc(len);
1827 f_fname_noext = malloc(len);
1828 f_fname_trim = malloc(len);
1830 tmp_fname_noext = malloc(len);
1831 tmp_fname_trim = malloc(len);
1832 tmp_fname_ext = malloc(len);
1834 tmpresult = malloc(len);
1836 result = malloc(sizeof(subfn)*MAX_SUBTITLE_FILES);
1837 memset(result, 0, sizeof(subfn)*MAX_SUBTITLE_FILES);
1839 subcnt = 0;
1841 tmp = strrchr(fname,'/');
1842 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1843 if(!tmp)tmp = strrchr(fname,'\\');
1844 if(!tmp)tmp = strrchr(fname,':');
1845 #endif
1847 // extract filename & dirname from fname
1848 if (tmp) {
1849 strcpy(f_fname, tmp+1);
1850 pos = tmp - fname;
1851 strncpy(f_dir, fname, pos+1);
1852 f_dir[pos+1] = 0;
1853 } else {
1854 strcpy(f_fname, fname);
1855 strcpy(f_dir, "./");
1858 strcpy_strip_ext(f_fname_noext, f_fname);
1859 strcpy_trim(f_fname_trim, f_fname_noext);
1861 tmp_sub_id = NULL;
1862 if (dvdsub_lang && !whiteonly(dvdsub_lang)) {
1863 tmp_sub_id = malloc(strlen(dvdsub_lang)+1);
1864 strcpy_trim(tmp_sub_id, dvdsub_lang);
1867 // 0 = nothing
1868 // 1 = any subtitle file
1869 // 2 = any sub file containing movie name
1870 // 3 = sub file containing movie name and the lang extension
1871 for (j = 0; j <= 1; j++) {
1872 d = opendir(j == 0 ? f_dir : path);
1873 if (d) {
1874 while ((de = readdir(d))) {
1875 // retrieve various parts of the filename
1876 strcpy_strip_ext(tmp_fname_noext, de->d_name);
1877 strcpy_get_ext(tmp_fname_ext, de->d_name);
1878 strcpy_trim(tmp_fname_trim, tmp_fname_noext);
1880 // does it end with a subtitle extension?
1881 found = 0;
1882 #ifdef CONFIG_ICONV
1883 #ifdef CONFIG_ENCA
1884 for (i = ((sub_cp && strncasecmp(sub_cp, "enca", 4) != 0) ? 3 : 0); sub_exts[i]; i++) {
1885 #else
1886 for (i = (sub_cp ? 3 : 0); sub_exts[i]; i++) {
1887 #endif
1888 #else
1889 for (i = 0; sub_exts[i]; i++) {
1890 #endif
1891 if (strcasecmp(sub_exts[i], tmp_fname_ext) == 0) {
1892 found = 1;
1893 break;
1897 // we have a (likely) subtitle file
1898 if (found) {
1899 int prio = 0;
1900 if (!prio && tmp_sub_id)
1902 sprintf(tmpresult, "%s %s", f_fname_trim, tmp_sub_id);
1903 mp_msg(MSGT_SUBREADER,MSGL_INFO,"dvdsublang...%s\n", tmpresult);
1904 if (strcmp(tmp_fname_trim, tmpresult) == 0 && sub_match_fuzziness >= 1) {
1905 // matches the movie name + lang extension
1906 prio = 5;
1909 if (!prio && strcmp(tmp_fname_trim, f_fname_trim) == 0) {
1910 // matches the movie name
1911 prio = 4;
1913 if (!prio && (tmp = strstr(tmp_fname_trim, f_fname_trim)) && (sub_match_fuzziness >= 1)) {
1914 // contains the movie name
1915 tmp += strlen(f_fname_trim);
1916 if (tmp_sub_id && strstr(tmp, tmp_sub_id)) {
1917 // with sub_id specified prefer localized subtitles
1918 prio = 3;
1919 } else if ((tmp_sub_id == NULL) && whiteonly(tmp)) {
1920 // without sub_id prefer "plain" name
1921 prio = 3;
1922 } else {
1923 // with no localized subs found, try any else instead
1924 prio = 2;
1927 if (!prio) {
1928 // doesn't contain the movie name
1929 // don't try in the mplayer subtitle directory
1930 if ((j == 0) && (sub_match_fuzziness >= 2)) {
1931 prio = 1;
1935 if (prio) {
1936 prio += prio;
1937 #ifdef CONFIG_ICONV
1938 if (i<3){ // prefer UTF-8 coded
1939 prio++;
1941 #endif
1942 sprintf(tmpresult, "%s%s", j == 0 ? f_dir : path, de->d_name);
1943 // fprintf(stderr, "%s priority %d\n", tmpresult, prio);
1944 if ((f = fopen(tmpresult, "rt"))) {
1945 fclose(f);
1946 result[subcnt].priority = prio;
1947 result[subcnt].fname = strdup(tmpresult);
1948 subcnt++;
1953 if (subcnt >= MAX_SUBTITLE_FILES) break;
1955 closedir(d);
1960 if (tmp_sub_id) free(tmp_sub_id);
1962 free(f_dir);
1963 free(f_fname);
1964 free(f_fname_noext);
1965 free(f_fname_trim);
1967 free(tmp_fname_noext);
1968 free(tmp_fname_trim);
1969 free(tmp_fname_ext);
1971 free(tmpresult);
1973 qsort(result, subcnt, sizeof(subfn), compare_sub_priority);
1975 result2 = malloc(sizeof(char*)*(subcnt+1));
1976 memset(result2, 0, sizeof(char*)*(subcnt+1));
1978 for (i = 0; i < subcnt; i++) {
1979 result2[i] = result[i].fname;
1981 result2[subcnt] = NULL;
1983 free(result);
1985 return result2;
1988 void list_sub_file(sub_data* subd){
1989 int i,j;
1990 subtitle *subs = subd->subtitles;
1992 for(j=0; j < subd->sub_num; j++){
1993 subtitle* egysub=&subs[j];
1994 mp_msg(MSGT_SUBREADER,MSGL_INFO,"%i line%c (%li-%li)\n",
1995 egysub->lines,
1996 (1==egysub->lines)?' ':'s',
1997 egysub->start,
1998 egysub->end);
1999 for (i=0; i<egysub->lines; i++) {
2000 mp_msg(MSGT_SUBREADER,MSGL_INFO,"\t\t%d: %s%s", i,egysub->text[i], i==egysub->lines-1?"":" \n ");
2002 mp_msg(MSGT_SUBREADER,MSGL_INFO,"\n");
2005 mp_msg(MSGT_SUBREADER,MSGL_INFO,"Subtitle format %s time.\n",
2006 subd->sub_uses_time ? "uses":"doesn't use");
2007 mp_msg(MSGT_SUBREADER,MSGL_INFO,"Read %i subtitles, %i errors.\n", subd->sub_num, subd->sub_errs);
2010 void dump_srt(sub_data* subd, float fps){
2011 int i,j;
2012 int h,m,s,ms;
2013 FILE * fd;
2014 subtitle * onesub;
2015 unsigned long temp;
2016 subtitle *subs = subd->subtitles;
2018 if (!subd->sub_uses_time && sub_fps == 0)
2019 sub_fps = fps;
2020 fd=fopen("dumpsub.srt","w");
2021 if(!fd)
2023 perror("dump_srt: fopen");
2024 return;
2026 for(i=0; i < subd->sub_num; i++)
2028 onesub=subs+i; //=&subs[i];
2029 fprintf(fd,"%d\n",i+1);//line number
2031 temp=onesub->start;
2032 if (!subd->sub_uses_time)
2033 temp = temp * 100 / sub_fps;
2034 temp -= sub_delay * 100;
2035 h=temp/360000;temp%=360000; //h =1*100*60*60
2036 m=temp/6000; temp%=6000; //m =1*100*60
2037 s=temp/100; temp%=100; //s =1*100
2038 ms=temp*10; //ms=1*10
2039 fprintf(fd,"%02d:%02d:%02d,%03d --> ",h,m,s,ms);
2041 temp=onesub->end;
2042 if (!subd->sub_uses_time)
2043 temp = temp * 100 / sub_fps;
2044 temp -= sub_delay * 100;
2045 h=temp/360000;temp%=360000;
2046 m=temp/6000; temp%=6000;
2047 s=temp/100; temp%=100;
2048 ms=temp*10;
2049 fprintf(fd,"%02d:%02d:%02d,%03d\n",h,m,s,ms);
2051 for(j=0;j<onesub->lines;j++)
2052 fprintf(fd,"%s\n",onesub->text[j]);
2054 fprintf(fd,"\n");
2056 fclose(fd);
2057 mp_msg(MSGT_SUBREADER,MSGL_INFO,"SUB: Subtitles dumped in \'dumpsub.srt\'.\n");
2060 void dump_mpsub(sub_data* subd, float fps){
2061 int i,j;
2062 FILE *fd;
2063 float a,b;
2064 subtitle *subs = subd->subtitles;
2066 mpsub_position = subd->sub_uses_time? (sub_delay*100) : (sub_delay*fps);
2067 if (sub_fps==0) sub_fps=fps;
2069 fd=fopen ("dump.mpsub", "w");
2070 if (!fd) {
2071 perror ("dump_mpsub: fopen");
2072 return;
2076 if (subd->sub_uses_time) fprintf (fd,"FORMAT=TIME\n\n");
2077 else fprintf (fd, "FORMAT=%5.2f\n\n", fps);
2079 for(j=0; j < subd->sub_num; j++){
2080 subtitle* egysub=&subs[j];
2081 if (subd->sub_uses_time) {
2082 a=((egysub->start-mpsub_position)/100.0);
2083 b=((egysub->end-egysub->start)/100.0);
2084 if ( (float)((int)a) == a)
2085 fprintf (fd, "%.0f",a);
2086 else
2087 fprintf (fd, "%.2f",a);
2089 if ( (float)((int)b) == b)
2090 fprintf (fd, " %.0f\n",b);
2091 else
2092 fprintf (fd, " %.2f\n",b);
2093 } else {
2094 fprintf (fd, "%ld %ld\n", (long)((egysub->start*(fps/sub_fps))-((mpsub_position*(fps/sub_fps)))),
2095 (long)(((egysub->end)-(egysub->start))*(fps/sub_fps)));
2098 mpsub_position = egysub->end;
2099 for (i=0; i<egysub->lines; i++) {
2100 fprintf (fd, "%s\n",egysub->text[i]);
2102 fprintf (fd, "\n");
2104 fclose (fd);
2105 mp_msg(MSGT_SUBREADER,MSGL_INFO,"SUB: Subtitles dumped in \'dump.mpsub\'.\n");
2108 void dump_microdvd(sub_data* subd, float fps) {
2109 int i, delay;
2110 FILE *fd;
2111 subtitle *subs = subd->subtitles;
2112 if (sub_fps == 0)
2113 sub_fps = fps;
2114 fd = fopen("dumpsub.sub", "w");
2115 if (!fd) {
2116 perror("dumpsub.sub: fopen");
2117 return;
2119 delay = sub_delay * sub_fps;
2120 for (i = 0; i < subd->sub_num; ++i) {
2121 int j, start, end;
2122 start = subs[i].start;
2123 end = subs[i].end;
2124 if (subd->sub_uses_time) {
2125 start = start * sub_fps / 100 ;
2126 end = end * sub_fps / 100;
2128 else {
2129 start = start * sub_fps / fps;
2130 end = end * sub_fps / fps;
2132 start -= delay;
2133 end -= delay;
2134 fprintf(fd, "{%d}{%d}", start, end);
2135 for (j = 0; j < subs[i].lines; ++j)
2136 fprintf(fd, "%s%s", j ? "|" : "", subs[i].text[j]);
2137 fprintf(fd, "\n");
2139 fclose(fd);
2140 mp_msg(MSGT_SUBREADER,MSGL_INFO,"SUB: Subtitles dumped in \'dumpsub.sub\'.\n");
2143 void dump_jacosub(sub_data* subd, float fps) {
2144 int i,j;
2145 int h,m,s,cs;
2146 FILE * fd;
2147 subtitle * onesub;
2148 unsigned long temp;
2149 subtitle *subs = subd->subtitles;
2151 if (!subd->sub_uses_time && sub_fps == 0)
2152 sub_fps = fps;
2153 fd=fopen("dumpsub.jss","w");
2154 if(!fd)
2156 perror("dump_jacosub: fopen");
2157 return;
2159 fprintf(fd, "#TIMERES %d\n", (subd->sub_uses_time) ? 100 : (int)sub_fps);
2160 for(i=0; i < subd->sub_num; i++)
2162 onesub=subs+i; //=&subs[i];
2164 temp=onesub->start;
2165 if (!subd->sub_uses_time)
2166 temp = temp * 100 / sub_fps;
2167 temp -= sub_delay * 100;
2168 h=temp/360000;temp%=360000; //h =1*100*60*60
2169 m=temp/6000; temp%=6000; //m =1*100*60
2170 s=temp/100; temp%=100; //s =1*100
2171 cs=temp; //cs=1*10
2172 fprintf(fd,"%02d:%02d:%02d.%02d ",h,m,s,cs);
2174 temp=onesub->end;
2175 if (!subd->sub_uses_time)
2176 temp = temp * 100 / sub_fps;
2177 temp -= sub_delay * 100;
2178 h=temp/360000;temp%=360000;
2179 m=temp/6000; temp%=6000;
2180 s=temp/100; temp%=100;
2181 cs=temp;
2182 fprintf(fd,"%02d:%02d:%02d.%02d {~} ",h,m,s,cs);
2184 for(j=0;j<onesub->lines;j++)
2185 fprintf(fd,"%s%s",j ? "\\n" : "", onesub->text[j]);
2187 fprintf(fd,"\n");
2189 fclose(fd);
2190 mp_msg(MSGT_SUBREADER,MSGL_INFO,"SUB: Subtitles dumped in \'dumpsub.js\'.\n");
2193 void dump_sami(sub_data* subd, float fps) {
2194 int i,j;
2195 FILE * fd;
2196 subtitle * onesub;
2197 unsigned long temp;
2198 subtitle *subs = subd->subtitles;
2200 if (!subd->sub_uses_time && sub_fps == 0)
2201 sub_fps = fps;
2202 fd=fopen("dumpsub.smi","w");
2203 if(!fd)
2205 perror("dump_jacosub: fopen");
2206 return;
2208 fprintf(fd, "<SAMI>\n"
2209 "<HEAD>\n"
2210 " <STYLE TYPE=\"Text/css\">\n"
2211 " <!--\n"
2212 " 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"
2213 " .SUBTTL {Name: 'Subtitles'; Lang: en-US; SAMIType: CC;}\n"
2214 " -->\n"
2215 " </STYLE>\n"
2216 "</HEAD>\n"
2217 "<BODY>\n");
2218 for(i=0; i < subd->sub_num; i++)
2220 onesub=subs+i; //=&subs[i];
2222 temp=onesub->start;
2223 if (!subd->sub_uses_time)
2224 temp = temp * 100 / sub_fps;
2225 temp -= sub_delay * 100;
2226 fprintf(fd,"\t<SYNC Start=%lu>\n"
2227 "\t <P>", temp * 10);
2229 for(j=0;j<onesub->lines;j++)
2230 fprintf(fd,"%s%s",j ? "<br>" : "", onesub->text[j]);
2232 fprintf(fd,"\n");
2234 temp=onesub->end;
2235 if (!subd->sub_uses_time)
2236 temp = temp * 100 / sub_fps;
2237 temp -= sub_delay * 100;
2238 fprintf(fd,"\t<SYNC Start=%lu>\n"
2239 "\t <P>&nbsp;\n", temp * 10);
2241 fprintf(fd, "</BODY>\n"
2242 "</SAMI>\n");
2243 fclose(fd);
2244 mp_msg(MSGT_SUBREADER,MSGL_INFO,"SUB: Subtitles dumped in \'dumpsub.smi\'.\n");
2247 void sub_free( sub_data * subd )
2249 int i;
2251 if ( !subd ) return;
2253 if (subd->subtitles) {
2254 for (i=0; i < subd->subtitles->lines; i++) free( subd->subtitles->text[i] );
2255 free( subd->subtitles );
2257 if (subd->filename) free( subd->filename );
2258 free( subd );
2261 #define MAX_SUBLINE 512
2263 * \brief parse text and append it to subtitle in sub
2264 * \param sub subtitle struct to add text to
2265 * \param txt text to parse
2266 * \param len length of text in txt
2267 * \param endpts pts at which this subtitle text should be removed again
2269 * <> and {} are interpreted as comment delimiters, "\n", "\N", '\n', '\r'
2270 * and '\0' are interpreted as newlines, duplicate, leading and trailing
2271 * newlines are ignored.
2273 void sub_add_text(subtitle *sub, const char *txt, int len, double endpts) {
2274 int comment = 0;
2275 int double_newline = 1; // ignore newlines at the beginning
2276 int i, pos;
2277 char *buf;
2278 int orig_lines = sub->lines;
2279 if (sub->lines >= SUB_MAX_TEXT) return;
2280 pos = 0;
2281 buf = malloc(MAX_SUBLINE + 1);
2282 sub->text[sub->lines] = buf;
2283 sub->endpts[sub->lines] = endpts;
2284 for (i = 0; i < len && pos < MAX_SUBLINE; i++) {
2285 char c = txt[i];
2286 if (c == '<') comment |= 1;
2287 if (c == '{') comment |= 2;
2288 if (comment) {
2289 if (c == '}') comment &= ~2;
2290 if (c == '>') comment &= ~1;
2291 continue;
2293 if (pos == MAX_SUBLINE - 1) {
2294 i--;
2295 c = 0;
2297 if (c == '\\' && i + 1 < len) {
2298 c = txt[++i];
2299 if (c == 'n' || c == 'N') c = 0;
2301 if (c == '\n' || c == '\r') c = 0;
2302 if (c) {
2303 double_newline = 0;
2304 buf[pos++] = c;
2305 } else if (!double_newline) {
2306 if (sub->lines >= SUB_MAX_TEXT - 1) {
2307 mp_msg(MSGT_VO, MSGL_WARN, "Too many subtitle lines\n");
2308 break;
2310 double_newline = 1;
2311 buf[pos] = 0;
2312 sub->lines++;
2313 pos = 0;
2314 buf = malloc(MAX_SUBLINE + 1);
2315 sub->text[sub->lines] = buf;
2316 sub->endpts[sub->lines] = endpts;
2319 buf[pos] = 0;
2320 if (sub->lines < SUB_MAX_TEXT &&
2321 strlen(sub->text[sub->lines]))
2322 sub->lines++;
2323 #ifdef CONFIG_FRIBIDI
2324 sub = sub_fribidi(sub, sub_utf8, orig_lines);
2325 #endif
2328 #define MP_NOPTS_VALUE (-1LL<<63)
2330 * \brief remove outdated subtitle lines.
2331 * \param sub subtitle struct to modify
2332 * \param pts current pts. All lines with endpts <= this will be removed.
2333 * Use MP_NOPTS_VALUE to remove all lines
2334 * \return 1 if sub was modified, 0 otherwise.
2336 int sub_clear_text(subtitle *sub, double pts) {
2337 int i = 0;
2338 int changed = 0;
2339 while (i < sub->lines) {
2340 double endpts = sub->endpts[i];
2341 if (pts == MP_NOPTS_VALUE || (endpts != MP_NOPTS_VALUE && pts >= endpts)) {
2342 int j;
2343 free(sub->text[i]);
2344 for (j = i + 1; j < sub->lines; j++) {
2345 sub->text[j - 1] = sub->text[j];
2346 sub->endpts[j - 1] = sub->endpts[j];
2348 sub->lines--;
2349 changed = 1;
2350 } else
2351 i++;
2353 return changed;