2 Copyright (C) 2014-2016 Carl Hetherington <cth@carlh.net>
4 This file is part of DCP-o-matic.
6 DCP-o-matic is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
11 DCP-o-matic is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with DCP-o-matic. If not, see <http://www.gnu.org/licenses/>.
21 #include "text_subtitle.h"
23 #include "exceptions.h"
24 #include "text_subtitle_content.h"
25 #include <sub/subrip_reader.h>
26 #include <sub/ssa_reader.h>
27 #include <sub/collect.h>
28 #include <unicode/ucsdet.h>
29 #include <unicode/ucnv.h>
37 using boost::shared_ptr;
38 using boost::scoped_array;
41 TextSubtitle::TextSubtitle (shared_ptr<const TextSubtitleContent> content)
43 Data in (content->path (0));
45 UErrorCode status = U_ZERO_ERROR;
46 UCharsetDetector* detector = ucsdet_open (&status);
47 ucsdet_setText (detector, reinterpret_cast<const char *> (in.data().get()), in.size(), &status);
49 UCharsetMatch const * match = ucsdet_detect (detector, &status);
50 char const * in_charset = ucsdet_getName (match, &status);
52 UConverter* to_utf16 = ucnv_open (in_charset, &status);
53 /* This is a guess; I think we should be able to encode any input in 4 times its input size */
54 scoped_array<uint16_t> utf16 (new uint16_t[in.size() * 2]);
55 int const utf16_len = ucnv_toUChars (
56 to_utf16, reinterpret_cast<UChar*>(utf16.get()), in.size() * 2,
57 reinterpret_cast<const char *> (in.data().get()), in.size(),
61 UConverter* to_utf8 = ucnv_open ("UTF-8", &status);
63 scoped_array<char> utf8 (new char[utf16_len * 2]);
64 ucnv_fromUChars (to_utf8, utf8.get(), utf16_len * 2, reinterpret_cast<UChar*>(utf16.get()), utf16_len, &status);
66 ucsdet_close (detector);
67 ucnv_close (to_utf16);
70 sub::Reader* reader = 0;
72 if (content->path(0).extension() == ".srt" || content->path(0).extension() == ".SRT") {
73 reader = new sub::SubripReader (utf8.get());
74 } else if (content->path(0).extension() == ".ssa" || content->path(0).extension() == ".SSA") {
75 reader = new sub::SSAReader (utf8.get());
79 _subtitles = sub::collect<vector<sub::Subtitle> > (reader->subtitles ());
86 TextSubtitle::length () const
88 if (_subtitles.empty ()) {
89 return ContentTime ();
92 return ContentTime::from_seconds (_subtitles.back().to.all_as_seconds ());