Support reading of encrypted subtitles.
[libdcp.git] / src / subtitle_asset.cc
index 89269fb039afeac18e973c81a6c23b2f643f0491..b9f6336c594928d09c6990aeaf035e2f37c936dd 100644 (file)
 /*
-    Copyright (C) 2012 Carl Hetherington <cth@carlh.net>
+    Copyright (C) 2012-2015 Carl Hetherington <cth@carlh.net>
 
-    This program is free software; you can redistribute it and/or modify
+    This file is part of libdcp.
+
+    libdcp is free software; you can redistribute it and/or modify
     it under the terms of the GNU General Public License as published by
     the Free Software Foundation; either version 2 of the License, or
     (at your option) any later version.
 
-    This program is distributed in the hope that it will be useful,
+    libdcp is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     GNU General Public License for more details.
 
     You should have received a copy of the GNU General Public License
-    along with this program; if not, write to the Free Software
-    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
-
+    along with libdcp.  If not, see <http://www.gnu.org/licenses/>.
+
+    In addition, as a special exception, the copyright holders give
+    permission to link the code of portions of this program with the
+    OpenSSL library under certain conditions as described in each
+    individual source file, and distribute linked combinations
+    including the two.
+
+    You must obey the GNU General Public License in all respects
+    for all of the code used other than OpenSSL.  If you modify
+    file(s) with this exception, you may extend this exception to your
+    version of the file(s), but you are not obligated to do so.  If you
+    do not wish to do so, delete this exception statement from your
+    version.  If you delete this exception statement from all source
+    files in the program, then also delete it here.
 */
 
-#include <fstream>
-#include <cerrno>
-#include <boost/algorithm/string.hpp>
-#include <libxml++/nodes/element.h>
-#include "AS_DCP.h"
-#include "KM_util.h"
+#include "raw_convert.h"
 #include "subtitle_asset.h"
-#include "parse/subtitle.h"
 #include "util.h"
 #include "xml.h"
-#include "raw_convert.h"
+#include "font_node.h"
+#include "text_node.h"
+#include "subtitle_string.h"
+#include "dcp_assert.h"
+#include <asdcp/AS_DCP.h>
+#include <asdcp/KM_util.h>
+#include <libxml++/nodes/element.h>
+#include <boost/algorithm/string.hpp>
+#include <boost/shared_array.hpp>
+#include <boost/foreach.hpp>
 
 using std::string;
 using std::list;
-using std::ostream;
-using std::ofstream;
-using std::stringstream;
 using std::cout;
+using std::cerr;
+using std::map;
 using boost::shared_ptr;
+using boost::shared_array;
 using boost::optional;
-using namespace libdcp;
-
-SubtitleAsset::SubtitleAsset (string directory, string file)
-       : Asset (directory, file)
-       , _need_sort (false)
-{
-       /* Grotesque hack: we should look in the PKL to see what type this file is;
-          instead we'll look at the first character to decide what to do.
-          I think this is easily fixable (properly) in 1.0.
-       */
-
-       FILE* f = fopen_boost (path(), "r");
-       if (!f) {
-               throw FileError ("Could not open file for reading", file, errno);
-       }
-       unsigned char test[1];
-       fread (test, 1, 1, f);
-       fclose (f);
-
-       if (test[0] == '<' || test[0] == 0xef) {
-               read_xml (path().string());
-       } else {
-               read_mxf (path().string());
-       }
-}
+using boost::dynamic_pointer_cast;
+using namespace dcp;
 
-SubtitleAsset::SubtitleAsset (string directory, string movie_title, string language)
-       : Asset (directory)
-       , _movie_title (movie_title)
-       , _reel_number ("1")
-       , _language (language)
-       , _need_sort (false)
+SubtitleAsset::SubtitleAsset ()
 {
 
 }
 
-void
-SubtitleAsset::read_mxf (string mxf_file)
+SubtitleAsset::SubtitleAsset (boost::filesystem::path file)
+       : Asset (file)
 {
-       ASDCP::TimedText::MXFReader reader;
-       Kumu::Result_t r = reader.OpenRead (mxf_file.c_str ());
-       if (ASDCP_FAILURE (r)) {
-               boost::throw_exception (MXFFileError ("could not open MXF file for reading", mxf_file, r));
-       }
 
-       string s;
-       reader.ReadTimedTextResource (s, 0, 0);
-       shared_ptr<cxml::Document> xml (new cxml::Document ("SubtitleReel"));
-       stringstream t;
-       t << s;
-       xml->read_stream (t);
-       read_xml (xml);
 }
 
 void
-SubtitleAsset::read_xml (string xml_file)
+SubtitleAsset::parse_subtitles (
+       shared_ptr<cxml::Document> xml,
+       list<shared_ptr<dcp::FontNode> > font_nodes,
+       list<shared_ptr<dcp::SubtitleNode> > subtitle_nodes
+       )
 {
-       shared_ptr<cxml::Document> xml (new cxml::Document ("DCSubtitle"));
-       xml->read_file (xml_file);
-       read_xml (xml);
+       /* Make Subtitle objects to represent the raw XML nodes in a sane way */
+       ParseState parse_state;
+       examine_nodes (xml, font_nodes, parse_state);
+       examine_nodes (xml, subtitle_nodes, parse_state);
 }
 
 void
-SubtitleAsset::read_xml (shared_ptr<cxml::Document> xml)
+SubtitleAsset::examine_nodes (
+       shared_ptr<const cxml::Node> xml,
+       list<shared_ptr<dcp::SubtitleNode> > const & subtitle_nodes,
+       ParseState& parse_state
+       )
 {
-       /* XXX: hacks aplenty in here; need separate parsers for DCSubtitle and SubtitleReel */
-       
-       /* DCSubtitle */
-       optional<string> x = xml->optional_string_child ("SubtitleID");
-       if (!x) {
-               /* SubtitleReel */
-               x = xml->optional_string_child ("Id");
-       }
-       _uuid = x.get_value_or ("");
-
-       _movie_title = xml->optional_string_child ("MovieTitle");
-       _reel_number = xml->string_child ("ReelNumber");
-       _language = xml->string_child ("Language");
-
-       xml->ignore_child ("LoadFont");
-
-       list<shared_ptr<libdcp::parse::Font> > font_nodes = type_children<libdcp::parse::Font> (xml, "Font");
-       _load_font_nodes = type_children<libdcp::parse::LoadFont> (xml, "LoadFont");
-
-       /* Now make Subtitle objects to represent the raw XML nodes
-          in a sane way.
-       */
-
-       shared_ptr<cxml::Node> subtitle_list = xml->optional_node_child ("SubtitleList");
-       if (subtitle_list) {
-               list<shared_ptr<libdcp::parse::Font> > font = type_children<libdcp::parse::Font> (subtitle_list, "Font");
-               copy (font.begin(), font.end(), back_inserter (font_nodes));
+       BOOST_FOREACH (shared_ptr<dcp::SubtitleNode> i, subtitle_nodes) {
+               parse_state.subtitle_nodes.push_back (i);
+               examine_nodes (xml, i->text_nodes, parse_state);
+               examine_nodes (xml, i->font_nodes, parse_state);
+               parse_state.subtitle_nodes.pop_back ();
        }
-       
-       ParseState parse_state;
-       examine_font_nodes (xml, font_nodes, parse_state);
 }
 
 void
-SubtitleAsset::examine_font_nodes (
+SubtitleAsset::examine_nodes (
        shared_ptr<const cxml::Node> xml,
-       list<shared_ptr<libdcp::parse::Font> > const & font_nodes,
+       list<shared_ptr<dcp::FontNode> > const & font_nodes,
        ParseState& parse_state
        )
 {
-       for (list<shared_ptr<libdcp::parse::Font> >::const_iterator i = font_nodes.begin(); i != font_nodes.end(); ++i) {
+       BOOST_FOREACH (shared_ptr<dcp::FontNode> i, font_nodes) {
 
-               parse_state.font_nodes.push_back (*i);
-               maybe_add_subtitle ((*i)->text, parse_state);
+               parse_state.font_nodes.push_back (i);
+               maybe_add_subtitle (i->text, parse_state);
+
+               examine_nodes (xml, i->subtitle_nodes, parse_state);
+               examine_nodes (xml, i->font_nodes, parse_state);
+               examine_nodes (xml, i->text_nodes, parse_state);
 
-               for (list<shared_ptr<libdcp::parse::Subtitle> >::iterator j = (*i)->subtitle_nodes.begin(); j != (*i)->subtitle_nodes.end(); ++j) {
-                       parse_state.subtitle_nodes.push_back (*j);
-                       examine_text_nodes (xml, (*j)->text_nodes, parse_state);
-                       examine_font_nodes (xml, (*j)->font_nodes, parse_state);
-                       parse_state.subtitle_nodes.pop_back ();
-               }
-       
-               examine_font_nodes (xml, (*i)->font_nodes, parse_state);
-               examine_text_nodes (xml, (*i)->text_nodes, parse_state);
-               
                parse_state.font_nodes.pop_back ();
        }
 }
 
 void
-SubtitleAsset::examine_text_nodes (
+SubtitleAsset::examine_nodes (
        shared_ptr<const cxml::Node> xml,
-       list<shared_ptr<libdcp::parse::Text> > const & text_nodes,
+       list<shared_ptr<dcp::TextNode> > const & text_nodes,
        ParseState& parse_state
        )
 {
-       for (list<shared_ptr<libdcp::parse::Text> >::const_iterator i = text_nodes.begin(); i != text_nodes.end(); ++i) {
-               parse_state.text_nodes.push_back (*i);
-               maybe_add_subtitle ((*i)->text, parse_state);
-               examine_font_nodes (xml, (*i)->font_nodes, parse_state);
+       BOOST_FOREACH (shared_ptr<dcp::TextNode> i, text_nodes) {
+               parse_state.text_nodes.push_back (i);
+               maybe_add_subtitle (i->text, parse_state);
+               examine_nodes (xml, i->font_nodes, parse_state);
                parse_state.text_nodes.pop_back ();
        }
 }
@@ -182,239 +137,136 @@ SubtitleAsset::maybe_add_subtitle (string text, ParseState const & parse_state)
        if (empty_or_white_space (text)) {
                return;
        }
-       
+
        if (parse_state.text_nodes.empty() || parse_state.subtitle_nodes.empty ()) {
                return;
        }
 
-       assert (!parse_state.text_nodes.empty ());
-       assert (!parse_state.subtitle_nodes.empty ());
-       
-       libdcp::parse::Font effective_font (parse_state.font_nodes);
-       libdcp::parse::Text effective_text (*parse_state.text_nodes.back ());
-       libdcp::parse::Subtitle effective_subtitle (*parse_state.subtitle_nodes.back ());
+       DCP_ASSERT (!parse_state.text_nodes.empty ());
+       DCP_ASSERT (!parse_state.subtitle_nodes.empty ());
+
+       dcp::FontNode effective_font (parse_state.font_nodes);
+       dcp::TextNode effective_text (*parse_state.text_nodes.back ());
+       dcp::SubtitleNode effective_subtitle (*parse_state.subtitle_nodes.back ());
 
        _subtitles.push_back (
-               shared_ptr<Subtitle> (
-                       new Subtitle (
-                               font_id_to_name (effective_font.id),
-                               effective_font.italic.get(),
-                               effective_font.color.get(),
-                               effective_font.size,
-                               effective_subtitle.in,
-                               effective_subtitle.out,
-                               effective_text.v_position,
-                               effective_text.v_align,
-                               text,
-                               effective_font.effect ? effective_font.effect.get() : NONE,
-                               effective_font.effect_color.get(),
-                               effective_subtitle.fade_up_time,
-                               effective_subtitle.fade_down_time
-                               )
+               SubtitleString (
+                       effective_font.id,
+                       effective_font.italic.get_value_or (false),
+                       effective_font.bold.get_value_or (false),
+                       effective_font.underline.get_value_or (false),
+                       effective_font.colour.get_value_or (dcp::Colour (255, 255, 255)),
+                       effective_font.size,
+                       effective_font.aspect_adjust.get_value_or (1.0),
+                       effective_subtitle.in,
+                       effective_subtitle.out,
+                       effective_text.h_position,
+                       effective_text.h_align,
+                       effective_text.v_position,
+                       effective_text.v_align,
+                       effective_text.direction,
+                       text,
+                       effective_font.effect.get_value_or (NONE),
+                       effective_font.effect_colour.get_value_or (dcp::Colour (0, 0, 0)),
+                       effective_subtitle.fade_up_time,
+                       effective_subtitle.fade_down_time
                        )
                );
 }
 
-list<shared_ptr<Subtitle> >
-SubtitleAsset::subtitles_at (Time t) const
+list<SubtitleString>
+SubtitleAsset::subtitles_during (Time from, Time to, bool starting) const
 {
-       list<shared_ptr<Subtitle> > s;
-       for (list<shared_ptr<Subtitle> >::const_iterator i = _subtitles.begin(); i != _subtitles.end(); ++i) {
-               if ((*i)->in() <= t && t <= (*i)->out ()) {
-                       s.push_back (*i);
+       list<SubtitleString> s;
+       BOOST_FOREACH (SubtitleString const & i, _subtitles) {
+               if ((starting && from <= i.in() && i.in() < to) || (!starting && i.out() >= from && i.in() <= to)) {
+                       s.push_back (i);
                }
        }
 
        return s;
 }
 
-std::string
-SubtitleAsset::font_id_to_name (string id) const
+void
+SubtitleAsset::add (SubtitleString s)
 {
-       list<shared_ptr<libdcp::parse::LoadFont> >::const_iterator i = _load_font_nodes.begin();
-       while (i != _load_font_nodes.end() && (*i)->id != id) {
-               ++i;
-       }
-
-       if (i == _load_font_nodes.end ()) {
-               return "";
-       }
-
-       if ((*i)->uri && (*i)->uri.get() == "arial.ttf") {
-               return "Arial";
-       }
-
-       return "";
+       _subtitles.push_back (s);
 }
 
-Subtitle::Subtitle (
-       string font,
-       bool italic,
-       Color color,
-       int size,
-       Time in,
-       Time out,
-       float v_position,
-       VAlign v_align,
-       string text,
-       Effect effect,
-       Color effect_color,
-       Time fade_up_time,
-       Time fade_down_time
-       )
-       : _font (font)
-       , _italic (italic)
-       , _color (color)
-       , _size (size)
-       , _in (in)
-       , _out (out)
-       , _v_position (v_position)
-       , _v_align (v_align)
-       , _text (text)
-       , _effect (effect)
-       , _effect_color (effect_color)
-       , _fade_up_time (fade_up_time)
-       , _fade_down_time (fade_down_time)
+Time
+SubtitleAsset::latest_subtitle_out () const
 {
+       Time t;
+       BOOST_FOREACH (SubtitleString const & i, _subtitles) {
+               if (i.out() > t) {
+                       t = i.out ();
+               }
+       }
 
-}
-
-int
-Subtitle::size_in_pixels (int screen_height) const
-{
-       /* Size in the subtitle file is given in points as if the screen
-          height is 11 inches, so a 72pt font would be 1/11th of the screen
-          height.
-       */
-       
-       return _size * screen_height / (11 * 72);
+       return t;
 }
 
 bool
-libdcp::operator== (Subtitle const & a, Subtitle const & b)
+SubtitleAsset::equals (shared_ptr<const Asset> other_asset, EqualityOptions options, NoteHandler note) const
 {
-       return (
-               a.font() == b.font() &&
-               a.italic() == b.italic() &&
-               a.color() == b.color() &&
-               a.size() == b.size() &&
-               a.in() == b.in() &&
-               a.out() == b.out() &&
-               a.v_position() == b.v_position() &&
-               a.v_align() == b.v_align() &&
-               a.text() == b.text() &&
-               a.effect() == b.effect() &&
-               a.effect_color() == b.effect_color() &&
-               a.fade_up_time() == b.fade_up_time() &&
-               a.fade_down_time() == b.fade_down_time()
-               );
-}
-
-ostream&
-libdcp::operator<< (ostream& s, Subtitle const & sub)
-{
-       s << "\n`" << sub.text() << "' from " << sub.in() << " to " << sub.out() << ";\n"
-         << "fade up " << sub.fade_up_time() << ", fade down " << sub.fade_down_time() << ";\n"
-         << "font " << sub.font() << ", ";
-
-       if (sub.italic()) {
-               s << "italic";
-       } else {
-               s << "non-italic";
+       if (!Asset::equals (other_asset, options, note)) {
+               return false;
        }
-       
-       s << ", size " << sub.size() << ", color " << sub.color() << ", vpos " << sub.v_position() << ", valign " << ((int) sub.v_align()) << ";\n"
-         << "effect " << ((int) sub.effect()) << ", effect color " << sub.effect_color();
-
-       return s;
-}
 
-void
-SubtitleAsset::add (shared_ptr<Subtitle> s)
-{
-       _subtitles.push_back (s);
-       _need_sort = true;
-}
+       shared_ptr<const SubtitleAsset> other = dynamic_pointer_cast<const SubtitleAsset> (other_asset);
+       if (!other) {
+               return false;
+       }
 
-void
-SubtitleAsset::write_to_cpl (xmlpp::Element* node) const
-{
-       /* XXX: should EditRate, Duration and IntrinsicDuration be in here? */
+       if (_subtitles != other->_subtitles) {
+               note (DCP_ERROR, "subtitles differ");
+               return false;
+       }
 
-       xmlpp::Node* ms = node->add_child ("MainSubtitle");
-       ms->add_child("Id")->add_child_text("urn:uuid:" + _uuid);
-       ms->add_child("AnnotationText")->add_child_text (_file_name.string ());
-       /* XXX */
-       ms->add_child("EntryPoint")->add_child_text ("0");
+       return true;
 }
 
 struct SubtitleSorter {
-       bool operator() (shared_ptr<Subtitle> a, shared_ptr<Subtitle> b) {
-               if (a->in() != b->in()) {
-                       return a->in() < b->in();
+       bool operator() (SubtitleString const & a, SubtitleString const & b) {
+               if (a.in() != b.in()) {
+                       return a.in() < b.in();
                }
-               return a->v_position() < b->v_position();
+               return a.v_position() < b.v_position();
        }
 };
 
+/** @param standard Standard (INTEROP or SMPTE); this is used rather than putting things in the child
+ *  class because the differences between the two are fairly subtle.
+ */
 void
-SubtitleAsset::write_xml () const
+SubtitleAsset::subtitles_as_xml (xmlpp::Element* root, int time_code_rate, Standard standard) const
 {
-       FILE* f = fopen_boost (path (), "r");
-       Glib::ustring const s = xml_as_string ();
-       fwrite (s.c_str(), 1, s.length(), f);
-       fclose (f);
-}
-
-Glib::ustring
-SubtitleAsset::xml_as_string () const
-{
-       xmlpp::Document doc;
-       xmlpp::Element* root = doc.create_root_node ("DCSubtitle");
-       root->set_attribute ("Version", "1.0");
-
-       root->add_child("SubtitleID")->add_child_text (_uuid);
-       if (_movie_title) {
-               root->add_child("MovieTitle")->add_child_text (_movie_title.get ());
-       }
-       root->add_child("ReelNumber")->add_child_text (raw_convert<string> (_reel_number));
-       root->add_child("Language")->add_child_text (_language);
-
-       if (_load_font_nodes.size() > 1) {
-               boost::throw_exception (MiscError ("multiple LoadFont nodes not supported"));
-       }
-
-       if (!_load_font_nodes.empty ()) {
-               xmlpp::Element* load_font = root->add_child("LoadFont");
-               load_font->set_attribute("Id", _load_font_nodes.front()->id);
-               if (_load_font_nodes.front()->uri) {
-                       load_font->set_attribute("URI",  _load_font_nodes.front()->uri.get ());
-               }
-       }
+       list<SubtitleString> sorted = _subtitles;
+       sorted.sort (SubtitleSorter ());
 
-       list<shared_ptr<Subtitle> > sorted = _subtitles;
-       if (_need_sort) {
-               sorted.sort (SubtitleSorter ());
-       }
+       string const xmlns = standard == SMPTE ? "dcst" : "";
 
-       /* XXX: multiple fonts not supported */
-       /* XXX: script, underlined, weight not supported */
+       /* XXX: script not supported */
 
+       optional<string> font;
        bool italic = false;
-       Color color;
+       bool bold = false;
+       bool underline = false;
+       Colour colour;
        int size = 0;
+       float aspect_adjust = 1.0;
        Effect effect = NONE;
-       Color effect_color;
+       Colour effect_colour;
        int spot_number = 1;
        Time last_in;
        Time last_out;
        Time last_fade_up_time;
        Time last_fade_down_time;
 
-       xmlpp::Element* font = 0;
-       xmlpp::Element* subtitle = 0;
+       xmlpp::Element* font_element = 0;
+       xmlpp::Element* subtitle_element = 0;
 
-       for (list<shared_ptr<Subtitle> >::iterator i = sorted.begin(); i != sorted.end(); ++i) {
+       BOOST_FOREACH (SubtitleString const & i, sorted) {
 
                /* We will start a new <Font>...</Font> whenever some font property changes.
                   I suppose we should really make an optimal hierarchy of <Font> tags, but
@@ -422,63 +274,134 @@ SubtitleAsset::xml_as_string () const
                */
 
                bool const font_changed =
-                       italic       != (*i)->italic()       ||
-                       color        != (*i)->color()        ||
-                       size         != (*i)->size()         ||
-                       effect       != (*i)->effect()       ||
-                       effect_color != (*i)->effect_color();
+                       font          != i.font()          ||
+                       italic        != i.italic()        ||
+                       bold          != i.bold()          ||
+                       underline     != i.underline()     ||
+                       colour        != i.colour()        ||
+                       size          != i.size()          ||
+                       fabs (aspect_adjust - i.aspect_adjust()) > ASPECT_ADJUST_EPSILON ||
+                       effect        != i.effect()        ||
+                       effect_colour != i.effect_colour();
 
                if (font_changed) {
-                       italic = (*i)->italic ();
-                       color = (*i)->color ();
-                       size = (*i)->size ();
-                       effect = (*i)->effect ();
-                       effect_color = (*i)->effect_color ();
+                       font = i.font ();
+                       italic = i.italic ();
+                       bold = i.bold ();
+                       underline = i.underline ();
+                       colour = i.colour ();
+                       size = i.size ();
+                       aspect_adjust = i.aspect_adjust ();
+                       effect = i.effect ();
+                       effect_colour = i.effect_colour ();
                }
 
-               if (!font || font_changed) {
-                       font = root->add_child ("Font");
-                       string id = "theFontId";
-                       if (!_load_font_nodes.empty()) {
-                               id = _load_font_nodes.front()->id;
+               if (!font_element || font_changed) {
+                       font_element = root->add_child ("Font", xmlns);
+                       if (font) {
+                               if (standard == SMPTE) {
+                                       font_element->set_attribute ("ID", font.get ());
+                               } else {
+                                       font_element->set_attribute ("Id", font.get ());
+                               }
+                       }
+                       font_element->set_attribute ("Italic", italic ? "yes" : "no");
+                       font_element->set_attribute ("Color", colour.to_argb_string());
+                       font_element->set_attribute ("Size", raw_convert<string> (size));
+                       if (fabs (aspect_adjust - 1.0) > ASPECT_ADJUST_EPSILON) {
+                               font_element->set_attribute ("AspectAdjust", raw_convert<string> (aspect_adjust));
                        }
-                       font->set_attribute ("Id", id);
-                       font->set_attribute ("Italic", italic ? "yes" : "no");
-                       font->set_attribute ("Color", color.to_argb_string());
-                       font->set_attribute ("Size", raw_convert<string> (size));
-                       font->set_attribute ("Effect", effect_to_string (effect));
-                       font->set_attribute ("EffectColor", effect_color.to_argb_string());
-                       font->set_attribute ("Script", "normal");
-                       font->set_attribute ("Underlined", "no");
-                       font->set_attribute ("Weight", "normal");
+                       font_element->set_attribute ("Effect", effect_to_string (effect));
+                       font_element->set_attribute ("EffectColor", effect_colour.to_argb_string());
+                       font_element->set_attribute ("Script", "normal");
+                       if (standard == SMPTE) {
+                               font_element->set_attribute ("Underline", underline ? "yes" : "no");
+                       } else {
+                               font_element->set_attribute ("Underlined", underline ? "yes" : "no");
+                       }
+                       font_element->set_attribute ("Weight", bold ? "bold" : "normal");
                }
 
-               if (!subtitle || font_changed ||
-                   (last_in != (*i)->in() ||
-                    last_out != (*i)->out() ||
-                    last_fade_up_time != (*i)->fade_up_time() ||
-                    last_fade_down_time != (*i)->fade_down_time()
+               if (!subtitle_element || font_changed ||
+                   (last_in != i.in() ||
+                    last_out != i.out() ||
+                    last_fade_up_time != i.fade_up_time() ||
+                    last_fade_down_time != i.fade_down_time()
                            )) {
 
-                       subtitle = font->add_child ("Subtitle");
-                       subtitle->set_attribute ("SpotNumber", raw_convert<string> (spot_number++));
-                       subtitle->set_attribute ("TimeIn", (*i)->in().to_string());
-                       subtitle->set_attribute ("TimeOut", (*i)->out().to_string());
-                       subtitle->set_attribute ("FadeUpTime", raw_convert<string> ((*i)->fade_up_time().to_ticks()));
-                       subtitle->set_attribute ("FadeDownTime", raw_convert<string> ((*i)->fade_down_time().to_ticks()));
-
-                       last_in = (*i)->in ();
-                       last_out = (*i)->out ();
-                       last_fade_up_time = (*i)->fade_up_time ();
-                       last_fade_down_time = (*i)->fade_down_time ();
+                       subtitle_element = font_element->add_child ("Subtitle", xmlns);
+                       subtitle_element->set_attribute ("SpotNumber", raw_convert<string> (spot_number++));
+                       subtitle_element->set_attribute ("TimeIn", i.in().rebase(time_code_rate).as_string(standard));
+                       subtitle_element->set_attribute ("TimeOut", i.out().rebase(time_code_rate).as_string(standard));
+                       if (standard == SMPTE) {
+                               subtitle_element->set_attribute ("FadeUpTime", i.fade_up_time().rebase(time_code_rate).as_string(standard));
+                               subtitle_element->set_attribute ("FadeDownTime", i.fade_down_time().rebase(time_code_rate).as_string(standard));
+                       } else {
+                               subtitle_element->set_attribute ("FadeUpTime", raw_convert<string> (i.fade_up_time().as_editable_units(time_code_rate)));
+                               subtitle_element->set_attribute ("FadeDownTime", raw_convert<string> (i.fade_down_time().as_editable_units(time_code_rate)));
+                       }
+
+                       last_in = i.in ();
+                       last_out = i.out ();
+                       last_fade_up_time = i.fade_up_time ();
+                       last_fade_down_time = i.fade_down_time ();
                }
 
-               xmlpp::Element* text = subtitle->add_child ("Text");
-               text->set_attribute ("VAlign", valign_to_string ((*i)->v_align()));             
-               text->set_attribute ("VPosition", raw_convert<string> ((*i)->v_position()));
-               text->add_child_text ((*i)->text());
-       }
+               xmlpp::Element* text = subtitle_element->add_child ("Text", xmlns);
+
+               if (i.h_align() != HALIGN_CENTER) {
+                       if (standard == SMPTE) {
+                               text->set_attribute ("Halign", halign_to_string (i.h_align ()));
+                       } else {
+                               text->set_attribute ("HAlign", halign_to_string (i.h_align ()));
+                       }
+               }
+
+               if (i.h_position() > ALIGN_EPSILON) {
+                       if (standard == SMPTE) {
+                               text->set_attribute ("Hposition", raw_convert<string> (i.h_position() * 100, 6));
+                       } else {
+                               text->set_attribute ("HPosition", raw_convert<string> (i.h_position() * 100, 6));
+                       }
+               }
+
+               if (standard == SMPTE) {
+                       text->set_attribute ("Valign", valign_to_string (i.v_align()));
+               } else {
+                       text->set_attribute ("VAlign", valign_to_string (i.v_align()));
+               }
 
-       return doc.write_to_string_formatted ("UTF-8");
+               if (i.v_position() > ALIGN_EPSILON) {
+                       if (standard == SMPTE) {
+                               text->set_attribute ("Vposition", raw_convert<string> (i.v_position() * 100, 6));
+                       } else {
+                               text->set_attribute ("VPosition", raw_convert<string> (i.v_position() * 100, 6));
+                       }
+               } else {
+                       if (standard == SMPTE) {
+                               text->set_attribute ("Vposition", "0");
+                       } else {
+                               text->set_attribute ("VPosition", "0");
+                       }
+               }
+
+               /* Interop only supports "horizontal" or "vertical" for direction, so only write this
+                  for SMPTE.
+               */
+               if (i.direction() != DIRECTION_LTR && standard == SMPTE) {
+                       text->set_attribute ("Direction", direction_to_string (i.direction ()));
+               }
+
+               text->add_child_text (i.text());
+       }
 }
 
+map<string, Data>
+SubtitleAsset::fonts_with_load_ids () const
+{
+       map<string, Data> out;
+       BOOST_FOREACH (Font const & i, _fonts) {
+               out[i.load_id] = i.data;
+       }
+       return out;
+}