907f7dd5105fcb34d31278bf9000d8345dd687a3
[libdcp.git] / src / dcp.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 /** @file  src/dcp.cc
21  *  @brief A class to create a DCP.
22  */
23
24 #include <sstream>
25 #include <fstream>
26 #include <iomanip>
27 #include <cassert>
28 #include <iostream>
29 #include <boost/filesystem.hpp>
30 #include <libxml++/libxml++.h>
31 #include "dcp.h"
32 #include "asset.h"
33 #include "sound_asset.h"
34 #include "picture_asset.h"
35 #include "subtitle_asset.h"
36 #include "util.h"
37 #include "metadata.h"
38 #include "exceptions.h"
39 #include "cpl_file.h"
40 #include "pkl_file.h"
41 #include "asset_map.h"
42 #include "reel.h"
43
44 using namespace std;
45 using namespace boost;
46 using namespace libdcp;
47
48 DCP::DCP (string directory, string name, ContentKind content_kind, int fps, int length)
49         : _directory (directory)
50         , _name (name)
51         , _content_kind (content_kind)
52         , _fps (fps)
53         , _length (length)
54 {
55         filesystem::create_directories (directory);
56 }
57
58 void
59 DCP::add_reel (shared_ptr<const Reel> reel)
60 {
61         _reels.push_back (reel);
62 }
63
64 void
65 DCP::write_xml () const
66 {
67         string cpl_uuid = make_uuid ();
68         string cpl_path = write_cpl (cpl_uuid);
69         int cpl_length = filesystem::file_size (cpl_path);
70         string cpl_digest = make_digest (cpl_path, 0);
71
72         string pkl_uuid = make_uuid ();
73         string pkl_path = write_pkl (pkl_uuid, cpl_uuid, cpl_digest, cpl_length);
74         
75         write_volindex ();
76         write_assetmap (cpl_uuid, cpl_length, pkl_uuid, filesystem::file_size (pkl_path));
77 }
78
79 string
80 DCP::write_cpl (string cpl_uuid) const
81 {
82         filesystem::path p;
83         p /= _directory;
84         stringstream s;
85         s << cpl_uuid << "_cpl.xml";
86         p /= s.str();
87         ofstream cpl (p.string().c_str());
88         
89         cpl << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
90             << "<CompositionPlaylist xmlns=\"http://www.smpte-ra.org/schemas/429-7/2006/CPL\">\n"
91             << "  <Id>urn:uuid:" << cpl_uuid << "</Id>\n"
92             << "  <AnnotationText>" << _name << "</AnnotationText>\n"
93             << "  <IssueDate>" << Metadata::instance()->issue_date << "</IssueDate>\n"
94             << "  <Creator>" << Metadata::instance()->creator << "</Creator>\n"
95             << "  <ContentTitleText>" << _name << "</ContentTitleText>\n"
96             << "  <ContentKind>" << content_kind_to_string (_content_kind) << "</ContentKind>\n"
97             << "  <ContentVersion>\n"
98             << "    <Id>urn:uri:" << cpl_uuid << "_" << Metadata::instance()->issue_date << "</Id>\n"
99             << "    <LabelText>" << cpl_uuid << "_" << Metadata::instance()->issue_date << "</LabelText>\n"
100             << "  </ContentVersion>\n"
101             << "  <RatingList/>\n"
102             << "  <ReelList>\n";
103
104         for (list<shared_ptr<const Reel> >::const_iterator i = _reels.begin(); i != _reels.end(); ++i) {
105                 (*i)->write_to_cpl (cpl);
106         }
107
108         cpl << "      </AssetList>\n"
109             << "    </Reel>\n"
110             << "  </ReelList>\n"
111             << "</CompositionPlaylist>\n";
112
113         return p.string ();
114 }
115
116 std::string
117 DCP::write_pkl (string pkl_uuid, string cpl_uuid, string cpl_digest, int cpl_length) const
118 {
119         filesystem::path p;
120         p /= _directory;
121         stringstream s;
122         s << pkl_uuid << "_pkl.xml";
123         p /= s.str();
124         ofstream pkl (p.string().c_str());
125
126         pkl << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
127             << "<PackingList xmlns=\"http://www.smpte-ra.org/schemas/429-8/2007/PKL\">\n"
128             << "  <Id>urn:uuid:" << pkl_uuid << "</Id>\n"
129             << "  <AnnotationText>" << _name << "</AnnotationText>\n"
130             << "  <IssueDate>" << Metadata::instance()->issue_date << "</IssueDate>\n"
131             << "  <Issuer>" << Metadata::instance()->issuer << "</Issuer>\n"
132             << "  <Creator>" << Metadata::instance()->creator << "</Creator>\n"
133             << "  <AssetList>\n";
134
135         for (list<shared_ptr<const Reel> >::const_iterator i = _reels.begin(); i != _reels.end(); ++i) {
136                 (*i)->write_to_pkl (pkl);
137         }
138
139         pkl << "    <Asset>\n"
140             << "      <Id>urn:uuid:" << cpl_uuid << "</Id>\n"
141             << "      <Hash>" << cpl_digest << "</Hash>\n"
142             << "      <Size>" << cpl_length << "</Size>\n"
143             << "      <Type>text/xml</Type>\n"
144             << "    </Asset>\n";
145
146         pkl << "  </AssetList>\n"
147             << "</PackingList>\n";
148
149         return p.string ();
150 }
151
152 void
153 DCP::write_volindex () const
154 {
155         filesystem::path p;
156         p /= _directory;
157         p /= "VOLINDEX.xml";
158         ofstream vi (p.string().c_str());
159
160         vi << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
161            << "<VolumeIndex xmlns=\"http://www.smpte-ra.org/schemas/429-9/2007/AM\">\n"
162            << "  <Index>1</Index>\n"
163            << "</VolumeIndex>\n";
164 }
165
166 void
167 DCP::write_assetmap (string cpl_uuid, int cpl_length, string pkl_uuid, int pkl_length) const
168 {
169         filesystem::path p;
170         p /= _directory;
171         p /= "ASSETMAP.xml";
172         ofstream am (p.string().c_str());
173
174         am << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
175            << "<AssetMap xmlns=\"http://www.smpte-ra.org/schemas/429-9/2007/AM\">\n"
176            << "  <Id>urn:uuid:" << make_uuid() << "</Id>\n"
177            << "  <Creator>" << Metadata::instance()->creator << "</Creator>\n"
178            << "  <VolumeCount>1</VolumeCount>\n"
179            << "  <IssueDate>" << Metadata::instance()->issue_date << "</IssueDate>\n"
180            << "  <Issuer>" << Metadata::instance()->issuer << "</Issuer>\n"
181            << "  <AssetList>\n";
182
183         am << "    <Asset>\n"
184            << "      <Id>urn:uuid:" << pkl_uuid << "</Id>\n"
185            << "      <PackingList>true</PackingList>\n"
186            << "      <ChunkList>\n"
187            << "        <Chunk>\n"
188            << "          <Path>" << pkl_uuid << "_pkl.xml</Path>\n"
189            << "          <VolumeIndex>1</VolumeIndex>\n"
190            << "          <Offset>0</Offset>\n"
191            << "          <Length>" << pkl_length << "</Length>\n"
192            << "        </Chunk>\n"
193            << "      </ChunkList>\n"
194            << "    </Asset>\n";
195
196         am << "    <Asset>\n"
197            << "      <Id>urn:uuid:" << cpl_uuid << "</Id>\n"
198            << "      <ChunkList>\n"
199            << "        <Chunk>\n"
200            << "          <Path>" << cpl_uuid << "_cpl.xml</Path>\n"
201            << "          <VolumeIndex>1</VolumeIndex>\n"
202            << "          <Offset>0</Offset>\n"
203            << "          <Length>" << cpl_length << "</Length>\n"
204            << "        </Chunk>\n"
205            << "      </ChunkList>\n"
206            << "    </Asset>\n";
207         
208         for (list<shared_ptr<const Reel> >::const_iterator i = _reels.begin(); i != _reels.end(); ++i) {
209                 (*i)->write_to_assetmap (am);
210         }
211
212         am << "  </AssetList>\n"
213            << "</AssetMap>\n";
214 }
215
216
217 DCP::DCP (string directory, bool require_mxfs)
218         : _directory (directory)
219 {
220         Files files;
221
222         shared_ptr<AssetMap> asset_map;
223         try {
224                 filesystem::path p = _directory;
225                 p /= "ASSETMAP";
226                 if (filesystem::exists (p)) {
227                         asset_map.reset (new AssetMap (p.string ()));
228                 } else {
229                         p = _directory;
230                         p /= "ASSETMAP.xml";
231                         if (filesystem::exists (p)) {
232                                 asset_map.reset (new AssetMap (p.string ()));
233                         } else {
234                                 throw DCPReadError ("could not find AssetMap file");
235                         }
236                 }
237                 
238         } catch (FileError& e) {
239                 throw FileError ("could not load AssetMap file", files.asset_map);
240         }
241
242         for (list<shared_ptr<AssetMapAsset> >::const_iterator i = asset_map->assets.begin(); i != asset_map->assets.end(); ++i) {
243                 if ((*i)->chunks.size() != 1) {
244                         throw XMLError ("unsupported asset chunk count");
245                 }
246
247                 filesystem::path t = _directory;
248                 t /= (*i)->chunks.front()->path;
249                 
250                 if (ends_with (t.string(), ".mxf") || ends_with (t.string(), ".ttf")) {
251                         continue;
252                 }
253
254                 xmlpp::DomParser* p = new xmlpp::DomParser;
255                 try {
256                         p->parse_file (t.string());
257                 } catch (std::exception& e) {
258                         delete p;
259                         continue;
260                 }
261
262                 string const root = p->get_document()->get_root_node()->get_name ();
263                 delete p;
264
265                 if (root == "CompositionPlaylist") {
266                         if (files.cpl.empty ()) {
267                                 files.cpl = t.string();
268                         } else {
269                                 throw DCPReadError ("duplicate CPLs found");
270                         }
271                 } else if (root == "PackingList") {
272                         if (files.pkl.empty ()) {
273                                 files.pkl = t.string();
274                         } else {
275                                 throw DCPReadError ("duplicate PKLs found");
276                         }
277                 } else if (root == "DCSubtitle") {
278                         files.subtitles.push_back (t.string());
279                 }
280         }
281         
282         if (files.cpl.empty ()) {
283                 throw FileError ("no CPL file found", "");
284         }
285
286         if (files.pkl.empty ()) {
287                 throw FileError ("no PKL file found", "");
288         }
289
290         /* Read the XML */
291         shared_ptr<CPLFile> cpl;
292         try {
293                 cpl.reset (new CPLFile (files.cpl));
294         } catch (FileError& e) {
295                 throw FileError ("could not load CPL file", files.cpl);
296         }
297
298         shared_ptr<PKLFile> pkl;
299         try {
300                 pkl.reset (new PKLFile (files.pkl));
301         } catch (FileError& e) {
302                 throw FileError ("could not load PKL file", files.pkl);
303         }
304
305         /* Cross-check */
306         /* XXX */
307
308         /* Now cherry-pick the required bits into our own data structure */
309         
310         _name = cpl->annotation_text;
311         _content_kind = cpl->content_kind;
312         _length = 0;
313         _fps = 0;
314
315         for (list<shared_ptr<CPLReel> >::iterator i = cpl->reels.begin(); i != cpl->reels.end(); ++i) {
316
317                 shared_ptr<Picture> p;
318
319                 if ((*i)->asset_list->main_picture) {
320                         p = (*i)->asset_list->main_picture;
321                 } else {
322                         p = (*i)->asset_list->main_stereoscopic_picture;
323                 }
324                 
325                 assert (_fps == 0 || _fps == p->edit_rate.numerator);
326                 _fps = p->edit_rate.numerator;
327                 _length += p->duration;
328
329                 shared_ptr<PictureAsset> picture;
330                 shared_ptr<SoundAsset> sound;
331                 shared_ptr<SubtitleAsset> subtitle;
332
333                 if ((*i)->asset_list->main_picture) {
334
335                         try {
336                                 picture.reset (new MonoPictureAsset (
337                                                        _directory,
338                                                        asset_map->asset_from_id ((*i)->asset_list->main_picture->id)->chunks.front()->path,
339                                                        _fps,
340                                                        (*i)->asset_list->main_picture->entry_point,
341                                                        (*i)->asset_list->main_picture->duration
342                                                        )
343                                         );
344                         } catch (MXFFileError) {
345                                 if (require_mxfs) {
346                                         throw;
347                                 }
348                         }
349                         
350                 } else if ((*i)->asset_list->main_stereoscopic_picture) {
351                         
352                         try {
353                                 picture.reset (new StereoPictureAsset (
354                                                        _directory,
355                                                        asset_map->asset_from_id ((*i)->asset_list->main_stereoscopic_picture->id)->chunks.front()->path,
356                                                        _fps,
357                                                        (*i)->asset_list->main_stereoscopic_picture->entry_point,
358                                                        (*i)->asset_list->main_stereoscopic_picture->duration
359                                                        )
360                                         );
361                         } catch (MXFFileError) {
362                                 if (require_mxfs) {
363                                         throw;
364                                 }
365                         }
366                         
367                 }
368                 
369                 if ((*i)->asset_list->main_sound) {
370                         
371                         try {
372                                 sound.reset (new SoundAsset (
373                                                      _directory,
374                                                      asset_map->asset_from_id ((*i)->asset_list->main_sound->id)->chunks.front()->path,
375                                                      _fps,
376                                                      (*i)->asset_list->main_sound->entry_point,
377                                                      (*i)->asset_list->main_sound->duration
378                                                      )
379                                         );
380                         } catch (MXFFileError) {
381                                 if (require_mxfs) {
382                                         throw;
383                                 }
384                         }
385                 }
386
387                 if ((*i)->asset_list->main_subtitle) {
388                         
389                         subtitle.reset (new SubtitleAsset (
390                                                 _directory,
391                                                 asset_map->asset_from_id ((*i)->asset_list->main_subtitle->id)->chunks.front()->path
392                                                 )
393                                 );
394                 }
395                         
396                 _reels.push_back (shared_ptr<Reel> (new Reel (picture, sound, subtitle)));
397         }
398 }
399
400 list<string>
401 DCP::equals (DCP const & other, EqualityOptions opt) const
402 {
403         list<string> notes;
404         
405         if (opt.flags & LIBDCP_METADATA) {
406                 if (_name != other._name) {
407                         notes.push_back ("names differ");
408                 }
409                 if (_content_kind != other._content_kind) {
410                         notes.push_back ("content kinds differ");
411                 }
412                 if (_fps != other._fps) {
413                         notes.push_back ("frames per second differ");
414                 }
415                 if (_length != other._length) {
416                         notes.push_back ("lengths differ");
417                 }
418         }
419
420         if (_reels.size() != other._reels.size()) {
421                 notes.push_back ("reel counts differ");
422         }
423         
424         list<shared_ptr<const Reel> >::const_iterator a = _reels.begin ();
425         list<shared_ptr<const Reel> >::const_iterator b = other._reels.begin ();
426         
427         while (a != _reels.end ()) {
428                 list<string> n = (*a)->equals (*b, opt);
429                 notes.merge (n);
430                 ++a;
431                 ++b;
432         }
433
434         return notes;
435 }
436