Use $_target-pkg-config if available
[mplayer/kovensky.git] / subreader.c
blobf1b5b44f5eac1fb758f966704f11b93256e4c760
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 /* Avoid n^2 memory use for the "placeholder" data structure
1530 * below with subtitles that have a huge number of
1531 * consecutive overlapping lines. */
1532 lines_to_add = FFMIN(lines_to_add, SUB_MAX_TEXT);
1534 // we need a structure to keep trace of the screen lines
1535 // used by the subs, a 'placeholder'
1536 counter = 2 * sub_to_add + 1; // the maximum number of subs derived
1537 // from a block of sub_to_add+1 subs
1538 placeholder = malloc(sizeof(int *) * counter);
1539 for (i = 0; i < counter; ++i) {
1540 placeholder[i] = malloc(sizeof(int) * lines_to_add);
1541 for (j = 0; j < lines_to_add; ++j) {
1542 placeholder[i][j] = -1;
1546 counter = 0;
1547 local_end = global_start - 1;
1548 do {
1549 int ls;
1551 // here we find the beginning and the end of a new
1552 // subtitle in the block
1553 local_start = local_end + 1;
1554 local_end = global_end;
1555 for (j = 0; j <= sub_to_add; ++j) {
1556 if ((first[sub_first + j].start - 1 > local_start) && (first[sub_first + j].start - 1 < local_end)) {
1557 local_end = first[sub_first + j].start - 1;
1558 } else if ((first[sub_first + j].end > local_start) && (first[sub_first + j].end < local_end)) {
1559 local_end = first[sub_first + j].end;
1562 // here we allocate the screen lines to subs we must
1563 // display in current local_start-local_end interval.
1564 // if the subs were yet presents in the previous interval
1565 // they keep the same lines, otherside they get unused lines
1566 for (j = 0; j <= sub_to_add; ++j) {
1567 if ((first[sub_first + j].start <= local_end) && (first[sub_first + j].end > local_start)) {
1568 unsigned long sub_lines = first[sub_first + j].lines, fragment_length = lines_to_add + 1,
1569 tmp = 0;
1570 char boolean = 0;
1571 int fragment_position = -1;
1573 // if this is not the first new sub of the block
1574 // we find if this sub was present in the previous
1575 // new sub
1576 if (counter)
1577 for (i = 0; i < lines_to_add; ++i) {
1578 if (placeholder[counter - 1][i] == sub_first + j) {
1579 placeholder[counter][i] = sub_first + j;
1580 boolean = 1;
1583 if (boolean)
1584 continue;
1586 // we are looking for the shortest among all groups of
1587 // sequential blank lines whose length is greater than or
1588 // equal to sub_lines. we store in fragment_position the
1589 // position of the shortest group, in fragment_length its
1590 // length, and in tmp the length of the group currently
1591 // examinated
1592 for (i = 0; i < lines_to_add; ++i) {
1593 if (placeholder[counter][i] == -1) {
1594 // placeholder[counter][i] is part of the current group
1595 // of blank lines
1596 ++tmp;
1597 } else {
1598 if (tmp == sub_lines) {
1599 // current group's size fits exactly the one we
1600 // need, so we stop looking
1601 fragment_position = i - tmp;
1602 tmp = 0;
1603 break;
1605 if ((tmp) && (tmp > sub_lines) && (tmp < fragment_length)) {
1606 // current group is the best we found till here,
1607 // but is still bigger than the one we are looking
1608 // for, so we keep on looking
1609 fragment_length = tmp;
1610 fragment_position = i - tmp;
1611 tmp = 0;
1612 } else {
1613 // current group doesn't fit at all, so we forget it
1614 tmp = 0;
1618 if (tmp) {
1619 // last screen line is blank, a group ends with it
1620 if ((tmp >= sub_lines) && (tmp < fragment_length)) {
1621 fragment_position = i - tmp;
1624 if (fragment_position == -1) {
1625 // it was not possible to find free screen line(s) for a subtitle,
1626 // usually this means a bug in the code; however we do not overlap
1627 mp_msg(MSGT_SUBREADER, MSGL_WARN, "SUB: we could not find a suitable position for an overlapping subtitle\n");
1628 higher_line = SUB_MAX_TEXT + 1;
1629 break;
1630 } else {
1631 for (tmp = 0; tmp < sub_lines; ++tmp) {
1632 placeholder[counter][fragment_position + tmp] = sub_first + j;
1637 for (j = higher_line + 1; j < lines_to_add; ++j) {
1638 if (placeholder[counter][j] != -1)
1639 higher_line = j;
1640 else
1641 break;
1643 if (higher_line >= SUB_MAX_TEXT) {
1644 // the 'block' has too much lines, so we don't overlap the
1645 // subtitles
1646 second = (subtitle *) realloc(second, (sub_num + sub_to_add + 1) * sizeof(subtitle));
1647 for (j = 0; j <= sub_to_add; ++j) {
1648 int ls;
1649 memset(&second[sub_num + j], '\0', sizeof(subtitle));
1650 second[sub_num + j].start = first[sub_first + j].start;
1651 second[sub_num + j].end = first[sub_first + j].end;
1652 second[sub_num + j].lines = first[sub_first + j].lines;
1653 second[sub_num + j].alignment = first[sub_first + j].alignment;
1654 for (ls = 0; ls < second[sub_num + j].lines; ls++) {
1655 second[sub_num + j].text[ls] = strdup(first[sub_first + j].text[ls]);
1658 sub_num += sub_to_add + 1;
1659 sub_first += sub_to_add;
1660 real_block = 0;
1661 break;
1664 // we read the placeholder structure and create the new
1665 // subs.
1666 second = (subtitle *) realloc(second, (sub_num + 1) * sizeof(subtitle));
1667 memset(&second[sub_num], '\0', sizeof(subtitle));
1668 second[sub_num].start = local_start;
1669 second[sub_num].end = local_end;
1670 second[sub_num].alignment = first[sub_first].alignment;
1671 n_max = (lines_to_add < SUB_MAX_TEXT) ? lines_to_add : SUB_MAX_TEXT;
1672 for (i = 0, j = 0; j < n_max; ++j) {
1673 if (placeholder[counter][j] != -1) {
1674 int lines = first[placeholder[counter][j]].lines;
1675 for (ls = 0; ls < lines; ++ls) {
1676 second[sub_num].text[i++] = strdup(first[placeholder[counter][j]].text[ls]);
1678 j += lines - 1;
1679 } else {
1680 second[sub_num].text[i++] = strdup(" ");
1683 ++sub_num;
1684 ++counter;
1685 } while (local_end < global_end);
1686 if (real_block)
1687 for (i = 0; i < counter; ++i)
1688 second[start_block_sub + i].lines = higher_line + 1;
1690 counter = 2 * sub_to_add + 1;
1691 for (i = 0; i < counter; ++i) {
1692 free(placeholder[i]);
1694 free(placeholder);
1695 sub_first += sub_to_add;
1698 for (j = sub_orig - 1; j >= 0; --j) {
1699 for (i = first[j].lines - 1; i >= 0; --i) {
1700 free(first[j].text[i]);
1703 free(first);
1705 return_sub = second;
1706 } else { //if(suboverlap_enabled)
1707 adjust_subs_time(first, 6.0, fps, 1, sub_num, uses_time);/*~6 secs AST*/
1708 return_sub = first;
1710 if (return_sub == NULL) return NULL;
1711 subt_data = malloc(sizeof(sub_data));
1712 subt_data->filename = strdup(filename);
1713 subt_data->sub_uses_time = uses_time;
1714 subt_data->sub_num = sub_num;
1715 subt_data->sub_errs = sub_errs;
1716 subt_data->subtitles = return_sub;
1717 return subt_data;
1720 #if 0
1721 char * strreplace( char * in,char * what,char * whereof )
1723 int i;
1724 char * tmp;
1726 if ( ( in == NULL )||( what == NULL )||( whereof == NULL )||( ( tmp=strstr( in,what ) ) == NULL ) ) return NULL;
1727 for( i=0;i<strlen( whereof );i++ ) tmp[i]=whereof[i];
1728 if ( strlen( what ) > strlen( whereof ) ) tmp[i]=0;
1729 return in;
1731 #endif
1734 static void strcpy_trim(char *d, char *s)
1736 // skip leading whitespace
1737 while (*s && !isalnum(*s)) {
1738 s++;
1740 for (;;) {
1741 // copy word
1742 while (*s && isalnum(*s)) {
1743 *d = tolower(*s);
1744 s++; d++;
1746 if (*s == 0) break;
1747 // trim excess whitespace
1748 while (*s && !isalnum(*s)) {
1749 s++;
1751 if (*s == 0) break;
1752 *d++ = ' ';
1754 *d = 0;
1757 static void strcpy_strip_ext(char *d, char *s)
1759 char *tmp = strrchr(s,'.');
1760 if (!tmp) {
1761 strcpy(d, s);
1762 return;
1763 } else {
1764 strncpy(d, s, tmp-s);
1765 d[tmp-s] = 0;
1767 while (*d) {
1768 *d = tolower(*d);
1769 d++;
1773 static void strcpy_get_ext(char *d, char *s)
1775 char *tmp = strrchr(s,'.');
1776 if (!tmp) {
1777 strcpy(d, "");
1778 return;
1779 } else {
1780 strcpy(d, tmp+1);
1784 static int whiteonly(char *s)
1786 while (*s) {
1787 if (isalnum(*s)) return 0;
1788 s++;
1790 return 1;
1793 typedef struct subfn
1795 int priority;
1796 char *fname;
1797 } subfn;
1799 static int compare_sub_priority(const void *a, const void *b)
1801 if (((const subfn*)a)->priority > ((const subfn*)b)->priority) {
1802 return -1;
1803 } else if (((const subfn*)a)->priority < ((const subfn*)b)->priority) {
1804 return 1;
1805 } else {
1806 return strcoll(((const subfn*)a)->fname, ((const subfn*)b)->fname);
1810 char** sub_filenames(const char* path, char *fname)
1812 char *f_dir, *f_fname, *f_fname_noext, *f_fname_trim, *tmp, *tmp_sub_id;
1813 char *tmp_fname_noext, *tmp_fname_trim, *tmp_fname_ext, *tmpresult;
1815 int len, pos, found, i, j;
1816 char * sub_exts[] = { "utf", "utf8", "utf-8", "sub", "srt", "smi", "rt", "txt", "ssa", "aqt", "jss", "js", "ass", NULL};
1817 subfn *result;
1818 char **result2;
1820 int subcnt;
1822 FILE *f;
1824 DIR *d;
1825 struct dirent *de;
1827 len = (strlen(fname) > 256 ? strlen(fname) : 256)
1828 +(strlen(path) > 256 ? strlen(path) : 256)+2;
1830 f_dir = malloc(len);
1831 f_fname = malloc(len);
1832 f_fname_noext = malloc(len);
1833 f_fname_trim = malloc(len);
1835 tmp_fname_noext = malloc(len);
1836 tmp_fname_trim = malloc(len);
1837 tmp_fname_ext = malloc(len);
1839 tmpresult = malloc(len);
1841 result = malloc(sizeof(subfn)*MAX_SUBTITLE_FILES);
1842 memset(result, 0, sizeof(subfn)*MAX_SUBTITLE_FILES);
1844 subcnt = 0;
1846 tmp = strrchr(fname,'/');
1847 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1848 if(!tmp)tmp = strrchr(fname,'\\');
1849 if(!tmp)tmp = strrchr(fname,':');
1850 #endif
1852 // extract filename & dirname from fname
1853 if (tmp) {
1854 strcpy(f_fname, tmp+1);
1855 pos = tmp - fname;
1856 strncpy(f_dir, fname, pos+1);
1857 f_dir[pos+1] = 0;
1858 } else {
1859 strcpy(f_fname, fname);
1860 strcpy(f_dir, "./");
1863 strcpy_strip_ext(f_fname_noext, f_fname);
1864 strcpy_trim(f_fname_trim, f_fname_noext);
1866 tmp_sub_id = NULL;
1867 if (dvdsub_lang && !whiteonly(dvdsub_lang)) {
1868 tmp_sub_id = malloc(strlen(dvdsub_lang)+1);
1869 strcpy_trim(tmp_sub_id, dvdsub_lang);
1872 // 0 = nothing
1873 // 1 = any subtitle file
1874 // 2 = any sub file containing movie name
1875 // 3 = sub file containing movie name and the lang extension
1876 for (j = 0; j <= 1; j++) {
1877 d = opendir(j == 0 ? f_dir : path);
1878 if (d) {
1879 while ((de = readdir(d))) {
1880 // retrieve various parts of the filename
1881 strcpy_strip_ext(tmp_fname_noext, de->d_name);
1882 strcpy_get_ext(tmp_fname_ext, de->d_name);
1883 strcpy_trim(tmp_fname_trim, tmp_fname_noext);
1885 // does it end with a subtitle extension?
1886 found = 0;
1887 #ifdef CONFIG_ICONV
1888 #ifdef CONFIG_ENCA
1889 for (i = ((sub_cp && strncasecmp(sub_cp, "enca", 4) != 0) ? 3 : 0); sub_exts[i]; i++) {
1890 #else
1891 for (i = (sub_cp ? 3 : 0); sub_exts[i]; i++) {
1892 #endif
1893 #else
1894 for (i = 0; sub_exts[i]; i++) {
1895 #endif
1896 if (strcasecmp(sub_exts[i], tmp_fname_ext) == 0) {
1897 found = 1;
1898 break;
1902 // we have a (likely) subtitle file
1903 if (found) {
1904 int prio = 0;
1905 if (!prio && tmp_sub_id)
1907 sprintf(tmpresult, "%s %s", f_fname_trim, tmp_sub_id);
1908 mp_msg(MSGT_SUBREADER,MSGL_INFO,"dvdsublang...%s\n", tmpresult);
1909 if (strcmp(tmp_fname_trim, tmpresult) == 0 && sub_match_fuzziness >= 1) {
1910 // matches the movie name + lang extension
1911 prio = 5;
1914 if (!prio && strcmp(tmp_fname_trim, f_fname_trim) == 0) {
1915 // matches the movie name
1916 prio = 4;
1918 if (!prio && (tmp = strstr(tmp_fname_trim, f_fname_trim)) && (sub_match_fuzziness >= 1)) {
1919 // contains the movie name
1920 tmp += strlen(f_fname_trim);
1921 if (tmp_sub_id && strstr(tmp, tmp_sub_id)) {
1922 // with sub_id specified prefer localized subtitles
1923 prio = 3;
1924 } else if ((tmp_sub_id == NULL) && whiteonly(tmp)) {
1925 // without sub_id prefer "plain" name
1926 prio = 3;
1927 } else {
1928 // with no localized subs found, try any else instead
1929 prio = 2;
1932 if (!prio) {
1933 // doesn't contain the movie name
1934 // don't try in the mplayer subtitle directory
1935 if ((j == 0) && (sub_match_fuzziness >= 2)) {
1936 prio = 1;
1940 if (prio) {
1941 prio += prio;
1942 #ifdef CONFIG_ICONV
1943 if (i<3){ // prefer UTF-8 coded
1944 prio++;
1946 #endif
1947 sprintf(tmpresult, "%s%s", j == 0 ? f_dir : path, de->d_name);
1948 // fprintf(stderr, "%s priority %d\n", tmpresult, prio);
1949 if ((f = fopen(tmpresult, "rt"))) {
1950 fclose(f);
1951 result[subcnt].priority = prio;
1952 result[subcnt].fname = strdup(tmpresult);
1953 subcnt++;
1958 if (subcnt >= MAX_SUBTITLE_FILES) break;
1960 closedir(d);
1965 if (tmp_sub_id) free(tmp_sub_id);
1967 free(f_dir);
1968 free(f_fname);
1969 free(f_fname_noext);
1970 free(f_fname_trim);
1972 free(tmp_fname_noext);
1973 free(tmp_fname_trim);
1974 free(tmp_fname_ext);
1976 free(tmpresult);
1978 qsort(result, subcnt, sizeof(subfn), compare_sub_priority);
1980 result2 = malloc(sizeof(char*)*(subcnt+1));
1981 memset(result2, 0, sizeof(char*)*(subcnt+1));
1983 for (i = 0; i < subcnt; i++) {
1984 result2[i] = result[i].fname;
1986 result2[subcnt] = NULL;
1988 free(result);
1990 return result2;
1993 void list_sub_file(sub_data* subd){
1994 int i,j;
1995 subtitle *subs = subd->subtitles;
1997 for(j=0; j < subd->sub_num; j++){
1998 subtitle* egysub=&subs[j];
1999 mp_msg(MSGT_SUBREADER,MSGL_INFO,"%i line%c (%li-%li)\n",
2000 egysub->lines,
2001 (1==egysub->lines)?' ':'s',
2002 egysub->start,
2003 egysub->end);
2004 for (i=0; i<egysub->lines; i++) {
2005 mp_msg(MSGT_SUBREADER,MSGL_INFO,"\t\t%d: %s%s", i,egysub->text[i], i==egysub->lines-1?"":" \n ");
2007 mp_msg(MSGT_SUBREADER,MSGL_INFO,"\n");
2010 mp_msg(MSGT_SUBREADER,MSGL_INFO,"Subtitle format %s time.\n",
2011 subd->sub_uses_time ? "uses":"doesn't use");
2012 mp_msg(MSGT_SUBREADER,MSGL_INFO,"Read %i subtitles, %i errors.\n", subd->sub_num, subd->sub_errs);
2015 void dump_srt(sub_data* subd, float fps){
2016 int i,j;
2017 int h,m,s,ms;
2018 FILE * fd;
2019 subtitle * onesub;
2020 unsigned long temp;
2021 subtitle *subs = subd->subtitles;
2023 if (!subd->sub_uses_time && sub_fps == 0)
2024 sub_fps = fps;
2025 fd=fopen("dumpsub.srt","w");
2026 if(!fd)
2028 perror("dump_srt: fopen");
2029 return;
2031 for(i=0; i < subd->sub_num; i++)
2033 onesub=subs+i; //=&subs[i];
2034 fprintf(fd,"%d\n",i+1);//line number
2036 temp=onesub->start;
2037 if (!subd->sub_uses_time)
2038 temp = temp * 100 / sub_fps;
2039 temp -= sub_delay * 100;
2040 h=temp/360000;temp%=360000; //h =1*100*60*60
2041 m=temp/6000; temp%=6000; //m =1*100*60
2042 s=temp/100; temp%=100; //s =1*100
2043 ms=temp*10; //ms=1*10
2044 fprintf(fd,"%02d:%02d:%02d,%03d --> ",h,m,s,ms);
2046 temp=onesub->end;
2047 if (!subd->sub_uses_time)
2048 temp = temp * 100 / sub_fps;
2049 temp -= sub_delay * 100;
2050 h=temp/360000;temp%=360000;
2051 m=temp/6000; temp%=6000;
2052 s=temp/100; temp%=100;
2053 ms=temp*10;
2054 fprintf(fd,"%02d:%02d:%02d,%03d\n",h,m,s,ms);
2056 for(j=0;j<onesub->lines;j++)
2057 fprintf(fd,"%s\n",onesub->text[j]);
2059 fprintf(fd,"\n");
2061 fclose(fd);
2062 mp_msg(MSGT_SUBREADER,MSGL_INFO,"SUB: Subtitles dumped in \'dumpsub.srt\'.\n");
2065 void dump_mpsub(sub_data* subd, float fps){
2066 int i,j;
2067 FILE *fd;
2068 float a,b;
2069 subtitle *subs = subd->subtitles;
2071 mpsub_position = subd->sub_uses_time? (sub_delay*100) : (sub_delay*fps);
2072 if (sub_fps==0) sub_fps=fps;
2074 fd=fopen ("dump.mpsub", "w");
2075 if (!fd) {
2076 perror ("dump_mpsub: fopen");
2077 return;
2081 if (subd->sub_uses_time) fprintf (fd,"FORMAT=TIME\n\n");
2082 else fprintf (fd, "FORMAT=%5.2f\n\n", fps);
2084 for(j=0; j < subd->sub_num; j++){
2085 subtitle* egysub=&subs[j];
2086 if (subd->sub_uses_time) {
2087 a=((egysub->start-mpsub_position)/100.0);
2088 b=((egysub->end-egysub->start)/100.0);
2089 if ( (float)((int)a) == a)
2090 fprintf (fd, "%.0f",a);
2091 else
2092 fprintf (fd, "%.2f",a);
2094 if ( (float)((int)b) == b)
2095 fprintf (fd, " %.0f\n",b);
2096 else
2097 fprintf (fd, " %.2f\n",b);
2098 } else {
2099 fprintf (fd, "%ld %ld\n", (long)((egysub->start*(fps/sub_fps))-((mpsub_position*(fps/sub_fps)))),
2100 (long)(((egysub->end)-(egysub->start))*(fps/sub_fps)));
2103 mpsub_position = egysub->end;
2104 for (i=0; i<egysub->lines; i++) {
2105 fprintf (fd, "%s\n",egysub->text[i]);
2107 fprintf (fd, "\n");
2109 fclose (fd);
2110 mp_msg(MSGT_SUBREADER,MSGL_INFO,"SUB: Subtitles dumped in \'dump.mpsub\'.\n");
2113 void dump_microdvd(sub_data* subd, float fps) {
2114 int i, delay;
2115 FILE *fd;
2116 subtitle *subs = subd->subtitles;
2117 if (sub_fps == 0)
2118 sub_fps = fps;
2119 fd = fopen("dumpsub.sub", "w");
2120 if (!fd) {
2121 perror("dumpsub.sub: fopen");
2122 return;
2124 delay = sub_delay * sub_fps;
2125 for (i = 0; i < subd->sub_num; ++i) {
2126 int j, start, end;
2127 start = subs[i].start;
2128 end = subs[i].end;
2129 if (subd->sub_uses_time) {
2130 start = start * sub_fps / 100 ;
2131 end = end * sub_fps / 100;
2133 else {
2134 start = start * sub_fps / fps;
2135 end = end * sub_fps / fps;
2137 start -= delay;
2138 end -= delay;
2139 fprintf(fd, "{%d}{%d}", start, end);
2140 for (j = 0; j < subs[i].lines; ++j)
2141 fprintf(fd, "%s%s", j ? "|" : "", subs[i].text[j]);
2142 fprintf(fd, "\n");
2144 fclose(fd);
2145 mp_msg(MSGT_SUBREADER,MSGL_INFO,"SUB: Subtitles dumped in \'dumpsub.sub\'.\n");
2148 void dump_jacosub(sub_data* subd, float fps) {
2149 int i,j;
2150 int h,m,s,cs;
2151 FILE * fd;
2152 subtitle * onesub;
2153 unsigned long temp;
2154 subtitle *subs = subd->subtitles;
2156 if (!subd->sub_uses_time && sub_fps == 0)
2157 sub_fps = fps;
2158 fd=fopen("dumpsub.jss","w");
2159 if(!fd)
2161 perror("dump_jacosub: fopen");
2162 return;
2164 fprintf(fd, "#TIMERES %d\n", (subd->sub_uses_time) ? 100 : (int)sub_fps);
2165 for(i=0; i < subd->sub_num; i++)
2167 onesub=subs+i; //=&subs[i];
2169 temp=onesub->start;
2170 if (!subd->sub_uses_time)
2171 temp = temp * 100 / sub_fps;
2172 temp -= sub_delay * 100;
2173 h=temp/360000;temp%=360000; //h =1*100*60*60
2174 m=temp/6000; temp%=6000; //m =1*100*60
2175 s=temp/100; temp%=100; //s =1*100
2176 cs=temp; //cs=1*10
2177 fprintf(fd,"%02d:%02d:%02d.%02d ",h,m,s,cs);
2179 temp=onesub->end;
2180 if (!subd->sub_uses_time)
2181 temp = temp * 100 / sub_fps;
2182 temp -= sub_delay * 100;
2183 h=temp/360000;temp%=360000;
2184 m=temp/6000; temp%=6000;
2185 s=temp/100; temp%=100;
2186 cs=temp;
2187 fprintf(fd,"%02d:%02d:%02d.%02d {~} ",h,m,s,cs);
2189 for(j=0;j<onesub->lines;j++)
2190 fprintf(fd,"%s%s",j ? "\\n" : "", onesub->text[j]);
2192 fprintf(fd,"\n");
2194 fclose(fd);
2195 mp_msg(MSGT_SUBREADER,MSGL_INFO,"SUB: Subtitles dumped in \'dumpsub.js\'.\n");
2198 void dump_sami(sub_data* subd, float fps) {
2199 int i,j;
2200 FILE * fd;
2201 subtitle * onesub;
2202 unsigned long temp;
2203 subtitle *subs = subd->subtitles;
2205 if (!subd->sub_uses_time && sub_fps == 0)
2206 sub_fps = fps;
2207 fd=fopen("dumpsub.smi","w");
2208 if(!fd)
2210 perror("dump_jacosub: fopen");
2211 return;
2213 fprintf(fd, "<SAMI>\n"
2214 "<HEAD>\n"
2215 " <STYLE TYPE=\"Text/css\">\n"
2216 " <!--\n"
2217 " 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"
2218 " .SUBTTL {Name: 'Subtitles'; Lang: en-US; SAMIType: CC;}\n"
2219 " -->\n"
2220 " </STYLE>\n"
2221 "</HEAD>\n"
2222 "<BODY>\n");
2223 for(i=0; i < subd->sub_num; i++)
2225 onesub=subs+i; //=&subs[i];
2227 temp=onesub->start;
2228 if (!subd->sub_uses_time)
2229 temp = temp * 100 / sub_fps;
2230 temp -= sub_delay * 100;
2231 fprintf(fd,"\t<SYNC Start=%lu>\n"
2232 "\t <P>", temp * 10);
2234 for(j=0;j<onesub->lines;j++)
2235 fprintf(fd,"%s%s",j ? "<br>" : "", onesub->text[j]);
2237 fprintf(fd,"\n");
2239 temp=onesub->end;
2240 if (!subd->sub_uses_time)
2241 temp = temp * 100 / sub_fps;
2242 temp -= sub_delay * 100;
2243 fprintf(fd,"\t<SYNC Start=%lu>\n"
2244 "\t <P>&nbsp;\n", temp * 10);
2246 fprintf(fd, "</BODY>\n"
2247 "</SAMI>\n");
2248 fclose(fd);
2249 mp_msg(MSGT_SUBREADER,MSGL_INFO,"SUB: Subtitles dumped in \'dumpsub.smi\'.\n");
2252 void sub_free( sub_data * subd )
2254 int i;
2256 if ( !subd ) return;
2258 if (subd->subtitles) {
2259 for (i=0; i < subd->subtitles->lines; i++) free( subd->subtitles->text[i] );
2260 free( subd->subtitles );
2262 if (subd->filename) free( subd->filename );
2263 free( subd );
2266 #define MAX_SUBLINE 512
2268 * \brief parse text and append it to subtitle in sub
2269 * \param sub subtitle struct to add text to
2270 * \param txt text to parse
2271 * \param len length of text in txt
2272 * \param endpts pts at which this subtitle text should be removed again
2274 * <> and {} are interpreted as comment delimiters, "\n", "\N", '\n', '\r'
2275 * and '\0' are interpreted as newlines, duplicate, leading and trailing
2276 * newlines are ignored.
2278 void sub_add_text(subtitle *sub, const char *txt, int len, double endpts) {
2279 int comment = 0;
2280 int double_newline = 1; // ignore newlines at the beginning
2281 int i, pos;
2282 char *buf;
2283 int orig_lines = sub->lines;
2284 if (sub->lines >= SUB_MAX_TEXT) return;
2285 pos = 0;
2286 buf = malloc(MAX_SUBLINE + 1);
2287 sub->text[sub->lines] = buf;
2288 sub->endpts[sub->lines] = endpts;
2289 for (i = 0; i < len && pos < MAX_SUBLINE; i++) {
2290 char c = txt[i];
2291 if (c == '<') comment |= 1;
2292 if (c == '{') comment |= 2;
2293 if (comment) {
2294 if (c == '}') comment &= ~2;
2295 if (c == '>') comment &= ~1;
2296 continue;
2298 if (pos == MAX_SUBLINE - 1) {
2299 i--;
2300 c = 0;
2302 if (c == '\\' && i + 1 < len) {
2303 c = txt[++i];
2304 if (c == 'n' || c == 'N') c = 0;
2306 if (c == '\n' || c == '\r') c = 0;
2307 if (c) {
2308 double_newline = 0;
2309 buf[pos++] = c;
2310 } else if (!double_newline) {
2311 if (sub->lines >= SUB_MAX_TEXT - 1) {
2312 mp_msg(MSGT_VO, MSGL_WARN, "Too many subtitle lines\n");
2313 break;
2315 double_newline = 1;
2316 buf[pos] = 0;
2317 sub->lines++;
2318 pos = 0;
2319 buf = malloc(MAX_SUBLINE + 1);
2320 sub->text[sub->lines] = buf;
2321 sub->endpts[sub->lines] = endpts;
2324 buf[pos] = 0;
2325 if (sub->lines < SUB_MAX_TEXT &&
2326 strlen(sub->text[sub->lines]))
2327 sub->lines++;
2328 #ifdef CONFIG_FRIBIDI
2329 sub = sub_fribidi(sub, sub_utf8, orig_lines);
2330 #endif
2333 #define MP_NOPTS_VALUE (-1LL<<63)
2335 * \brief remove outdated subtitle lines.
2336 * \param sub subtitle struct to modify
2337 * \param pts current pts. All lines with endpts <= this will be removed.
2338 * Use MP_NOPTS_VALUE to remove all lines
2339 * \return 1 if sub was modified, 0 otherwise.
2341 int sub_clear_text(subtitle *sub, double pts) {
2342 int i = 0;
2343 int changed = 0;
2344 while (i < sub->lines) {
2345 double endpts = sub->endpts[i];
2346 if (pts == MP_NOPTS_VALUE || (endpts != MP_NOPTS_VALUE && pts >= endpts)) {
2347 int j;
2348 free(sub->text[i]);
2349 for (j = i + 1; j < sub->lines; j++) {
2350 sub->text[j - 1] = sub->text[j];
2351 sub->endpts[j - 1] = sub->endpts[j];
2353 sub->lines--;
2354 changed = 1;
2355 } else
2356 i++;
2358 return changed;