Various tweaks; work on read_dcp example.
[libdcp.git] / src / dcp.cc
1 /*
2     Copyright (C) 2012-2014 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 /** @file  src/dcp.cc
21  *  @brief DCP class.
22  */
23
24 #include "dcp.h"
25 #include "sound_mxf.h"
26 #include "picture_mxf.h"
27 #include "subtitle_content.h"
28 #include "mono_picture_mxf.h"
29 #include "stereo_picture_mxf.h"
30 #include "util.h"
31 #include "metadata.h"
32 #include "exceptions.h"
33 #include "reel.h"
34 #include "cpl.h"
35 #include "signer.h"
36 #include "kdm.h"
37 #include "compose.hpp"
38 #include "AS_DCP.h"
39 #include <xmlsec/xmldsig.h>
40 #include <xmlsec/app.h>
41 #include <libxml++/libxml++.h>
42 #include <boost/filesystem.hpp>
43 #include <boost/algorithm/string.hpp>
44 #include <boost/lexical_cast.hpp>
45 #include <sstream>
46 #include <iomanip>
47 #include <cassert>
48 #include <iostream>
49
50 using std::string;
51 using std::list;
52 using std::stringstream;
53 using std::ostream;
54 using std::make_pair;
55 using std::map;
56 using boost::shared_ptr;
57 using boost::lexical_cast;
58 using namespace dcp;
59
60 DCP::DCP (boost::filesystem::path directory)
61         : _directory (directory)
62 {
63         boost::filesystem::create_directories (directory);
64 }
65
66 void
67 DCP::read ()
68 {
69         /* Read the ASSETMAP */
70         
71         boost::filesystem::path asset_map_file;
72         if (boost::filesystem::exists (_directory / "ASSETMAP")) {
73                 asset_map_file = _directory / "ASSETMAP";
74         } else if (boost::filesystem::exists (_directory / "ASSETMAP.xml")) {
75                 asset_map_file = _directory / "ASSETMAP.xml";
76         } else {
77                 boost::throw_exception (DCPReadError ("could not find AssetMap file"));
78         }
79
80         cxml::Document asset_map ("AssetMap");
81         asset_map.read_file (asset_map_file);
82         list<shared_ptr<cxml::Node> > asset_nodes = asset_map.node_child("AssetList")->node_children ("Asset");
83         map<string, boost::filesystem::path> paths;
84         for (list<shared_ptr<cxml::Node> >::const_iterator i = asset_nodes.begin(); i != asset_nodes.end(); ++i) {
85                 if ((*i)->node_child("ChunkList")->node_children("Chunk").size() != 1) {
86                         boost::throw_exception (XMLError ("unsupported asset chunk count"));
87                 }
88                 paths.insert (make_pair (
89                         (*i)->string_child ("Id"),
90                         (*i)->node_child("ChunkList")->node_child("Chunk")->string_child ("Path")
91                                       ));
92         }
93
94         /* Read all the assets from the asset map */
95         
96         for (map<string, boost::filesystem::path>::const_iterator i = paths.begin(); i != paths.end(); ++i) {
97                 boost::filesystem::path path = _directory / i->second;
98                 if (boost::algorithm::ends_with (path.string(), ".xml")) {
99                         xmlpp::DomParser* p = new xmlpp::DomParser;
100                         try {
101                                 p->parse_file (path.string());
102                         } catch (std::exception& e) {
103                                 delete p;
104                                 continue;
105                         }
106                         
107                         string const root = p->get_document()->get_root_node()->get_name ();
108                         delete p;
109                         
110                         if (root == "CompositionPlaylist") {
111                                 _assets.push_back (shared_ptr<CPL> (new CPL (path)));
112                         } else if (root == "DCSubtitle") {
113                                 _assets.push_back (shared_ptr<SubtitleContent> (new SubtitleContent (path)));
114                         }
115                 } else if (boost::algorithm::ends_with (path.string(), ".mxf")) {
116                         ASDCP::EssenceType_t type;
117                         if (ASDCP::EssenceType (path.string().c_str(), type) != ASDCP::RESULT_OK) {
118                                 throw DCPReadError ("Could not find essence type");
119                         }
120                         switch (type) {
121                                 case ASDCP::ESS_UNKNOWN:
122                                 case ASDCP::ESS_MPEG2_VES:
123                                         throw DCPReadError ("MPEG2 video essences are not supported");
124                                 case ASDCP::ESS_JPEG_2000:
125                                         _assets.push_back (shared_ptr<MonoPictureMXF> (new MonoPictureMXF (path)));
126                                         break;
127                                 case ASDCP::ESS_PCM_24b_48k:
128                                 case ASDCP::ESS_PCM_24b_96k:
129                                         _assets.push_back (shared_ptr<SoundMXF> (new SoundMXF (path)));
130                                         break;
131                                 case ASDCP::ESS_JPEG_2000_S:
132                                         _assets.push_back (shared_ptr<StereoPictureMXF> (new StereoPictureMXF (path)));
133                                         break;
134                                 default:
135                                         throw DCPReadError ("Unknown MXF essence type");
136                                 }
137                 }
138         }
139
140         list<shared_ptr<CPL> > cpl = cpls ();
141         for (list<shared_ptr<CPL> >::const_iterator i = cpl.begin(); i != cpl.end(); ++i) {
142                 (*i)->resolve_refs (list_of_type<Asset, Object> (assets ()));
143         }
144 }
145
146 bool
147 DCP::equals (DCP const & other, EqualityOptions opt, boost::function<void (NoteType, string)> note) const
148 {
149         if (_assets.size() != other._assets.size()) {
150                 note (ERROR, "Asset counts differ");
151                 return false;
152         }
153
154         list<shared_ptr<Asset> >::const_iterator a = _assets.begin ();
155         list<shared_ptr<Asset> >::const_iterator b = other._assets.begin ();
156
157         while (a != _assets.end ()) {
158                 if (!(*a)->equals (*b, opt, note)) {
159                         return false;
160                 }
161                 ++a;
162                 ++b;
163         }
164
165         return true;
166 }
167
168 void
169 DCP::add (boost::shared_ptr<Asset> asset)
170 {
171         _assets.push_back (asset);
172 }
173
174 class AssetComparator
175 {
176 public:
177         bool operator() (shared_ptr<const Content> a, shared_ptr<const Content> b) {
178                 return a->id() < b->id();
179         }
180 };
181
182 bool
183 DCP::encrypted () const
184 {
185         list<shared_ptr<CPL> > cpl = cpls ();
186         for (list<shared_ptr<CPL> >::const_iterator i = cpl.begin(); i != cpl.end(); ++i) {
187                 if ((*i)->encrypted ()) {
188                         return true;
189                 }
190         }
191
192         return false;
193 }
194
195 void
196 DCP::add (KDM const & kdm)
197 {
198         list<KDMKey> keys = kdm.keys ();
199         list<shared_ptr<CPL> > cpl = cpls ();
200         
201         for (list<shared_ptr<CPL> >::iterator i = cpl.begin(); i != cpl.end(); ++i) {
202                 for (list<KDMKey>::iterator j = keys.begin(); j != keys.end(); ++j) {
203                         if (j->cpl_id() == (*i)->id()) {
204                                 (*i)->add (kdm);
205                         }                               
206                 }
207         }
208 }
209
210 boost::filesystem::path
211 DCP::write_pkl (Standard standard, string pkl_uuid, XMLMetadata metadata, shared_ptr<const Signer> signer) const
212 {
213         boost::filesystem::path p = _directory;
214         stringstream s;
215         s << pkl_uuid << "_pkl.xml";
216         p /= s.str();
217
218         xmlpp::Document doc;
219         xmlpp::Element* pkl;
220         if (standard == INTEROP) {
221                 pkl = doc.create_root_node("PackingList", "http://www.digicine.com/PROTO-ASDCP-PKL-20040311#");
222         } else {
223                 pkl = doc.create_root_node("PackingList", "http://www.smpte-ra.org/schemas/429-8/2007/PKL");
224         }
225         
226         if (signer) {
227                 pkl->set_namespace_declaration ("http://www.w3.org/2000/09/xmldsig#", "dsig");
228         }
229
230         pkl->add_child("Id")->add_child_text ("urn:uuid:" + pkl_uuid);
231
232         /* XXX: this is a bit of a hack */
233         assert (cpls().size() > 0);
234         pkl->add_child("AnnotationText")->add_child_text (cpls().front()->annotation_text ());
235         
236         pkl->add_child("IssueDate")->add_child_text (metadata.issue_date);
237         pkl->add_child("Issuer")->add_child_text (metadata.issuer);
238         pkl->add_child("Creator")->add_child_text (metadata.creator);
239
240         xmlpp::Element* asset_list = pkl->add_child("AssetList");
241         for (list<shared_ptr<Asset> >::const_iterator i = _assets.begin(); i != _assets.end(); ++i) {
242                 (*i)->write_to_pkl (asset_list);
243         }
244
245         if (signer) {
246                 signer->sign (pkl, standard);
247         }
248                 
249         doc.write_to_file (p.string (), "UTF-8");
250         return p.string ();
251 }
252
253 /** Write the VOLINDEX file.
254  *  @param standard DCP standard to use (INTEROP or SMPTE)
255  */
256 void
257 DCP::write_volindex (Standard standard) const
258 {
259         boost::filesystem::path p = _directory;
260         if (standard == INTEROP) {
261                 p /= "VOLINDEX";
262         } else {
263                 p /= "VOLINDEX.xml";
264         }
265
266         xmlpp::Document doc;
267         xmlpp::Element* root = doc.create_root_node ("VolumeIndex", "http://www.smpte-ra.org/schemas/429-9/2007/AM");
268         root->add_child("Index")->add_child_text ("1");
269         doc.write_to_file (p.string (), "UTF-8");
270 }
271
272 void
273 DCP::write_assetmap (Standard standard, string pkl_uuid, int pkl_length, XMLMetadata metadata) const
274 {
275         boost::filesystem::path p = _directory;
276         if (standard == INTEROP) {
277                 p /= "ASSETMAP";
278         } else {
279                 p /= "ASSETMAP.xml";
280         }
281
282         xmlpp::Document doc;
283         xmlpp::Element* root;
284         if (standard == INTEROP) {
285                 root = doc.create_root_node ("AssetMap", "http://www.digicine.com/PROTO-ASDCP-AM-20040311#");
286         } else {
287                 root = doc.create_root_node ("AssetMap", "http://www.smpte-ra.org/schemas/429-9/2007/AM");
288         }
289
290         root->add_child("Id")->add_child_text ("urn:uuid:" + make_uuid());
291         root->add_child("AnnotationText")->add_child_text ("Created by " + metadata.creator);
292         if (standard == INTEROP) {
293                 root->add_child("VolumeCount")->add_child_text ("1");
294                 root->add_child("IssueDate")->add_child_text (metadata.issue_date);
295                 root->add_child("Issuer")->add_child_text (metadata.issuer);
296                 root->add_child("Creator")->add_child_text (metadata.creator);
297         } else {
298                 root->add_child("Creator")->add_child_text (metadata.creator);
299                 root->add_child("VolumeCount")->add_child_text ("1");
300                 root->add_child("IssueDate")->add_child_text (metadata.issue_date);
301                 root->add_child("Issuer")->add_child_text (metadata.issuer);
302         }
303                 
304         xmlpp::Node* asset_list = root->add_child ("AssetList");
305
306         xmlpp::Node* asset = asset_list->add_child ("Asset");
307         asset->add_child("Id")->add_child_text ("urn:uuid:" + pkl_uuid);
308         asset->add_child("PackingList")->add_child_text ("true");
309         xmlpp::Node* chunk_list = asset->add_child ("ChunkList");
310         xmlpp::Node* chunk = chunk_list->add_child ("Chunk");
311         chunk->add_child("Path")->add_child_text (pkl_uuid + "_pkl.xml");
312         chunk->add_child("VolumeIndex")->add_child_text ("1");
313         chunk->add_child("Offset")->add_child_text ("0");
314         chunk->add_child("Length")->add_child_text (lexical_cast<string> (pkl_length));
315         
316         for (list<shared_ptr<Asset> >::const_iterator i = _assets.begin(); i != _assets.end(); ++i) {
317                 (*i)->write_to_assetmap (asset_list);
318         }
319
320         /* This must not be the _formatted version otherwise signature digests will be wrong */
321         doc.write_to_file (p.string (), "UTF-8");
322 }
323
324 void
325 DCP::write_xml (
326         Standard standard,
327         XMLMetadata metadata,
328         shared_ptr<const Signer> signer
329         )
330 {
331         string const pkl_uuid = make_uuid ();
332         boost::filesystem::path const pkl_path = write_pkl (standard, pkl_uuid, metadata, signer);
333         
334         write_volindex (standard);
335         write_assetmap (standard, pkl_uuid, boost::filesystem::file_size (pkl_path), metadata);
336
337         list<shared_ptr<CPL> > cpl = cpls ();
338         for (list<shared_ptr<CPL> >::const_iterator i = cpl.begin(); i != cpl.end(); ++i) {
339                 string const filename = (*i)->id() + "_cpl.xml";
340                 (*i)->write_xml (_directory / filename, standard, metadata, signer);
341         }
342 }
343
344 list<shared_ptr<CPL> >
345 DCP::cpls () const
346 {
347         return list_of_type<Asset, CPL> (_assets);
348 }