Debian Codegraph @

lib/subtitle/subread.c

raw
1 #include "config.h"
2 #include "subtitle.h"
3 #include <ctype.h>
4 #include <string.h>
5 #include <stdlib.h>
6 #include <stdio.h>
7 #include <langinfo.h>
8
9 #include <sys/types.h>
10 #include <sys/stat.h>
11 #include <fcntl.h>
12 #include <assert.h>
13
14 #ifdef HAVE_ICONV
15 #include <iconv.h>
16 #include <errno.h>
17 #endif
18
19 static void skip_to_eol(FILE* file)
20 {
21 int c;
22
23 while ((c = fgetc(file)) && (c == '\r' || c == '\n'))
24 ;
25 ungetc(c, file);
26 }
27
28 static inline char* skip_spaces(char* buf)
29 {
30 while (*buf && isspace((int)*buf))
31 buf++;
32
33 return buf;
34 }
35
36 static inline char* trim_spaces(char* buf)
37 {
38 char* e = buf = skip_spaces(buf);
39 // move to the end of buffer
40 while (*e)
41 e++;
42
43 while (e > buf && isspace((int)e[-1]))
44 e--;
45 *e = 0;
46 return buf;
47 }
48
49 static inline void trim_http(char* buf)
50 {
51 enum { NORMAL, HTTP } state = NORMAL;
52 char* e = buf;
53 char* d = buf;
54
55 while (*e) {
56 if (*e == '<' && (toupper(e[1]) == 'I' || e[1] == '/'))
57 state = HTTP;
58 else if (state == HTTP)
59 {
60 if (*e == '>')
61 state = NORMAL;
62 }
63 else
64 *d++ = *e;
65 e++;
66 }
67 *d = 0;
68 }
69
70 static inline unsigned get_subtime(unsigned sh, unsigned sm, unsigned ss, unsigned su)
71 {
72 return ((sh * 60 + sm) * 60 + ss) * 1000 + su;
73 }
74
75 // read line and remove window \r character from it
76 static char* read_line(char* buf, size_t size, FILE* file)
77 {
78 unsigned pos = 0;
79 size--;
80 while (pos < size)
81 {
82 int c = fgetc(file);
83 if (c == EOF)
84 {
85 if (pos == 0)
86 return 0; // no new line available EOF
87 break;
88 }
89 if (c == '\n')
90 break; // we have line
91 if (c != '\r')
92 buf[pos++] = (char)c;
93 }
94 buf[pos] = 0;
95 return buf;
96 }
97
98 static void add_line(subtitles_t* l, subtitle_line_t* sl, char *txt)
99 {
100 if (sl->lines < SUBTITLE_MAX_LINES && txt)
101 {
102 size_t n;
103 char* t;
104 char* b = trim_spaces(txt);
105 trim_http(b);
106
107 // skip color and font-style change - not supported right now
108 // {c:$00ffff} {y:i}
109 if ((t = strchr(b, '{')))
110 {
111 int u = toupper(t[1]);
112 if ((u == 'C' || u == 'Y') && t[2] == ':'
113 && (t = strchr(t + 3, '}')))
114 b = t + 1;
115 }
116
117 n = strlen(b);
118
119 if (sl->lines > 0 || n > 0)
120 {
121 size_t sz = n + 1;
122 char* e;
123 #ifdef HAVE_ICONV
124 char local[1024]; // at most this chars per line
125 char* out_p = local;
126 iconv_t icvsts = iconv_open("UTF-8", l->encoding);
127 if (icvsts != (iconv_t)(-1)) {
128 char* in_p = b;
129 size_t in_size = n;
130 size_t out_size = sizeof(local) - 1;
131 if (-1 == iconv(icvsts, (ICONV_CONST_CAST char**) &in_p, &in_size, &out_p, &out_size))
132 {
133 printf("subtitles: iconv convert error %s %s\n", b, strerror(errno));
134 }
135 iconv_close(icvsts);
136 //printf("SZ %d -> %d (%s)\n", (int)sz, (int)(out_p - b + 1), l->encoding);
137 b = local;
138 sz = (size_t)(out_p - b + 1);
139 }
140 else
141 printf("subtitles: iconv open error\n");
142 #endif
143
144 e = (char*) malloc(sz);
145 if (e)
146 {
147 memcpy(e, b, sz - 1);
148 e[sz - 1] = 0;
149 sl->line[sl->lines++] = e;
150 }
151 }
152 }
153 else
154 printf("Too many subtitle lines: %d ignoring: %s\n", sl->lines, txt);
155
156 if (sl->end < sl->start)
157 // some subtitles end with {XX}{0} - confusing our searcher
158 sl->end = sl->start + 1;
159 //printf("ADDLINE %d >%s< %d %d\n", l->lines, txt, l->start, l->end);
160 }
161
162 static void add_line_columned(subtitles_t* l, subtitle_line_t* sl, char* text)
163 {
164 char* s;
165 while ((s = strchr(text, '|')))
166 {
167 //printf("text %s %p\n", text, s);
168 *s++ = 0;
169 add_line(l, sl, text);
170 text = s;
171 }
172
173 add_line(l, sl, text);
174 }
175
176 static void add_sub_line(subtitles_t* l, subtitle_line_t* sl)
177 {
178
179 if (l->allocated <= (l->count + 1))
180 {
181 l->allocated += 200;
182 //printf("Realloc %p %d\n", l->subtitle, sizeof(*sl) * l->allocated);
183 l->subtitle = (subtitle_line_t*) realloc(l->subtitle, sizeof(*sl) * l->allocated);
184 }
185
186 if (l->subtitle)
187 {
188 if (l->count > 0)
189 {
190 // this trick is for weird subtitles
191 // i.e. joined two files subtitles from 2 CDs
192 sl->start = (unsigned int)(sl->start + l->time_diff);
193 sl->end = (unsigned int)(sl->start + l->time_diff);
194 if (l->subtitle[l->count - 1].end > sl->start)
195 {
196 //printf("TIMEDIFF %d %d s:%d e:%d\n", l->time_diff, sl->start, l->subtitle[l->count - 1].start, l->subtitle[l->count - 1].end);
197 if (l->subtitle[l->count - 1].start < sl->start)
198 l->subtitle[l->count - 1].end = sl->start - 1;
199
200 l->time_diff = l->subtitle[l->count - 1].end - sl->start;
201 if (l->time_diff < 1000000)
202 {
203 l->time_diff = 0;
204 //return; // discard
205 }
206 //printf("TM %d %s\n", l->time_diff, sl->line[0]);
207 }
208 }
209 memcpy(&l->subtitle[l->count], sl, sizeof(*sl));
210 l->count++;
211 }
212 }
213
214 typedef enum {
215 SAMI_START,
216 SAMI_P,
217 SAMI_INSIDE_P,
218 SAMI_TEXT,
219 SAMI_SKIP,
220 SAMI_END
221 } sami_state_t;
222
223 /**
224 * parse one line of SAMI subtitles
225 * \return new state
226 */
227 static sami_state_t parse_SAMI(subtitles_t* l, subtitle_line_t* sl, char* s,
228 sami_state_t state, char* temp)
229 {
230 char* p = temp + strlen(temp);
231
232 do
233 {
234 char* q;
235 //printf("SAMI %d %s\n", state, s);
236 switch (state) {
237
238 case SAMI_START: /* find "START=" */
239 if ((s = strstr(s, "Start=")))
240 {
241 sl->start = (unsigned)strtol(s + 6, &s, 0);
242 state = SAMI_P;
243 continue;
244 }
245 break;
246 case SAMI_P: /* find "<P" */
247 if ((s = strstr(s, "<P")))
248 {
249 s += 2;
250 state = SAMI_INSIDE_P;
251 continue;
252 }
253 break;
254 case SAMI_INSIDE_P: /* find ">" */
255 if ((s = strchr(s, '>')))
256 {
257 s++;
258 p = temp;
259 state = SAMI_TEXT;
260 continue;
261 }
262 break;
263 case SAMI_TEXT: /* get all text until '<' appears */
264 if (*s == '<')
265 state = SAMI_SKIP;
266 else if (!strncasecmp(s, "&nbsp;", 6))
267 {
268 *p++ = ' ';
269 s += 6;
270 }
271 else if (!strncasecmp(s, "<br>", 4) || *s == 0)
272 {
273 *p = 0;
274 add_line(l, sl, temp);
275 p = temp;
276 if (*s == 0)
277 break;
278 s += 4; // <br>
279 }
280 else
281 *p++ = *s++; // copy
282 continue;
283
284 case SAMI_SKIP: /* get end or skip <TAG> */
285 q = strstr(s, "Start=");
286 if (q) {
287 sl->end = (unsigned)strtol(q + 6, &q, 0) - 1;
288 *p = 0;
289 state = SAMI_END; // finished one subtitle
290 break;
291 }
292 s = strchr(s, '>');
293 if (s)
294 {
295 s++;
296 state = SAMI_TEXT;
297 continue;
298 }
299 break;
300 case SAMI_END:
301 assert(1 == 0); // never happens
302 }
303 // when we get here we need next line
304 } while (0);
305 *p = 0;
306 return state;
307 }
308
309
310 #define IS_SUB(type) (!stype || (stype == type))
311
312 #define SHOWSUBTIME 5 /* approx. 5 seconds */
313
314 static void subtitle_reread(subtitles_t* l)
315 {
316 unsigned dummy, sh, sm, ss, su, eh, em, es, eu;
317 int c = 0;
318 int line = 0;
319 subtitle_t stype = SUBTITLE_UNSELECTED;
320 char bfr[1024];
321 fpos_t fpos;
322 int tdiff = 0;
323 float mpsub_position = 0;
324
325 FILE* file = fdopen(l->fd, "rt");
326 if (!file)
327 {
328 perror("subtitle open:");
329 return;
330 }
331
332 // ORDER OF 'if's IS IMPORTANT!!!!!
333 // this piece of code seem to be looking a bit complicated
334 // but it is quite efficient and allows to read even subtitles
335 // with different types in the same file :) (not very useful thought :))
336
337 while (read_line(bfr, sizeof(bfr), file))
338 {
339 subtitle_line_t sl;
340 int n = 0;
341
342 memset(&sl, 0, sizeof(sl));
343 //printf("LINE %d %d %s\n", line, stype, bfr);
344 // MicroDVD (.sub)
345 if (IS_SUB(SUBTITLE_MICRODVD))
346 {
347 if (sscanf(bfr, "{%d}{%d}%n", &sl.start, &sl.end, &n) == 2)
348 {
349 stype = SUBTITLE_MICRODVD;
350
351 if (sl.end < sl.start)
352 {
353 if (l->fps > 0. && sl.end / l->fps > SHOWSUBTIME)
354 sl.end = SHOWSUBTIME;
355 sl.end = sl.start + (unsigned)(sl.end * l->fps);
356 }
357 add_line_columned(l, &sl, bfr + n);
358 skip_to_eol(file);
359 }
360 else if (sscanf(bfr, "{%d}{}%n", &sl.start, &n) == 1)
361 {
362 stype = SUBTITLE_MICRODVD;
363
364 sl.end = sl.start + (unsigned)(SHOWSUBTIME * l->fps);
365 add_line_columned(l, &sl, bfr + n);
366 skip_to_eol(file);
367 }
368 }
369
370 // SubRipper
371 if (IS_SUB(SUBTITLE_SUBRIP)
372 && sscanf(bfr, "%d:%d:%d.%d,%d:%d:%d.%d",
373 &sh, &sm, &ss, &su, &eh, &em, &es, &eu) == 8)
374 {
375 stype = SUBTITLE_SUBRIP;
376
377 sl.start = get_subtime(sh, sm, ss, su);
378 sl.end = get_subtime(eh, em, es, eu);
379 // now there can be 0, 1 or 2 lines of subtitles... ended by a newline
380 while (read_line(bfr, sizeof(bfr), file))
381 {
382 // we skip whitespace and check whether the line's empty
383 char* p = skip_spaces(bfr);
384 char* out;
385 if (*p == '\0')
386 break; // this was a blank line -> end of titles here
387
388 // replace [br] [BR] -> |
389 out = p = bfr;
390 while (*p != 0)
391 {
392 if (!strncasecmp(p, "[br]", 4))
393 {
394 *p = 0;
395 p += 4;
396 add_line(l, &sl, out);
397 out = p;
398 }
399 else
400 p++;
401 }
402 if (out < p)
403 add_line(l, &sl, out);
404 }
405 }
406
407 // vplayer format
408 if (IS_SUB(SUBTITLE_VPLAYER)
409 && sscanf(bfr, "%d:%d:%d:%n", &sh, &sm, &ss, &n) == 3)
410 {
411 stype = SUBTITLE_VPLAYER;
412
413 sl.start = get_subtime(sh, sm, ss, 0);
414 sl.end = sl.start + SHOWSUBTIME * 1000;
415
416 add_line_columned(l, &sl, &bfr[n]);
417 skip_to_eol(file);
418 }
419
420 // Aqt (not sure who this is supposed to work)
421 if (IS_SUB(SUBTITLE_AQT)
422 && sscanf(bfr, "-->> %d", &sl.start) == 1)
423 {
424 int lineadded = 0;
425 unsigned chr = 0;
426 stype = SUBTITLE_AQT;
427
428 while (read_line(bfr, sizeof(bfr), file))
429 {
430 // we skip whitespace and check whether the line's empty
431 if (lineadded)
432 {
433 char *p = skip_spaces(bfr);
434 if (*p == '\0')
435 break; // this was a blank line -> end of titles here
436 }
437 // line's not empty, we add as much as we can to name
438 add_line(l, &sl, bfr);
439 chr += (unsigned)strlen(bfr);
440 lineadded = 1;
441 }
442 sl.end = sl.start + chr * 5;
443 }
444
445 // SAMI (.smi)
446 if (IS_SUB(SUBTITLE_SAMI)
447 && (stype || strstr(bfr, "SAMI")))
448 {
449 char temp[sizeof(bfr)];
450 sami_state_t state = SAMI_START;
451 stype = SUBTITLE_SAMI;
452 for (;;)
453 {
454 state = parse_SAMI(l, &sl, bfr, state, temp);
455 if (state == SAMI_END)
456 {
457 fsetpos(file, &fpos); // back to the begining of the current line
458 break;
459 }
460 fgetpos(file, &fpos);
461 if (!read_line(bfr, sizeof(bfr), file))
462 break;
463 }
464 if (feof(file))
465 break;
466 fgetpos(file, &fpos);
467 }
468 // OldSubViewer (.srt) {%d:%d:%d}{%d:%d:%d}
469 // SubViewer (.srt)
470 if (IS_SUB(SUBTITLE_SUBVIEWER)
471 && sscanf(bfr, "%d", &dummy) == 1)
472 {
473 // Skip this buffer with only one number
474 // this should be tested as last case
475 // as it destructs the line in buffer !!!
476 missnl:
477 if (read_line(bfr, sizeof(bfr), file)
478 // sscanf(bfr, "%02d%*c%02d%*c%02d%*c%03d --> %d:%d:%d,%d",
479 && sscanf(bfr, "%d:%d:%d,%d --> %d:%d:%d,%d",
480 &sh, &sm, &ss, &su, &eh, &em, &es, &eu) == 8)
481 {
482 int lineadded = 0;
483
484 stype = SUBTITLE_SUBVIEWER;
485 sl.start = get_subtime(sh, sm, ss, su);
486 sl.end = get_subtime(eh, em, es, eu);
487 // now there can be 0, 1 or 2 lines of subtitles...
488 // usually ended by a newline - but sometime this new line is missing
489 while (read_line(bfr, sizeof(bfr), file))
490 {
491 unsigned dummy1;
492 // we skip whitespace and check whether the line's empty
493 if (lineadded)
494 {
495 char* p = skip_spaces(bfr);
496 if (*p == '\0')
497 break; // this was a blank line -> end of titles here
498 }
499 // if line's not empty, we add as much as we can to name
500 // but we check if there is not begin of the new subtitle
501 if (sscanf(bfr, "%u", &dummy1) == 1 && ((dummy + 1) == dummy1))
502 {
503 int i;
504 //printf("DUMM %d %d\n", dummy, dummy1);
505 dummy = dummy1;
506 add_sub_line(l, &sl);
507 for (i = 0; i < sl.lines; i++)
508 sl.line[i] = NULL;
509 // no freeing lines -just reset counter
510 sl.lines = 0;
511 goto missnl;
512 }
513 add_line(l, &sl, bfr);
514 lineadded = 1;
515 }
516 }
517 }
518 if (IS_SUB(SUBTITLE_MPSUB)
519 && (stype || strstr(bfr, "FORMAT=TIME")
520 //|| (stype = SUBTIsscanf(line, "FORMAT=%d", &i) == 1)
521 ))
522 {
523 float a, b;
524
525 stype = SUBTITLE_MPSUB;
526
527 if (sscanf(bfr, "%f %f", &a, &b) == 2)
528 {
529 int lineadded = 0;
530 mpsub_position += a * 1000.f;
531 sl.start = (unsigned)mpsub_position;
532 mpsub_position += b * 1000.f;
533 sl.end = (unsigned)mpsub_position;
534 while (read_line(bfr, sizeof(bfr), file))
535 {
536 // we skip whitespace and check whether the line's empty
537 if (lineadded)
538 {
539 char *p = skip_spaces(bfr);
540 if (*p == '\0')
541 break; // this was a blank line -> end of titles here
542 }
543 add_line(l, &sl, bfr);
544 lineadded = 1;
545 }
546 }
547 }
548 if (!stype)
549 {
550 unsigned errch = 0;
551 unsigned i;
552 for (i = 0; bfr[i]; i++)
553 {
554 if (bfr[i] < ' ' && bfr[i] != '\t')
555 errch++;
556 }
557 if (errch > 10)
558 break; // these are not ASCII subtitles
559 //printf("ERR %d %d\n", errch, i);
560
561 if (line++ > 100)
562 break; // at most 100 unidentified lines
563 }
564 if (sl.lines > 0)
565 add_sub_line(l, &sl);
566 }
567
568 fclose(file);
569
570 l->type = stype;
571 switch (stype)
572 {
573 case SUBTITLE_MICRODVD:
574 /* formats which are using frames */
575 l->frame_based = 1;
576 break;
577 default:
578 l->frame_based = 0;
579 }
580 }
581
582 // SubRip example
583 //
584 // [INFORMATION]
585 // [TITLE]Me, myself and Irene
586 // [AUTHOR]Mysak
587 // [SOURCE]Subtitles captured by SubRip 0.93b
588 // [PRG]
589 // [FILEPATH]
590 // [DELAY]0
591 // [CD TRACK]0
592 // [COMMENT]
593 // [END INFORMATION]
594 // [SUBTITLE]
595 // [COLF]&HFFFFFF,[STYLE]bd,[SIZE]18,[FONT]Arial
596 // 00:00:01.02,00:00:07.00
597 // Titulky beta verze by My..
598 //
599 // 00:00:07.03,00:00:10.59
600 // text[br]text
601
602 static int test_filename_suffix(const char* filename, char** f)
603 {
604 const char const exts[][5] =
605 {
606 "",
607 ".sub", ".SUB",
608 ".srt", ".SRT",
609 ".txt", ".TXT",
610 ".aqt", ".AQT",
611 ".smi", ".SMI",
612 ".utf", ".UTF",
613 /*".rt", ".RT",
614 ".ssa", ".SSA",*/
615 "!"
616 };
617
618 int fd;
619 int i;
620 size_t n = strlen(filename);
621 char* fn = (char*) malloc(n + 8);
622
623 if (!fn)
624 return -1;
625
626 fd = -1;
627 for (i = 0; fd < 0 && exts[i][0] != '!'; i++)
628 {
629 strcpy(fn, filename);
630 strcpy(fn + n, exts[i]);
631
632 //printf("test %s %s %s\n", fn, filename, *s);
633 fd = open(fn, O_RDONLY);
634 }
635
636 if (fd >= 0 && f)
637 {
638 free(*f);
639 *f = fn;
640 }
641 else
642 free(fn);
643 return fd;
644 }
645
646
647 /*
648 * create name for subtitle file
649 */
650 int subtitle_filename(const char* filename, char** opened_filename)
651 {
652 int fd;
653 char* fn, *fdup;
654 unsigned long n;
655
656 if (!filename)
657 return -1;
658
659 if ((fd = test_filename_suffix(filename, opened_filename)) >= 0)
660 return fd;
661 /* try to cut .suffix */
662 if (!(fdup = strrchr(filename, '.')) || strchr(fdup, '/'))
663 return fd;
664
665 n = (unsigned long)(fdup - filename);
666 if (!(fdup = (char*) malloc(n + 1)))
667 return -1;
668
669 memcpy(fdup, filename, n);
670 fdup[n] = 0;
671
672 fd = test_filename_suffix(fdup, opened_filename);
673 free(fdup);
674
675 return fd;
676 }
677
678 subtitles_t* subtitle_open(int fd, double fps, const char* enc)
679 {
680 char* subname;
681 subtitles_t* l = (subtitles_t*) malloc(sizeof(*l));
682 if (!l)
683 return NULL;
684 memset(l, 0, sizeof(*l));
685
686 l->fd = fd;
687 l->fps = fps;
688 if (!enc || strstr(enc, "default"))
689 enc = nl_langinfo(CODESET);
690 l->encoding = strdup(enc);
691 subtitle_reread(l);
692
693 return l;
694 }