Simplify condition, since both time and time_last are unsigned.
[mplayer/glamo.git] / subreader.c
blob7402c97e9d158287846fb265e2b2a28aca9f3e5a
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 "libmpdemux/stream.h"
23 #ifdef HAVE_ENCA
24 #include <enca.h>
25 #endif
27 #define ERR ((void *) -1)
29 #ifdef USE_ICONV
30 #include <iconv.h>
31 char *sub_cp=NULL;
32 #endif
33 #ifdef USE_FRIBIDI
34 #include <fribidi/fribidi.h>
35 char *fribidi_charset = NULL; ///character set that will be passed to FriBiDi
36 int flip_hebrew = 1; ///flip subtitles using fribidi
37 int fribidi_flip_commas = 0; ///flip comma when fribidi is used
38 #endif
40 extern char* dvdsub_lang;
42 /* Maximal length of line of a subtitle */
43 #define LINE_LEN 1000
44 static float mpsub_position=0;
45 static float mpsub_multiplier=1.;
46 static int sub_slacktime = 20000; //20 sec
48 int sub_no_text_pp=0; // 1 => do not apply text post-processing
49 // like {\...} elimination in SSA format.
51 int sub_match_fuzziness=0; // level of sub name matching fuzziness
53 /* Use the SUB_* constant defined in the header file */
54 int sub_format=SUB_INVALID;
55 #ifdef USE_SORTSUB
56 /*
57 Some subtitling formats, namely AQT and Subrip09, define the end of a
58 subtitle as the beginning of the following. Since currently we read one
59 subtitle at time, for these format we keep two global *subtitle,
60 previous_aqt_sub and previous_subrip09_sub, pointing to previous subtitle,
61 so we can change its end when we read current subtitle starting time.
62 When USE_SORTSUB is defined, we use a single global unsigned long,
63 previous_sub_end, for both (and even future) formats, to store the end of
64 the previous sub: it is initialized to 0 in sub_read_file and eventually
65 modified by sub_read_aqt_line or sub_read_subrip09_line.
67 unsigned long previous_sub_end;
68 #endif
70 static int eol(char p) {
71 return (p=='\r' || p=='\n' || p=='\0');
74 /* Remove leading and trailing space */
75 static void trail_space(char *s) {
76 int i = 0;
77 while (isspace(s[i])) ++i;
78 if (i) strcpy(s, s + i);
79 i = strlen(s) - 1;
80 while (i > 0 && isspace(s[i])) s[i--] = '\0';
83 static char *stristr(const char *haystack, const char *needle) {
84 int len = 0;
85 const char *p = haystack;
87 if (!(haystack && needle)) return NULL;
89 len=strlen(needle);
90 while (*p != '\0') {
91 if (strncasecmp(p, needle, len) == 0) return (char*)p;
92 p++;
95 return NULL;
98 subtitle *sub_read_line_sami(stream_t* st, subtitle *current) {
99 static char line[LINE_LEN+1];
100 static char *s = NULL, *slacktime_s;
101 char text[LINE_LEN+1], *p=NULL, *q;
102 int state;
104 current->lines = current->start = current->end = 0;
105 current->alignment = SUB_ALIGNMENT_BOTTOMCENTER;
106 state = 0;
108 /* read the first line */
109 if (!s)
110 if (!(s = stream_read_line(st, line, LINE_LEN))) return 0;
112 do {
113 switch (state) {
115 case 0: /* find "START=" or "Slacktime:" */
116 slacktime_s = stristr (s, "Slacktime:");
117 if (slacktime_s)
118 sub_slacktime = strtol (slacktime_s+10, NULL, 0) / 10;
120 s = stristr (s, "Start=");
121 if (s) {
122 current->start = strtol (s + 6, &s, 0) / 10;
123 /* eat '>' */
124 for (; *s != '>' && *s != '\0'; s++);
125 s++;
126 state = 1; continue;
128 break;
130 case 1: /* find (optionnal) "<P", skip other TAGs */
131 for (; *s == ' ' || *s == '\t'; s++); /* strip blanks, if any */
132 if (*s == '\0') break;
133 if (*s != '<') { state = 3; p = text; continue; } /* not a TAG */
134 s++;
135 if (*s == 'P' || *s == 'p') { s++; state = 2; continue; } /* found '<P' */
136 for (; *s != '>' && *s != '\0'; s++); /* skip remains of non-<P> TAG */
137 if (s == '\0')
138 break;
139 s++;
140 continue;
142 case 2: /* find ">" */
143 if ((s = strchr (s, '>'))) { s++; state = 3; p = text; continue; }
144 break;
146 case 3: /* get all text until '<' appears */
147 if (*s == '\0') break;
148 else if (!strncasecmp (s, "<br>", 4)) {
149 *p = '\0'; p = text; trail_space (text);
150 if (text[0] != '\0')
151 current->text[current->lines++] = strdup (text);
152 s += 4;
154 else if ((*s == '{') && !sub_no_text_pp) { state = 5; ++s; continue; }
155 else if (*s == '<') { state = 4; }
156 else if (!strncasecmp (s, "&nbsp;", 6)) { *p++ = ' '; s += 6; }
157 else if (*s == '\t') { *p++ = ' '; s++; }
158 else if (*s == '\r' || *s == '\n') { s++; }
159 else *p++ = *s++;
161 /* skip duplicated space */
162 if (p > text + 2) if (*(p-1) == ' ' && *(p-2) == ' ') p--;
164 continue;
166 case 4: /* get current->end or skip <TAG> */
167 q = stristr (s, "Start=");
168 if (q) {
169 current->end = strtol (q + 6, &q, 0) / 10 - 1;
170 *p = '\0'; trail_space (text);
171 if (text[0] != '\0')
172 current->text[current->lines++] = strdup (text);
173 if (current->lines > 0) { state = 99; break; }
174 state = 0; continue;
176 s = strchr (s, '>');
177 if (s) { s++; state = 3; continue; }
178 break;
179 case 5: /* get rid of {...} text, but read the alignment code */
180 if ((*s == '\\') && (*(s + 1) == 'a') && !sub_no_text_pp) {
181 if (stristr(s, "\\a1") != NULL) {
182 current->alignment = SUB_ALIGNMENT_BOTTOMLEFT;
183 s = s + 3;
185 if (stristr(s, "\\a2") != NULL) {
186 current->alignment = SUB_ALIGNMENT_BOTTOMCENTER;
187 s = s + 3;
188 } else if (stristr(s, "\\a3") != NULL) {
189 current->alignment = SUB_ALIGNMENT_BOTTOMRIGHT;
190 s = s + 3;
191 } else if ((stristr(s, "\\a4") != NULL) || (stristr(s, "\\a5") != NULL) || (stristr(s, "\\a8") != NULL)) {
192 current->alignment = SUB_ALIGNMENT_TOPLEFT;
193 s = s + 3;
194 } else if (stristr(s, "\\a6") != NULL) {
195 current->alignment = SUB_ALIGNMENT_TOPCENTER;
196 s = s + 3;
197 } else if (stristr(s, "\\a7") != NULL) {
198 current->alignment = SUB_ALIGNMENT_TOPRIGHT;
199 s = s + 3;
200 } else if (stristr(s, "\\a9") != NULL) {
201 current->alignment = SUB_ALIGNMENT_MIDDLELEFT;
202 s = s + 3;
203 } else if (stristr(s, "\\a10") != NULL) {
204 current->alignment = SUB_ALIGNMENT_MIDDLECENTER;
205 s = s + 4;
206 } else if (stristr(s, "\\a11") != NULL) {
207 current->alignment = SUB_ALIGNMENT_MIDDLERIGHT;
208 s = s + 4;
211 if (*s == '}') state = 3;
212 ++s;
213 continue;
216 /* read next line */
217 if (state != 99 && !(s = stream_read_line (st, line, LINE_LEN))) {
218 if (current->start > 0) {
219 break; // if it is the last subtitle
220 } else {
221 return 0;
225 } while (state != 99);
227 // For the last subtitle
228 if (current->end <= 0) {
229 current->end = current->start + sub_slacktime;
230 *p = '\0'; trail_space (text);
231 if (text[0] != '\0')
232 current->text[current->lines++] = strdup (text);
235 return current;
239 char *sub_readtext(char *source, char **dest) {
240 int len=0;
241 char *p=source;
243 // printf("src=%p dest=%p \n",source,dest);
245 while ( !eol(*p) && *p!= '|' ) {
246 p++,len++;
249 *dest= (char *)malloc (len+1);
250 if (!dest) {return ERR;}
252 strncpy(*dest, source, len);
253 (*dest)[len]=0;
255 while (*p=='\r' || *p=='\n' || *p=='|') p++;
257 if (*p) return p; // not-last text field
258 else return NULL; // last text field
261 subtitle *sub_read_line_microdvd(stream_t *st,subtitle *current) {
262 char line[LINE_LEN+1];
263 char line2[LINE_LEN+1];
264 char *p, *next;
265 int i;
267 do {
268 if (!stream_read_line (st, line, LINE_LEN)) return NULL;
269 } while ((sscanf (line,
270 "{%ld}{}%[^\r\n]",
271 &(current->start), line2) < 2) &&
272 (sscanf (line,
273 "{%ld}{%ld}%[^\r\n]",
274 &(current->start), &(current->end), line2) < 3));
276 p=line2;
278 next=p, i=0;
279 while ((next =sub_readtext (next, &(current->text[i])))) {
280 if (current->text[i]==ERR) {return ERR;}
281 i++;
282 if (i>=SUB_MAX_TEXT) { mp_msg(MSGT_SUBREADER,MSGL_WARN,"Too many lines in a subtitle\n");current->lines=i;return current;}
284 current->lines= ++i;
286 return current;
289 subtitle *sub_read_line_mpl2(stream_t *st,subtitle *current) {
290 char line[LINE_LEN+1];
291 char line2[LINE_LEN+1];
292 char *p, *next;
293 int i;
295 do {
296 if (!stream_read_line (st, line, LINE_LEN)) return NULL;
297 } while ((sscanf (line,
298 "[%ld][%ld]%[^\r\n]",
299 &(current->start), &(current->end), line2) < 3));
300 current->start *= 10;
301 current->end *= 10;
302 p=line2;
304 next=p, i=0;
305 while ((next =sub_readtext (next, &(current->text[i])))) {
306 if (current->text[i]==ERR) {return ERR;}
307 i++;
308 if (i>=SUB_MAX_TEXT) { mp_msg(MSGT_SUBREADER,MSGL_WARN,"Too many lines in a subtitle\n");current->lines=i;return current;}
310 current->lines= ++i;
312 return current;
315 subtitle *sub_read_line_subrip(stream_t* st, subtitle *current) {
316 char line[LINE_LEN+1];
317 int a1,a2,a3,a4,b1,b2,b3,b4;
318 char *p=NULL, *q=NULL;
319 int len;
321 while (1) {
322 if (!stream_read_line (st, line, LINE_LEN)) return NULL;
323 if (sscanf (line, "%d:%d:%d.%d,%d:%d:%d.%d",&a1,&a2,&a3,&a4,&b1,&b2,&b3,&b4) < 8) continue;
324 current->start = a1*360000+a2*6000+a3*100+a4;
325 current->end = b1*360000+b2*6000+b3*100+b4;
327 if (!stream_read_line (st, line, LINE_LEN)) return NULL;
329 p=q=line;
330 for (current->lines=1; current->lines < SUB_MAX_TEXT; current->lines++) {
331 for (q=p,len=0; *p && *p!='\r' && *p!='\n' && *p!='|' && strncmp(p,"[br]",4); p++,len++);
332 current->text[current->lines-1]=(char *)malloc (len+1);
333 if (!current->text[current->lines-1]) return ERR;
334 strncpy (current->text[current->lines-1], q, len);
335 current->text[current->lines-1][len]='\0';
336 if (!*p || *p=='\r' || *p=='\n') break;
337 if (*p=='|') p++;
338 else while (*p++!=']');
340 break;
342 return current;
345 subtitle *sub_read_line_subviewer(stream_t *st,subtitle *current) {
346 char line[LINE_LEN+1];
347 int a1,a2,a3,a4,b1,b2,b3,b4;
348 char *p=NULL;
349 int i,len;
351 while (!current->text[0]) {
352 if (!stream_read_line (st, line, LINE_LEN)) return NULL;
353 if ((len=sscanf (line, "%d:%d:%d%[,.:]%d --> %d:%d:%d%[,.:]%d",&a1,&a2,&a3,(char *)&i,&a4,&b1,&b2,&b3,(char *)&i,&b4)) < 10)
354 continue;
355 current->start = a1*360000+a2*6000+a3*100+a4/10;
356 current->end = b1*360000+b2*6000+b3*100+b4/10;
357 for (i=0; i<SUB_MAX_TEXT;) {
358 if (!stream_read_line (st, line, LINE_LEN)) break;
359 len=0;
360 for (p=line; *p!='\n' && *p!='\r' && *p; p++,len++);
361 if (len) {
362 int j=0,skip=0;
363 char *curptr=current->text[i]=(char *)malloc (len+1);
364 if (!current->text[i]) return ERR;
365 //strncpy (current->text[i], line, len); current->text[i][len]='\0';
366 for(; j<len; j++) {
367 /* let's filter html tags ::atmos */
368 if(line[j]=='>') {
369 skip=0;
370 continue;
372 if(line[j]=='<') {
373 skip=1;
374 continue;
376 if(skip) {
377 continue;
379 *curptr=line[j];
380 curptr++;
382 *curptr='\0';
384 i++;
385 } else {
386 break;
389 current->lines=i;
391 return current;
394 subtitle *sub_read_line_subviewer2(stream_t *st,subtitle *current) {
395 char line[LINE_LEN+1];
396 int a1,a2,a3,a4;
397 char *p=NULL;
398 int i,len;
400 while (!current->text[0]) {
401 if (!stream_read_line (st, line, LINE_LEN)) return NULL;
402 if (line[0]!='{')
403 continue;
404 if ((len=sscanf (line, "{T %d:%d:%d:%d",&a1,&a2,&a3,&a4)) < 4)
405 continue;
406 current->start = a1*360000+a2*6000+a3*100+a4/10;
407 for (i=0; i<SUB_MAX_TEXT;) {
408 if (!stream_read_line (st, line, LINE_LEN)) break;
409 if (line[0]=='}') break;
410 len=0;
411 for (p=line; *p!='\n' && *p!='\r' && *p; ++p,++len);
412 if (len) {
413 current->text[i]=(char *)malloc (len+1);
414 if (!current->text[i]) return ERR;
415 strncpy (current->text[i], line, len); current->text[i][len]='\0';
416 ++i;
417 } else {
418 break;
421 current->lines=i;
423 return current;
427 subtitle *sub_read_line_vplayer(stream_t *st,subtitle *current) {
428 char line[LINE_LEN+1];
429 int a1,a2,a3;
430 char *p=NULL, *next,separator;
431 int i,len,plen;
433 while (!current->text[0]) {
434 if (!stream_read_line (st, line, LINE_LEN)) return NULL;
435 if ((len=sscanf (line, "%d:%d:%d%c%n",&a1,&a2,&a3,&separator,&plen)) < 4)
436 continue;
438 if (!(current->start = a1*360000+a2*6000+a3*100))
439 continue;
440 /* removed by wodzu
441 p=line;
442 // finds the body of the subtitle
443 for (i=0; i<3; i++){
444 p=strchr(p,':');
445 if (p==NULL) break;
446 ++p;
448 if (p==NULL) {
449 printf("SUB: Skipping incorrect subtitle line!\n");
450 continue;
453 // by wodzu: hey! this time we know what length it has! what is
454 // that magic for? it can't deal with space instead of third
455 // colon! look, what simple it can be:
456 p = &line[ plen ];
458 i=0;
459 if (*p!='|') {
461 next = p,i=0;
462 while ((next =sub_readtext (next, &(current->text[i])))) {
463 if (current->text[i]==ERR) {return ERR;}
464 i++;
465 if (i>=SUB_MAX_TEXT) { mp_msg(MSGT_SUBREADER,MSGL_WARN,"Too many lines in a subtitle\n");current->lines=i;return current;}
467 current->lines=i+1;
470 return current;
473 subtitle *sub_read_line_rt(stream_t *st,subtitle *current) {
474 //TODO: This format uses quite rich (sub/super)set of xhtml
475 // I couldn't check it since DTD is not included.
476 // WARNING: full XML parses can be required for proper parsing
477 char line[LINE_LEN+1];
478 int a1,a2,a3,a4,b1,b2,b3,b4;
479 char *p=NULL,*next=NULL;
480 int i,len,plen;
482 while (!current->text[0]) {
483 if (!stream_read_line (st, line, LINE_LEN)) return NULL;
484 //TODO: it seems that format of time is not easily determined, it may be 1:12, 1:12.0 or 0:1:12.0
485 //to describe the same moment in time. Maybe there are even more formats in use.
486 //if ((len=sscanf (line, "<Time Begin=\"%d:%d:%d.%d\" End=\"%d:%d:%d.%d\"",&a1,&a2,&a3,&a4,&b1,&b2,&b3,&b4)) < 8)
487 plen=a1=a2=a3=a4=b1=b2=b3=b4=0;
488 if (
489 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d.%d\" %*[Ee]nd=\"%d.%d\"%*[^<]<clear/>%n",&a3,&a4,&b3,&b4,&plen)) < 4) &&
490 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d.%d\" %*[Ee]nd=\"%d:%d.%d\"%*[^<]<clear/>%n",&a3,&a4,&b2,&b3,&b4,&plen)) < 5) &&
491 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d:%d\" %*[Ee]nd=\"%d:%d\"%*[^<]<clear/>%n",&a2,&a3,&b2,&b3,&plen)) < 4) &&
492 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d:%d\" %*[Ee]nd=\"%d:%d.%d\"%*[^<]<clear/>%n",&a2,&a3,&b2,&b3,&b4,&plen)) < 5) &&
493 // ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d:%d.%d\" %*[Ee]nd=\"%d:%d\"%*[^<]<clear/>%n",&a2,&a3,&a4,&b2,&b3,&plen)) < 5) &&
494 ((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) &&
495 ((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) &&
496 //now try it without end time
497 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d.%d\"%*[^<]<clear/>%n",&a3,&a4,&plen)) < 2) &&
498 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d:%d\"%*[^<]<clear/>%n",&a2,&a3,&plen)) < 2) &&
499 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d:%d.%d\"%*[^<]<clear/>%n",&a2,&a3,&a4,&plen)) < 3) &&
500 ((len=sscanf (line, "<%*[tT]ime %*[bB]egin=\"%d:%d:%d.%d\"%*[^<]<clear/>%n",&a1,&a2,&a3,&a4,&plen)) < 4)
502 continue;
503 current->start = a1*360000+a2*6000+a3*100+a4/10;
504 current->end = b1*360000+b2*6000+b3*100+b4/10;
505 if (b1 == 0 && b2 == 0 && b3 == 0 && b4 == 0)
506 current->end = current->start+200;
507 p=line; p+=plen;i=0;
508 // TODO: I don't know what kind of convention is here for marking multiline subs, maybe <br/> like in xml?
509 next = strstr(line,"<clear/>");
510 if(next && strlen(next)>8){
511 next+=8;i=0;
512 while ((next =sub_readtext (next, &(current->text[i])))) {
513 if (current->text[i]==ERR) {return ERR;}
514 i++;
515 if (i>=SUB_MAX_TEXT) { mp_msg(MSGT_SUBREADER,MSGL_WARN,"Too many lines in a subtitle\n");current->lines=i;return current;}
518 current->lines=i+1;
520 return current;
523 subtitle *sub_read_line_ssa(stream_t *st,subtitle *current) {
525 * Sub Station Alpha v4 (and v2?) scripts have 9 commas before subtitle
526 * other Sub Station Alpha scripts have only 8 commas before subtitle
527 * Reading the "ScriptType:" field is not reliable since many scripts appear
528 * w/o it
530 * http://www.scriptclub.org is a good place to find more examples
531 * http://www.eswat.demon.co.uk is where the SSA specs can be found
533 int comma;
534 static int max_comma = 32; /* let's use 32 for the case that the */
535 /* amount of commas increase with newer SSA versions */
537 int hour1, min1, sec1, hunsec1,
538 hour2, min2, sec2, hunsec2, nothing;
539 int num;
541 char line[LINE_LEN+1],
542 line3[LINE_LEN+1],
543 *line2;
544 char *tmp;
546 do {
547 if (!stream_read_line (st, line, LINE_LEN)) return NULL;
548 } while (sscanf (line, "Dialogue: Marked=%d,%d:%d:%d.%d,%d:%d:%d.%d,"
549 "%[^\n\r]", &nothing,
550 &hour1, &min1, &sec1, &hunsec1,
551 &hour2, &min2, &sec2, &hunsec2,
552 line3) < 9
554 sscanf (line, "Dialogue: %d,%d:%d:%d.%d,%d:%d:%d.%d,"
555 "%[^\n\r]", &nothing,
556 &hour1, &min1, &sec1, &hunsec1,
557 &hour2, &min2, &sec2, &hunsec2,
558 line3) < 9 );
560 line2=strchr(line3, ',');
562 for (comma = 4; comma < max_comma; comma ++)
564 tmp = line2;
565 if(!(tmp=strchr(++tmp, ','))) break;
566 if(*(++tmp) == ' ') break;
567 /* a space after a comma means we're already in a sentence */
568 line2 = tmp;
571 if(comma < max_comma)max_comma = comma;
572 /* eliminate the trailing comma */
573 if(*line2 == ',') line2++;
575 current->lines=0;num=0;
576 current->start = 360000*hour1 + 6000*min1 + 100*sec1 + hunsec1;
577 current->end = 360000*hour2 + 6000*min2 + 100*sec2 + hunsec2;
579 while (((tmp=strstr(line2, "\\n")) != NULL) || ((tmp=strstr(line2, "\\N")) != NULL) ){
580 current->text[num]=(char *)malloc(tmp-line2+1);
581 strncpy (current->text[num], line2, tmp-line2);
582 current->text[num][tmp-line2]='\0';
583 line2=tmp+2;
584 num++;
585 current->lines++;
586 if (current->lines >= SUB_MAX_TEXT) return current;
589 current->text[num]=strdup(line2);
590 current->lines++;
592 return current;
595 void sub_pp_ssa(subtitle *sub) {
596 int l=sub->lines;
597 char *so,*de,*start;
599 while (l){
600 /* eliminate any text enclosed with {}, they are font and color settings */
601 so=de=sub->text[--l];
602 while (*so) {
603 if(*so == '{' && so[1]=='\\') {
604 for (start=so; *so && *so!='}'; so++);
605 if(*so) so++; else so=start;
607 if(*so) {
608 *de=*so;
609 so++; de++;
612 *de=*so;
617 * PJS subtitles reader.
618 * That's the "Phoenix Japanimation Society" format.
619 * I found some of them in http://www.scriptsclub.org/ (used for anime).
620 * The time is in tenths of second.
622 * by set, based on code by szabi (dunnowhat sub format ;-)
624 subtitle *sub_read_line_pjs(stream_t *st,subtitle *current) {
625 char line[LINE_LEN+1];
626 char text[LINE_LEN+1], *s, *d;
628 if (!stream_read_line (st, line, LINE_LEN))
629 return NULL;
630 /* skip spaces */
631 for (s=line; *s && isspace(*s); s++);
632 /* allow empty lines at the end of the file */
633 if (*s==0)
634 return NULL;
635 /* get the time */
636 if (sscanf (s, "%ld,%ld,", &(current->start),
637 &(current->end)) <2) {
638 return ERR;
640 /* the files I have are in tenths of second */
641 current->start *= 10;
642 current->end *= 10;
643 /* walk to the beggining of the string */
644 for (; *s; s++) if (*s==',') break;
645 if (*s) {
646 for (s++; *s; s++) if (*s==',') break;
647 if (*s) s++;
649 if (*s!='"') {
650 return ERR;
652 /* copy the string to the text buffer */
653 for (s++, d=text; *s && *s!='"'; s++, d++)
654 *d=*s;
655 *d=0;
656 current->text[0] = strdup(text);
657 current->lines = 1;
659 return current;
662 subtitle *sub_read_line_mpsub(stream_t *st, subtitle *current) {
663 char line[LINE_LEN+1];
664 float a,b;
665 int num=0;
666 char *p, *q;
670 if (!stream_read_line(st, line, LINE_LEN)) return NULL;
671 } while (sscanf (line, "%f %f", &a, &b) !=2);
673 mpsub_position += a*mpsub_multiplier;
674 current->start=(int) mpsub_position;
675 mpsub_position += b*mpsub_multiplier;
676 current->end=(int) mpsub_position;
678 while (num < SUB_MAX_TEXT) {
679 if (!stream_read_line (st, line, LINE_LEN)) {
680 if (num == 0) return NULL;
681 else return current;
683 p=line;
684 while (isspace(*p)) p++;
685 if (eol(*p) && num > 0) return current;
686 if (eol(*p)) return NULL;
688 for (q=p; !eol(*q); q++);
689 *q='\0';
690 if (strlen(p)) {
691 current->text[num]=strdup(p);
692 // printf (">%s<\n",p);
693 current->lines = ++num;
694 } else {
695 if (num) return current;
696 else return NULL;
699 return NULL; // we should have returned before if it's OK
702 #ifndef USE_SORTSUB
703 //we don't need this if we use previous_sub_end
704 subtitle *previous_aqt_sub = NULL;
705 #endif
707 subtitle *sub_read_line_aqt(stream_t *st,subtitle *current) {
708 char line[LINE_LEN+1];
709 char *next;
710 int i;
712 while (1) {
713 // try to locate next subtitle
714 if (!stream_read_line (st, line, LINE_LEN))
715 return NULL;
716 if (!(sscanf (line, "-->> %ld", &(current->start)) <1))
717 break;
720 #ifdef USE_SORTSUB
721 previous_sub_end = (current->start) ? current->start - 1 : 0;
722 #else
723 if (previous_aqt_sub != NULL)
724 previous_aqt_sub->end = current->start-1;
726 previous_aqt_sub = current;
727 #endif
729 if (!stream_read_line (st, line, LINE_LEN))
730 return NULL;
732 sub_readtext((char *) &line,&current->text[0]);
733 current->lines = 1;
734 current->end = current->start; // will be corrected by next subtitle
736 if (!stream_read_line (st, line, LINE_LEN))
737 return current;
739 next = line,i=1;
740 while ((next =sub_readtext (next, &(current->text[i])))) {
741 if (current->text[i]==ERR) {return ERR;}
742 i++;
743 if (i>=SUB_MAX_TEXT) { mp_msg(MSGT_SUBREADER,MSGL_WARN,"Too many lines in a subtitle\n");current->lines=i;return current;}
745 current->lines=i+1;
747 if ((current->text[0]=="") && (current->text[1]=="")) {
748 #ifdef USE_SORTSUB
749 previous_sub_end = 0;
750 #else
751 // void subtitle -> end of previous marked and exit
752 previous_aqt_sub = NULL;
753 #endif
754 return NULL;
757 return current;
760 #ifndef USE_SORTSUB
761 subtitle *previous_subrip09_sub = NULL;
762 #endif
764 subtitle *sub_read_line_subrip09(stream_t *st,subtitle *current) {
765 char line[LINE_LEN+1];
766 int a1,a2,a3;
767 char * next=NULL;
768 int i,len;
770 while (1) {
771 // try to locate next subtitle
772 if (!stream_read_line (st, line, LINE_LEN))
773 return NULL;
774 if (!((len=sscanf (line, "[%d:%d:%d]",&a1,&a2,&a3)) < 3))
775 break;
778 current->start = a1*360000+a2*6000+a3*100;
780 #ifdef USE_SORTSUB
781 previous_sub_end = (current->start) ? current->start - 1 : 0;
782 #else
783 if (previous_subrip09_sub != NULL)
784 previous_subrip09_sub->end = current->start-1;
786 previous_subrip09_sub = current;
787 #endif
789 if (!stream_read_line (st, line, LINE_LEN))
790 return NULL;
792 next = line,i=0;
794 current->text[0]=""; // just to be sure that string is clear
796 while ((next =sub_readtext (next, &(current->text[i])))) {
797 if (current->text[i]==ERR) {return ERR;}
798 i++;
799 if (i>=SUB_MAX_TEXT) { mp_msg(MSGT_SUBREADER,MSGL_WARN,"Too many lines in a subtitle\n");current->lines=i;return current;}
801 current->lines=i+1;
803 if ((current->text[0]=="") && (i==0)) {
804 #ifdef USE_SORTSUB
805 previous_sub_end = 0;
806 #else
807 // void subtitle -> end of previous marked and exit
808 previous_subrip09_sub = NULL;
809 #endif
810 return NULL;
813 return current;
816 subtitle *sub_read_line_jacosub(stream_t* st, subtitle * current)
818 char line1[LINE_LEN], line2[LINE_LEN], directive[LINE_LEN], *p, *q;
819 unsigned a1, a2, a3, a4, b1, b2, b3, b4, comment = 0;
820 static unsigned jacoTimeres = 30;
821 static int jacoShift = 0;
823 memset(current, 0, sizeof(subtitle));
824 memset(line1, 0, LINE_LEN);
825 memset(line2, 0, LINE_LEN);
826 memset(directive, 0, LINE_LEN);
827 while (!current->text[0]) {
828 if (!stream_read_line(st, line1, LINE_LEN)) {
829 return NULL;
831 if (sscanf
832 (line1, "%u:%u:%u.%u %u:%u:%u.%u %[^\n\r]", &a1, &a2, &a3, &a4,
833 &b1, &b2, &b3, &b4, line2) < 9) {
834 if (sscanf(line1, "@%u @%u %[^\n\r]", &a4, &b4, line2) < 3) {
835 if (line1[0] == '#') {
836 int hours = 0, minutes = 0, seconds, delta, inverter =
838 unsigned units = jacoShift;
839 switch (toupper(line1[1])) {
840 case 'S':
841 if (isalpha(line1[2])) {
842 delta = 6;
843 } else {
844 delta = 2;
846 if (sscanf(&line1[delta], "%d", &hours)) {
847 if (hours < 0) {
848 hours *= -1;
849 inverter = -1;
851 if (sscanf(&line1[delta], "%*d:%d", &minutes)) {
852 if (sscanf
853 (&line1[delta], "%*d:%*d:%d",
854 &seconds)) {
855 sscanf(&line1[delta], "%*d:%*d:%*d.%d",
856 &units);
857 } else {
858 hours = 0;
859 sscanf(&line1[delta], "%d:%d.%d",
860 &minutes, &seconds, &units);
861 minutes *= inverter;
863 } else {
864 hours = minutes = 0;
865 sscanf(&line1[delta], "%d.%d", &seconds,
866 &units);
867 seconds *= inverter;
869 jacoShift =
870 ((hours * 3600 + minutes * 60 +
871 seconds) * jacoTimeres +
872 units) * inverter;
874 break;
875 case 'T':
876 if (isalpha(line1[2])) {
877 delta = 8;
878 } else {
879 delta = 2;
881 sscanf(&line1[delta], "%u", &jacoTimeres);
882 break;
885 continue;
886 } else {
887 current->start =
888 (unsigned long) ((a4 + jacoShift) * 100.0 /
889 jacoTimeres);
890 current->end =
891 (unsigned long) ((b4 + jacoShift) * 100.0 /
892 jacoTimeres);
894 } else {
895 current->start =
896 (unsigned
897 long) (((a1 * 3600 + a2 * 60 + a3) * jacoTimeres + a4 +
898 jacoShift) * 100.0 / jacoTimeres);
899 current->end =
900 (unsigned
901 long) (((b1 * 3600 + b2 * 60 + b3) * jacoTimeres + b4 +
902 jacoShift) * 100.0 / jacoTimeres);
904 current->lines = 0;
905 p = line2;
906 while ((*p == ' ') || (*p == '\t')) {
907 ++p;
909 if (isalpha(*p)||*p == '[') {
910 int cont, jLength;
912 if (sscanf(p, "%s %[^\n\r]", directive, line1) < 2)
913 return (subtitle *) ERR;
914 jLength = strlen(directive);
915 for (cont = 0; cont < jLength; ++cont) {
916 if (isalpha(*(directive + cont)))
917 *(directive + cont) = toupper(*(directive + cont));
919 if ((strstr(directive, "RDB") != NULL)
920 || (strstr(directive, "RDC") != NULL)
921 || (strstr(directive, "RLB") != NULL)
922 || (strstr(directive, "RLG") != NULL)) {
923 continue;
925 if (strstr(directive, "JL") != NULL) {
926 current->alignment = SUB_ALIGNMENT_BOTTOMLEFT;
927 } else if (strstr(directive, "JR") != NULL) {
928 current->alignment = SUB_ALIGNMENT_BOTTOMRIGHT;
929 } else {
930 current->alignment = SUB_ALIGNMENT_BOTTOMCENTER;
932 strcpy(line2, line1);
933 p = line2;
935 for (q = line1; (!eol(*p)) && (current->lines < SUB_MAX_TEXT); ++p) {
936 switch (*p) {
937 case '{':
938 comment++;
939 break;
940 case '}':
941 if (comment) {
942 --comment;
943 //the next line to get rid of a blank after the comment
944 if ((*(p + 1)) == ' ')
945 p++;
947 break;
948 case '~':
949 if (!comment) {
950 *q = ' ';
951 ++q;
953 break;
954 case ' ':
955 case '\t':
956 if ((*(p + 1) == ' ') || (*(p + 1) == '\t'))
957 break;
958 if (!comment) {
959 *q = ' ';
960 ++q;
962 break;
963 case '\\':
964 if (*(p + 1) == 'n') {
965 *q = '\0';
966 q = line1;
967 current->text[current->lines++] = strdup(line1);
968 ++p;
969 break;
971 if ((toupper(*(p + 1)) == 'C')
972 || (toupper(*(p + 1)) == 'F')) {
973 ++p,++p;
974 break;
976 if ((*(p + 1) == 'B') || (*(p + 1) == 'b') || (*(p + 1) == 'D') || //actually this means "insert current date here"
977 (*(p + 1) == 'I') || (*(p + 1) == 'i') || (*(p + 1) == 'N') || (*(p + 1) == 'T') || //actually this means "insert current time here"
978 (*(p + 1) == 'U') || (*(p + 1) == 'u')) {
979 ++p;
980 break;
982 if ((*(p + 1) == '\\') ||
983 (*(p + 1) == '~') || (*(p + 1) == '{')) {
984 ++p;
985 } else if (eol(*(p + 1))) {
986 if (!stream_read_line(st, directive, LINE_LEN))
987 return NULL;
988 trail_space(directive);
989 strncat(line2, directive,
990 (LINE_LEN > 511) ? LINE_LEN : 511);
991 break;
993 default:
994 if (!comment) {
995 *q = *p;
996 ++q;
998 } //-- switch
999 } //-- for
1000 *q = '\0';
1001 current->text[current->lines] = strdup(line1);
1002 } //-- while
1003 current->lines++;
1004 return current;
1007 int sub_autodetect (stream_t* st, int *uses_time) {
1008 char line[LINE_LEN+1];
1009 int i,j=0;
1010 char p;
1012 while (j < 100) {
1013 j++;
1014 if (!stream_read_line (st, line, LINE_LEN))
1015 return SUB_INVALID;
1017 if (sscanf (line, "{%d}{%d}", &i, &i)==2)
1018 {*uses_time=0;return SUB_MICRODVD;}
1019 if (sscanf (line, "{%d}{}", &i)==1)
1020 {*uses_time=0;return SUB_MICRODVD;}
1021 if (sscanf (line, "[%d][%d]", &i, &i)==2)
1022 {*uses_time=1;return SUB_MPL2;}
1023 if (sscanf (line, "%d:%d:%d.%d,%d:%d:%d.%d", &i, &i, &i, &i, &i, &i, &i, &i)==8)
1024 {*uses_time=1;return SUB_SUBRIP;}
1025 if (sscanf (line, "%d:%d:%d%[,.:]%d --> %d:%d:%d%[,.:]%d", &i, &i, &i, (char *)&i, &i, &i, &i, &i, (char *)&i, &i)==10)
1026 {*uses_time=1;return SUB_SUBVIEWER;}
1027 if (sscanf (line, "{T %d:%d:%d:%d",&i, &i, &i, &i)==4)
1028 {*uses_time=1;return SUB_SUBVIEWER2;}
1029 if (strstr (line, "<SAMI>"))
1030 {*uses_time=1; return SUB_SAMI;}
1031 if (sscanf(line, "%d:%d:%d.%d %d:%d:%d.%d", &i, &i, &i, &i, &i, &i, &i, &i) == 8)
1032 {*uses_time = 1; return SUB_JACOSUB;}
1033 if (sscanf(line, "@%d @%d", &i, &i) == 2)
1034 {*uses_time = 1; return SUB_JACOSUB;}
1035 if (sscanf (line, "%d:%d:%d:", &i, &i, &i )==3)
1036 {*uses_time=1;return SUB_VPLAYER;}
1037 if (sscanf (line, "%d:%d:%d ", &i, &i, &i )==3)
1038 {*uses_time=1;return SUB_VPLAYER;}
1039 //TODO: just checking if first line of sub starts with "<" is WAY
1040 // too weak test for RT
1041 // Please someone who knows the format of RT... FIX IT!!!
1042 // It may conflict with other sub formats in the future (actually it doesn't)
1043 if ( *line == '<' )
1044 {*uses_time=1;return SUB_RT;}
1046 if (!memcmp(line, "Dialogue: Marked", 16))
1047 {*uses_time=1; return SUB_SSA;}
1048 if (!memcmp(line, "Dialogue: ", 10))
1049 {*uses_time=1; return SUB_SSA;}
1050 if (sscanf (line, "%d,%d,\"%c", &i, &i, (char *) &i) == 3)
1051 {*uses_time=1;return SUB_PJS;}
1052 if (sscanf (line, "FORMAT=%d", &i) == 1)
1053 {*uses_time=0; return SUB_MPSUB;}
1054 if (sscanf (line, "FORMAT=TIM%c", &p)==1 && p=='E')
1055 {*uses_time=1; return SUB_MPSUB;}
1056 if (strstr (line, "-->>"))
1057 {*uses_time=0; return SUB_AQTITLE;}
1058 if (sscanf (line, "[%d:%d:%d]", &i, &i, &i)==3)
1059 {*uses_time=1;return SUB_SUBRIP09;}
1062 return SUB_INVALID; // too many bad lines
1065 #ifdef DUMPSUBS
1066 int sub_utf8=0;
1067 #else
1068 extern int sub_utf8;
1069 int sub_utf8_prev=0;
1070 #endif
1072 extern float sub_delay;
1073 extern float sub_fps;
1075 #ifdef USE_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 char *cp_tmp = sub_cp;
1084 #ifdef HAVE_ENCA
1085 char enca_lang[3], enca_fallback[100];
1086 int free_cp_tmp = 0;
1087 if (sscanf(sub_cp, "enca:%2s:%99s", enca_lang, enca_fallback) == 2
1088 || sscanf(sub_cp, "ENCA:%2s:%99s", enca_lang, enca_fallback) == 2) {
1089 if (st && st->flags & STREAM_SEEK ) {
1090 cp_tmp = guess_cp(st, enca_lang, enca_fallback);
1091 free_cp_tmp = 1;
1092 } else {
1093 cp_tmp = enca_fallback;
1094 mp_msg(MSGT_SUBREADER,MSGL_WARN,"SUB: enca faild, stream must be seakable.\n");
1097 #endif
1098 if ((icdsc = iconv_open (tocp, cp_tmp)) != (iconv_t)(-1)){
1099 mp_msg(MSGT_SUBREADER,MSGL_V,"SUB: opened iconv descriptor.\n");
1100 sub_utf8 = 2;
1101 } else
1102 mp_msg(MSGT_SUBREADER,MSGL_ERR,"SUB: error opening iconv descriptor.\n");
1103 #ifdef HAVE_ENCA
1104 if (free_cp_tmp && cp_tmp) free(cp_tmp);
1105 #endif
1109 void subcp_close (void)
1111 if (icdsc != (iconv_t)(-1)){
1112 (void) iconv_close (icdsc);
1113 icdsc = (iconv_t)(-1);
1114 mp_msg(MSGT_SUBREADER,MSGL_V,"SUB: closed iconv descriptor.\n");
1118 #define ICBUFFSIZE 512
1119 static char icbuffer[ICBUFFSIZE];
1121 subtitle* subcp_recode (subtitle *sub)
1123 int l=sub->lines;
1124 size_t ileft, oleft;
1125 char *op, *ip, *ot;
1127 while (l){
1128 op = icbuffer;
1129 ip = sub->text[--l];
1130 ileft = strlen(ip);
1131 oleft = ICBUFFSIZE - 1;
1133 if (iconv(icdsc, &ip, &ileft,
1134 &op, &oleft) == (size_t)(-1)) {
1135 mp_msg(MSGT_SUBREADER,MSGL_WARN,"SUB: error recoding line (1).\n");
1136 l++;
1137 break;
1139 if (!(ot = (char *)malloc(op - icbuffer + 1))){
1140 mp_msg(MSGT_SUBREADER,MSGL_WARN,"SUB: error allocating mem.\n");
1141 l++;
1142 break;
1144 *op='\0' ;
1145 strcpy (ot, icbuffer);
1146 free (sub->text[l]);
1147 sub->text[l] = ot;
1149 if (l){
1150 for (l = sub->lines; l;)
1151 free (sub->text[--l]);
1152 return ERR;
1154 return sub;
1157 // for demux_ogg.c:
1158 subtitle* subcp_recode1 (subtitle *sub)
1160 int l=sub->lines;
1161 size_t ileft, oleft;
1163 if(icdsc == (iconv_t)(-1)) return sub;
1165 while (l){
1166 char *ip = icbuffer;
1167 char *op = sub->text[--l];
1168 strlcpy(ip, op, ICBUFFSIZE);
1169 ileft = strlen(ip);
1170 oleft = ICBUFFSIZE - 1;
1172 if (iconv(icdsc, &ip, &ileft,
1173 &op, &oleft) == (size_t)(-1)) {
1174 mp_msg(MSGT_SUBREADER,MSGL_V,"SUB: error recoding line (2).\n");
1175 return sub;
1177 *op='\0' ;
1179 return sub;
1181 #endif
1183 #ifdef USE_FRIBIDI
1184 #ifndef max
1185 #define max(a,b) (((a)>(b))?(a):(b))
1186 #endif
1187 subtitle* sub_fribidi (subtitle *sub, int sub_utf8)
1189 FriBidiChar logical[LINE_LEN+1], visual[LINE_LEN+1]; // Hopefully these two won't smash the stack
1190 char *ip = NULL, *op = NULL;
1191 FriBidiCharType base;
1192 size_t len,orig_len;
1193 int l=sub->lines;
1194 int char_set_num;
1195 fribidi_boolean log2vis;
1196 if(flip_hebrew) { // Please fix the indentation someday
1197 fribidi_set_mirroring (FRIBIDI_TRUE);
1198 fribidi_set_reorder_nsm (FRIBIDI_FALSE);
1200 if( sub_utf8 == 0 ) {
1201 char_set_num = fribidi_parse_charset (fribidi_charset?fribidi_charset:"ISO8859-8");
1202 }else {
1203 char_set_num = fribidi_parse_charset ("UTF-8");
1205 while (l) {
1206 ip = sub->text[--l];
1207 orig_len = len = strlen( ip ); // We assume that we don't use full unicode, only UTF-8 or ISO8859-x
1208 if(len > LINE_LEN) {
1209 mp_msg(MSGT_SUBREADER,MSGL_WARN,"SUB: sub->text is longer than LINE_LEN.\n");
1210 l++;
1211 break;
1213 len = fribidi_charset_to_unicode (char_set_num, ip, len, logical);
1214 base = fribidi_flip_commas?FRIBIDI_TYPE_ON:FRIBIDI_TYPE_L;
1215 log2vis = fribidi_log2vis (logical, len, &base,
1216 /* output */
1217 visual, NULL, NULL, NULL);
1218 if(log2vis) {
1219 len = fribidi_remove_bidi_marks (visual, len, NULL, NULL,
1220 NULL);
1221 if((op = (char*)malloc(sizeof(char)*(max(2*orig_len,2*len) + 1))) == NULL) {
1222 mp_msg(MSGT_SUBREADER,MSGL_WARN,"SUB: error allocating mem.\n");
1223 l++;
1224 break;
1226 fribidi_unicode_to_charset ( char_set_num, visual, len,op);
1227 free (ip);
1228 sub->text[l] = op;
1231 if (l){
1232 for (l = sub->lines; l;)
1233 free (sub->text[--l]);
1234 return ERR;
1237 return sub;
1240 #endif
1242 static void adjust_subs_time(subtitle* sub, float subtime, float fps, int block,
1243 int sub_num, int sub_uses_time) {
1244 int n,m;
1245 subtitle* nextsub;
1246 int i = sub_num;
1247 unsigned long subfms = (sub_uses_time ? 100 : fps) * subtime;
1248 unsigned long overlap = (sub_uses_time ? 100 : fps) / 5; // 0.2s
1250 n=m=0;
1251 if (i) for (;;){
1252 if (sub->end <= sub->start){
1253 sub->end = sub->start + subfms;
1254 m++;
1255 n++;
1257 if (!--i) break;
1258 nextsub = sub + 1;
1259 if(block){
1260 if ((sub->end > nextsub->start) && (sub->end <= nextsub->start + overlap)) {
1261 // these subtitles overlap for less than 0.2 seconds
1262 // and would result in very short overlapping subtitle
1263 // so let's fix the problem here, before overlapping code
1264 // get its hands on them
1265 unsigned delta = sub->end - nextsub->start, half = delta / 2;
1266 sub->end -= half + 1;
1267 nextsub->start += delta - half;
1269 if (sub->end >= nextsub->start){
1270 sub->end = nextsub->start - 1;
1271 if (sub->end - sub->start > subfms)
1272 sub->end = sub->start + subfms;
1273 if (!m)
1274 n++;
1278 /* Theory:
1279 * Movies are often converted from FILM (24 fps)
1280 * to PAL (25) by simply speeding it up, so we
1281 * to multiply the original timestmaps by
1282 * (Movie's FPS / Subtitle's (guessed) FPS)
1283 * so eg. for 23.98 fps movie and PAL time based
1284 * subtitles we say -subfps 25 and we're fine!
1287 /* timed sub fps correction ::atmos */
1288 if(sub_uses_time && sub_fps) {
1289 sub->start *= sub_fps/fps;
1290 sub->end *= sub_fps/fps;
1293 sub = nextsub;
1294 m = 0;
1296 if (n) mp_msg(MSGT_SUBREADER,MSGL_INFO,"SUB: Adjusted %d subtitle(s).\n", n);
1299 struct subreader {
1300 subtitle * (*read)(stream_t *st,subtitle *dest);
1301 void (*post)(subtitle *dest);
1302 const char *name;
1305 #ifdef HAVE_ENCA
1306 #define MAX_GUESS_BUFFER_SIZE (256*1024)
1307 void* guess_cp(stream_t *st, char *preferred_language, char *fallback)
1309 const char **languages;
1310 size_t langcnt, buflen;
1311 EncaAnalyser analyser;
1312 EncaEncoding encoding;
1313 unsigned char *buffer;
1314 char *detected_sub_cp = NULL;
1315 int i;
1317 buffer = (unsigned char*)malloc(MAX_GUESS_BUFFER_SIZE*sizeof(char));
1318 buflen = stream_read(st,buffer, MAX_GUESS_BUFFER_SIZE);
1320 languages = enca_get_languages(&langcnt);
1321 mp_msg(MSGT_SUBREADER, MSGL_V, "ENCA supported languages: ");
1322 for (i = 0; i < langcnt; i++) {
1323 mp_msg(MSGT_SUBREADER, MSGL_V, "%s ", languages[i]);
1325 mp_msg(MSGT_SUBREADER, MSGL_V, "\n");
1327 for (i = 0; i < langcnt; i++) {
1328 char *tmp;
1330 if (strcasecmp(languages[i], preferred_language) != 0) continue;
1331 analyser = enca_analyser_alloc(languages[i]);
1332 encoding = enca_analyse_const(analyser, buffer, buflen);
1333 tmp = enca_charset_name(encoding.charset, ENCA_NAME_STYLE_ICONV);
1334 if (tmp && encoding.charset != ENCA_CS_UNKNOWN) {
1335 detected_sub_cp = strdup(tmp);
1336 mp_msg(MSGT_SUBREADER, MSGL_INFO, "ENCA detected charset: %s\n", tmp);
1338 enca_analyser_free(analyser);
1341 free(languages);
1342 free(buffer);
1343 stream_reset(st);
1344 stream_seek(st,0);
1346 if (!detected_sub_cp) {
1347 detected_sub_cp = strdup(fallback);
1348 mp_msg(MSGT_SUBREADER, MSGL_INFO, "ENCA detection failed: fallback to %s\n", fallback);
1351 return detected_sub_cp;
1353 #endif
1355 sub_data* sub_read_file (char *filename, float fps) {
1356 stream_t* fd;
1357 int n_max, n_first, i, j, sub_first, sub_orig;
1358 subtitle *first, *second, *sub, *return_sub;
1359 sub_data *subt_data;
1360 int uses_time = 0, sub_num = 0, sub_errs = 0;
1361 struct subreader sr[]=
1363 { sub_read_line_microdvd, NULL, "microdvd" },
1364 { sub_read_line_subrip, NULL, "subrip" },
1365 { sub_read_line_subviewer, NULL, "subviewer" },
1366 { sub_read_line_sami, NULL, "sami" },
1367 { sub_read_line_vplayer, NULL, "vplayer" },
1368 { sub_read_line_rt, NULL, "rt" },
1369 { sub_read_line_ssa, sub_pp_ssa, "ssa" },
1370 { sub_read_line_pjs, NULL, "pjs" },
1371 { sub_read_line_mpsub, NULL, "mpsub" },
1372 { sub_read_line_aqt, NULL, "aqt" },
1373 { sub_read_line_subviewer2, NULL, "subviewer 2.0" },
1374 { sub_read_line_subrip09, NULL, "subrip 0.9" },
1375 { sub_read_line_jacosub, NULL, "jacosub" },
1376 { sub_read_line_mpl2, NULL, "mpl2" }
1378 struct subreader *srp;
1380 if(filename==NULL) return NULL; //qnx segfault
1381 fd=open_stream (filename, NULL, &i); if (!fd) return NULL;
1383 sub_format=sub_autodetect (fd, &uses_time);
1384 mpsub_multiplier = (uses_time ? 100.0 : 1.0);
1385 if (sub_format==SUB_INVALID) {mp_msg(MSGT_SUBREADER,MSGL_WARN,"SUB: Could not determine file format\n");return NULL;}
1386 srp=sr+sub_format;
1387 mp_msg(MSGT_SUBREADER,MSGL_INFO,"SUB: Detected subtitle file format: %s\n", srp->name);
1389 stream_reset(fd);
1390 stream_seek(fd,0);
1392 #ifdef USE_ICONV
1393 sub_utf8_prev=sub_utf8;
1395 int l,k;
1396 k = -1;
1397 if ((l=strlen(filename))>4){
1398 char *exts[] = {".utf", ".utf8", ".utf-8" };
1399 for (k=3;--k>=0;)
1400 if (!strcasecmp(filename+(l - strlen(exts[k])), exts[k])){
1401 sub_utf8 = 1;
1402 break;
1405 if (k<0) subcp_open(fd);
1407 #endif
1409 sub_num=0;n_max=32;
1410 first=(subtitle *)malloc(n_max*sizeof(subtitle));
1411 if(!first){
1412 #ifdef USE_ICONV
1413 subcp_close();
1414 sub_utf8=sub_utf8_prev;
1415 #endif
1416 return NULL;
1419 #ifdef USE_SORTSUB
1420 sub = (subtitle *)malloc(sizeof(subtitle));
1421 //This is to deal with those formats (AQT & Subrip) which define the end of a subtitle
1422 //as the beginning of the following
1423 previous_sub_end = 0;
1424 #endif
1425 while(1){
1426 if(sub_num>=n_max){
1427 n_max+=16;
1428 first=realloc(first,n_max*sizeof(subtitle));
1430 #ifndef USE_SORTSUB
1431 sub = &first[sub_num];
1432 #endif
1433 memset(sub, '\0', sizeof(subtitle));
1434 sub=srp->read(fd,sub);
1435 if(!sub) break; // EOF
1436 #ifdef USE_ICONV
1437 if ((sub!=ERR) && (sub_utf8 & 2)) sub=subcp_recode(sub);
1438 #endif
1439 #ifdef USE_FRIBIDI
1440 if (sub!=ERR) sub=sub_fribidi(sub,sub_utf8);
1441 #endif
1442 if ( sub == ERR )
1444 #ifdef USE_ICONV
1445 subcp_close();
1446 #endif
1447 if ( first ) free(first);
1448 return NULL;
1450 // Apply any post processing that needs recoding first
1451 if ((sub!=ERR) && !sub_no_text_pp && srp->post) srp->post(sub);
1452 #ifdef USE_SORTSUB
1453 if(!sub_num || (first[sub_num - 1].start <= sub->start)){
1454 first[sub_num].start = sub->start;
1455 first[sub_num].end = sub->end;
1456 first[sub_num].lines = sub->lines;
1457 first[sub_num].alignment = sub->alignment;
1458 for(i = 0; i < sub->lines; ++i){
1459 first[sub_num].text[i] = sub->text[i];
1461 if (previous_sub_end){
1462 first[sub_num - 1].end = previous_sub_end;
1463 previous_sub_end = 0;
1465 } else {
1466 for(j = sub_num - 1; j >= 0; --j){
1467 first[j + 1].start = first[j].start;
1468 first[j + 1].end = first[j].end;
1469 first[j + 1].lines = first[j].lines;
1470 first[j + 1].alignment = first[j].alignment;
1471 for(i = 0; i < first[j].lines; ++i){
1472 first[j + 1].text[i] = first[j].text[i];
1474 if(!j || (first[j - 1].start <= sub->start)){
1475 first[j].start = sub->start;
1476 first[j].end = sub->end;
1477 first[j].lines = sub->lines;
1478 first[j].alignment = sub->alignment;
1479 for(i = 0; i < SUB_MAX_TEXT; ++i){
1480 first[j].text[i] = sub->text[i];
1482 if (previous_sub_end){
1483 first[j].end = first[j - 1].end;
1484 first[j - 1].end = previous_sub_end;
1485 previous_sub_end = 0;
1487 break;
1491 #endif
1492 if(sub==ERR) ++sub_errs; else ++sub_num; // Error vs. Valid
1495 free_stream(fd);
1497 #ifdef USE_ICONV
1498 subcp_close();
1499 #endif
1501 // printf ("SUB: Subtitle format %s time.\n", uses_time?"uses":"doesn't use");
1502 mp_msg(MSGT_SUBREADER,MSGL_INFO,"SUB: Read %i subtitles", sub_num);
1503 if (sub_errs) mp_msg(MSGT_SUBREADER,MSGL_INFO,", %i bad line(s).\n", sub_errs);
1504 else mp_msg(MSGT_SUBREADER,MSGL_INFO,".\n");
1506 if(sub_num<=0){
1507 free(first);
1508 return NULL;
1511 // we do overlap if the user forced it (suboverlap_enable == 2) or
1512 // the user didn't forced no-overlapsub and the format is Jacosub or Ssa.
1513 // this is because usually overlapping subtitles are found in these formats,
1514 // while in others they are probably result of bad timing
1515 if ((suboverlap_enabled == 2) ||
1516 ((suboverlap_enabled) && ((sub_format == SUB_JACOSUB) || (sub_format == SUB_SSA)))) {
1517 adjust_subs_time(first, 6.0, fps, 0, sub_num, uses_time);/*~6 secs AST*/
1518 // here we manage overlapping subtitles
1519 sub_orig = sub_num;
1520 n_first = sub_num;
1521 sub_num = 0;
1522 second = NULL;
1523 // for each subtitle in first[] we deal with its 'block' of
1524 // bonded subtitles
1525 for (sub_first = 0; sub_first < n_first; ++sub_first) {
1526 unsigned long global_start = first[sub_first].start,
1527 global_end = first[sub_first].end, local_start, local_end;
1528 int lines_to_add = first[sub_first].lines, sub_to_add = 0,
1529 **placeholder = NULL, higher_line = 0, counter, start_block_sub = sub_num;
1530 char real_block = 1;
1532 // here we find the number of subtitles inside the 'block'
1533 // and its span interval. this works well only with sorted
1534 // subtitles
1535 while ((sub_first + sub_to_add + 1 < n_first) && (first[sub_first + sub_to_add + 1].start < global_end)) {
1536 ++sub_to_add;
1537 lines_to_add += first[sub_first + sub_to_add].lines;
1538 if (first[sub_first + sub_to_add].start < global_start) {
1539 global_start = first[sub_first + sub_to_add].start;
1541 if (first[sub_first + sub_to_add].end > global_end) {
1542 global_end = first[sub_first + sub_to_add].end;
1546 // we need a structure to keep trace of the screen lines
1547 // used by the subs, a 'placeholder'
1548 counter = 2 * sub_to_add + 1; // the maximum number of subs derived
1549 // from a block of sub_to_add+1 subs
1550 placeholder = (int **) malloc(sizeof(int *) * counter);
1551 for (i = 0; i < counter; ++i) {
1552 placeholder[i] = (int *) malloc(sizeof(int) * lines_to_add);
1553 for (j = 0; j < lines_to_add; ++j) {
1554 placeholder[i][j] = -1;
1558 counter = 0;
1559 local_end = global_start - 1;
1560 do {
1561 int ls;
1563 // here we find the beginning and the end of a new
1564 // subtitle in the block
1565 local_start = local_end + 1;
1566 local_end = global_end;
1567 for (j = 0; j <= sub_to_add; ++j) {
1568 if ((first[sub_first + j].start - 1 > local_start) && (first[sub_first + j].start - 1 < local_end)) {
1569 local_end = first[sub_first + j].start - 1;
1570 } else if ((first[sub_first + j].end > local_start) && (first[sub_first + j].end < local_end)) {
1571 local_end = first[sub_first + j].end;
1574 // here we allocate the screen lines to subs we must
1575 // display in current local_start-local_end interval.
1576 // if the subs were yet presents in the previous interval
1577 // they keep the same lines, otherside they get unused lines
1578 for (j = 0; j <= sub_to_add; ++j) {
1579 if ((first[sub_first + j].start <= local_end) && (first[sub_first + j].end > local_start)) {
1580 unsigned long sub_lines = first[sub_first + j].lines, fragment_length = lines_to_add + 1,
1581 tmp = 0;
1582 char boolean = 0;
1583 int fragment_position = -1;
1585 // if this is not the first new sub of the block
1586 // we find if this sub was present in the previous
1587 // new sub
1588 if (counter)
1589 for (i = 0; i < lines_to_add; ++i) {
1590 if (placeholder[counter - 1][i] == sub_first + j) {
1591 placeholder[counter][i] = sub_first + j;
1592 boolean = 1;
1595 if (boolean)
1596 continue;
1598 // we are looking for the shortest among all groups of
1599 // sequential blank lines whose length is greater than or
1600 // equal to sub_lines. we store in fragment_position the
1601 // position of the shortest group, in fragment_length its
1602 // length, and in tmp the length of the group currently
1603 // examinated
1604 for (i = 0; i < lines_to_add; ++i) {
1605 if (placeholder[counter][i] == -1) {
1606 // placeholder[counter][i] is part of the current group
1607 // of blank lines
1608 ++tmp;
1609 } else {
1610 if (tmp == sub_lines) {
1611 // current group's size fits exactly the one we
1612 // need, so we stop looking
1613 fragment_position = i - tmp;
1614 tmp = 0;
1615 break;
1617 if ((tmp) && (tmp > sub_lines) && (tmp < fragment_length)) {
1618 // current group is the best we found till here,
1619 // but is still bigger than the one we are looking
1620 // for, so we keep on looking
1621 fragment_length = tmp;
1622 fragment_position = i - tmp;
1623 tmp = 0;
1624 } else {
1625 // current group doesn't fit at all, so we forget it
1626 tmp = 0;
1630 if (tmp) {
1631 // last screen line is blank, a group ends with it
1632 if ((tmp >= sub_lines) && (tmp < fragment_length)) {
1633 fragment_position = i - tmp;
1636 if (fragment_position == -1) {
1637 // it was not possible to find free screen line(s) for a subtitle,
1638 // usually this means a bug in the code; however we do not overlap
1639 mp_msg(MSGT_SUBREADER, MSGL_WARN, "SUB: we could not find a suitable position for an overlapping subtitle\n");
1640 higher_line = SUB_MAX_TEXT + 1;
1641 break;
1642 } else {
1643 for (tmp = 0; tmp < sub_lines; ++tmp) {
1644 placeholder[counter][fragment_position + tmp] = sub_first + j;
1649 for (j = higher_line + 1; j < lines_to_add; ++j) {
1650 if (placeholder[counter][j] != -1)
1651 higher_line = j;
1652 else
1653 break;
1655 if (higher_line >= SUB_MAX_TEXT) {
1656 // the 'block' has too much lines, so we don't overlap the
1657 // subtitles
1658 second = (subtitle *) realloc(second, (sub_num + sub_to_add + 1) * sizeof(subtitle));
1659 for (j = 0; j <= sub_to_add; ++j) {
1660 int ls;
1661 memset(&second[sub_num + j], '\0', sizeof(subtitle));
1662 second[sub_num + j].start = first[sub_first + j].start;
1663 second[sub_num + j].end = first[sub_first + j].end;
1664 second[sub_num + j].lines = first[sub_first + j].lines;
1665 second[sub_num + j].alignment = first[sub_first + j].alignment;
1666 for (ls = 0; ls < second[sub_num + j].lines; ls++) {
1667 second[sub_num + j].text[ls] = strdup(first[sub_first + j].text[ls]);
1670 sub_num += sub_to_add + 1;
1671 sub_first += sub_to_add;
1672 real_block = 0;
1673 break;
1676 // we read the placeholder structure and create the new
1677 // subs.
1678 second = (subtitle *) realloc(second, (sub_num + 1) * sizeof(subtitle));
1679 memset(&second[sub_num], '\0', sizeof(subtitle));
1680 second[sub_num].start = local_start;
1681 second[sub_num].end = local_end;
1682 second[sub_num].alignment = first[sub_first].alignment;
1683 n_max = (lines_to_add < SUB_MAX_TEXT) ? lines_to_add : SUB_MAX_TEXT;
1684 for (i = 0, j = 0; j < n_max; ++j) {
1685 if (placeholder[counter][j] != -1) {
1686 int lines = first[placeholder[counter][j]].lines;
1687 for (ls = 0; ls < lines; ++ls) {
1688 second[sub_num].text[i++] = strdup(first[placeholder[counter][j]].text[ls]);
1690 j += lines - 1;
1691 } else {
1692 second[sub_num].text[i++] = strdup(" ");
1695 ++sub_num;
1696 ++counter;
1697 } while (local_end < global_end);
1698 if (real_block)
1699 for (i = 0; i < counter; ++i)
1700 second[start_block_sub + i].lines = higher_line + 1;
1702 counter = 2 * sub_to_add + 1;
1703 for (i = 0; i < counter; ++i) {
1704 free(placeholder[i]);
1706 free(placeholder);
1707 sub_first += sub_to_add;
1710 for (j = sub_orig - 1; j >= 0; --j) {
1711 for (i = first[j].lines - 1; i >= 0; --i) {
1712 free(first[j].text[i]);
1715 free(first);
1717 return_sub = second;
1718 } else { //if(suboverlap_enabled)
1719 adjust_subs_time(first, 6.0, fps, 1, sub_num, uses_time);/*~6 secs AST*/
1720 return_sub = first;
1722 if (return_sub == NULL) return NULL;
1723 subt_data = (sub_data *)malloc(sizeof(sub_data));
1724 subt_data->filename = strdup(filename);
1725 subt_data->sub_uses_time = uses_time;
1726 subt_data->sub_num = sub_num;
1727 subt_data->sub_errs = sub_errs;
1728 subt_data->subtitles = return_sub;
1729 return subt_data;
1732 #if 0
1733 char * strreplace( char * in,char * what,char * whereof )
1735 int i;
1736 char * tmp;
1738 if ( ( in == NULL )||( what == NULL )||( whereof == NULL )||( ( tmp=strstr( in,what ) ) == NULL ) ) return NULL;
1739 for( i=0;i<strlen( whereof );i++ ) tmp[i]=whereof[i];
1740 if ( strlen( what ) > strlen( whereof ) ) tmp[i]=0;
1741 return in;
1743 #endif
1746 static void strcpy_trim(char *d, char *s)
1748 // skip leading whitespace
1749 while (*s && !isalnum(*s)) {
1750 s++;
1752 for (;;) {
1753 // copy word
1754 while (*s && isalnum(*s)) {
1755 *d = tolower(*s);
1756 s++; d++;
1758 if (*s == 0) break;
1759 // trim excess whitespace
1760 while (*s && !isalnum(*s)) {
1761 s++;
1763 if (*s == 0) break;
1764 *d++ = ' ';
1766 *d = 0;
1769 static void strcpy_strip_ext(char *d, char *s)
1771 char *tmp = strrchr(s,'.');
1772 if (!tmp) {
1773 strcpy(d, s);
1774 return;
1775 } else {
1776 strncpy(d, s, tmp-s);
1777 d[tmp-s] = 0;
1779 while (*d) {
1780 *d = tolower(*d);
1781 d++;
1785 static void strcpy_get_ext(char *d, char *s)
1787 char *tmp = strrchr(s,'.');
1788 if (!tmp) {
1789 strcpy(d, "");
1790 return;
1791 } else {
1792 strcpy(d, tmp+1);
1796 static int whiteonly(char *s)
1798 while (*s) {
1799 if (isalnum(*s)) return 0;
1800 s++;
1802 return 1;
1805 typedef struct _subfn
1807 int priority;
1808 char *fname;
1809 } subfn;
1811 static int compare_sub_priority(const void *a, const void *b)
1813 if (((subfn*)a)->priority > ((subfn*)b)->priority) {
1814 return -1;
1815 } else if (((subfn*)a)->priority < ((subfn*)b)->priority) {
1816 return 1;
1817 } else {
1818 return strcoll(((subfn*)a)->fname, ((subfn*)b)->fname);
1822 char** sub_filenames(char* path, char *fname)
1824 char *f_dir, *f_fname, *f_fname_noext, *f_fname_trim, *tmp, *tmp_sub_id;
1825 char *tmp_fname_noext, *tmp_fname_trim, *tmp_fname_ext, *tmpresult;
1827 int len, pos, found, i, j;
1828 char * sub_exts[] = { "utf", "utf8", "utf-8", "sub", "srt", "smi", "rt", "txt", "ssa", "aqt", "jss", "js", "ass", NULL};
1829 subfn *result;
1830 char **result2;
1832 int subcnt;
1834 FILE *f;
1836 DIR *d;
1837 struct dirent *de;
1839 len = (strlen(fname) > 256 ? strlen(fname) : 256)
1840 +(strlen(path) > 256 ? strlen(path) : 256)+2;
1842 f_dir = (char*)malloc(len);
1843 f_fname = (char*)malloc(len);
1844 f_fname_noext = (char*)malloc(len);
1845 f_fname_trim = (char*)malloc(len);
1847 tmp_fname_noext = (char*)malloc(len);
1848 tmp_fname_trim = (char*)malloc(len);
1849 tmp_fname_ext = (char*)malloc(len);
1851 tmpresult = (char*)malloc(len);
1853 result = (subfn*)malloc(sizeof(subfn)*MAX_SUBTITLE_FILES);
1854 memset(result, 0, sizeof(subfn)*MAX_SUBTITLE_FILES);
1856 subcnt = 0;
1858 tmp = strrchr(fname,'/');
1859 #ifdef WIN32
1860 if(!tmp)tmp = strrchr(fname,'\\');
1861 #endif
1863 // extract filename & dirname from fname
1864 if (tmp) {
1865 strcpy(f_fname, tmp+1);
1866 pos = tmp - fname;
1867 strncpy(f_dir, fname, pos+1);
1868 f_dir[pos+1] = 0;
1869 } else {
1870 strcpy(f_fname, fname);
1871 strcpy(f_dir, "./");
1874 strcpy_strip_ext(f_fname_noext, f_fname);
1875 strcpy_trim(f_fname_trim, f_fname_noext);
1877 tmp_sub_id = NULL;
1878 if (dvdsub_lang && !whiteonly(dvdsub_lang)) {
1879 tmp_sub_id = (char*)malloc(strlen(dvdsub_lang)+1);
1880 strcpy_trim(tmp_sub_id, dvdsub_lang);
1883 // 0 = nothing
1884 // 1 = any subtitle file
1885 // 2 = any sub file containing movie name
1886 // 3 = sub file containing movie name and the lang extension
1887 for (j = 0; j <= 1; j++) {
1888 d = opendir(j == 0 ? f_dir : path);
1889 if (d) {
1890 while ((de = readdir(d))) {
1891 // retrieve various parts of the filename
1892 strcpy_strip_ext(tmp_fname_noext, de->d_name);
1893 strcpy_get_ext(tmp_fname_ext, de->d_name);
1894 strcpy_trim(tmp_fname_trim, tmp_fname_noext);
1896 // does it end with a subtitle extension?
1897 found = 0;
1898 #ifdef USE_ICONV
1899 #ifdef HAVE_ENCA
1900 for (i = ((sub_cp && strncasecmp(sub_cp, "enca", 4) != 0) ? 3 : 0); sub_exts[i]; i++) {
1901 #else
1902 for (i = (sub_cp ? 3 : 0); sub_exts[i]; i++) {
1903 #endif
1904 #else
1905 for (i = 0; sub_exts[i]; i++) {
1906 #endif
1907 if (strcasecmp(sub_exts[i], tmp_fname_ext) == 0) {
1908 found = 1;
1909 break;
1913 // we have a (likely) subtitle file
1914 if (found) {
1915 int prio = 0;
1916 if (!prio && tmp_sub_id)
1918 sprintf(tmpresult, "%s %s", f_fname_trim, tmp_sub_id);
1919 mp_msg(MSGT_SUBREADER,MSGL_INFO,"dvdsublang...%s\n", tmpresult);
1920 if (strcmp(tmp_fname_trim, tmpresult) == 0 && sub_match_fuzziness >= 1) {
1921 // matches the movie name + lang extension
1922 prio = 5;
1925 if (!prio && strcmp(tmp_fname_trim, f_fname_trim) == 0) {
1926 // matches the movie name
1927 prio = 4;
1929 if (!prio && (tmp = strstr(tmp_fname_trim, f_fname_trim)) && (sub_match_fuzziness >= 1)) {
1930 // contains the movie name
1931 tmp += strlen(f_fname_trim);
1932 if (tmp_sub_id && strstr(tmp, tmp_sub_id)) {
1933 // with sub_id specified prefer localized subtitles
1934 prio = 3;
1935 } else if ((tmp_sub_id == NULL) && whiteonly(tmp)) {
1936 // without sub_id prefer "plain" name
1937 prio = 3;
1938 } else {
1939 // with no localized subs found, try any else instead
1940 prio = 2;
1943 if (!prio) {
1944 // doesn't contain the movie name
1945 // don't try in the mplayer subtitle directory
1946 if ((j == 0) && (sub_match_fuzziness >= 2)) {
1947 prio = 1;
1951 if (prio) {
1952 prio += prio;
1953 #ifdef USE_ICONV
1954 if (i<3){ // prefer UTF-8 coded
1955 prio++;
1957 #endif
1958 sprintf(tmpresult, "%s%s", j == 0 ? f_dir : path, de->d_name);
1959 // fprintf(stderr, "%s priority %d\n", tmpresult, prio);
1960 if ((f = fopen(tmpresult, "rt"))) {
1961 fclose(f);
1962 result[subcnt].priority = prio;
1963 result[subcnt].fname = strdup(tmpresult);
1964 subcnt++;
1969 if (subcnt >= MAX_SUBTITLE_FILES) break;
1971 closedir(d);
1976 if (tmp_sub_id) free(tmp_sub_id);
1978 free(f_dir);
1979 free(f_fname);
1980 free(f_fname_noext);
1981 free(f_fname_trim);
1983 free(tmp_fname_noext);
1984 free(tmp_fname_trim);
1985 free(tmp_fname_ext);
1987 free(tmpresult);
1989 qsort(result, subcnt, sizeof(subfn), compare_sub_priority);
1991 result2 = (char**)malloc(sizeof(char*)*(subcnt+1));
1992 memset(result2, 0, sizeof(char*)*(subcnt+1));
1994 for (i = 0; i < subcnt; i++) {
1995 result2[i] = result[i].fname;
1997 result2[subcnt] = NULL;
1999 free(result);
2001 return result2;
2004 void list_sub_file(sub_data* subd){
2005 int i,j;
2006 subtitle *subs = subd->subtitles;
2008 for(j=0; j < subd->sub_num; j++){
2009 subtitle* egysub=&subs[j];
2010 mp_msg(MSGT_SUBREADER,MSGL_INFO,"%i line%c (%li-%li)\n",
2011 egysub->lines,
2012 (1==egysub->lines)?' ':'s',
2013 egysub->start,
2014 egysub->end);
2015 for (i=0; i<egysub->lines; i++) {
2016 mp_msg(MSGT_SUBREADER,MSGL_INFO,"\t\t%d: %s%s", i,egysub->text[i], i==egysub->lines-1?"":" \n ");
2018 mp_msg(MSGT_SUBREADER,MSGL_INFO,"\n");
2021 mp_msg(MSGT_SUBREADER,MSGL_INFO,"Subtitle format %s time.\n",
2022 subd->sub_uses_time ? "uses":"doesn't use");
2023 mp_msg(MSGT_SUBREADER,MSGL_INFO,"Read %i subtitles, %i errors.\n", subd->sub_num, subd->sub_errs);
2026 void dump_srt(sub_data* subd, float fps){
2027 int i,j;
2028 int h,m,s,ms;
2029 FILE * fd;
2030 subtitle * onesub;
2031 unsigned long temp;
2032 subtitle *subs = subd->subtitles;
2034 if (!subd->sub_uses_time && sub_fps == 0)
2035 sub_fps = fps;
2036 fd=fopen("dumpsub.srt","w");
2037 if(!fd)
2039 perror("dump_srt: fopen");
2040 return;
2042 for(i=0; i < subd->sub_num; i++)
2044 onesub=subs+i; //=&subs[i];
2045 fprintf(fd,"%d\n",i+1);//line number
2047 temp=onesub->start;
2048 if (!subd->sub_uses_time)
2049 temp = temp * 100 / sub_fps;
2050 temp -= sub_delay * 100;
2051 h=temp/360000;temp%=360000; //h =1*100*60*60
2052 m=temp/6000; temp%=6000; //m =1*100*60
2053 s=temp/100; temp%=100; //s =1*100
2054 ms=temp*10; //ms=1*10
2055 fprintf(fd,"%02d:%02d:%02d,%03d --> ",h,m,s,ms);
2057 temp=onesub->end;
2058 if (!subd->sub_uses_time)
2059 temp = temp * 100 / sub_fps;
2060 temp -= sub_delay * 100;
2061 h=temp/360000;temp%=360000;
2062 m=temp/6000; temp%=6000;
2063 s=temp/100; temp%=100;
2064 ms=temp*10;
2065 fprintf(fd,"%02d:%02d:%02d,%03d\n",h,m,s,ms);
2067 for(j=0;j<onesub->lines;j++)
2068 fprintf(fd,"%s\n",onesub->text[j]);
2070 fprintf(fd,"\n");
2072 fclose(fd);
2073 mp_msg(MSGT_SUBREADER,MSGL_INFO,"SUB: Subtitles dumped in \'dumpsub.srt\'.\n");
2076 void dump_mpsub(sub_data* subd, float fps){
2077 int i,j;
2078 FILE *fd;
2079 float a,b;
2080 subtitle *subs = subd->subtitles;
2082 mpsub_position = subd->sub_uses_time? (sub_delay*100) : (sub_delay*fps);
2083 if (sub_fps==0) sub_fps=fps;
2085 fd=fopen ("dump.mpsub", "w");
2086 if (!fd) {
2087 perror ("dump_mpsub: fopen");
2088 return;
2092 if (subd->sub_uses_time) fprintf (fd,"FORMAT=TIME\n\n");
2093 else fprintf (fd, "FORMAT=%5.2f\n\n", fps);
2095 for(j=0; j < subd->sub_num; j++){
2096 subtitle* egysub=&subs[j];
2097 if (subd->sub_uses_time) {
2098 a=((egysub->start-mpsub_position)/100.0);
2099 b=((egysub->end-egysub->start)/100.0);
2100 if ( (float)((int)a) == a)
2101 fprintf (fd, "%.0f",a);
2102 else
2103 fprintf (fd, "%.2f",a);
2105 if ( (float)((int)b) == b)
2106 fprintf (fd, " %.0f\n",b);
2107 else
2108 fprintf (fd, " %.2f\n",b);
2109 } else {
2110 fprintf (fd, "%ld %ld\n", (long)((egysub->start*(fps/sub_fps))-((mpsub_position*(fps/sub_fps)))),
2111 (long)(((egysub->end)-(egysub->start))*(fps/sub_fps)));
2114 mpsub_position = egysub->end;
2115 for (i=0; i<egysub->lines; i++) {
2116 fprintf (fd, "%s\n",egysub->text[i]);
2118 fprintf (fd, "\n");
2120 fclose (fd);
2121 mp_msg(MSGT_SUBREADER,MSGL_INFO,"SUB: Subtitles dumped in \'dump.mpsub\'.\n");
2124 void dump_microdvd(sub_data* subd, float fps) {
2125 int i, delay;
2126 FILE *fd;
2127 subtitle *subs = subd->subtitles;
2128 if (sub_fps == 0)
2129 sub_fps = fps;
2130 fd = fopen("dumpsub.sub", "w");
2131 if (!fd) {
2132 perror("dumpsub.sub: fopen");
2133 return;
2135 delay = sub_delay * sub_fps;
2136 for (i = 0; i < subd->sub_num; ++i) {
2137 int j, start, end;
2138 start = subs[i].start;
2139 end = subs[i].end;
2140 if (subd->sub_uses_time) {
2141 start = start * sub_fps / 100 ;
2142 end = end * sub_fps / 100;
2144 else {
2145 start = start * sub_fps / fps;
2146 end = end * sub_fps / fps;
2148 start -= delay;
2149 end -= delay;
2150 fprintf(fd, "{%d}{%d}", start, end);
2151 for (j = 0; j < subs[i].lines; ++j)
2152 fprintf(fd, "%s%s", j ? "|" : "", subs[i].text[j]);
2153 fprintf(fd, "\n");
2155 fclose(fd);
2156 mp_msg(MSGT_SUBREADER,MSGL_INFO,"SUB: Subtitles dumped in \'dumpsub.sub\'.\n");
2159 void dump_jacosub(sub_data* subd, float fps) {
2160 int i,j;
2161 int h,m,s,cs;
2162 FILE * fd;
2163 subtitle * onesub;
2164 unsigned long temp;
2165 subtitle *subs = subd->subtitles;
2167 if (!subd->sub_uses_time && sub_fps == 0)
2168 sub_fps = fps;
2169 fd=fopen("dumpsub.jss","w");
2170 if(!fd)
2172 perror("dump_jacosub: fopen");
2173 return;
2175 fprintf(fd, "#TIMERES %d\n", (subd->sub_uses_time) ? 100 : (int)sub_fps);
2176 for(i=0; i < subd->sub_num; i++)
2178 onesub=subs+i; //=&subs[i];
2180 temp=onesub->start;
2181 if (!subd->sub_uses_time)
2182 temp = temp * 100 / sub_fps;
2183 temp -= sub_delay * 100;
2184 h=temp/360000;temp%=360000; //h =1*100*60*60
2185 m=temp/6000; temp%=6000; //m =1*100*60
2186 s=temp/100; temp%=100; //s =1*100
2187 cs=temp; //cs=1*10
2188 fprintf(fd,"%02d:%02d:%02d.%02d ",h,m,s,cs);
2190 temp=onesub->end;
2191 if (!subd->sub_uses_time)
2192 temp = temp * 100 / sub_fps;
2193 temp -= sub_delay * 100;
2194 h=temp/360000;temp%=360000;
2195 m=temp/6000; temp%=6000;
2196 s=temp/100; temp%=100;
2197 cs=temp;
2198 fprintf(fd,"%02d:%02d:%02d.%02d {~} ",h,m,s,cs);
2200 for(j=0;j<onesub->lines;j++)
2201 fprintf(fd,"%s%s",j ? "\\n" : "", onesub->text[j]);
2203 fprintf(fd,"\n");
2205 fclose(fd);
2206 mp_msg(MSGT_SUBREADER,MSGL_INFO,"SUB: Subtitles dumped in \'dumpsub.js\'.\n");
2209 void dump_sami(sub_data* subd, float fps) {
2210 int i,j;
2211 FILE * fd;
2212 subtitle * onesub;
2213 unsigned long temp;
2214 subtitle *subs = subd->subtitles;
2216 if (!subd->sub_uses_time && sub_fps == 0)
2217 sub_fps = fps;
2218 fd=fopen("dumpsub.smi","w");
2219 if(!fd)
2221 perror("dump_jacosub: fopen");
2222 return;
2224 fprintf(fd, "<SAMI>\n"
2225 "<HEAD>\n"
2226 " <STYLE TYPE=\"Text/css\">\n"
2227 " <!--\n"
2228 " 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"
2229 " .SUBTTL {Name: 'Subtitles'; Lang: en-US; SAMIType: CC;}\n"
2230 " -->\n"
2231 " </STYLE>\n"
2232 "</HEAD>\n"
2233 "<BODY>\n");
2234 for(i=0; i < subd->sub_num; i++)
2236 onesub=subs+i; //=&subs[i];
2238 temp=onesub->start;
2239 if (!subd->sub_uses_time)
2240 temp = temp * 100 / sub_fps;
2241 temp -= sub_delay * 100;
2242 fprintf(fd,"\t<SYNC Start=%lu>\n"
2243 "\t <P>", temp * 10);
2245 for(j=0;j<onesub->lines;j++)
2246 fprintf(fd,"%s%s",j ? "<br>" : "", onesub->text[j]);
2248 fprintf(fd,"\n");
2250 temp=onesub->end;
2251 if (!subd->sub_uses_time)
2252 temp = temp * 100 / sub_fps;
2253 temp -= sub_delay * 100;
2254 fprintf(fd,"\t<SYNC Start=%lu>\n"
2255 "\t <P>&nbsp;\n", temp * 10);
2257 fprintf(fd, "</BODY>\n"
2258 "</SAMI>\n");
2259 fclose(fd);
2260 mp_msg(MSGT_SUBREADER,MSGL_INFO,"SUB: Subtitles dumped in \'dumpsub.smi\'.\n");
2263 void sub_free( sub_data * subd )
2265 int i;
2267 if ( !subd ) return;
2269 if (subd->subtitles) {
2270 for (i=0; i < subd->subtitles->lines; i++) free( subd->subtitles->text[i] );
2271 free( subd->subtitles );
2273 if (subd->filename) free( subd->filename );
2274 free( subd );
2277 #ifdef DUMPSUBS
2278 int main(int argc, char **argv) { // for testing
2279 sub_data *subd;
2281 if(argc<2){
2282 printf("\nUsage: subreader filename.sub\n\n");
2283 exit(1);
2285 sub_cp = argv[2];
2286 subd = sub_read_file(argv[1]);
2287 if(!subd){
2288 printf("Couldn't load file.\n");
2289 exit(1);
2292 list_sub_file(subd);
2294 return 0;
2296 #endif