Debian Codegraph @

src/opustags.h

raw symbols SCIP
1 /**
2 * \file src/opustags.h
3 *
4 * Welcome to opustags!
5 *
6 * Let's have a quick tour around. The project is split into the following modules:
7 *
8 * - The system module provides a few generic tools for interating with the system.
9 * - The ogg module reads and writes Ogg files, letting you manipulate Ogg pages and packets.
10 * - The opus module parses the contents of Ogg packets according to the Opus specifications.
11 * - The cli module implements the main logic of the program.
12 * - The opustags module contains the main function, which is a simple wrapper around cli.
13 *
14 * Each module is implemented in its eponymous .cc file. Their interfaces are all defined and
15 * documented together in this header file. Look into the .cc files for implementation-specific
16 * details.
17 *
18 * To understand how this program works, you need to know what an Ogg files is made of, in
19 * particular the streams, pages, and packets. You hardly need any knowledge of the actual Opus
20 * audio codec, but need the RFC 7845 "Ogg Encapsulation for the Opus Audio Codec" that defines the
21 * format of the header packets that are essential to opustags.
22 *
23 */
24
25 #pragma once
26
27 #include <config.h>
28
29 #include <iconv.h>
30 #include <ogg/ogg.h>
31 #include <stdio.h>
32 #include <time.h>
33
34 #include <functional>
35 #include <list>
36 #include <memory>
37 #include <optional>
38 #include <string>
39 #include <string_view>
40 #include <vector>
41
42 #ifdef HAVE_ENDIAN_H
43 # include <endian.h>
44 #endif
45
46 #ifdef HAVE_SYS_ENDIAN_H
47 # include <sys/endian.h>
48 #endif
49
50 #ifdef __APPLE__
51 #include <libkern/OSByteOrder.h>
52 #define htole32(x) OSSwapHostToLittleInt32(x)
53 #define le32toh(x) OSSwapLittleToHostInt32(x)
54 #define htobe32(x) OSSwapHostToBigInt32(x)
55 #define be32toh(x) OSSwapBigToHostInt32(x)
56 #endif
57
58 using namespace std::literals;
59
60 namespace ot {
61
62 /**
63 * Possible return status code, ranging from errors to special statuses. They are usually
64 * accompanied with a message with the #status structure.
65 *
66 * Error codes do not need to be ultra specific, and are mainly used to report special conditions to
67 * the caller function. Ultimately, only the error message in the #status is shown to the user.
68 *
69 * The cut error family means that the end of packet was reached when attempting to read the
70 * overflowing value. For example, cut_comment_count means that after reading the vendor string,
71 * less than 4 bytes were left in the packet.
72 */
73 enum class st {
74 /* Generic */
75 ok,
76 error,
77 standard_error, /**< Error raised by the C standard library. */
78 int_overflow,
79 cancel,
80 /* System */
81 badly_encoded,
82 child_process_failed,
83 /* Ogg */
84 bad_stream,
85 libogg_error,
86 /* Opus */
87 bad_magic_number,
88 cut_magic_number,
89 cut_vendor_length,
90 cut_vendor_data,
91 cut_comment_count,
92 cut_comment_length,
93 cut_comment_data,
94 invalid_size,
95 /* CLI */
96 bad_arguments,
97 };
98
99 /**
100 * Wraps a status code with an optional message. It is implictly converted to and from a
101 * #status_code. It may be thrown on error by any of the ot:: functions.
102 *
103 * All the statuses except #st::ok should be accompanied with a relevant error message, in case it
104 * propagates back to the main function and is shown to the user.
105 */
106 struct status {
107 status(st code = st::ok) : code(code) {}
108 template<class T> status(st code, T&& message) : code(code), message(message) {}
109 operator st() const { return code; }
110 st code;
111 std::string message;
112 };
113
114 using byte_string = std::basic_string<uint8_t>;
115 using byte_string_view = std::basic_string_view<uint8_t>;
116
117 /***********************************************************************************************//**
118 * \defgroup system System
119 * \{
120 */
121
122 /**
123 * Smart auto-closing FILE* handle.
124 *
125 * It implictly converts from an already opened FILE*.
126 */
127 struct file : std::unique_ptr<FILE, decltype(&fclose)> {
128 file(FILE* f = nullptr) : std::unique_ptr<FILE, decltype(&fclose)>(f, &fclose) {}
129 };
130
131 /**
132 * A partial file is a temporary file created to store the result of something. When it is complete,
133 * it is moved to a final destination. Open it with #open and then you can either #commit it to save
134 * it to its destination, or you can #abort to delete the temporary file. When the #partial_file
135 * object is destroyed, it deletes the currently opened temporary file, if any.
136 */
137 class partial_file {
138 public:
139 ~partial_file() { abort(); }
140 /**
141 * Open a temporary file meant to be moved to the specified destination file path. The
142 * temporary file is created in the same directory as its destination in order to make the
143 * final move operation instant.
144 */
145 void open(const char* destination);
146 /** Close then move the partial file to its final location. */
147 void commit();
148 /** Delete the temporary file. */
149 void abort();
150 /** Get the underlying FILE* handle. */
151 FILE* get() { return file.get(); }
152 /** Get the name of the temporary file. */
153 const char* name() const { return file == nullptr ? nullptr : temporary_name.c_str(); }
154 private:
155 std::string temporary_name;
156 std::string final_name;
157 ot::file file;
158 };
159
160 /** Read a whole file into memory and return the read content. */
161 byte_string slurp_binary_file(const char* filename);
162
163 /** Convert a string from the system locale’s encoding to UTF-8. */
164 std::u8string encode_utf8(std::string_view);
165
166 /** Convert a string from UTF-8 to the system locale’s encoding. */
167 std::string decode_utf8(std::u8string_view);
168
169 /** Escape a string so that a POSIX shell interprets it as a single argument. */
170 std::string shell_escape(std::string_view word);
171
172 /**
173 * Execute the editor process specified in editor. Wait for the process to exit and
174 * return st::ok on success, or st::child_process_failed if it did not exit with 0.
175 *
176 * editor is passed unescaped to the shell, and may contain CLI options.
177 * path is the name of the file to edit, which will be passed as the last argument to editor.
178 */
179 void run_editor(std::string_view editor, std::string_view path);
180
181 /**
182 * Return the specified path’s mtime, i.e. the last data modification
183 * timestamp.
184 */
185 timespec get_file_timestamp(const char* path);
186
187 std::u8string encode_base64(byte_string_view src);
188 byte_string decode_base64(std::u8string_view src);
189
190 /** \} */
191
192 /***********************************************************************************************//**
193 * \defgroup ogg Ogg
194 * \{
195 */
196
197 /**
198 * RAII-aware wrapper around libogg's ogg_stream_state. Though it handles automatic destruction, it
199 * does not prevent copying or implement move semantics correctly, so it's your responsibility to
200 * ensure these operations don't happen.
201 */
202 struct ogg_logical_stream : ogg_stream_state {
203 ogg_logical_stream(int serialno) {
204 if (ogg_stream_init(this, serialno) != 0)
205 throw std::bad_alloc();
206 }
207 ~ogg_logical_stream() {
208 ogg_stream_clear(this);
209 }
210 };
211
212 /**
213 * Identify the codec of a logical stream based on the first bytes of the first packet of the first
214 * page. For Opus, the first 8 bytes must be OpusHead. Any other signature is assumed to be another
215 * codec.
216 */
217 bool is_opus_stream(const ogg_page& identification_header);
218
219 /**
220 * Ogg reader, combining a FILE input, an ogg_sync_state reading the pages.
221 *
222 * Call #read_page repeatedly until it returns false to consume the stream, and use #page to check
223 * its content.
224 */
225 struct ogg_reader {
226 /**
227 * Initialize the reader with the given input file handle. The caller is responsible for
228 * keeping the file handle alive, and to close it.
229 */
230 ogg_reader(FILE* input) : file(input) { ogg_sync_init(&sync); }
231 /**
232 * Clear all the internal memory allocated by libogg for the sync and stream state. The
233 * page and the packet are owned by these states, so nothing to do with them.
234 *
235 * The input file is not closed.
236 */
237 ~ogg_reader() { ogg_sync_clear(&sync); }
238 /**
239 * Read the next page from the input file. The result is made available in the #page field,
240 * is owned by the Ogg reader, and is valid until the next call to #read_page.
241 *
242 * Return true if a page was read, false on end of stream.
243 */
244 bool next_page();
245 /**
246 * Read the single packet contained in the last page read, assuming it's a header page, and
247 * call the function f on it. This function has no side effect, and calling it twice on the
248 * same page will read the same packet again.
249 *
250 * It is currently limited to packets that fit on a single page, and should be later
251 * extended to support packets spanning multiple pages.
252 */
253 void process_header_packet(const std::function<void(ogg_packet&)>& f);
254 /**
255 * Current page from the sync state.
256 *
257 * Its memory is managed by libogg, inside the sync state, and is valid until the next call
258 * to ogg_sync_pageout, wrapped by #read_page.
259 */
260 ogg_page page;
261 /**
262 * Page number in the physical stream of the last read page, disregarding multiplexed
263 * streams. The first page number is 0. When no page has been read, its value is
264 * (size_t) -1.
265 */
266 size_t absolute_page_no = -1;
267 /**
268 * The file is our source of binary data. It is not integrated to libogg, so we need to
269 * handle it ourselves.
270 *
271 * The file is not owned by the ogg_reader instance.
272 */
273 FILE* file;
274 /**
275 * The sync layer gets binary data and yields a sequence of pages.
276 *
277 * A page contains packets that we can extract using the #stream state, but we only do that
278 * for the headers. Once we got the OpusHead and OpusTags packets, all the following pages
279 * are simply forwarded to the Ogg writer.
280 */
281 ogg_sync_state sync;
282 };
283
284 /**
285 * An Ogg writer lets you write ogg_page objets to an output file, and assemble packets into pages.
286 *
287 * Its packet writing facility is limited to writing single-page header packets, because that's all
288 * we need for opustags.
289 */
290 struct ogg_writer {
291 /**
292 * Initialize the writer with the given output file handle. The caller is responsible for
293 * keeping the file handle alive, and to close it.
294 */
295 explicit ogg_writer(FILE* output) : file(output) {}
296 /**
297 * Write a whole Ogg page into the output stream.
298 *
299 * This is a basic I/O operation and does not even require libogg, or the stream.
300 */
301 void write_page(const ogg_page& page);
302 /**
303 * Write a header packet and flush the page. Header packets are always placed alone on their
304 * pages.
305 */
306 void write_header_packet(int serialno, int pageno, ogg_packet& packet);
307 /**
308 * Output file. It should be opened in binary mode. We use it to write whole pages,
309 * represented as a block of data and a length.
310 */
311 FILE* file;
312 /**
313 * Path to the output file.
314 */
315 std::optional<std::string> path;
316 /**
317 * Custom counter for the sequential page number to be written. It allows us to detect
318 * ogg_page_pageno mismatches and renumber the pages if needed.
319 */
320 long next_page_no = 0;
321 };
322
323 /**
324 * Ogg packet with dynamically allocated data.
325 *
326 * Provides a wrapper around libogg's ogg_packet with RAII.
327 */
328 struct dynamic_ogg_packet : ogg_packet {
329 /** Construct an ogg_packet of the given size. */
330 explicit dynamic_ogg_packet(size_t size) {
331 bytes = size;
332 data = std::make_unique<unsigned char[]>(size);
333 packet = data.get();
334 }
335 private:
336 /** Owning reference to the data. Use the packet field from ogg_packet instead. */
337 std::unique_ptr<unsigned char[]> data;
338 };
339
340 /** Update the Ogg pageno field in the given page. The CRC is recomputed if needed. */
341 void renumber_page(ogg_page& page, long new_pageno);
342
343 /** \} */
344
345 /***********************************************************************************************//**
346 * \defgroup opus Opus
347 * \{
348 */
349
350 /**
351 * Faithfully represent *all* the data in an OpusTags packet, exactly as they will be written in the
352 * final stream, disregarding the current system locale or anything else.
353 *
354 * The vendor and comment strings are expected to contain valid UTF-8, but we should keep their
355 * values intact even if the string is not UTF-8 clean, or encoded in any other way.
356 */
357 struct opus_tags {
358 /**
359 * OpusTags packets begin with a vendor string, meant to identify the implementation of the
360 * encoder. It is expected to be an arbitrary UTF-8 string.
361 */
362 std::u8string vendor;
363 /**
364 * Comments are strings in the NAME=Value format. A comment may also be called a field, or a
365 * tag.
366 *
367 * The field name in vorbis comments is usually case-insensitive and ASCII, while the value
368 * can be any valid UTF-8 string. The specification is not too clear for Opus, but let's
369 * assume it's the same.
370 */
371 std::list<std::u8string> comments;
372 /**
373 * According to RFC 7845:
374 * > Immediately following the user comment list, the comment header MAY contain
375 * > zero-padding or other binary data that is not specified here.
376 *
377 * The first byte is supposed to indicate whether this data should be kept or not, but let's
378 * assume it's here for a reason and always keep it. Better safe than sorry.
379 *
380 * In the future, we could add options to manipulate this data: view it, edit it, truncate
381 * it if it's marked as padding, truncate it unconditionally.
382 */
383 byte_string extra_data;
384 };
385
386 /**
387 * Read the given OpusTags packet and extract its content into an opus_tags object.
388 */
389 opus_tags parse_tags(const ogg_packet& packet);
390
391 /**
392 * Serialize an #opus_tags object into an OpusTags Ogg packet.
393 */
394 dynamic_ogg_packet render_tags(const opus_tags& tags);
395
396 /**
397 * Extracted data from the METADATA_BLOCK_PICTURE tag. See
398 * <https://xiph.org/flac/format.html#metadata_block_picture> for the full specifications.
399 *
400 * It may contain all kinds of metadata but most are not used at all. For now, let’s assume all
401 * pictures have picture type 3 (front cover), and empty metadata.
402 */
403 struct picture {
404 picture() = default;
405
406 /** Extract the picture information from serialized binary data.*/
407 picture(byte_string block);
408 byte_string_view mime_type;
409 byte_string_view picture_data;
410
411 /**
412 * Encode the picture attributes (mime_type, picture_data) into a binary block to be stored
413 * into METADATA_BLOCK_PICTURE.
414 */
415 byte_string serialize() const;
416
417 /** To avoid needless copies of the picture data, move the original data block there. The
418 * string_view attributes will refer to it. */
419 byte_string storage;
420 };
421
422 /** Extract the first picture embedded in the tags, regardless of its type. */
423 std::optional<picture> extract_cover(const opus_tags& tags);
424
425 /**
426 * Return a METADATA_BLOCK_PICTURE tag defining the front cover art to the given picture data (JPEG,
427 * PNG). The MIME type is deduced from the magic number.
428 */
429 std::u8string make_cover(byte_string_view picture_data);
430
431 /** \} */
432
433 /***********************************************************************************************//**
434 * \defgroup cli Command-Line Interface
435 * \{
436 */
437
438 /**
439 * Structured representation of the command-line arguments to opustags.
440 */
441 struct options {
442 /**
443 * When true, opustags prints a detailed help and exits. All the other options are ignored.
444 *
445 * Option: --help
446 */
447 bool print_help = false;
448 /**
449 * Paths to the input files. The special string "-" means stdin.
450 *
451 * At least one input file must be given. If `--in-place` is used,
452 * more than one may be given.
453 */
454 std::vector<std::string> paths_in;
455 /**
456 * Optional path to output file. The special string "-" means stdout. For in-place
457 * editing, the input file name is used. If no output file name is supplied, and
458 * --in-place is not used, opustags runs in read-only mode.
459 *
460 * Options: --output, --in-place
461 */
462 std::optional<std::string> path_out;
463 /**
464 * By default, opustags won't overwrite the output file if it already exists. This can be
465 * forced with --overwrite. It is also enabled by --in-place.
466 *
467 * Options: --overwrite, --in-place
468 */
469 bool overwrite = false;
470 /**
471 * Process files in-place.
472 *
473 * Options: --in-place
474 */
475 bool in_place = false;
476 /**
477 * Spawn EDITOR to edit tags interactively.
478 *
479 * stdin and stdout must be left free for the editor, so paths_in and
480 * path_out can’t take `-`, and --set-all is not supported.
481 *
482 * Option: --edit
483 */
484 bool edit_interactively = false;
485 /**
486 * List of comments to delete. Each string is a selector according to the definition of
487 * #delete_comments.
488 *
489 * When #delete_all is true, this option is meaningless.
490 *
491 * #to_add takes precedence over #to_delete, so if the same comment appears in both lists,
492 * the one in #to_delete applies only to the previously existing tags.
493 *
494 * Option: --delete, --set
495 */
496 std::list<std::u8string> to_delete;
497 /**
498 * Delete all the existing comments.
499 *
500 * Option: --delete-all, --set-all
501 */
502 bool delete_all = false;
503 /**
504 * List of comments to add, in the current system encoding. For exemple `TITLE=a b c`. They
505 * must be valid.
506 *
507 * Options: --add, --set, --set-all
508 */
509 std::list<std::u8string> to_add;
510 /**
511 * If set, the input file’s cover art is exported to the specified file. - for stdout. Does
512 * not overwrite the file if it already exists unless -y is specified. Does nothing if the
513 * input file does not contain a cover art.
514 *
515 * Option: --output-cover
516 */
517 std::optional<std::string> cover_out;
518 /**
519 * Print the vendor string at the beginning of the OpusTags packet instead of printing the
520 * tags. Only applicable in read-only mode.
521 *
522 * Option: --vendor
523 */
524 bool print_vendor = false;
525 /**
526 * Replace the vendor string by the one specified by the user.
527 *
528 * Option: --set-vendor
529 */
530 std::optional<std::u8string> set_vendor;
531 /**
532 * Disable encoding conversions. OpusTags are specified to always be encoded as UTF-8, but
533 * if for some reason a specific file contains binary tags that someone would like to
534 * extract and set as-is, encoding conversion would get in the way.
535 */
536 bool raw = false;
537 /**
538 * In text mode (default), tags are separated by a line feed. However, when combining
539 * opustags with grep or other line-based tools, this proves to be a bad separator because
540 * tag values may contain newlines. Changing the delimiter to '\0' with -z eases the
541 * processing of multi-line tags with other tools that support null-terminated lines.
542 */
543 char tag_delimiter = '\n';
544 };
545
546 /**
547 * Parse the command-line arguments. Does not perform I/O related validations, but checks the
548 * consistency of its arguments. Comments are read if necessary from the given stream.
549 */
550 options parse_options(int argc, char** argv, FILE* comments);
551
552 /**
553 * Print all the comments, separated by line breaks. Since a comment may contain line breaks, this
554 * output is not completely reliable, but it fits most cases.
555 *
556 * The comments must be encoded in UTF-8, and are converted to the system locale when printed,
557 * unless raw is true.
558 *
559 * The output generated is meant to be parseable by #ot::read_comments.
560 */
561 void print_comments(const std::list<std::u8string>& comments, FILE* output, const options& opt);
562
563 /**
564 * Parse the comments outputted by #ot::print_comments. Unless raw is true, the comments are
565 * converted from the system encoding to UTF-8, and returned as UTF-8.
566 */
567 std::list<std::u8string> read_comments(FILE* input, const options& opt);
568
569 /**
570 * Remove all comments matching the specified selector, which may either be a field name or a
571 * NAME=VALUE pair. The field name is case-insensitive.
572 */
573 void delete_comments(std::list<std::u8string>& comments, const std::u8string& selector);
574
575 /**
576 * Main entry point to the opustags program, and pretty much the same as calling opustags from the
577 * command-line.
578 */
579 void run(const options& opt);
580
581 /** \} */
582
583 }
584
585 /** Handy literal suffix for building byte strings. */
586 ot::byte_string operator""_bs(const char* data, size_t size);
587 ot::byte_string_view operator""_bsv(const char* data, size_t size);