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