Debian Codegraph @

tests/test_matroska.cpp

raw symbols SCIP
1 /***************************************************************************
2 copyright : (C) 2025 by Urs Fleisch
3 email : [email protected]
4 ***************************************************************************/
5
6 /***************************************************************************
7 * This library is free software; you can redistribute it and/or modify *
8 * it under the terms of the GNU Lesser General Public License version *
9 * 2.1 as published by the Free Software Foundation. *
10 * *
11 * This library is distributed in the hope that it will be useful, but *
12 * WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
14 * Lesser General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU Lesser General Public *
17 * License along with this library; if not, write to the Free Software *
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA *
19 * 02110-1301 USA *
20 * *
21 * Alternatively, this file is available under the Mozilla Public *
22 * License Version 1.1. You may obtain a copy of the License at *
23 * http://www.mozilla.org/MPL/ *
24 ***************************************************************************/
25
26 /*
27 * # Test files
28 *
29 * no-tags.mka was created from a small mp3 file using
30 * mkvmerge -o small.mka small.mp3
31 * The tags were removed afterwards.
32 *
33 * tags-before-cues.mkv was created using
34 * ffmpeg -t 0.1 -s qcif -f rawvideo -pix_fmt rgb24 -r 25 \
35 * -i /dev/zero zero_second.mkv
36 * The tags were added using Handbrake, which places them before the Cluster
37 * and Cues elements. The tags were rewritten to conform to the specification.
38 *
39 * optimized.mpk is the same as tags-before-cues.mkv, but optimized using
40 * mkclean --keep-cues --optimize tags-before-cues.mkv
41 * This is done to have a segment with the size encoded with fewer than 8 bytes,
42 * so the resizing of the segment can be verified by adding a large attachment.
43 *
44 * no-tags.webm was created using
45 * ffmpeg -f lavfi -i color=c=blue:s=64x64 -frames:v 1 \
46 * -pix_fmt yuv420p frame.yuv
47 * vpxenc --codec=vp8 --width=64 --height=64 --fps=10/1 \
48 * --end-usage=cq --cq-level=4 --lag-in-frames=0 --auto-alt-ref=0 \
49 * --profile=0 --target-bitrate=1000 -o onems.webm frame.yuv
50 * Then the EMBL void element after the seek head was transformed to have
51 * the content size encoded with 8 bytes instead of 1 byte to have it in the
52 * same format as used here.
53 *
54 * # File validation
55 *
56 * The files are read with read style "Accurate" to verify the segment positions
57 * in seek head and cues.
58 *
59 * # Manual testing
60 *
61 * The integrity of Matroska files modified with TagLib can be verified with
62 * mkvalidator v0.6.0. For inspection of files, mkvinfo and mkvtoolnix-gui
63 * are useful.
64 *
65 * All tags of Matroska files can be read and written using properties and
66 * complex properties, so tagwriter and tagreader are sufficient for testing.
67 *
68 * - Set standard tags
69 * examples/tagwriter -t 'Track Title' -a 'Artist Name' -A 'Album Title' \
70 * -c 'Comment' -g 'Genre' -y 2025 -T 1 test.mka
71 *
72 * To remove standard tags, set them to an empty string or 0 for numeric tags.
73 * Using the property interface, the properties listed in propertymapping.dox
74 * and arbitrary string tags with track target level can be written.
75 *
76 * - Insert property
77 * examples/tagwriter -I 'ALBUMARTIST' 'Album Artist' test.mka
78 * - Replace property
79 * examples/tagwriter -R 'ALBUMARTIST' 'Other Artist' test.mka
80 * - Delete property
81 * examples/tagwriter -D 'ALBUMARTIST' test.mka
82 *
83 * Pictures can be attached with a description
84 * examples/tagwriter -p file.jpg 'Picture description' test.mka
85 *
86 * Alternatively, they can be set using complex properties. A complex property
87 * can be set with
88 *
89 * examples/tagwriter -C <complex-property-key> <key1=val1,key2=val2,...> FILE
90 *
91 * The second parameter can be set to "" to delete complex properties with the
92 * given key. To set complex property values, a simple shorthand syntax can be
93 * used. Multiple maps are separated by ';', values within a map are assigned
94 * with key=value and separated by a ','. Types are automatically detected,
95 * double quotes can be used to force a string. A ByteVector can be constructed
96 * from the contents of a file with the path given after "file://". There is
97 * no escape character, but hex codes are supported, e.g. "\x2C" to include a ','
98 * and \x3B to include a ';'.
99 *
100 * - Set an attached file in a Matroska file:
101 * examples/tagwriter -C file.bin \
102 * 'fileName=file.bin,data=file://file.bin,mimeType=application/octet-stream' \
103 * file.mka
104 *
105 * - Set simple tag with target type in a Matroska file:
106 * examples/tagwriter -C PART_NUMBER \
107 * 'name=PART_NUMBER,targetTypeValue=20,value="2"' file.mka
108 *
109 * - Set simple tag with binary value in a Matroska file:
110 * examples/tagwriter -C BINARY \
111 * name=BINARY,data=file://file.bin,targetTypeValue=60 file.mka
112 *
113 * # Test coverage
114 *
115 * Not yet covered by the unit tests are:
116 * - MkCueDuration, MkCueBlockNumber, MkCueCodecState, MkCueReference, MkCueRefTime,
117 * MkBitDepth and the methods handling these elements because none of the test
118 * files has such elements,
119 * - some unused functions like EBML::parseVINT(), EBML::FloatElement::render(),
120 * - some error cases because they never occur with the unit tests.
121 */
122
123 #include <string>
124 #include <cstdio>
125
126 #include "tbytevectorlist.h"
127 #include "tbytevectorstream.h"
128 #include "tpropertymap.h"
129 #include "matroskafile.h"
130 #include "matroskatag.h"
131 #include "matroskaattachments.h"
132 #include "matroskaattachedfile.h"
133 #include "matroskachapter.h"
134 #include "matroskachapteredition.h"
135 #include "matroskachapters.h"
136 #include "matroskasimpletag.h"
137 #include "plainfile.h"
138 #include <cppunit/extensions/HelperMacros.h>
139 #include "utils.h"
140
141 using namespace std;
142 using namespace TagLib;
143
144 class TestMatroska : public CppUnit::TestFixture
145 {
146 CPPUNIT_TEST_SUITE(TestMatroska);
147 CPPUNIT_TEST(testPropertiesMka);
148 CPPUNIT_TEST(testPropertiesMkv);
149 CPPUNIT_TEST(testPropertiesWebm);
150 CPPUNIT_TEST(testSimpleTagsAndAttachments);
151 CPPUNIT_TEST(testAddRemoveTagsAttachments);
152 CPPUNIT_TEST(testTagsWebm);
153 CPPUNIT_TEST(testRepeatedSave);
154 CPPUNIT_TEST(testPropertyInterface);
155 CPPUNIT_TEST(testComplexProperties);
156 CPPUNIT_TEST(testOpenInvalid);
157 CPPUNIT_TEST(testSegmentSizeChange);
158 CPPUNIT_TEST(testChapters);
159 CPPUNIT_TEST(testSaveTypes);
160 CPPUNIT_TEST(testSaveTypesBeforeCues);
161 CPPUNIT_TEST(testSaveTypesNoTrailingVoid);
162 CPPUNIT_TEST(testSaveTypesReclaimVoid);
163 CPPUNIT_TEST_SUITE_END();
164
165 public:
166 void testPropertiesMka()
167 {
168 Matroska::File f(TEST_FILE_PATH_C("no-tags.mka"));
169 CPPUNIT_ASSERT(f.audioProperties());
170 CPPUNIT_ASSERT_EQUAL(0, f.audioProperties()->lengthInSeconds());
171 CPPUNIT_ASSERT_EQUAL(444, f.audioProperties()->lengthInMilliseconds());
172 CPPUNIT_ASSERT_EQUAL(223, f.audioProperties()->bitrate());
173 CPPUNIT_ASSERT_EQUAL(2, f.audioProperties()->channels());
174 CPPUNIT_ASSERT_EQUAL(44100, f.audioProperties()->sampleRate());
175 CPPUNIT_ASSERT_EQUAL(String("matroska"), f.audioProperties()->docType());
176 CPPUNIT_ASSERT_EQUAL(4, f.audioProperties()->docTypeVersion());
177 CPPUNIT_ASSERT_EQUAL(String("A_MPEG/L3"), f.audioProperties()->codecName());
178 CPPUNIT_ASSERT_EQUAL(String(""), f.audioProperties()->title());
179 }
180
181 void testPropertiesMkv()
182 {
183 Matroska::File f(TEST_FILE_PATH_C("tags-before-cues.mkv"));
184 CPPUNIT_ASSERT(f.audioProperties());
185 CPPUNIT_ASSERT_EQUAL(0, f.audioProperties()->lengthInSeconds());
186 CPPUNIT_ASSERT_EQUAL(120, f.audioProperties()->lengthInMilliseconds());
187 CPPUNIT_ASSERT_EQUAL(227, f.audioProperties()->bitrate());
188 CPPUNIT_ASSERT_EQUAL(0, f.audioProperties()->channels());
189 CPPUNIT_ASSERT_EQUAL(0, f.audioProperties()->sampleRate());
190 CPPUNIT_ASSERT_EQUAL(String("matroska"), f.audioProperties()->docType());
191 CPPUNIT_ASSERT_EQUAL(4, f.audioProperties()->docTypeVersion());
192 CPPUNIT_ASSERT_EQUAL(String(""), f.audioProperties()->codecName());
193 CPPUNIT_ASSERT_EQUAL(String("handbrake"), f.audioProperties()->title());
194 }
195
196 void testPropertiesWebm()
197 {
198 Matroska::File f(TEST_FILE_PATH_C("no-tags.webm"));
199 CPPUNIT_ASSERT(f.audioProperties());
200 CPPUNIT_ASSERT_EQUAL(0, f.audioProperties()->lengthInSeconds());
201 CPPUNIT_ASSERT_EQUAL(1, f.audioProperties()->lengthInMilliseconds());
202 CPPUNIT_ASSERT_EQUAL(2816, f.audioProperties()->bitrate());
203 CPPUNIT_ASSERT_EQUAL(0, f.audioProperties()->channels());
204 CPPUNIT_ASSERT_EQUAL(0, f.audioProperties()->sampleRate());
205 CPPUNIT_ASSERT_EQUAL(String("webm"), f.audioProperties()->docType());
206 CPPUNIT_ASSERT_EQUAL(4, f.audioProperties()->docTypeVersion());
207 CPPUNIT_ASSERT_EQUAL(String(""), f.audioProperties()->codecName());
208 CPPUNIT_ASSERT_EQUAL(String(""), f.audioProperties()->title());
209
210 Matroska::File noProps(TEST_FILE_PATH_C("no-tags.webm"), false);
211 CPPUNIT_ASSERT(!noProps.audioProperties());
212 }
213
214 void testSimpleTagsAndAttachments()
215 {
216 ScopedFileCopy copy("no-tags", ".mka");
217 string newname = copy.fileName();
218 {
219 Matroska::File f(newname.c_str());
220 CPPUNIT_ASSERT(f.isValid());
221 CPPUNIT_ASSERT(!f.tag(false));
222 CPPUNIT_ASSERT(!f.attachments(false));
223 auto tag = f.tag(true);
224 CPPUNIT_ASSERT(tag->isEmpty());
225 tag->addSimpleTag(Matroska::SimpleTag(
226 "Test Name 2", String("Test Value 2"),
227 Matroska::SimpleTag::TargetTypeValue::Album,
228 {}, true, 0x72ac, 0xed17, 0xca97, 0xa7ac));
229 tag->insertSimpleTag(0, Matroska::SimpleTag(
230 "Test Name 1", String("Test Value 1"),
231 Matroska::SimpleTag::TargetTypeValue::Track, "en"));
232 tag->insertSimpleTag(1, Matroska::SimpleTag(
233 "Test Name 3", String("Test Value 3")));
234 tag->removeSimpleTag(1);
235 tag->setTitle("Test title");
236 tag->setArtist("Test artist");
237 tag->setYear(1969);
238 auto attachments = f.attachments(true);
239 attachments->addAttachedFile(Matroska::AttachedFile(
240 "JPEG data", "cover.jpg", "image/jpeg", 5081000385627515072ULL,
241 "Cover"));
242 CPPUNIT_ASSERT(f.save());
243 }
244 {
245 Matroska::File f(newname.c_str(), true, AudioProperties::Accurate);
246 CPPUNIT_ASSERT(f.isValid());
247 auto tag = f.tag(false);
248 CPPUNIT_ASSERT(tag);
249 auto attachments = f.attachments(false);
250 CPPUNIT_ASSERT(attachments);
251 CPPUNIT_ASSERT(!tag->isEmpty());
252
253 CPPUNIT_ASSERT_EQUAL(String("Test title"), tag->title());
254 CPPUNIT_ASSERT_EQUAL(String("Test artist"), tag->artist());
255 CPPUNIT_ASSERT_EQUAL(1969U, tag->year());
256 CPPUNIT_ASSERT_EQUAL(String(""), tag->album());
257 CPPUNIT_ASSERT_EQUAL(String(""), tag->comment());
258 CPPUNIT_ASSERT_EQUAL(String(""), tag->genre());
259 CPPUNIT_ASSERT_EQUAL(0U, tag->track());
260
261 const auto &simpleTags = tag->simpleTagsList();
262 CPPUNIT_ASSERT_EQUAL(5U, simpleTags.size());
263
264 CPPUNIT_ASSERT_EQUAL(String("en"), simpleTags[0].language());
265 CPPUNIT_ASSERT_EQUAL(String("Test Name 1"), simpleTags[0].name());
266 CPPUNIT_ASSERT_EQUAL(String("Test Value 1"), simpleTags[0].toString());
267 CPPUNIT_ASSERT_EQUAL(ByteVector(), simpleTags[0].toByteVector());
268 CPPUNIT_ASSERT_EQUAL(true, simpleTags[0].defaultLanguageFlag());
269 CPPUNIT_ASSERT_EQUAL(Matroska::SimpleTag::TargetTypeValue::Track, simpleTags[0].targetTypeValue());
270 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[0].trackUid());
271 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[0].editionUid());
272 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[0].chapterUid());
273 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[0].attachmentUid());
274 CPPUNIT_ASSERT_EQUAL(Matroska::SimpleTag::ValueType::StringType, simpleTags[0].type());
275
276 CPPUNIT_ASSERT_EQUAL(String("und"), simpleTags[1].language());
277 CPPUNIT_ASSERT_EQUAL(String("TITLE"), simpleTags[1].name());
278 CPPUNIT_ASSERT_EQUAL(String("Test title"), simpleTags[1].toString());
279 CPPUNIT_ASSERT_EQUAL(ByteVector(), simpleTags[1].toByteVector());
280 CPPUNIT_ASSERT_EQUAL(true, simpleTags[1].defaultLanguageFlag());
281 CPPUNIT_ASSERT_EQUAL(Matroska::SimpleTag::TargetTypeValue::Track, simpleTags[1].targetTypeValue());
282 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[1].trackUid());
283 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[1].editionUid());
284 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[1].chapterUid());
285 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[1].attachmentUid());
286 CPPUNIT_ASSERT_EQUAL(Matroska::SimpleTag::ValueType::StringType, simpleTags[1].type());
287
288 CPPUNIT_ASSERT_EQUAL(String("und"), simpleTags[2].language());
289 CPPUNIT_ASSERT_EQUAL(String("ARTIST"), simpleTags[2].name());
290 CPPUNIT_ASSERT_EQUAL(String("Test artist"), simpleTags[2].toString());
291 CPPUNIT_ASSERT_EQUAL(ByteVector(), simpleTags[2].toByteVector());
292 CPPUNIT_ASSERT_EQUAL(true, simpleTags[2].defaultLanguageFlag());
293 CPPUNIT_ASSERT_EQUAL(Matroska::SimpleTag::TargetTypeValue::Track, simpleTags[2].targetTypeValue());
294 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[2].trackUid());
295 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[2].editionUid());
296 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[2].chapterUid());
297 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[2].attachmentUid());
298 CPPUNIT_ASSERT_EQUAL(Matroska::SimpleTag::ValueType::StringType, simpleTags[2].type());
299
300 CPPUNIT_ASSERT_EQUAL(String("und"), simpleTags[3].language());
301 CPPUNIT_ASSERT_EQUAL(String("DATE_RECORDED"), simpleTags[3].name());
302 CPPUNIT_ASSERT_EQUAL(String("1969"), simpleTags[3].toString());
303 CPPUNIT_ASSERT_EQUAL(ByteVector(), simpleTags[3].toByteVector());
304 CPPUNIT_ASSERT_EQUAL(true, simpleTags[3].defaultLanguageFlag());
305 CPPUNIT_ASSERT_EQUAL(Matroska::SimpleTag::TargetTypeValue::Track, simpleTags[3].targetTypeValue());
306 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[3].trackUid());
307 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[3].editionUid());
308 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[3].chapterUid());
309 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[3].attachmentUid());
310 CPPUNIT_ASSERT_EQUAL(Matroska::SimpleTag::ValueType::StringType, simpleTags[3].type());
311
312 CPPUNIT_ASSERT_EQUAL(String("und"), simpleTags[4].language());
313 CPPUNIT_ASSERT_EQUAL(String("Test Name 2"), simpleTags[4].name());
314 CPPUNIT_ASSERT_EQUAL(String("Test Value 2"), simpleTags[4].toString());
315 CPPUNIT_ASSERT_EQUAL(ByteVector(), simpleTags[4].toByteVector());
316 CPPUNIT_ASSERT_EQUAL(true, simpleTags[4].defaultLanguageFlag());
317 CPPUNIT_ASSERT_EQUAL(Matroska::SimpleTag::TargetTypeValue::Album, simpleTags[4].targetTypeValue());
318 CPPUNIT_ASSERT_EQUAL(0x72acULL, simpleTags[4].trackUid());
319 CPPUNIT_ASSERT_EQUAL(0xed17ULL, simpleTags[4].editionUid());
320 CPPUNIT_ASSERT_EQUAL(0xca97ULL, simpleTags[4].chapterUid());
321 CPPUNIT_ASSERT_EQUAL(0xa7acULL, simpleTags[4].attachmentUid());
322 CPPUNIT_ASSERT_EQUAL(Matroska::SimpleTag::ValueType::StringType, simpleTags[4].type());
323
324 const auto &attachedFiles = attachments->attachedFileList();
325 CPPUNIT_ASSERT_EQUAL(1U, attachedFiles.size());
326
327 CPPUNIT_ASSERT_EQUAL(String("Cover"), attachedFiles[0].description());
328 CPPUNIT_ASSERT_EQUAL(String("cover.jpg"), attachedFiles[0].fileName());
329 CPPUNIT_ASSERT_EQUAL(String("image/jpeg"), attachedFiles[0].mediaType());
330 CPPUNIT_ASSERT_EQUAL(ByteVector("JPEG data"), attachedFiles[0].data());
331 CPPUNIT_ASSERT_EQUAL(5081000385627515072ULL, attachedFiles[0].uid());
332
333 PropertyMap expectedProps;
334 expectedProps["ARTIST"] = StringList("Test artist");
335 expectedProps["DATE"] = StringList("1969");
336 expectedProps["TEST NAME 1"] = StringList("Test Value 1");
337 expectedProps["TITLE"] = StringList("Test title");
338 auto props = f.properties();
339 if (expectedProps != props) {
340 CPPUNIT_ASSERT_EQUAL(expectedProps.toString(), props.toString());
341 }
342 CPPUNIT_ASSERT(expectedProps == props);
343 CPPUNIT_ASSERT(expectedProps == tag->properties());
344
345 auto keys = f.complexPropertyKeys();
346 CPPUNIT_ASSERT_EQUAL(StringList({"Test Name 2", "PICTURE"}), keys);
347 auto pictures = f.complexProperties("PICTURE");
348 CPPUNIT_ASSERT_EQUAL(1U, pictures.size());
349 const VariantMap expectedPic {
350 {"data", ByteVector("JPEG data")},
351 {"mimeType", "image/jpeg"},
352 {"description", "Cover"},
353 {"fileName", "cover.jpg"},
354 {"uid", 5081000385627515072ULL}
355 };
356 CPPUNIT_ASSERT(List<VariantMap>({expectedPic}) == pictures);
357 const VariantMap expectedComplexProps {
358 {"defaultLanguage", true},
359 {"language", "und"},
360 {"name", "Test Name 2"},
361 {"value", "Test Value 2"},
362 {"targetTypeValue", 50},
363 {"trackUid", 0x72acULL},
364 {"editionUid", 0xed17ULL},
365 {"chapterUid", 0xca97ULL},
366 {"attachmentUid", 0xa7acULL},
367 };
368 auto complexProps = f.complexProperties("Test Name 2");
369 CPPUNIT_ASSERT(List<VariantMap>({expectedComplexProps}) == complexProps);
370
371 tag->clearSimpleTags();
372 attachments->clear();
373 f.save();
374 }
375 {
376 Matroska::File f(newname.c_str(), true, AudioProperties::Accurate);
377 CPPUNIT_ASSERT(f.isValid());
378 CPPUNIT_ASSERT(!f.tag(false));
379 CPPUNIT_ASSERT(!f.attachments(false));
380 }
381
382 // Check if file without tags is same as original empty file
383 const ByteVector origData = PlainFile(TEST_FILE_PATH_C("no-tags.mka")).readAll();
384 const ByteVector fileData = PlainFile(newname.c_str()).readAll();
385 CPPUNIT_ASSERT(origData == fileData);
386 }
387
388 void testAddRemoveTagsAttachments()
389 {
390 ScopedFileCopy copy("no-tags", ".mka");
391 string newname = copy.fileName();
392 {
393 Matroska::File f(newname.c_str());
394 f.tag(true)->setComment("C");
395 CPPUNIT_ASSERT(f.save());
396 }
397 {
398 Matroska::File f(newname.c_str(), true, AudioProperties::Accurate);
399 CPPUNIT_ASSERT(f.isValid());
400 CPPUNIT_ASSERT_EQUAL(String("C"), f.tag(false)->comment());
401 f.tag()->setComment("");
402 CPPUNIT_ASSERT(f.save());
403 }
404 {
405 Matroska::File f(newname.c_str(), true, AudioProperties::Accurate);
406 CPPUNIT_ASSERT(f.isValid());
407 CPPUNIT_ASSERT(!f.tag(false));
408 f.attachments(true)->addAttachedFile(Matroska::AttachedFile(
409 ByteVector(), "", ""));
410 CPPUNIT_ASSERT(f.save());
411 }
412 {
413 Matroska::File f(newname.c_str(), true, AudioProperties::Accurate);
414 CPPUNIT_ASSERT(f.isValid());
415 const auto &attachedFiles = f.attachments(false)->attachedFileList();
416 CPPUNIT_ASSERT_EQUAL(1U, attachedFiles.size());
417 f.attachments()->removeAttachedFile(attachedFiles.front().uid());
418 CPPUNIT_ASSERT(f.save());
419 }
420 {
421 Matroska::File f(newname.c_str(), true, AudioProperties::Accurate);
422 CPPUNIT_ASSERT(f.isValid());
423 CPPUNIT_ASSERT(!f.tag(false));
424 CPPUNIT_ASSERT(!f.attachments(false));
425 }
426 }
427
428 void testTagsWebm()
429 {
430 ScopedFileCopy copy("no-tags", ".webm");
431 string newname = copy.fileName();
432 {
433 Matroska::File f(newname.c_str());
434 CPPUNIT_ASSERT(f.isValid());
435 CPPUNIT_ASSERT(!f.tag(false));
436 CPPUNIT_ASSERT(!f.attachments(false));
437
438 f.setProperties(SimplePropertyMap{
439 {"ARTIST", {"First artist", "second artist"}},
440 {"", {"Invalid", "Ignored"}}
441 });
442 f.tag(false)->addSimpleTag(Matroska::SimpleTag("", ByteVector("Not valid")));
443 CPPUNIT_ASSERT(f.save());
444 }
445 {
446 Matroska::File f(newname.c_str(), false, AudioProperties::Accurate);
447 CPPUNIT_ASSERT(f.isValid());
448 auto tag = f.tag(false);
449 CPPUNIT_ASSERT(tag);
450 CPPUNIT_ASSERT(!f.attachments(false));
451 CPPUNIT_ASSERT_EQUAL(String("First artist"), tag->artist());
452 CPPUNIT_ASSERT_EQUAL(StringList({"First artist", "second artist"}), f.properties().value("ARTIST"));
453
454 tag->setAlbum("Album");
455 tag->setTrack(5);
456 CPPUNIT_ASSERT(f.save());
457 }
458 {
459 Matroska::File f(newname.c_str(), false, AudioProperties::Accurate);
460 CPPUNIT_ASSERT(f.isValid());
461 auto tag = f.tag(false);
462 CPPUNIT_ASSERT(tag);
463 CPPUNIT_ASSERT_EQUAL(String("First artist"), tag->artist());
464 CPPUNIT_ASSERT_EQUAL(String("Album"), tag->album());
465 CPPUNIT_ASSERT_EQUAL(5U, tag->track());
466
467 tag->setArtist("");
468 tag->removeSimpleTag("TITLE", Matroska::SimpleTag::TargetTypeValue::Album);
469 tag->setTrack(0);
470 CPPUNIT_ASSERT(f.save());
471 }
472 {
473 Matroska::File f(newname.c_str(), false, AudioProperties::Accurate);
474 CPPUNIT_ASSERT(!f.tag(false));
475 CPPUNIT_ASSERT(!f.attachments(false));
476 }
477
478 // Check if file without tags is same as original empty file
479 const ByteVector origData = PlainFile(TEST_FILE_PATH_C("no-tags.webm")).readAll();
480 const ByteVector fileData = PlainFile(newname.c_str()).readAll();
481 CPPUNIT_ASSERT(origData == fileData);
482 }
483
484 void testRepeatedSave()
485 {
486 ScopedFileCopy copy("no-tags", ".mka");
487 string newname = copy.fileName();
488 String text = "01234 56789 ABCDE FGHIJ 01234 56789 ABCDE FGHIJ 01234 56789";
489 {
490 Matroska::File f(newname.c_str());
491 CPPUNIT_ASSERT(f.save());
492 f.tag(true)->setTitle(text.substr(0, 23));
493 CPPUNIT_ASSERT(f.save());
494 f.tag(true)->setTitle(text.substr(0, 5));
495 CPPUNIT_ASSERT(f.save());
496 f.tag(true)->setTitle(text);
497 CPPUNIT_ASSERT(f.save());
498 }
499 {
500 Matroska::File f(newname.c_str(), true, AudioProperties::Accurate);
501 CPPUNIT_ASSERT(f.isValid());
502 CPPUNIT_ASSERT_EQUAL(text, f.tag()->title());
503 }
504 }
505
506 void testPropertyInterface()
507 {
508 ScopedFileCopy copy("tags-before-cues", ".mkv");
509 string newname = copy.fileName();
510
511 PropertyMap initialProps;
512 initialProps["ARTIST"] = StringList("Actors");
513 initialProps["RELEASEDATE"] = StringList("2023");
514 initialProps["DESCRIPTION"] = StringList("Description");
515 initialProps["DIRECTOR"] = StringList("Director");
516 initialProps["ENCODEDBY"] = StringList("Lavf59.27.100");
517 initialProps["GENRE"] = StringList("Genre");
518 initialProps["SUMMARY"] = StringList("Comment");
519 initialProps["SYNOPSIS"] = StringList("Plot");
520
521 const VariantMap initialComplexProps {
522 {"defaultLanguage", true},
523 {"language", "und"},
524 {"name", "DURATION"},
525 {"value", "00:00:00.120000000"},
526 {"trackUid", 9584013959154292683ULL},
527 };
528
529 PropertyMap newProps;
530 newProps["ALBUM"] = StringList("Album");
531 newProps["ALBUMARTIST"] = StringList("Album Artist");
532 newProps["ALBUMARTISTSORT"] = StringList("Album Artist Sort");
533 newProps["ALBUMSORT"] = StringList("Album Sort");
534 newProps["ARTIST"] = StringList("Artist");
535 newProps["ARTISTS"] = StringList("Artists");
536 newProps["ARTISTSORT"] = StringList("Artist Sort");
537 newProps["ASIN"] = StringList("ASIN");
538 newProps["BARCODE"] = StringList("Barcode");
539 newProps["CATALOGNUMBER"] = StringList("Catalog Number 1").append("Catalog Number 2");
540 newProps["COMMENT"] = StringList("Comment");
541 newProps["DATE"] = StringList("2021-01-10");
542 newProps["DISCNUMBER"] = StringList("3");
543 newProps["DISCTOTAL"] = StringList("5");
544 newProps["DJMIXER"] = StringList("Mixed by");
545 newProps["ENCODEDBY"] = StringList("Encoded by");
546 newProps["ENCODING"] = StringList("Encoder settings");
547 newProps["ENCODINGTIME"] = StringList("Date encoded");
548 newProps["GENRE"] = StringList("Genre");
549 newProps["INITIALKEY"] = StringList("Initial key");
550 newProps["ISRC"] = StringList("UKAAA0500001");
551 newProps["LABEL"] = StringList("Label 1").append("Label 2");
552 newProps["MEDIA"] = StringList("Media");
553 newProps["MUSICBRAINZ_ALBUMARTISTID"] = StringList("MusicBrainz_AlbumartistID");
554 newProps["MUSICBRAINZ_ALBUMID"] = StringList("MusicBrainz_AlbumID");
555 newProps["MUSICBRAINZ_ARTISTID"] = StringList("MusicBrainz_ArtistID");
556 newProps["MUSICBRAINZ_RELEASEGROUPID"] = StringList("MusicBrainz_ReleasegroupID");
557 newProps["MUSICBRAINZ_RELEASETRACKID"] = StringList("MusicBrainz_ReleasetrackID");
558 newProps["MUSICBRAINZ_TRACKID"] = StringList("MusicBrainz_TrackID");
559 newProps["OWNER"] = StringList("Purchase owner");
560 newProps["ORIGINALDATE"] = StringList("2021-01-09");
561 newProps["RELEASECOUNTRY"] = StringList("Release Country");
562 newProps["RELEASEDATE"] = StringList("2021-01-10");
563 newProps["RELEASESTATUS"] = StringList("Release Status");
564 newProps["RELEASETYPE"] = StringList("Release Type");
565 newProps["REMIXER"] = StringList("Remixed by");
566 newProps["SCRIPT"] = StringList("Script");
567 newProps["TAGGINGDATE"] = StringList("2021-01-08");
568 newProps["TITLE"] = StringList("Title");
569 newProps["TRACKNUMBER"] = StringList("2");
570 newProps["TRACKTOTAL"] = StringList("4");
571
572 const VariantMap newComplexProps {
573 {"defaultLanguage", false},
574 {"language", "en"},
575 {"name", "BINARY"},
576 {"data", ByteVector("\x01\x02\x03\x04\x05\x06")},
577 {"targetTypeValue", static_cast<int>(Matroska::SimpleTag::TargetTypeValue::Collection)},
578 };
579 {
580 Matroska::File f(newname.c_str());
581 CPPUNIT_ASSERT(f.isValid());
582 auto tag = f.tag(false);
583 CPPUNIT_ASSERT(tag);
584 CPPUNIT_ASSERT(!f.attachments(false));
585
586 CPPUNIT_ASSERT_EQUAL(String("handbrake"), tag->title());
587 CPPUNIT_ASSERT_EQUAL(String("Actors"), tag->artist());
588 CPPUNIT_ASSERT_EQUAL(String(""), tag->album());
589 CPPUNIT_ASSERT_EQUAL(String(""), tag->comment());
590 CPPUNIT_ASSERT_EQUAL(String("Genre"), tag->genre());
591 CPPUNIT_ASSERT_EQUAL(0U, tag->track());
592
593 const auto &simpleTags = tag->simpleTagsList();
594 CPPUNIT_ASSERT_EQUAL(9U, simpleTags.size());
595
596 CPPUNIT_ASSERT_EQUAL(String("und"), simpleTags[0].language());
597 CPPUNIT_ASSERT_EQUAL(String("DURATION"), simpleTags[0].name());
598 CPPUNIT_ASSERT_EQUAL(String("00:00:00.120000000"), simpleTags[0].toString());
599 CPPUNIT_ASSERT_EQUAL(ByteVector(), simpleTags[0].toByteVector());
600 CPPUNIT_ASSERT_EQUAL(true, simpleTags[0].defaultLanguageFlag());
601 CPPUNIT_ASSERT_EQUAL(Matroska::SimpleTag::TargetTypeValue::None, simpleTags[0].targetTypeValue());
602 CPPUNIT_ASSERT_EQUAL(9584013959154292683ULL, simpleTags[0].trackUid());
603 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[0].editionUid());
604 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[0].chapterUid());
605 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[0].attachmentUid());
606 CPPUNIT_ASSERT_EQUAL(Matroska::SimpleTag::ValueType::StringType, simpleTags[0].type());
607
608 CPPUNIT_ASSERT_EQUAL(String("und"), simpleTags[1].language());
609 CPPUNIT_ASSERT_EQUAL(String("ARTIST"), simpleTags[1].name());
610 CPPUNIT_ASSERT_EQUAL(String("Actors"), simpleTags[1].toString());
611 CPPUNIT_ASSERT_EQUAL(ByteVector(), simpleTags[1].toByteVector());
612 CPPUNIT_ASSERT_EQUAL(true, simpleTags[1].defaultLanguageFlag());
613 CPPUNIT_ASSERT_EQUAL(Matroska::SimpleTag::TargetTypeValue::Track, simpleTags[1].targetTypeValue());
614 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[1].trackUid());
615 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[1].editionUid());
616 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[1].chapterUid());
617 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[1].attachmentUid());
618 CPPUNIT_ASSERT_EQUAL(Matroska::SimpleTag::ValueType::StringType, simpleTags[1].type());
619
620 CPPUNIT_ASSERT_EQUAL(String("und"), simpleTags[2].language());
621 CPPUNIT_ASSERT_EQUAL(String("DESCRIPTION"), simpleTags[2].name());
622 CPPUNIT_ASSERT_EQUAL(String("Description"), simpleTags[2].toString());
623 CPPUNIT_ASSERT_EQUAL(ByteVector(), simpleTags[2].toByteVector());
624 CPPUNIT_ASSERT_EQUAL(true, simpleTags[2].defaultLanguageFlag());
625 CPPUNIT_ASSERT_EQUAL(Matroska::SimpleTag::TargetTypeValue::Track, simpleTags[2].targetTypeValue());
626 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[2].trackUid());
627 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[2].editionUid());
628 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[2].chapterUid());
629 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[2].attachmentUid());
630 CPPUNIT_ASSERT_EQUAL(Matroska::SimpleTag::ValueType::StringType, simpleTags[2].type());
631
632 CPPUNIT_ASSERT_EQUAL(String("und"), simpleTags[3].language());
633 CPPUNIT_ASSERT_EQUAL(String("DIRECTOR"), simpleTags[3].name());
634 CPPUNIT_ASSERT_EQUAL(String("Director"), simpleTags[3].toString());
635 CPPUNIT_ASSERT_EQUAL(ByteVector(), simpleTags[3].toByteVector());
636 CPPUNIT_ASSERT_EQUAL(true, simpleTags[3].defaultLanguageFlag());
637 CPPUNIT_ASSERT_EQUAL(Matroska::SimpleTag::TargetTypeValue::Track, simpleTags[3].targetTypeValue());
638 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[3].trackUid());
639 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[3].editionUid());
640 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[3].chapterUid());
641 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[3].attachmentUid());
642 CPPUNIT_ASSERT_EQUAL(Matroska::SimpleTag::ValueType::StringType, simpleTags[3].type());
643
644 CPPUNIT_ASSERT_EQUAL(String("und"), simpleTags[4].language());
645 CPPUNIT_ASSERT_EQUAL(String("ENCODER"), simpleTags[4].name());
646 CPPUNIT_ASSERT_EQUAL(String("Lavf59.27.100"), simpleTags[4].toString());
647 CPPUNIT_ASSERT_EQUAL(ByteVector(), simpleTags[4].toByteVector());
648 CPPUNIT_ASSERT_EQUAL(true, simpleTags[4].defaultLanguageFlag());
649 CPPUNIT_ASSERT_EQUAL(Matroska::SimpleTag::TargetTypeValue::Track, simpleTags[4].targetTypeValue());
650 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[4].trackUid());
651 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[4].editionUid());
652 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[4].chapterUid());
653 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[4].attachmentUid());
654 CPPUNIT_ASSERT_EQUAL(Matroska::SimpleTag::ValueType::StringType, simpleTags[4].type());
655
656 CPPUNIT_ASSERT_EQUAL(String("und"), simpleTags[5].language());
657 CPPUNIT_ASSERT_EQUAL(String("GENRE"), simpleTags[5].name());
658 CPPUNIT_ASSERT_EQUAL(String("Genre"), simpleTags[5].toString());
659 CPPUNIT_ASSERT_EQUAL(ByteVector(), simpleTags[5].toByteVector());
660 CPPUNIT_ASSERT_EQUAL(true, simpleTags[5].defaultLanguageFlag());
661 CPPUNIT_ASSERT_EQUAL(Matroska::SimpleTag::TargetTypeValue::Track, simpleTags[5].targetTypeValue());
662 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[5].trackUid());
663 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[5].editionUid());
664 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[5].chapterUid());
665 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[5].attachmentUid());
666 CPPUNIT_ASSERT_EQUAL(Matroska::SimpleTag::ValueType::StringType, simpleTags[5].type());
667
668 CPPUNIT_ASSERT_EQUAL(String("und"), simpleTags[6].language());
669 CPPUNIT_ASSERT_EQUAL(String("SUMMARY"), simpleTags[6].name());
670 CPPUNIT_ASSERT_EQUAL(String("Comment"), simpleTags[6].toString());
671 CPPUNIT_ASSERT_EQUAL(ByteVector(), simpleTags[6].toByteVector());
672 CPPUNIT_ASSERT_EQUAL(true, simpleTags[6].defaultLanguageFlag());
673 CPPUNIT_ASSERT_EQUAL(Matroska::SimpleTag::TargetTypeValue::Track, simpleTags[6].targetTypeValue());
674 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[6].trackUid());
675 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[6].editionUid());
676 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[6].chapterUid());
677 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[6].attachmentUid());
678 CPPUNIT_ASSERT_EQUAL(Matroska::SimpleTag::ValueType::StringType, simpleTags[6].type());
679
680 CPPUNIT_ASSERT_EQUAL(String("und"), simpleTags[7].language());
681 CPPUNIT_ASSERT_EQUAL(String("SYNOPSIS"), simpleTags[7].name());
682 CPPUNIT_ASSERT_EQUAL(String("Plot"), simpleTags[7].toString());
683 CPPUNIT_ASSERT_EQUAL(ByteVector(), simpleTags[7].toByteVector());
684 CPPUNIT_ASSERT_EQUAL(true, simpleTags[7].defaultLanguageFlag());
685 CPPUNIT_ASSERT_EQUAL(Matroska::SimpleTag::TargetTypeValue::Track, simpleTags[7].targetTypeValue());
686 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[7].trackUid());
687 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[7].editionUid());
688 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[7].chapterUid());
689 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[7].attachmentUid());
690 CPPUNIT_ASSERT_EQUAL(Matroska::SimpleTag::ValueType::StringType, simpleTags[7].type());
691
692 CPPUNIT_ASSERT_EQUAL(String("und"), simpleTags[8].language());
693 CPPUNIT_ASSERT_EQUAL(String("DATE_RELEASED"), simpleTags[8].name());
694 CPPUNIT_ASSERT_EQUAL(String("2023"), simpleTags[8].toString());
695 CPPUNIT_ASSERT_EQUAL(ByteVector(), simpleTags[8].toByteVector());
696 CPPUNIT_ASSERT_EQUAL(true, simpleTags[8].defaultLanguageFlag());
697 CPPUNIT_ASSERT_EQUAL(Matroska::SimpleTag::TargetTypeValue::Album, simpleTags[8].targetTypeValue());
698 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[8].trackUid());
699 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[8].editionUid());
700 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[8].chapterUid());
701 CPPUNIT_ASSERT_EQUAL(0ULL, simpleTags[8].attachmentUid());
702 CPPUNIT_ASSERT_EQUAL(Matroska::SimpleTag::ValueType::StringType, simpleTags[8].type());
703
704 auto props = f.properties();
705 if (initialProps != props) {
706 CPPUNIT_ASSERT_EQUAL(initialProps.toString(), props.toString());
707 }
708 CPPUNIT_ASSERT(initialProps == props);
709 CPPUNIT_ASSERT(initialProps == tag->properties());
710
711 auto keys = f.complexPropertyKeys();
712 CPPUNIT_ASSERT_EQUAL(StringList({"DURATION"}), keys);
713 auto complexProps = f.complexProperties("DURATION");
714 CPPUNIT_ASSERT(List<VariantMap>({initialComplexProps}) == complexProps);
715
716 CPPUNIT_ASSERT(f.setComplexProperties("DURATION", {}));
717 CPPUNIT_ASSERT(f.setComplexProperties("BINARY", {newComplexProps}));
718 CPPUNIT_ASSERT(f.setProperties(newProps).isEmpty());
719 CPPUNIT_ASSERT(f.save());
720 }
721 {
722 Matroska::File f(newname.c_str(), true, AudioProperties::Accurate);
723 CPPUNIT_ASSERT(f.isValid());
724 auto tag = f.tag(false);
725 CPPUNIT_ASSERT(tag);
726 CPPUNIT_ASSERT(!f.attachments(false));
727
728 auto props = f.properties();
729 if (newProps != props) {
730 CPPUNIT_ASSERT_EQUAL(newProps.toString(), props.toString());
731 }
732 CPPUNIT_ASSERT(newProps == props);
733 CPPUNIT_ASSERT(newProps == tag->properties());
734
735 auto keys = f.complexPropertyKeys();
736 CPPUNIT_ASSERT_EQUAL(StringList({"BINARY"}), keys);
737 auto complexProps = f.complexProperties("BINARY");
738 CPPUNIT_ASSERT(List<VariantMap>({newComplexProps}) == complexProps);
739
740 const auto &simpleTags = tag->simpleTagsList();
741 StringList simpleTagNames;
742 for(const auto &simpleTag : simpleTags) {
743 simpleTagNames.append(simpleTag.name());
744 }
745 const StringList expectedSimpleTagNames {
746 "BINARY", "TITLE", "ARTIST", "ARTISTSORT", "TITLESORT",
747 "PART_NUMBER", "TOTAL_PARTS", "MUSICBRAINZ_ALBUMARTISTID", "MUSICBRAINZ_ALBUMID",
748 "MUSICBRAINZ_RELEASEGROUPID", "DATE_RELEASED", "ARTIST", "ARTISTS", "ARTISTSORT",
749 "ASIN", "BARCODE", "CATALOG_NUMBER", "CATALOG_NUMBER", "COMMENT",
750 "DATE_RECORDED", "MIXED_BY", "ENCODER", "ENCODER_SETTINGS", "DATE_ENCODED",
751 "GENRE", "INITIAL_KEY", "ISRC", "LABEL_CODE", "LABEL_CODE",
752 "ORIGINAL_MEDIA_TYPE", "MUSICBRAINZ_ARTISTID",
753 "MUSICBRAINZ_RELEASETRACKID", "MUSICBRAINZ_TRACKID", "ORIGINALDATE",
754 "PURCHASE_OWNER", "RELEASECOUNTRY", "RELEASESTATUS",
755 "RELEASETYPE", "REMIXED_BY", "SCRIPT", "DATE_TAGGED", "TITLE",
756 "PART_NUMBER", "TOTAL_PARTS"
757 };
758 CPPUNIT_ASSERT_EQUAL(expectedSimpleTagNames, simpleTagNames);
759
760 CPPUNIT_ASSERT(f.setComplexProperties("DURATION", {initialComplexProps}));
761 CPPUNIT_ASSERT(f.setComplexProperties("BINARY", {}));
762 CPPUNIT_ASSERT(f.setProperties(initialProps).isEmpty());
763 CPPUNIT_ASSERT(f.save());
764 }
765 {
766 Matroska::File f(newname.c_str(), true, AudioProperties::Accurate);
767 CPPUNIT_ASSERT(f.isValid());
768 CPPUNIT_ASSERT(f.tag(false));
769 CPPUNIT_ASSERT(!f.attachments(false));
770 }
771
772 // Check if file with initial tags is same as original file
773 const ByteVector origData = PlainFile(TEST_FILE_PATH_C("tags-before-cues.mkv")).readAll();
774 const ByteVector fileData = PlainFile(newname.c_str()).readAll();
775 CPPUNIT_ASSERT(origData == fileData);
776 }
777
778 void testComplexProperties()
779 {
780 ScopedFileCopy copy("no-tags", ".mka");
781 string newname = copy.fileName();
782 const VariantMap picture {
783 {"data", ByteVector("JPEG data")},
784 {"mimeType", "image/jpeg"},
785 {"description", "Cover"},
786 {"fileName", "folder.jpg"},
787 {"uid", 123ULL}
788 };
789 const VariantMap font {
790 {"data", ByteVector("TTF data")},
791 {"mimeType", "font/ttf"},
792 {"description", "Subtitle font"},
793 {"fileName", "file.ttf"},
794 {"uid", 456ULL}
795 };
796 const VariantMap trackUidTag {
797 {"defaultLanguage", true},
798 {"language", "und"},
799 {"name", "DURATION"},
800 {"trackUid", 8315232342706310039ULL},
801 {"value", "00:00:00.120000000"},
802 };
803 const VariantMap targetTypeTag {
804 {"defaultLanguage", false},
805 {"language", "en"},
806 {"name", "PART_NUMBER"},
807 {"targetTypeValue", 20},
808 {"value", "2"},
809 };
810 const VariantMap binaryTag {
811 {"defaultLanguage", false},
812 {"language", "und"},
813 {"name", "THUMBNAIL"},
814 {"targetTypeValue", 30},
815 {"data", ByteVector("JPEG data")},
816 };
817 {
818 Matroska::File f(newname.c_str());
819 CPPUNIT_ASSERT(f.isValid());
820 CPPUNIT_ASSERT(!f.tag(false));
821 CPPUNIT_ASSERT(!f.attachments(false));
822 CPPUNIT_ASSERT(f.complexPropertyKeys().isEmpty());
823 CPPUNIT_ASSERT(f.complexProperties("PICTURE").isEmpty());
824
825 CPPUNIT_ASSERT(f.setComplexProperties("PICTURE", {picture}));
826 CPPUNIT_ASSERT(f.setComplexProperties("file.ttf", {font}));
827 CPPUNIT_ASSERT(f.save());
828 }
829 {
830 Matroska::File f(newname.c_str(), true, AudioProperties::Accurate);
831 CPPUNIT_ASSERT(f.isValid());
832 CPPUNIT_ASSERT(!f.tag(false));
833 auto attachments = f.attachments(false);
834 CPPUNIT_ASSERT(attachments);
835
836 const auto &attachedFiles = attachments->attachedFileList();
837 CPPUNIT_ASSERT_EQUAL(2U, attachedFiles.size());
838 CPPUNIT_ASSERT_EQUAL(picture.value("fileName").value<String>(), attachedFiles[0].fileName());
839 CPPUNIT_ASSERT_EQUAL(picture.value("data").value<ByteVector>(), attachedFiles[0].data());
840 CPPUNIT_ASSERT_EQUAL(picture.value("description").value<String>(), attachedFiles[0].description());
841 CPPUNIT_ASSERT_EQUAL(picture.value("mimeType").value<String>(), attachedFiles[0].mediaType());
842 CPPUNIT_ASSERT_EQUAL(picture.value("uid").value<unsigned long long>(), attachedFiles[0].uid());
843 CPPUNIT_ASSERT_EQUAL(font.value("fileName").value<String>(), attachedFiles[1].fileName());
844 CPPUNIT_ASSERT_EQUAL(font.value("data").value<ByteVector>(), attachedFiles[1].data());
845 CPPUNIT_ASSERT_EQUAL(font.value("description").value<String>(), attachedFiles[1].description());
846 CPPUNIT_ASSERT_EQUAL(font.value("mimeType").value<String>(), attachedFiles[1].mediaType());
847 CPPUNIT_ASSERT_EQUAL(font.value("uid").value<unsigned long long>(), attachedFiles[1].uid());
848
849 CPPUNIT_ASSERT_EQUAL(StringList({"PICTURE", "file.ttf"}), f.complexPropertyKeys());
850 CPPUNIT_ASSERT(List<VariantMap>({picture}) == f.complexProperties("PICTURE"));
851 CPPUNIT_ASSERT(List<VariantMap>({font}) == f.complexProperties("file.ttf"));
852
853 CPPUNIT_ASSERT(f.setComplexProperties("DURATION", {trackUidTag}));
854 CPPUNIT_ASSERT(f.save());
855 }
856 {
857 Matroska::File f(newname.c_str(), true, AudioProperties::Accurate);
858 CPPUNIT_ASSERT(f.isValid());
859 auto tag = f.tag(true);
860 CPPUNIT_ASSERT(tag);
861 CPPUNIT_ASSERT(f.attachments(false));
862
863 const auto &simpleTags = tag->simpleTagsList();
864 CPPUNIT_ASSERT_EQUAL(1U, simpleTags.size());
865 CPPUNIT_ASSERT_EQUAL(trackUidTag.value("value").value<String>(), simpleTags[0].toString());
866 CPPUNIT_ASSERT_EQUAL(trackUidTag.value("language").value<String>(), simpleTags[0].language());
867 CPPUNIT_ASSERT_EQUAL(trackUidTag.value("name").value<String>(), simpleTags[0].name());
868 CPPUNIT_ASSERT_EQUAL(trackUidTag.value("defaultLanguage").value<bool>(), simpleTags[0].defaultLanguageFlag());
869 CPPUNIT_ASSERT_EQUAL(trackUidTag.value("trackUid").value<unsigned long long>(), simpleTags[0].trackUid());
870 CPPUNIT_ASSERT_EQUAL(trackUidTag.value("editionUid").value<unsigned long long>(), simpleTags[0].editionUid());
871 CPPUNIT_ASSERT_EQUAL(trackUidTag.value("chapterUid").value<unsigned long long>(), simpleTags[0].chapterUid());
872 CPPUNIT_ASSERT_EQUAL(trackUidTag.value("attachmentUid").value<unsigned long long>(), simpleTags[0].attachmentUid());
873 CPPUNIT_ASSERT_EQUAL(Matroska::SimpleTag::TargetTypeValue::None, simpleTags[0].targetTypeValue());
874 CPPUNIT_ASSERT_EQUAL(ByteVector(), simpleTags[0].toByteVector());
875 CPPUNIT_ASSERT_EQUAL(Matroska::SimpleTag::ValueType::StringType, simpleTags[0].type());
876
877 CPPUNIT_ASSERT_EQUAL(StringList({ "DURATION", "PICTURE", "file.ttf"}), f.complexPropertyKeys());
878 CPPUNIT_ASSERT(List<VariantMap>({trackUidTag}) == f.complexProperties("DURATION"));
879
880 CPPUNIT_ASSERT(f.setComplexProperties("PICTURE", {}));
881 CPPUNIT_ASSERT(f.setComplexProperties("file.ttf", {}));
882 CPPUNIT_ASSERT(f.setComplexProperties("PART_NUMBER", {targetTypeTag}));
883 CPPUNIT_ASSERT(f.setComplexProperties("THUMBNAIL", {binaryTag}));
884 CPPUNIT_ASSERT(f.save());
885 }
886 {
887 Matroska::File f(newname.c_str(), true, AudioProperties::Accurate);
888 CPPUNIT_ASSERT(f.isValid());
889 auto tag = f.tag(true);
890 CPPUNIT_ASSERT(tag);
891 CPPUNIT_ASSERT(!f.attachments(false));
892
893 const auto &simpleTags = tag->simpleTagsList();
894 CPPUNIT_ASSERT_EQUAL(3U, simpleTags.size());
895 CPPUNIT_ASSERT_EQUAL(trackUidTag.value("value").value<String>(), simpleTags[0].toString());
896 CPPUNIT_ASSERT_EQUAL(trackUidTag.value("language").value<String>(), simpleTags[0].language());
897 CPPUNIT_ASSERT_EQUAL(trackUidTag.value("name").value<String>(), simpleTags[0].name());
898 CPPUNIT_ASSERT_EQUAL(trackUidTag.value("defaultLanguage").value<bool>(), simpleTags[0].defaultLanguageFlag());
899 CPPUNIT_ASSERT_EQUAL(trackUidTag.value("trackUid").value<unsigned long long>(), simpleTags[0].trackUid());
900 CPPUNIT_ASSERT_EQUAL(trackUidTag.value("editionUid").value<unsigned long long>(), simpleTags[0].editionUid());
901 CPPUNIT_ASSERT_EQUAL(trackUidTag.value("chapterUid").value<unsigned long long>(), simpleTags[0].chapterUid());
902 CPPUNIT_ASSERT_EQUAL(trackUidTag.value("attachmentUid").value<unsigned long long>(), simpleTags[0].attachmentUid());
903 CPPUNIT_ASSERT_EQUAL(Matroska::SimpleTag::TargetTypeValue::None, simpleTags[0].targetTypeValue());
904 CPPUNIT_ASSERT_EQUAL(ByteVector(), simpleTags[0].toByteVector());
905 CPPUNIT_ASSERT_EQUAL(Matroska::SimpleTag::ValueType::StringType, simpleTags[0].type());
906
907 CPPUNIT_ASSERT_EQUAL(targetTypeTag.value("value").value<String>(), simpleTags[1].toString());
908 CPPUNIT_ASSERT_EQUAL(targetTypeTag.value("language").value<String>(), simpleTags[1].language());
909 CPPUNIT_ASSERT_EQUAL(targetTypeTag.value("name").value<String>(), simpleTags[1].name());
910 CPPUNIT_ASSERT_EQUAL(targetTypeTag.value("defaultLanguage").value<bool>(), simpleTags[1].defaultLanguageFlag());
911 CPPUNIT_ASSERT_EQUAL(targetTypeTag.value("trackUid").value<unsigned long long>(), simpleTags[1].trackUid());
912 CPPUNIT_ASSERT_EQUAL(targetTypeTag.value("editionUid").value<unsigned long long>(), simpleTags[1].editionUid());
913 CPPUNIT_ASSERT_EQUAL(targetTypeTag.value("chapterUid").value<unsigned long long>(), simpleTags[1].chapterUid());
914 CPPUNIT_ASSERT_EQUAL(targetTypeTag.value("attachmentUid").value<unsigned long long>(), simpleTags[1].attachmentUid());
915 CPPUNIT_ASSERT_EQUAL(Matroska::SimpleTag::TargetTypeValue::Subtrack, simpleTags[1].targetTypeValue());
916 CPPUNIT_ASSERT_EQUAL(ByteVector(), simpleTags[1].toByteVector());
917 CPPUNIT_ASSERT_EQUAL(Matroska::SimpleTag::ValueType::StringType, simpleTags[1].type());
918
919 CPPUNIT_ASSERT_EQUAL(binaryTag.value("data").value<ByteVector>(), simpleTags[2].toByteVector());
920 CPPUNIT_ASSERT_EQUAL(binaryTag.value("language").value<String>(), simpleTags[2].language());
921 CPPUNIT_ASSERT_EQUAL(binaryTag.value("name").value<String>(), simpleTags[2].name());
922 CPPUNIT_ASSERT_EQUAL(binaryTag.value("defaultLanguage").value<bool>(), simpleTags[2].defaultLanguageFlag());
923 CPPUNIT_ASSERT_EQUAL(binaryTag.value("trackUid").value<unsigned long long>(), simpleTags[2].trackUid());
924 CPPUNIT_ASSERT_EQUAL(binaryTag.value("editionUid").value<unsigned long long>(), simpleTags[2].editionUid());
925 CPPUNIT_ASSERT_EQUAL(binaryTag.value("chapterUid").value<unsigned long long>(), simpleTags[2].chapterUid());
926 CPPUNIT_ASSERT_EQUAL(binaryTag.value("attachmentUid").value<unsigned long long>(), simpleTags[2].attachmentUid());
927 CPPUNIT_ASSERT_EQUAL(Matroska::SimpleTag::TargetTypeValue::Track, simpleTags[2].targetTypeValue());
928 CPPUNIT_ASSERT_EQUAL(String(), simpleTags[2].toString());
929 CPPUNIT_ASSERT_EQUAL(Matroska::SimpleTag::ValueType::BinaryType, simpleTags[2].type());
930
931 CPPUNIT_ASSERT_EQUAL(StringList({"DURATION", "PART_NUMBER", "THUMBNAIL"}), f.complexPropertyKeys());
932 CPPUNIT_ASSERT(List<VariantMap>({trackUidTag}) == f.complexProperties("DURATION"));
933 CPPUNIT_ASSERT(List<VariantMap>({targetTypeTag}) == f.complexProperties("PART_NUMBER"));
934 CPPUNIT_ASSERT(List<VariantMap>({binaryTag}) == f.complexProperties("THUMBNAIL"));
935
936 CPPUNIT_ASSERT(f.setComplexProperties("PART_NUMBER", {}));
937 CPPUNIT_ASSERT(f.setComplexProperties("THUMBNAIL", {}));
938 CPPUNIT_ASSERT(f.setComplexProperties("DURATION", {}));
939 CPPUNIT_ASSERT(f.save());
940 }
941 {
942 Matroska::File f(newname.c_str(), true, AudioProperties::Accurate);
943 CPPUNIT_ASSERT(f.isValid());
944 CPPUNIT_ASSERT(!f.tag(false));
945 CPPUNIT_ASSERT(!f.attachments(false));
946
947 CPPUNIT_ASSERT(f.setComplexProperties("font/ttf", {{
948 {"data", ByteVector("TTF data")},
949 {"description", "Subtitle font"},
950 {"fileName", "file.ttf"},
951 }}));
952 CPPUNIT_ASSERT(f.setComplexProperties("file.otf", {{
953 {"data", ByteVector("OTF data")},
954 {"mimeType", "font/otf"},
955 {"description", "OpenType"},
956 }}));
957 CPPUNIT_ASSERT(f.save());
958 }
959 {
960 Matroska::File f(newname.c_str(), true, AudioProperties::Accurate);
961 CPPUNIT_ASSERT(f.isValid());
962 CPPUNIT_ASSERT(!f.tag(false));
963 CPPUNIT_ASSERT(f.attachments(false));
964
965 CPPUNIT_ASSERT_EQUAL(StringList({"file.ttf", "file.otf"}), f.complexPropertyKeys());
966 auto ttfs = f.complexProperties("file.ttf");
967 auto otfs = f.complexProperties("file.otf");
968 CPPUNIT_ASSERT_EQUAL(1U, ttfs.size());
969 CPPUNIT_ASSERT_EQUAL(1U, otfs.size());
970 auto ttf = ttfs.front();
971 auto otf = otfs.front();
972 CPPUNIT_ASSERT_EQUAL(ByteVector("TTF data"), ttf.value("data").value<ByteVector>());
973 CPPUNIT_ASSERT_EQUAL(String("Subtitle font"), ttf.value("description").value<String>());
974 CPPUNIT_ASSERT_EQUAL(String("file.ttf"), ttf.value("fileName").value<String>());
975 CPPUNIT_ASSERT_EQUAL(String("font/ttf"), ttf.value("mimeType").value<String>());
976 CPPUNIT_ASSERT(ttf.value("uid").value<unsigned long long>() != 0ULL);
977 CPPUNIT_ASSERT_EQUAL(ByteVector("OTF data"), otf.value("data").value<ByteVector>());
978 CPPUNIT_ASSERT_EQUAL(String("OpenType"), otf.value("description").value<String>());
979 CPPUNIT_ASSERT_EQUAL(String("file.otf"), otf.value("fileName").value<String>());
980 CPPUNIT_ASSERT_EQUAL(String("font/otf"), otf.value("mimeType").value<String>());
981 CPPUNIT_ASSERT(otf.value("uid").value<unsigned long long>() != 0ULL);
982
983 CPPUNIT_ASSERT(f.setComplexProperties("file.ttf", {}));
984 CPPUNIT_ASSERT(f.setComplexProperties("file.otf", {}));
985 CPPUNIT_ASSERT(f.save());
986 }
987
988 // Check if file without tags is same as original empty file
989 const ByteVector origData = PlainFile(TEST_FILE_PATH_C("no-tags.mka")).readAll();
990 const ByteVector fileData = PlainFile(newname.c_str()).readAll();
991 CPPUNIT_ASSERT(origData == fileData);
992 }
993
994 void testOpenInvalid()
995 {
996 {
997 Matroska::File f(TEST_FILE_PATH_C("garbage.mp3"));
998 CPPUNIT_ASSERT(!f.isValid());
999 }
1000 {
1001 ByteVector origData = PlainFile(TEST_FILE_PATH_C("no-tags.mka")).readAll();
1002 ByteVectorStream origStream(origData);
1003 Matroska::File origFile(&origStream, true, AudioProperties::Accurate);
1004 CPPUNIT_ASSERT(origFile.isValid());
1005
1006 ByteVector truncatedData = origData.mid(0, 4000);
1007 ByteVectorStream truncatedStream(truncatedData);
1008 Matroska::File truncatedFile(&truncatedStream, true, AudioProperties::Accurate);
1009 CPPUNIT_ASSERT(!truncatedFile.isValid());
1010 }
1011 }
1012
1013 void testSegmentSizeChange()
1014 {
1015 ScopedFileCopy copy("optimized", ".mkv");
1016 string newname = copy.fileName();
1017 {
1018 Matroska::File f(newname.c_str());
1019 CPPUNIT_ASSERT(f.isValid());
1020 CPPUNIT_ASSERT(f.tag(false));
1021 CPPUNIT_ASSERT(!f.attachments(false));
1022 auto attachments = f.attachments(true);
1023 // Large enough for emitSizeChanged() from Matroska::Segment::render()
1024 attachments->addAttachedFile(Matroska::AttachedFile(
1025 ByteVector(20000, 'x'), "cover.jpg", "image/jpeg",
1026 5081000385627515072ULL, "Cover"));
1027 CPPUNIT_ASSERT(f.save());
1028 }
1029 {
1030 Matroska::File f(newname.c_str(), true, AudioProperties::Accurate);
1031 CPPUNIT_ASSERT(f.isValid());
1032 auto tag = f.tag(true);
1033 CPPUNIT_ASSERT(tag);
1034 auto attachments = f.attachments(false);
1035 CPPUNIT_ASSERT(attachments);
1036 CPPUNIT_ASSERT(PropertyMap(SimplePropertyMap{
1037 {"ARTIST", {"Actors"}},
1038 {"DESCRIPTION", {"Description"}},
1039 {"DIRECTOR", {"Director"}},
1040 {"ENCODEDBY", {"Lavf59.27.100"}},
1041 {"GENRE", {"Genre"}},
1042 {"RELEASEDATE", {"2023"}},
1043 {"SUMMARY", {"Comment"}},
1044 {"SYNOPSIS", {"Plot"}}
1045 }) == tag->properties());
1046
1047 attachments->clear();
1048 f.save();
1049 }
1050 {
1051 Matroska::File f(newname.c_str(), true, AudioProperties::Accurate);
1052 CPPUNIT_ASSERT(f.isValid());
1053 CPPUNIT_ASSERT(f.tag(false));
1054 CPPUNIT_ASSERT(!f.attachments(false));
1055 }
1056 }
1057
1058 void testChapters()
1059 {
1060 const Matroska::ChapterEdition edition1(
1061 List<Matroska::Chapter>{
1062 Matroska::Chapter(
1063 0, 40000,
1064 List{
1065 Matroska::Chapter::Display("Chapter 1", "eng")},
1066 1, false),
1067 Matroska::Chapter(
1068 40000, 80000,
1069 List{
1070 Matroska::Chapter::Display("Chapter 2", "eng"),
1071 Matroska::Chapter::Display("Kapitel 2", "deu"),
1072 },
1073 2),
1074 Matroska::Chapter(
1075 80000, 120000,
1076 List{
1077 Matroska::Chapter::Display("Chapter 3", "und")},
1078 3, true)
1079 },
1080 true, false);
1081 const VariantMap chapterEdition1 {
1082 {"chapters",
1083 VariantList{
1084 VariantMap{
1085 {"displays", VariantList{
1086 VariantMap{{"language", "eng"}, {"string", "Chapter 1"}}}},
1087 {"timeEnd", 40000ULL},
1088 {"timeStart", 0ULL},
1089 {"uid", 1ULL}
1090 },
1091 VariantMap{
1092 {"displays", VariantList{
1093 VariantMap{{"language", "eng"}, {"string", "Chapter 2"}},
1094 VariantMap{{"language", "deu"}, {"string", "Kapitel 2"}}}},
1095 {"timeEnd", 80000ULL},
1096 {"timeStart", 40000ULL},
1097 {"uid", 2ULL}
1098 },
1099 VariantMap{
1100 {
1101 "displays", VariantList{
1102 VariantMap{{"language", "und"}, {"string", "Chapter 3"}}}
1103 },
1104 {"isHidden", true},
1105 {"timeEnd", 120000ULL},
1106 {"timeStart", 80000ULL},
1107 {"uid", 3ULL}
1108 }
1109 }
1110 },
1111 {"isDefault", true}
1112 };
1113 const VariantMap chapterEdition2 {
1114 {"chapters",
1115 VariantList{
1116 VariantMap{
1117 {"displays", VariantList{
1118 VariantMap{{"string", "Chapter A"}}}},
1119 {"timeStart", 10000ULL},
1120 {"uid", 1234567890ULL}
1121 },
1122 }
1123 },
1124 {"isOrdered", true},
1125 {"uid", 321ULL}
1126 };
1127
1128 ScopedFileCopy copy("tags-before-cues", ".mkv");
1129 string newname = copy.fileName();
1130 {
1131 Matroska::File f(newname.c_str());
1132 CPPUNIT_ASSERT(f.isValid());
1133 CPPUNIT_ASSERT(f.tag(false));
1134 CPPUNIT_ASSERT(!f.attachments(false));
1135 CPPUNIT_ASSERT(!f.chapters(false));
1136 CPPUNIT_ASSERT_EQUAL(StringList({"DURATION"}), f.complexPropertyKeys());
1137 CPPUNIT_ASSERT(f.complexProperties("CHAPTERS").isEmpty());
1138
1139 f.chapters(true)->addChapterEdition(edition1);
1140 CPPUNIT_ASSERT(f.save());
1141 }
1142 {
1143 Matroska::File f(newname.c_str());
1144 CPPUNIT_ASSERT(f.isValid());
1145 CPPUNIT_ASSERT(f.tag(false));
1146 CPPUNIT_ASSERT(!f.attachments(false));
1147 auto chapters = f.chapters(false);
1148 CPPUNIT_ASSERT(chapters);
1149 CPPUNIT_ASSERT_EQUAL(StringList({"DURATION", "CHAPTERS"}), f.complexPropertyKeys());
1150 auto chaptersProperties = f.complexProperties("CHAPTERS");
1151 CPPUNIT_ASSERT_EQUAL(1U, chaptersProperties.size());
1152 CPPUNIT_ASSERT_EQUAL(chapterEdition1, chaptersProperties.front());
1153
1154 CPPUNIT_ASSERT_EQUAL(1U, chapters->chapterEditionList().size());
1155 const auto &edition = chapters->chapterEditionList().front();
1156 CPPUNIT_ASSERT_EQUAL(true, edition.isDefault());
1157 CPPUNIT_ASSERT_EQUAL(false, edition.isOrdered());
1158 CPPUNIT_ASSERT_EQUAL(0ULL, edition.uid());
1159 const auto &chapterAtoms = edition.chapterList();
1160 CPPUNIT_ASSERT_EQUAL(3U, chapterAtoms.size());
1161 CPPUNIT_ASSERT_EQUAL(1ULL, chapterAtoms[0].uid());
1162 CPPUNIT_ASSERT_EQUAL(false, chapterAtoms[0].isHidden());
1163 CPPUNIT_ASSERT_EQUAL(0ULL, chapterAtoms[0].timeStart());
1164 CPPUNIT_ASSERT_EQUAL(40000ULL, chapterAtoms[0].timeEnd());
1165 CPPUNIT_ASSERT_EQUAL(1U, chapterAtoms[0].displayList().size());
1166 CPPUNIT_ASSERT_EQUAL(String("Chapter 1"), chapterAtoms[0].displayList()[0].string());
1167 CPPUNIT_ASSERT_EQUAL(String("eng"), chapterAtoms[0].displayList()[0].language());
1168 CPPUNIT_ASSERT_EQUAL(2ULL, chapterAtoms[1].uid());
1169 CPPUNIT_ASSERT_EQUAL(false, chapterAtoms[1].isHidden());
1170 CPPUNIT_ASSERT_EQUAL(40000ULL, chapterAtoms[1].timeStart());
1171 CPPUNIT_ASSERT_EQUAL(80000ULL, chapterAtoms[1].timeEnd());
1172 CPPUNIT_ASSERT_EQUAL(2U, chapterAtoms[1].displayList().size());
1173 CPPUNIT_ASSERT_EQUAL(String("Chapter 2"), chapterAtoms[1].displayList()[0].string());
1174 CPPUNIT_ASSERT_EQUAL(String("eng"), chapterAtoms[1].displayList()[0].language());
1175 CPPUNIT_ASSERT_EQUAL(String("Kapitel 2"), chapterAtoms[1].displayList()[1].string());
1176 CPPUNIT_ASSERT_EQUAL(String("deu"), chapterAtoms[1].displayList()[1].language());
1177 CPPUNIT_ASSERT_EQUAL(3ULL, chapterAtoms[2].uid());
1178 CPPUNIT_ASSERT_EQUAL(true, chapterAtoms[2].isHidden());
1179 CPPUNIT_ASSERT_EQUAL(80000ULL, chapterAtoms[2].timeStart());
1180 CPPUNIT_ASSERT_EQUAL(120000ULL, chapterAtoms[2].timeEnd());
1181 CPPUNIT_ASSERT_EQUAL(1U, chapterAtoms[2].displayList().size());
1182 CPPUNIT_ASSERT_EQUAL(String("Chapter 3"), chapterAtoms[2].displayList()[0].string());
1183 CPPUNIT_ASSERT_EQUAL(String("und"), chapterAtoms[2].displayList()[0].language());
1184
1185 CPPUNIT_ASSERT(f.setComplexProperties("CHAPTERS", {chapterEdition2}));
1186 CPPUNIT_ASSERT(f.save());
1187 }
1188 {
1189 Matroska::File f(newname.c_str(), true, AudioProperties::Accurate);
1190 CPPUNIT_ASSERT(f.isValid());
1191 CPPUNIT_ASSERT(f.tag(false));
1192 CPPUNIT_ASSERT(!f.attachments(false));
1193 auto chapters = f.chapters(false);
1194 CPPUNIT_ASSERT(chapters);
1195 CPPUNIT_ASSERT_EQUAL(StringList({"DURATION", "CHAPTERS"}), f.complexPropertyKeys());
1196 auto chaptersProperties = f.complexProperties("CHAPTERS");
1197 CPPUNIT_ASSERT_EQUAL(1U, chaptersProperties.size());
1198 CPPUNIT_ASSERT_EQUAL(chapterEdition2, chaptersProperties.front());
1199
1200 CPPUNIT_ASSERT_EQUAL(1U, chapters->chapterEditionList().size());
1201 const auto &edition = chapters->chapterEditionList().front();
1202 CPPUNIT_ASSERT_EQUAL(false, edition.isDefault());
1203 CPPUNIT_ASSERT_EQUAL(true, edition.isOrdered());
1204 CPPUNIT_ASSERT_EQUAL(321ULL, edition.uid());
1205 const auto &chapterAtoms = edition.chapterList();
1206 CPPUNIT_ASSERT_EQUAL(1U, chapterAtoms.size());
1207 CPPUNIT_ASSERT_EQUAL(1234567890ULL, chapterAtoms[0].uid());
1208 CPPUNIT_ASSERT_EQUAL(false, chapterAtoms[0].isHidden());
1209 CPPUNIT_ASSERT_EQUAL(10000ULL, chapterAtoms[0].timeStart());
1210 CPPUNIT_ASSERT_EQUAL(0ULL, chapterAtoms[0].timeEnd());
1211 CPPUNIT_ASSERT_EQUAL(1U, chapterAtoms[0].displayList().size());
1212 CPPUNIT_ASSERT_EQUAL(String("Chapter A"), chapterAtoms[0].displayList()[0].string());
1213 CPPUNIT_ASSERT_EQUAL(String(), chapterAtoms[0].displayList()[0].language());
1214
1215 const Matroska::ChapterEdition edition2 = chapters->chapterEditionList().front();
1216 chapters->removeChapterEdition(321ULL);
1217 chapters->addChapterEdition(edition1);
1218 chapters->addChapterEdition(edition2);
1219
1220 f.attachments(true)->addAttachedFile(Matroska::AttachedFile(
1221 ByteVector("PNG data"), "folder.png", "image/png", 1763187649ULL,
1222 "Cover"));
1223 CPPUNIT_ASSERT(f.save());
1224 }
1225 {
1226 Matroska::File f(newname.c_str(), true, AudioProperties::Accurate);
1227 CPPUNIT_ASSERT(f.isValid());
1228 CPPUNIT_ASSERT(f.tag(false));
1229 CPPUNIT_ASSERT(f.attachments(false));
1230 CPPUNIT_ASSERT(f.chapters(false));
1231
1232 CPPUNIT_ASSERT_EQUAL(StringList({"DURATION", "PICTURE", "CHAPTERS"}),
1233 f.complexPropertyKeys());
1234 auto chaptersProperties = f.complexProperties("CHAPTERS");
1235 CPPUNIT_ASSERT_EQUAL(2U, chaptersProperties.size());
1236 CPPUNIT_ASSERT_EQUAL(chapterEdition1, chaptersProperties.front());
1237 CPPUNIT_ASSERT_EQUAL(chapterEdition2, chaptersProperties.back());
1238
1239 f.attachments()->clear();
1240 f.chapters()->clear();
1241 CPPUNIT_ASSERT(f.save());
1242 }
1243 {
1244 Matroska::File f(newname.c_str(), true, AudioProperties::Accurate);
1245 CPPUNIT_ASSERT(f.isValid());
1246 CPPUNIT_ASSERT(f.tag(false));
1247 CPPUNIT_ASSERT(!f.attachments(false));
1248 }
1249
1250 // Check if file with initial tags is same as original file
1251 const ByteVector origData = PlainFile(TEST_FILE_PATH_C("tags-before-cues.mkv")).readAll();
1252 const ByteVector fileData = PlainFile(newname.c_str()).readAll();
1253 CPPUNIT_ASSERT(origData == fileData);
1254 }
1255
1256 void testSaveTypesBeforeCues()
1257 {
1258 // tags-before-cues.mkv layout:
1259 // SeekHead | Void | SegInfo | Tracks | Tags | Cluster | Cues
1260 //
1261 // Verify all three WriteStyles correctly grow the Tags element which
1262 // sits *before* the Cluster:
1263 // - Compact / DoNotShrink: bytes are inserted before the Cluster, the
1264 // Cluster shifts, the seek head and cue cluster positions must be
1265 // updated accordingly; the file must remain valid and tag content
1266 // must round-trip.
1267 // - AvoidInsert: the Tags element is replaced with a Void at its
1268 // original position and appended at the end of the segment, so the
1269 // Cluster must NOT shift; tag content must round-trip.
1270
1271 const ByteVector origData =
1272 PlainFile(TEST_FILE_PATH_C("tags-before-cues.mkv")).readAll();
1273
1274 // Cluster ID 0x1F43B675 does not appear in the SeekHead of this file,
1275 // so find() returns the offset of the actual Cluster element.
1276 const ByteVector clusterId = ByteVector::fromUInt(0x1F43B675U, true);
1277 const ByteVector tagsId = ByteVector::fromUInt(0x1254C367U, true);
1278 const ByteVector cuesId = ByteVector::fromUInt(0x1C53BB6BU, true);
1279 const int origClusterPos = origData.find(clusterId);
1280 CPPUNIT_ASSERT(origClusterPos > 0);
1281
1282 const String longTitle =
1283 "An Extremely Long Title Value That Is Definitely Larger Than The Original "
1284 "Tags Element In The File Because It Contains Many Characters To Ensure "
1285 "That The AvoidInsert Move-To-End Behavior Triggers Here";
1286 const String longArtist =
1287 "An Extremely Long Artist Name Value That Is Also Larger Than The Original "
1288 "Tags Element And Together With The Title Tag Makes The Rendered Output "
1289 "Exceed The Original Tags Size So The AvoidInsert Triggers";
1290
1291 for(const auto writeStyle : {Matroska::WriteStyle::Compact,
1292 Matroska::WriteStyle::DoNotShrink,
1293 Matroska::WriteStyle::AvoidInsert}) {
1294 const auto wsLabel = String::number(static_cast<int>(writeStyle)).to8Bit();
1295 ScopedFileCopy copy("tags-before-cues", ".mkv");
1296 const string newname = copy.fileName();
1297
1298 // Save with Tags significantly larger than the original Tags element.
1299 {
1300 Matroska::File f(newname.c_str());
1301 CPPUNIT_ASSERT_MESSAGE("Open ws=" + wsLabel, f.isValid());
1302 auto tag = f.tag(true);
1303 tag->clearSimpleTags();
1304 tag->addSimpleTag(Matroska::SimpleTag(
1305 String("TITLE"), longTitle,
1306 Matroska::SimpleTag::TargetTypeValue::Track));
1307 tag->addSimpleTag(Matroska::SimpleTag(
1308 String("ARTIST"), longArtist,
1309 Matroska::SimpleTag::TargetTypeValue::Track));
1310 CPPUNIT_ASSERT_MESSAGE("Save ws=" + wsLabel, f.save(writeStyle));
1311 }
1312
1313 // File must be valid: Accurate mode verifies seek-head and cue positions.
1314 // Tag content must round-trip exactly.
1315 {
1316 Matroska::File f(newname.c_str(), true, AudioProperties::Accurate);
1317 CPPUNIT_ASSERT_MESSAGE("Reopen valid ws=" + wsLabel, f.isValid());
1318 auto tag = f.tag(false);
1319 CPPUNIT_ASSERT_MESSAGE("Tag exists ws=" + wsLabel, tag != nullptr);
1320 const auto &simpleTags = tag->simpleTagsList();
1321 bool foundTitle = false, foundArtist = false;
1322 for(const auto &st : simpleTags) {
1323 if(st.name() == "TITLE" && st.toString() == longTitle)
1324 foundTitle = true;
1325 else if(st.name() == "ARTIST" && st.toString() == longArtist)
1326 foundArtist = true;
1327 }
1328 CPPUNIT_ASSERT_MESSAGE("TITLE roundtrip ws=" + wsLabel, foundTitle);
1329 CPPUNIT_ASSERT_MESSAGE("ARTIST roundtrip ws=" + wsLabel, foundArtist);
1330 }
1331
1332 const ByteVector newData = PlainFile(newname.c_str()).readAll();
1333 const int newClusterPos = newData.find(clusterId);
1334 CPPUNIT_ASSERT_MESSAGE("Cluster present ws=" + wsLabel, newClusterPos > 0);
1335
1336 if(writeStyle == Matroska::WriteStyle::AvoidInsert) {
1337 // Cluster must not shift in AvoidInsert mode.
1338 CPPUNIT_ASSERT_EQUAL_MESSAGE(
1339 "AvoidInsert must not shift Cluster",
1340 origClusterPos, newClusterPos);
1341 // Tags must be appended after Cues.
1342 const int cuesPos = newData.find(cuesId, newClusterPos);
1343 const int newTagsPos = newData.find(tagsId, cuesPos + 4);
1344 CPPUNIT_ASSERT_MESSAGE("Tags appended after Cues ws=" + wsLabel,
1345 newTagsPos > cuesPos);
1346 }
1347 else {
1348 // Compact / DoNotShrink: Tags grew in place, so Cluster must have
1349 // shifted to a higher offset.
1350 CPPUNIT_ASSERT_MESSAGE(
1351 "Cluster must shift when growing in place ws=" + wsLabel,
1352 newClusterPos > origClusterPos);
1353 }
1354 }
1355 }
1356
1357 void testSaveTypesNoTrailingVoid()
1358 {
1359 // After AvoidInsert moved the Tags element to the end of the segment,
1360 // a subsequent save with smaller content must not leave a trailing
1361 // EBML void at the very end of the segment. The trailing element may
1362 // shrink freely because no element follows it.
1363 ScopedFileCopy copy("tags-before-cues", ".mkv");
1364 const string newname = copy.fileName();
1365
1366 // Round 1: enlarge Tags so they get moved to the end.
1367 {
1368 Matroska::File f(newname.c_str());
1369 CPPUNIT_ASSERT(f.isValid());
1370 auto tag = f.tag(true);
1371 tag->clearSimpleTags();
1372 tag->addSimpleTag(Matroska::SimpleTag(
1373 String("TITLE"),
1374 String("An Extremely Long Title Value That Is Definitely Larger Than The Original "
1375 "Tags Element In The File Because It Contains Many Characters To Ensure "
1376 "That The AvoidInsert Move-To-End Behavior Triggers Here"),
1377 Matroska::SimpleTag::TargetTypeValue::Track));
1378 tag->addSimpleTag(Matroska::SimpleTag(
1379 String("ARTIST"),
1380 String("An Extremely Long Artist Name Value That Is Also Larger Than The Original "
1381 "Tags Element And Together With The Title Tag Makes The Rendered Output "
1382 "Exceed The Original Tags Size So The AvoidInsert Triggers"),
1383 Matroska::SimpleTag::TargetTypeValue::Track));
1384 CPPUNIT_ASSERT(f.save(Matroska::WriteStyle::AvoidInsert));
1385 }
1386 const size_t sizeAfterRound1 = PlainFile(newname.c_str()).readAll().size();
1387
1388 // Round 2: shrink Tags. The trailing element must shrink without
1389 // leaving a void at the end.
1390 {
1391 Matroska::File f(newname.c_str());
1392 CPPUNIT_ASSERT(f.isValid());
1393 auto tag = f.tag(true);
1394 tag->clearSimpleTags();
1395 tag->addSimpleTag(Matroska::SimpleTag(
1396 String("TITLE"), String("X"),
1397 Matroska::SimpleTag::TargetTypeValue::Track));
1398 CPPUNIT_ASSERT(f.save(Matroska::WriteStyle::AvoidInsert));
1399 }
1400 {
1401 Matroska::File f(newname.c_str(), true, AudioProperties::Accurate);
1402 CPPUNIT_ASSERT(f.isValid());
1403 CPPUNIT_ASSERT(f.tag(false) != nullptr);
1404 }
1405 const ByteVector newData = PlainFile(newname.c_str()).readAll();
1406
1407 // File must have shrunk because the trailing Tags element shrank.
1408 CPPUNIT_ASSERT(newData.size() < sizeAfterRound1);
1409
1410 // The last bytes of the file must be the (small) Tags element, not a
1411 // Void element. Find the Tags element after the Cues element and parse
1412 // its VINT size: the file must end exactly at Tags' end with nothing
1413 // (no Void) after it.
1414 const ByteVector clusterId = ByteVector::fromUInt(0x1F43B675U, true);
1415 const ByteVector cuesId = ByteVector::fromUInt(0x1C53BB6BU, true);
1416 const ByteVector tagsId = ByteVector::fromUInt(0x1254C367U, true);
1417 const int clusterPos = newData.find(clusterId);
1418 const int cuesPos = newData.find(cuesId, clusterPos);
1419 const int tagsPos = newData.find(tagsId, cuesPos + 4);
1420 CPPUNIT_ASSERT(tagsPos > cuesPos);
1421
1422 // Decode VINT data size of the Tags element. The first byte after the
1423 // 4-byte ID has a leading marker bit indicating the VINT length.
1424 const auto vintFirst = static_cast<unsigned char>(newData[tagsPos + 4]);
1425 int vintLen = 1;
1426 for(int b = 0; b < 8; ++b) {
1427 if(vintFirst & (0x80 >> b)) { vintLen = b + 1; break; }
1428 }
1429 unsigned long long dataSize = vintFirst & ((0x80 >> (vintLen - 1)) - 1);
1430 for(int i = 1; i < vintLen; ++i)
1431 dataSize = (dataSize << 8) | static_cast<unsigned char>(newData[tagsPos + 4 + i]);
1432 const unsigned long long tagsEnd =
1433 static_cast<unsigned long long>(tagsPos) + 4 + vintLen + dataSize;
1434 CPPUNIT_ASSERT_EQUAL_MESSAGE(
1435 "No trailing EBML void must remain at the end of the segment",
1436 static_cast<unsigned long long>(newData.size()), tagsEnd);
1437 }
1438
1439 void testSaveTypesReclaimVoid()
1440 {
1441 // After AvoidInsert moves a Tags element to the end (leaving a Void at
1442 // its original position), a subsequent save with WriteStyle::Compact
1443 // must produce a tightly packed file: the void left by the move must
1444 // be reclaimed and the file must be at most as large as the original.
1445 ScopedFileCopy copy("tags-before-cues", ".mkv");
1446 const string newname = copy.fileName();
1447
1448 // Step 1: AvoidInsert with enlarged Tags -> Tags moved to end, Void in
1449 // original slot. File grows.
1450 {
1451 Matroska::File f(newname.c_str());
1452 CPPUNIT_ASSERT(f.isValid());
1453 auto tag = f.tag(true);
1454 tag->clearSimpleTags();
1455 tag->addSimpleTag(Matroska::SimpleTag(String("TITLE"),
1456 String("An Extremely Long Title Value That Is Definitely Larger Than The Original "
1457 "Tags Element In The File Because It Contains Many Characters To Ensure "
1458 "That The AvoidInsert Move-To-End Behavior Triggers Here"),
1459 Matroska::SimpleTag::TargetTypeValue::Track));
1460 tag->addSimpleTag(Matroska::SimpleTag(String("ARTIST"),
1461 String("An Extremely Long Artist Name Value That Is Also Larger Than The Original "
1462 "Tags Element And Together With The Title Tag Makes The Rendered Output "
1463 "Exceed The Original Tags Size So The AvoidInsert Triggers"),
1464 Matroska::SimpleTag::TargetTypeValue::Track));
1465 CPPUNIT_ASSERT(f.save(Matroska::WriteStyle::AvoidInsert));
1466 }
1467 const size_t sizeAfterAvoidInsert =
1468 PlainFile(newname.c_str()).readAll().size();
1469 CPPUNIT_ASSERT(sizeAfterAvoidInsert >
1470 PlainFile(TEST_FILE_PATH_C("tags-before-cues.mkv")).readAll().size());
1471
1472 // Step 2: Save again with Compact and short tag values. Compact must
1473 // reclaim the void left by the prior move and produce a file no
1474 // larger than the original.
1475 {
1476 Matroska::File f(newname.c_str());
1477 CPPUNIT_ASSERT(f.isValid());
1478 auto tag = f.tag(true);
1479 tag->clearSimpleTags();
1480 tag->addSimpleTag(Matroska::SimpleTag(String("TITLE"), String("X"),
1481 Matroska::SimpleTag::TargetTypeValue::Track));
1482 CPPUNIT_ASSERT(f.save(Matroska::WriteStyle::Compact));
1483 }
1484 const size_t sizeAfterCompact =
1485 PlainFile(newname.c_str()).readAll().size();
1486 CPPUNIT_ASSERT_MESSAGE(
1487 "Compact must reclaim space after AvoidInsert grew the file",
1488 sizeAfterCompact < sizeAfterAvoidInsert);
1489
1490 // Reference: applying Compact directly to the original file with the
1491 // same tiny tags. Note: an orphan Void left in the middle of the
1492 // segment by AvoidInsert is not currently reclaimed by Compact (it is
1493 // attached as padding to a neighbouring element), so the post-Compact
1494 // size is allowed to be slightly larger than the reference. The
1495 // result must, however, be no larger than the original input file.
1496 ScopedFileCopy reference("tags-before-cues", ".mkv");
1497 {
1498 Matroska::File f(reference.fileName().c_str());
1499 CPPUNIT_ASSERT(f.isValid());
1500 auto tag = f.tag(true);
1501 tag->clearSimpleTags();
1502 tag->addSimpleTag(Matroska::SimpleTag(String("TITLE"), String("X"),
1503 Matroska::SimpleTag::TargetTypeValue::Track));
1504 CPPUNIT_ASSERT(f.save(Matroska::WriteStyle::Compact));
1505 }
1506 const size_t referenceCompactSize =
1507 PlainFile(reference.fileName().c_str()).readAll().size();
1508 CPPUNIT_ASSERT(referenceCompactSize <= sizeAfterCompact);
1509
1510 // File must round-trip correctly.
1511 {
1512 Matroska::File f(newname.c_str(), true, AudioProperties::Accurate);
1513 CPPUNIT_ASSERT(f.isValid());
1514 auto tag = f.tag(false);
1515 CPPUNIT_ASSERT(tag != nullptr);
1516 bool foundTitle = false;
1517 for(const auto &st : tag->simpleTagsList()) {
1518 if(st.name() == "TITLE" && st.toString() == "X") {
1519 foundTitle = true;
1520 break;
1521 }
1522 }
1523 CPPUNIT_ASSERT(foundTitle);
1524 }
1525 }
1526
1527 void testSaveTypes()
1528 {
1529 // Helper lambdas for adding data of different sizes
1530 // largeTags: 2 simple tags with long values
1531 const auto setLargeTags = [](Matroska::File &f) {
1532 auto tag = f.tag(true);
1533 tag->addSimpleTag(Matroska::SimpleTag(String("TITLE"),
1534 String("A Very Long Title That Takes Up A Lot Of Space In The File 1234567890"),
1535 Matroska::SimpleTag::TargetTypeValue::Track));
1536 tag->addSimpleTag(Matroska::SimpleTag(String("ARTIST"),
1537 String("A Very Long Artist Name That Takes Up A Lot Of Space In The File 1234567890"),
1538 Matroska::SimpleTag::TargetTypeValue::Track));
1539 };
1540 const auto setSmallTags = [](Matroska::File &f) {
1541 auto tag = f.tag(true);
1542 tag->addSimpleTag(Matroska::SimpleTag(String("TITLE"), String("Short"),
1543 Matroska::SimpleTag::TargetTypeValue::Track));
1544 };
1545 const auto setMediumTags = [](Matroska::File &f) {
1546 auto tag = f.tag(true);
1547 tag->addSimpleTag(Matroska::SimpleTag(String("TITLE"), String("Medium Title 12345678901234"),
1548 Matroska::SimpleTag::TargetTypeValue::Track));
1549 tag->addSimpleTag(Matroska::SimpleTag(String("ARTIST"), String("Medium Artist"),
1550 Matroska::SimpleTag::TargetTypeValue::Track));
1551 };
1552 const auto setExtraLargeTags = [](Matroska::File &f) {
1553 auto tag = f.tag(true);
1554 tag->addSimpleTag(Matroska::SimpleTag(String("TITLE"),
1555 String("An Extremely Long Title That Is Even Larger Than The Previous Large Title "
1556 "With Extra Content To Ensure Growth 0123456789ABCDEF"),
1557 Matroska::SimpleTag::TargetTypeValue::Track));
1558 tag->addSimpleTag(Matroska::SimpleTag(String("ARTIST"),
1559 String("An Extremely Long Artist Name Exceeding The Prior Large Artist Value "
1560 "With Even More Content To Guarantee Growth 0123456789ABCDEF"),
1561 Matroska::SimpleTag::TargetTypeValue::Track));
1562 };
1563
1564 const auto setLargeAttachments = [](Matroska::File &f) {
1565 auto atts = f.attachments(true);
1566 atts->addAttachedFile(Matroska::AttachedFile(
1567 ByteVector(200, 'x'), "cover.jpg", "image/jpeg", 111ULL, "Cover"));
1568 };
1569 const auto setSmallAttachments = [](Matroska::File &f) {
1570 auto atts = f.attachments(true);
1571 atts->addAttachedFile(Matroska::AttachedFile(
1572 ByteVector(20, 'x'), "img.png", "image/png", 222ULL, "Img"));
1573 };
1574 const auto setMediumAttachments = [](Matroska::File &f) {
1575 auto atts = f.attachments(true);
1576 atts->addAttachedFile(Matroska::AttachedFile(
1577 ByteVector(80, 'x'), "cover.jpg", "image/jpeg", 333ULL, "Cover"));
1578 };
1579 const auto setExtraLargeAttachments = [](Matroska::File &f) {
1580 auto atts = f.attachments(true);
1581 atts->addAttachedFile(Matroska::AttachedFile(
1582 ByteVector(500, 'x'), "cover.jpg", "image/jpeg", 444ULL, "Cover"));
1583 };
1584
1585 const auto setLargeChapters = [](Matroska::File &f) {
1586 auto chs = f.chapters(true);
1587 chs->addChapterEdition(Matroska::ChapterEdition(
1588 List<Matroska::Chapter>{
1589 Matroska::Chapter(0, 40000,
1590 List{Matroska::Chapter::Display("Chapter One Long Name", "eng")},
1591 1, false),
1592 Matroska::Chapter(40000, 80000,
1593 List{Matroska::Chapter::Display("Chapter Two Long Name", "eng")},
1594 2, false),
1595 }, true, false));
1596 };
1597 const auto setSmallChapters = [](Matroska::File &f) {
1598 auto chs = f.chapters(true);
1599 chs->addChapterEdition(Matroska::ChapterEdition(
1600 List<Matroska::Chapter>{
1601 Matroska::Chapter(0, 1000,
1602 List{Matroska::Chapter::Display("A", "und")},
1603 1, false),
1604 }, false, false));
1605 };
1606 const auto setMediumChapters = [](Matroska::File &f) {
1607 auto chs = f.chapters(true);
1608 chs->addChapterEdition(Matroska::ChapterEdition(
1609 List<Matroska::Chapter>{
1610 Matroska::Chapter(0, 40000,
1611 List{Matroska::Chapter::Display("Chapter Medium", "eng")},
1612 1, false),
1613 }, true, false));
1614 };
1615 const auto setExtraLargeChapters = [](Matroska::File &f) {
1616 auto chs = f.chapters(true);
1617 chs->addChapterEdition(Matroska::ChapterEdition(
1618 List<Matroska::Chapter>{
1619 Matroska::Chapter(0, 40000,
1620 List{Matroska::Chapter::Display("Chapter One Extremely Long Name Here", "eng"),
1621 Matroska::Chapter::Display("Kapitel Eins Sehr Langer Name", "deu")},
1622 1, false),
1623 Matroska::Chapter(40000, 80000,
1624 List{Matroska::Chapter::Display("Chapter Two Extremely Long Name Here", "eng"),
1625 Matroska::Chapter::Display("Kapitel Zwei Sehr Langer Name", "deu")},
1626 2, false),
1627 Matroska::Chapter(80000, 120000,
1628 List{Matroska::Chapter::Display("Chapter Three Extra Large", "eng")},
1629 3, true),
1630 }, true, true));
1631 };
1632
1633 for(const auto writeStyle : {Matroska::WriteStyle::Compact,
1634 Matroska::WriteStyle::DoNotShrink,
1635 Matroska::WriteStyle::AvoidInsert}) {
1636 ScopedFileCopy copy("no-tags", ".mka");
1637 const string newname = copy.fileName();
1638 const int wsIdx = static_cast<int>(writeStyle);
1639
1640 // Verify tag/attachment/chapter content for a saved file. Each round
1641 // uses unique identifiers (specific TITLE value, attachment UID,
1642 // chapter timeStart) so any cross-round leakage or corruption is
1643 // caught here.
1644 const auto verifyRound = [&](const std::string &label,
1645 const String &expectedTitle,
1646 unsigned long long expectedAttachmentUid,
1647 unsigned int expectedChapterCount,
1648 unsigned long long expectedFirstChapterEnd) {
1649 Matroska::File f(newname.c_str(), true, AudioProperties::Accurate);
1650 CPPUNIT_ASSERT_MESSAGE(label + " valid", f.isValid());
1651 auto tag = f.tag(false);
1652 CPPUNIT_ASSERT_MESSAGE(label + " tag", tag != nullptr);
1653 bool foundTitle = false;
1654 for(const auto &st : tag->simpleTagsList()) {
1655 if(st.name() == "TITLE" && st.toString() == expectedTitle) {
1656 foundTitle = true;
1657 break;
1658 }
1659 }
1660 CPPUNIT_ASSERT_MESSAGE(label + " TITLE roundtrip", foundTitle);
1661 auto atts = f.attachments(false);
1662 CPPUNIT_ASSERT_MESSAGE(label + " attachments", atts != nullptr);
1663 bool foundAtt = false;
1664 for(const auto &a : atts->attachedFileList()) {
1665 if(a.uid() == expectedAttachmentUid) {
1666 foundAtt = true;
1667 break;
1668 }
1669 }
1670 CPPUNIT_ASSERT_MESSAGE(label + " attachment uid roundtrip", foundAtt);
1671 auto chs = f.chapters(false);
1672 CPPUNIT_ASSERT_MESSAGE(label + " chapters", chs != nullptr);
1673 CPPUNIT_ASSERT_EQUAL_MESSAGE(label + " edition count", 1U,
1674 chs->chapterEditionList().size());
1675 const auto &edition = chs->chapterEditionList().front();
1676 CPPUNIT_ASSERT_EQUAL_MESSAGE(label + " chapter count",
1677 expectedChapterCount, edition.chapterList().size());
1678 CPPUNIT_ASSERT_EQUAL_MESSAGE(label + " first chapter end",
1679 expectedFirstChapterEnd, edition.chapterList()[0].timeEnd());
1680 };
1681
1682 // --- Round 1: save large data ---
1683 {
1684 Matroska::File f(newname.c_str());
1685 CPPUNIT_ASSERT(f.isValid());
1686 setLargeTags(f);
1687 setLargeAttachments(f);
1688 setLargeChapters(f);
1689 CPPUNIT_ASSERT_MESSAGE("Round1 save ws=" + String::number(wsIdx).to8Bit(), f.save(writeStyle));
1690 }
1691 const size_t sizeAfterRound1 = PlainFile(newname.c_str()).readAll().size();
1692 verifyRound("Round1 ws=" + std::to_string(wsIdx),
1693 String("A Very Long Title That Takes Up A Lot Of Space In The File 1234567890"),
1694 111ULL, 2U, 40000ULL);
1695
1696 // --- Round 2: save smaller data → slot must not shrink for DoNotShrink/AvoidInsert ---
1697 {
1698 Matroska::File f(newname.c_str());
1699 CPPUNIT_ASSERT(f.isValid());
1700 f.tag(true)->clearSimpleTags();
1701 f.attachments(true)->clear();
1702 f.chapters(true)->clear();
1703 setSmallTags(f);
1704 setSmallAttachments(f);
1705 setSmallChapters(f);
1706 CPPUNIT_ASSERT_MESSAGE("Round2 save ws=" + String::number(wsIdx).to8Bit(), f.save(writeStyle));
1707 }
1708 const size_t sizeAfterRound2 = PlainFile(newname.c_str()).readAll().size();
1709 verifyRound("Round2 ws=" + std::to_string(wsIdx),
1710 String("Short"), 222ULL, 1U, 1000ULL);
1711
1712 if(writeStyle == Matroska::WriteStyle::Compact) {
1713 // Compact always shrinks, so file is smaller
1714 CPPUNIT_ASSERT(sizeAfterRound2 < sizeAfterRound1);
1715 } else if(writeStyle == Matroska::WriteStyle::AvoidInsert) {
1716 // AvoidInsert: existing slots are kept, but the segment-trailing
1717 // element may shrink (no element follows it -- shrinking only
1718 // truncates the file, no inserts are needed).
1719 CPPUNIT_ASSERT(sizeAfterRound2 <= sizeAfterRound1);
1720 } else {
1721 // DoNotShrink: elements keep their original slot size.
1722 // The file size must not be smaller than after round 1
1723 CPPUNIT_ASSERT_EQUAL(sizeAfterRound1, sizeAfterRound2);
1724 }
1725
1726 // --- Round 3: save medium data (fits in round2's slot if DoNotShrink/AvoidInsert) ---
1727 {
1728 Matroska::File f(newname.c_str());
1729 CPPUNIT_ASSERT(f.isValid());
1730 f.tag(true)->clearSimpleTags();
1731 f.attachments(true)->clear();
1732 f.chapters(true)->clear();
1733 setMediumTags(f);
1734 setMediumAttachments(f);
1735 setMediumChapters(f);
1736 CPPUNIT_ASSERT_MESSAGE("Round3 save ws=" + String::number(wsIdx).to8Bit(), f.save(writeStyle));
1737 }
1738 const size_t sizeAfterRound3 = PlainFile(newname.c_str()).readAll().size();
1739 verifyRound("Round3 ws=" + std::to_string(wsIdx),
1740 String("Medium Title 12345678901234"), 333ULL, 1U, 40000ULL);
1741
1742 if(writeStyle == Matroska::WriteStyle::Compact) {
1743 // Compact: medium > small, but exact, so different from round2
1744 CPPUNIT_ASSERT(sizeAfterRound3 != sizeAfterRound2);
1745 CPPUNIT_ASSERT(sizeAfterRound3 < sizeAfterRound1);
1746 } else if(writeStyle == Matroska::WriteStyle::AvoidInsert) {
1747 // AvoidInsert: medium fits in round1's slot for non-trailing
1748 // elements, but the trailing element may take less space than in
1749 // round 1. File size therefore stays <= round 1.
1750 CPPUNIT_ASSERT(sizeAfterRound3 <= sizeAfterRound1);
1751 } else {
1752 // DoNotShrink: medium fits in round1's slot (with remaining void)
1753 // so file size stays the same as round1/round2
1754 CPPUNIT_ASSERT_EQUAL(sizeAfterRound1, sizeAfterRound3);
1755 }
1756
1757 // --- Round 4: save extra-large data (larger than round 1) ---
1758 {
1759 Matroska::File f(newname.c_str());
1760 CPPUNIT_ASSERT(f.isValid());
1761 f.tag(true)->clearSimpleTags();
1762 f.attachments(true)->clear();
1763 f.chapters(true)->clear();
1764 setExtraLargeTags(f);
1765 setExtraLargeAttachments(f);
1766 setExtraLargeChapters(f);
1767 CPPUNIT_ASSERT_MESSAGE("Round4 save ws=" + String::number(wsIdx).to8Bit(), f.save(writeStyle));
1768 }
1769 const size_t sizeAfterRound4 = PlainFile(newname.c_str()).readAll().size();
1770 verifyRound("Round4 ws=" + std::to_string(wsIdx),
1771 String("An Extremely Long Title That Is Even Larger Than The Previous Large Title "
1772 "With Extra Content To Ensure Growth 0123456789ABCDEF"),
1773 444ULL, 3U, 40000ULL);
1774
1775 // All styles must accommodate the larger data: file must be larger than round1
1776 CPPUNIT_ASSERT(sizeAfterRound4 > sizeAfterRound1);
1777 }
1778 }
1779
1780 };
1781
1782 CPPUNIT_TEST_SUITE_REGISTRATION(TestMatroska);