0e76a62d734ee1a044e9376414021c0c33cd7013
[libdcp.git] / src / subtitle_asset.cc
1 /*
2     Copyright (C) 2012-2015 Carl Hetherington <cth@carlh.net>
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include <fstream>
21 #include <cerrno>
22 #include <boost/algorithm/string.hpp>
23 #include <libxml++/nodes/element.h>
24 #include "AS_DCP.h"
25 #include "KM_util.h"
26 #include "subtitle_asset.h"
27 #include "parse/subtitle.h"
28 #include "util.h"
29 #include "xml.h"
30 #include "raw_convert.h"
31
32 using std::string;
33 using std::list;
34 using std::ostream;
35 using std::ofstream;
36 using std::stringstream;
37 using std::cout;
38 using boost::shared_ptr;
39 using boost::optional;
40 using namespace libdcp;
41
42 SubtitleAsset::SubtitleAsset (string directory, string file)
43         : Asset (directory, file)
44         , _need_sort (false)
45 {
46         /* Grotesque hack: we should look in the PKL to see what type this file is;
47            instead we'll look at the first character to decide what to do.
48            I think this is easily fixable (properly) in 1.0.
49         */
50
51         FILE* f = fopen_boost (path(), "r");
52         if (!f) {
53                 throw FileError ("Could not open file for reading", file, errno);
54         }
55         unsigned char test[1];
56         fread (test, 1, 1, f);
57         fclose (f);
58
59         if (test[0] == '<' || test[0] == 0xef) {
60                 read_xml (path().string());
61         } else {
62                 read_mxf (path().string());
63         }
64 }
65
66 SubtitleAsset::SubtitleAsset (string directory, string movie_title, string language)
67         : Asset (directory)
68         , _movie_title (movie_title)
69         , _reel_number ("1")
70         , _language (language)
71         , _need_sort (false)
72 {
73
74 }
75
76 void
77 SubtitleAsset::read_mxf (string mxf_file)
78 {
79         ASDCP::TimedText::MXFReader reader;
80         Kumu::Result_t r = reader.OpenRead (mxf_file.c_str ());
81         if (ASDCP_FAILURE (r)) {
82                 boost::throw_exception (MXFFileError ("could not open MXF file for reading", mxf_file, r));
83         }
84
85         string s;
86         reader.ReadTimedTextResource (s, 0, 0);
87         shared_ptr<cxml::Document> xml (new cxml::Document ("SubtitleReel"));
88         stringstream t;
89         t << s;
90         xml->read_stream (t);
91         read_xml (xml, true);
92 }
93
94 void
95 SubtitleAsset::read_xml (string xml_file)
96 {
97         try {
98                 shared_ptr<cxml::Document> xml (new cxml::Document ("DCSubtitle"));
99                 xml->read_file (xml_file);
100                 read_xml (xml, false);
101         } catch (cxml::Error& e) {
102                 shared_ptr<cxml::Document> xml (new cxml::Document ("SubtitleReel"));
103                 xml->read_file (xml_file);
104                 read_xml (xml, true);
105         }               
106 }
107
108 void
109 SubtitleAsset::read_xml (shared_ptr<cxml::Document> xml, bool smpte)
110 {
111         /* XXX: hacks aplenty in here; need separate parsers for DCSubtitle (Interop) and SubtitleReel (SMPTE) */
112         
113         /* DCSubtitle */
114         optional<string> x = xml->optional_string_child ("SubtitleID");
115         if (!x) {
116                 /* SubtitleReel */
117                 x = xml->optional_string_child ("Id");
118         }
119         _uuid = x.get_value_or ("");
120
121         _movie_title = xml->optional_string_child ("MovieTitle");
122         _reel_number = xml->string_child ("ReelNumber");
123         _language = xml->string_child ("Language");
124
125         optional<int> tcr;
126         if (smpte) {
127                 tcr = xml->optional_number_child<int> ("TimeCodeRate");
128         }
129
130         _load_font_nodes = type_children<libdcp::parse::LoadFont> (xml, "LoadFont");
131
132         /* Now make Subtitle objects to represent the raw XML nodes
133            in a sane way.
134         */
135
136         ParseState parse_state;
137         parse_node (xml->node(), parse_state, tcr);
138 }
139
140 void
141 SubtitleAsset::parse_node (xmlpp::Node* node, ParseState& parse_state, optional<int> tcr)
142 {
143         xmlpp::Node::NodeList children = node->get_children ();
144         for (xmlpp::Node::NodeList::const_iterator i = children.begin(); i != children.end(); ++i) {
145                 xmlpp::ContentNode* c = dynamic_cast<xmlpp::ContentNode *> (*i);
146                 if (c) {
147                         maybe_add_subtitle (c->get_content (), parse_state);
148                 }
149
150                 xmlpp::Element* e = dynamic_cast<xmlpp::Element *> (*i);
151                 if (e) {
152                         cxml::ConstNodePtr n (new cxml::Node (e));
153                         if (n->name() == "Font") {
154                                 parse_state.font_nodes.push_back (shared_ptr<parse::Font> (new parse::Font (n, tcr)));
155                                 parse_node (e, parse_state, tcr);
156                                 parse_state.font_nodes.pop_back ();
157                         } else if (n->name() == "Text") {
158                                 parse_state.text_nodes.push_back (shared_ptr<parse::Text> (new parse::Text (n, tcr)));
159                                 parse_node (e, parse_state, tcr);
160                                 parse_state.text_nodes.pop_back ();
161                         } else if (n->name() == "Subtitle") {
162                                 parse_state.subtitle_nodes.push_back (shared_ptr<parse::Subtitle> (new parse::Subtitle (n, tcr)));
163                                 parse_node (e, parse_state, tcr);
164                                 parse_state.subtitle_nodes.pop_back ();
165                         } else if (n->name() == "SubtitleList") {
166                                 parse_node (e, parse_state, tcr);
167                         }
168                 }
169         }
170 }
171
172 void
173 SubtitleAsset::maybe_add_subtitle (string text, ParseState& parse_state)
174 {
175         if (empty_or_white_space (text)) {
176                 return;
177         }
178         
179         if (parse_state.text_nodes.empty() || parse_state.subtitle_nodes.empty ()) {
180                 return;
181         }
182
183         assert (!parse_state.text_nodes.empty ());
184         assert (!parse_state.subtitle_nodes.empty ());
185         
186         libdcp::parse::Font effective_font (parse_state.font_nodes);
187         libdcp::parse::Text effective_text (*parse_state.text_nodes.back ());
188         libdcp::parse::Subtitle effective_subtitle (*parse_state.subtitle_nodes.back ());
189
190         shared_ptr<Subtitle> c = parse_state.current;
191         if (!c ||
192             effective_subtitle.in != c->in() ||
193             effective_subtitle.out != c->out() ||
194             effective_text.v_position != c->v_position() ||
195             effective_text.v_align != c->v_align() ||
196             effective_text.h_align != c->h_align()) {
197
198                 parse_state.current.reset (
199                         new Subtitle (
200                                 font_id_to_name (effective_font.id),
201                                 effective_font.italic.get(),
202                                 effective_font.color.get(),
203                                 effective_font.size,
204                                 effective_subtitle.in,
205                                 effective_subtitle.out,
206                                 effective_text.v_position,
207                                 effective_text.v_align,
208                                 effective_text.h_align,
209                                 "",
210                                 effective_font.effect ? effective_font.effect.get() : NONE,
211                                 effective_font.effect_color.get(),
212                                 effective_subtitle.fade_up_time,
213                                 effective_subtitle.fade_down_time
214                                 )
215                         );
216                 
217                 _subtitles.push_back (parse_state.current);
218         }
219         
220         if (effective_font.italic.get()) {
221                 parse_state.current->set_text (parse_state.current->text() + "<i>" + text + "</i>");
222         } else {
223                 parse_state.current->set_text (parse_state.current->text() + text);
224         }
225 }
226
227 list<shared_ptr<Subtitle> >
228 SubtitleAsset::subtitles_during (Time from, Time to) const
229 {
230         list<shared_ptr<Subtitle> > s;
231         for (list<shared_ptr<Subtitle> >::const_iterator i = _subtitles.begin(); i != _subtitles.end(); ++i) {
232                 if ((*i)->out() >= from && (*i)->in() <= to) {
233                         s.push_back (*i);
234                 }
235         }
236
237         return s;
238 }
239
240 std::string
241 SubtitleAsset::font_id_to_name (string id) const
242 {
243         list<shared_ptr<libdcp::parse::LoadFont> >::const_iterator i = _load_font_nodes.begin();
244         while (i != _load_font_nodes.end() && (*i)->id != id) {
245                 ++i;
246         }
247
248         if (i == _load_font_nodes.end ()) {
249                 return "";
250         }
251
252         if ((*i)->uri && (*i)->uri.get() == "arial.ttf") {
253                 return "Arial";
254         }
255
256         return "";
257 }
258
259 Subtitle::Subtitle (
260         string font,
261         bool italic,
262         Color color,
263         int size,
264         Time in,
265         Time out,
266         float v_position,
267         VAlign v_align,
268         HAlign h_align,
269         string text,
270         Effect effect,
271         Color effect_color,
272         Time fade_up_time,
273         Time fade_down_time
274         )
275         : _font (font)
276         , _italic (italic)
277         , _color (color)
278         , _size (size)
279         , _in (in)
280         , _out (out)
281         , _v_position (v_position)
282         , _v_align (v_align)
283         , _h_align (h_align)
284         , _text (text)
285         , _effect (effect)
286         , _effect_color (effect_color)
287         , _fade_up_time (fade_up_time)
288         , _fade_down_time (fade_down_time)
289 {
290
291 }
292
293 int
294 Subtitle::size_in_pixels (int screen_height) const
295 {
296         /* Size in the subtitle file is given in points as if the screen
297            height is 11 inches, so a 72pt font would be 1/11th of the screen
298            height.
299         */
300         
301         return _size * screen_height / (11 * 72);
302 }
303
304 bool
305 libdcp::operator== (Subtitle const & a, Subtitle const & b)
306 {
307         return (
308                 a.font() == b.font() &&
309                 a.italic() == b.italic() &&
310                 a.color() == b.color() &&
311                 a.size() == b.size() &&
312                 a.in() == b.in() &&
313                 a.out() == b.out() &&
314                 a.v_position() == b.v_position() &&
315                 a.v_align() == b.v_align() &&
316                 a.h_align() == b.h_align() &&
317                 a.text() == b.text() &&
318                 a.effect() == b.effect() &&
319                 a.effect_color() == b.effect_color() &&
320                 a.fade_up_time() == b.fade_up_time() &&
321                 a.fade_down_time() == b.fade_down_time()
322                 );
323 }
324
325 ostream&
326 libdcp::operator<< (ostream& s, Subtitle const & sub)
327 {
328         s << "\n`" << sub.text() << "' from " << sub.in() << " to " << sub.out() << ";\n"
329           << "fade up " << sub.fade_up_time() << ", fade down " << sub.fade_down_time() << ";\n"
330           << "font " << sub.font() << ", ";
331
332         if (sub.italic()) {
333                 s << "italic";
334         } else {
335                 s << "non-italic";
336         }
337         
338         s << ", size " << sub.size() << ", color " << sub.color()
339           << ", vpos " << sub.v_position() << ", valign " << ((int) sub.v_align()) << ", halign " << ((int) sub.h_align()) << "; "
340           << "effect " << ((int) sub.effect()) << ", effect color " << sub.effect_color();
341
342         return s;
343 }
344
345 void
346 SubtitleAsset::add (shared_ptr<Subtitle> s)
347 {
348         _subtitles.push_back (s);
349         _need_sort = true;
350 }
351
352 void
353 SubtitleAsset::write_to_cpl (xmlpp::Element* node) const
354 {
355         /* XXX: should EditRate, Duration and IntrinsicDuration be in here? */
356
357         xmlpp::Node* ms = node->add_child ("MainSubtitle");
358         ms->add_child("Id")->add_child_text("urn:uuid:" + _uuid);
359         ms->add_child("AnnotationText")->add_child_text (_file_name.string ());
360         /* XXX */
361         ms->add_child("EntryPoint")->add_child_text ("0");
362 }
363
364 struct SubtitleSorter {
365         bool operator() (shared_ptr<Subtitle> a, shared_ptr<Subtitle> b) {
366                 if (a->in() != b->in()) {
367                         return a->in() < b->in();
368                 }
369                 return a->v_position() < b->v_position();
370         }
371 };
372
373 void
374 SubtitleAsset::write_xml () const
375 {
376         FILE* f = fopen_boost (path (), "r");
377         Glib::ustring const s = xml_as_string ();
378         fwrite (s.c_str(), 1, s.length(), f);
379         fclose (f);
380 }
381
382 Glib::ustring
383 SubtitleAsset::xml_as_string () const
384 {
385         xmlpp::Document doc;
386         xmlpp::Element* root = doc.create_root_node ("DCSubtitle");
387         root->set_attribute ("Version", "1.0");
388
389         root->add_child("SubtitleID")->add_child_text (_uuid);
390         if (_movie_title) {
391                 root->add_child("MovieTitle")->add_child_text (_movie_title.get ());
392         }
393         root->add_child("ReelNumber")->add_child_text (raw_convert<string> (_reel_number));
394         root->add_child("Language")->add_child_text (_language);
395
396         if (_load_font_nodes.size() > 1) {
397                 boost::throw_exception (MiscError ("multiple LoadFont nodes not supported"));
398         }
399
400         if (!_load_font_nodes.empty ()) {
401                 xmlpp::Element* load_font = root->add_child("LoadFont");
402                 load_font->set_attribute("Id", _load_font_nodes.front()->id);
403                 if (_load_font_nodes.front()->uri) {
404                         load_font->set_attribute("URI",  _load_font_nodes.front()->uri.get ());
405                 }
406         }
407
408         list<shared_ptr<Subtitle> > sorted = _subtitles;
409         if (_need_sort) {
410                 sorted.sort (SubtitleSorter ());
411         }
412
413         /* XXX: multiple fonts not supported */
414         /* XXX: script, underlined, weight not supported */
415
416         bool italic = false;
417         Color color;
418         int size = 0;
419         Effect effect = NONE;
420         Color effect_color;
421         int spot_number = 1;
422         Time last_in;
423         Time last_out;
424         Time last_fade_up_time;
425         Time last_fade_down_time;
426
427         xmlpp::Element* font = 0;
428         xmlpp::Element* subtitle = 0;
429
430         for (list<shared_ptr<Subtitle> >::iterator i = sorted.begin(); i != sorted.end(); ++i) {
431
432                 /* We will start a new <Font>...</Font> whenever some font property changes.
433                    I suppose we should really make an optimal hierarchy of <Font> tags, but
434                    that seems hard.
435                 */
436
437                 bool const font_changed =
438                         italic       != (*i)->italic()       ||
439                         color        != (*i)->color()        ||
440                         size         != (*i)->size()         ||
441                         effect       != (*i)->effect()       ||
442                         effect_color != (*i)->effect_color();
443
444                 if (font_changed) {
445                         italic = (*i)->italic ();
446                         color = (*i)->color ();
447                         size = (*i)->size ();
448                         effect = (*i)->effect ();
449                         effect_color = (*i)->effect_color ();
450                 }
451
452                 if (!font || font_changed) {
453                         font = root->add_child ("Font");
454                         string id = "theFontId";
455                         if (!_load_font_nodes.empty()) {
456                                 id = _load_font_nodes.front()->id;
457                         }
458                         font->set_attribute ("Id", id);
459                         font->set_attribute ("Italic", italic ? "yes" : "no");
460                         font->set_attribute ("Color", color.to_argb_string());
461                         font->set_attribute ("Size", raw_convert<string> (size));
462                         font->set_attribute ("Effect", effect_to_string (effect));
463                         font->set_attribute ("EffectColor", effect_color.to_argb_string());
464                         font->set_attribute ("Script", "normal");
465                         font->set_attribute ("Underlined", "no");
466                         font->set_attribute ("Weight", "normal");
467                 }
468
469                 if (!subtitle || font_changed ||
470                     (last_in != (*i)->in() ||
471                      last_out != (*i)->out() ||
472                      last_fade_up_time != (*i)->fade_up_time() ||
473                      last_fade_down_time != (*i)->fade_down_time()
474                             )) {
475
476                         subtitle = font->add_child ("Subtitle");
477                         subtitle->set_attribute ("SpotNumber", raw_convert<string> (spot_number++));
478                         subtitle->set_attribute ("TimeIn", (*i)->in().to_string());
479                         subtitle->set_attribute ("TimeOut", (*i)->out().to_string());
480                         subtitle->set_attribute ("FadeUpTime", raw_convert<string> ((*i)->fade_up_time().to_editable_units(250)));
481                         subtitle->set_attribute ("FadeDownTime", raw_convert<string> ((*i)->fade_down_time().to_editable_units(250)));
482
483                         last_in = (*i)->in ();
484                         last_out = (*i)->out ();
485                         last_fade_up_time = (*i)->fade_up_time ();
486                         last_fade_down_time = (*i)->fade_down_time ();
487                 }
488
489                 xmlpp::Element* text = subtitle->add_child ("Text");
490                 text->set_attribute ("VAlign", valign_to_string ((*i)->v_align()));             
491                 text->set_attribute ("HAlign", halign_to_string ((*i)->h_align()));
492                 text->set_attribute ("VPosition", raw_convert<string> ((*i)->v_position()));
493                 text->add_child_text ((*i)->text());
494         }
495
496         return doc.write_to_string_formatted ("UTF-8");
497 }
498