| 1 | /** |
| 2 | * \file src/cli.cc |
| 3 | * \ingroup cli |
| 4 | * |
| 5 | * Provide all the features of the opustags executable from a C++ API. The main point of separating |
| 6 | * this module from the main one is to allow easy testing. |
| 7 | */ |
| 8 | |
| 9 | #include <opustags.h> |
| 10 | |
| 11 | #include <errno.h> |
| 12 | #include <getopt.h> |
| 13 | #include <limits.h> |
| 14 | #include <stdlib.h> |
| 15 | #include <string.h> |
| 16 | #include <sys/stat.h> |
| 17 | #include <unistd.h> |
| 18 | #include <algorithm> |
| 19 | |
| 20 | static const char help_message[] = |
| 21 | PROJECT_NAME " version " PROJECT_VERSION |
| 22 | R"raw( |
| 23 | |
| 24 | Usage: opustags --help |
| 25 | opustags [OPTIONS] FILE |
| 26 | opustags OPTIONS -i FILE... |
| 27 | opustags OPTIONS FILE -o FILE |
| 28 | |
| 29 | Options: |
| 30 | -h, --help print this help |
| 31 | -o, --output FILE specify the output file |
| 32 | -i, --in-place overwrite the input files |
| 33 | -y, --overwrite overwrite the output file if it already exists |
| 34 | -a, --add FIELD=VALUE add a comment |
| 35 | -d, --delete FIELD[=VALUE] delete previously existing comments |
| 36 | -D, --delete-all delete all the previously existing comments |
| 37 | -s, --set FIELD=VALUE replace a comment |
| 38 | -S, --set-all import comments from standard input |
| 39 | -e, --edit edit tags interactively in VISUAL/EDITOR |
| 40 | --output-cover FILE extract and save the cover art, if any |
| 41 | --set-cover FILE sets the cover art |
| 42 | --vendor print the vendor string |
| 43 | --set-vendor VALUE set the vendor string |
| 44 | --raw disable encoding conversion |
| 45 | -z delimit tags with NUL |
| 46 | |
| 47 | See the man page for extensive documentation. |
| 48 | )raw"; |
| 49 | |
| 50 | static struct option getopt_options[] = { |
| 51 | {"help", no_argument, 0, 'h'}, |
| 52 | {"output", required_argument, 0, 'o'}, |
| 53 | {"in-place", optional_argument, 0, 'i'}, |
| 54 | {"overwrite", no_argument, 0, 'y'}, |
| 55 | {"delete", required_argument, 0, 'd'}, |
| 56 | {"add", required_argument, 0, 'a'}, |
| 57 | {"set", required_argument, 0, 's'}, |
| 58 | {"delete-all", no_argument, 0, 'D'}, |
| 59 | {"set-all", no_argument, 0, 'S'}, |
| 60 | {"edit", no_argument, 0, 'e'}, |
| 61 | {"output-cover", required_argument, 0, 'c'}, |
| 62 | {"set-cover", required_argument, 0, 'C'}, |
| 63 | {"vendor", no_argument, 0, 'v'}, |
| 64 | {"set-vendor", required_argument, 0, 'V'}, |
| 65 | {"raw", no_argument, 0, 'r'}, |
| 66 | {NULL, 0, 0, 0} |
| 67 | }; |
| 68 | |
| 69 | ot::options ot::parse_options(int argc, char** argv, FILE* comments_input) |
| 70 | { |
| 71 | options opt; |
| 72 | const char* equal; |
| 73 | ot::status rc; |
| 74 | std::list<std::string> local_to_add; // opt.to_add before UTF-8 conversion. |
| 75 | std::list<std::string> local_to_delete; // opt.to_delete before UTF-8 conversion. |
| 76 | bool set_all = false; |
| 77 | std::optional<std::string> set_cover; |
| 78 | std::optional<std::string> set_vendor; |
| 79 | opt = {}; |
| 80 | if (argc == 1) |
| 81 | throw status {st::bad_arguments, "No arguments specified. Use -h for help."}; |
| 82 | int c; |
| 83 | optind = 0; |
| 84 | while ((c = getopt_long(argc, argv, ":ho:iyd:a:s:DSez", getopt_options, NULL)) != -1) { |
| 85 | switch (c) { |
| 86 | case 'h': |
| 87 | opt.print_help = true; |
| 88 | break; |
| 89 | case 'o': |
| 90 | if (opt.path_out) |
| 91 | throw status {st::bad_arguments, "Cannot specify --output more than once."}; |
| 92 | opt.path_out = optarg; |
| 93 | break; |
| 94 | case 'i': |
| 95 | opt.in_place = true; |
| 96 | opt.overwrite = true; |
| 97 | break; |
| 98 | case 'y': |
| 99 | opt.overwrite = true; |
| 100 | break; |
| 101 | case 'd': |
| 102 | local_to_delete.emplace_back(optarg); |
| 103 | break; |
| 104 | case 'a': |
| 105 | case 's': |
| 106 | equal = strchr(optarg, '='); |
| 107 | if (equal == nullptr) |
| 108 | throw status {st::bad_arguments, "Comment does not contain an equal sign: "s + optarg + "."}; |
| 109 | if (c == 's') |
| 110 | local_to_delete.emplace_back(optarg, equal - optarg); |
| 111 | local_to_add.emplace_back(optarg); |
| 112 | break; |
| 113 | case 'S': |
| 114 | opt.delete_all = true; |
| 115 | set_all = true; |
| 116 | break; |
| 117 | case 'D': |
| 118 | opt.delete_all = true; |
| 119 | break; |
| 120 | case 'e': |
| 121 | opt.edit_interactively = true; |
| 122 | break; |
| 123 | case 'c': |
| 124 | if (opt.cover_out) |
| 125 | throw status {st::bad_arguments, "Cannot specify --output-cover more than once."}; |
| 126 | opt.cover_out = optarg; |
| 127 | break; |
| 128 | case 'C': |
| 129 | if (set_cover) |
| 130 | throw status {st::bad_arguments, "Cannot specify --set-cover more than once."}; |
| 131 | set_cover = optarg; |
| 132 | break; |
| 133 | case 'v': |
| 134 | opt.print_vendor = true; |
| 135 | break; |
| 136 | case 'V': |
| 137 | if (set_vendor) |
| 138 | throw status {st::bad_arguments, "Cannot specify --set-vendor more than once."}; |
| 139 | set_vendor = optarg; |
| 140 | break; |
| 141 | case 'r': |
| 142 | opt.raw = true; |
| 143 | break; |
| 144 | case 'z': |
| 145 | opt.tag_delimiter = '\0'; |
| 146 | break; |
| 147 | case ':': |
| 148 | throw status {st::bad_arguments, "Missing value for option '"s + argv[optind - 1] + "'."}; |
| 149 | default: |
| 150 | throw status {st::bad_arguments, "Unrecognized option '" + |
| 151 | (optopt ? "-"s + static_cast<char>(optopt) : argv[optind - 1]) + "'."}; |
| 152 | } |
| 153 | } |
| 154 | if (opt.print_help) |
| 155 | return opt; |
| 156 | |
| 157 | // All non-option arguments are input files. |
| 158 | size_t stdin_uses = 0; |
| 159 | for (int i = optind; i < argc; i++) { |
| 160 | if (strcmp(argv[i], "-") == 0) |
| 161 | ++stdin_uses; |
| 162 | opt.paths_in.emplace_back(argv[i]); |
| 163 | } |
| 164 | bool stdin_as_input = stdin_uses > 0; |
| 165 | |
| 166 | if (set_cover == "-") |
| 167 | ++stdin_uses; |
| 168 | if (set_all) |
| 169 | ++stdin_uses; |
| 170 | if (stdin_uses > 1) |
| 171 | throw status { st::bad_arguments, "Cannot use standard input more than once." }; |
| 172 | |
| 173 | // Convert arguments to UTF-8. |
| 174 | if (opt.raw) { |
| 175 | // Cast the user data without any encoding conversion. |
| 176 | auto cast_to_utf8 = [](std::string_view in) |
| 177 | { return std::u8string(reinterpret_cast<const char8_t*>(in.data()), in.size()); }; |
| 178 | std::transform(local_to_add.begin(), local_to_add.end(), |
| 179 | std::back_inserter(opt.to_add), cast_to_utf8); |
| 180 | std::transform(local_to_delete.begin(), local_to_delete.end(), |
| 181 | std::back_inserter(opt.to_delete), cast_to_utf8); |
| 182 | if (set_vendor) |
| 183 | opt.set_vendor = cast_to_utf8(*set_vendor); |
| 184 | } else { |
| 185 | try { |
| 186 | std::transform(local_to_add.begin(), local_to_add.end(), |
| 187 | std::back_inserter(opt.to_add), encode_utf8); |
| 188 | std::transform(local_to_delete.begin(), local_to_delete.end(), |
| 189 | std::back_inserter(opt.to_delete), encode_utf8); |
| 190 | if (set_vendor) |
| 191 | opt.set_vendor = encode_utf8(*set_vendor); |
| 192 | } catch (const ot::status& rc) { |
| 193 | throw status {st::bad_arguments, "Could not encode argument into UTF-8: " + rc.message}; |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | bool read_only = !opt.in_place && !opt.path_out.has_value(); |
| 198 | |
| 199 | if (opt.in_place && opt.path_out) |
| 200 | throw status {st::bad_arguments, "Cannot combine --in-place and --output."}; |
| 201 | |
| 202 | if (opt.in_place && stdin_as_input) |
| 203 | throw status {st::bad_arguments, "Cannot modify standard input in place."}; |
| 204 | |
| 205 | if ((!opt.in_place || opt.edit_interactively) && opt.paths_in.size() != 1) |
| 206 | throw status {st::bad_arguments, "Exactly one input file must be specified."}; |
| 207 | |
| 208 | if (opt.edit_interactively && (stdin_as_input || opt.path_out == "-" || opt.cover_out == "-")) |
| 209 | throw status {st::bad_arguments, "Cannot edit interactively when standard input or standard output are already used."}; |
| 210 | |
| 211 | if (opt.edit_interactively && read_only) |
| 212 | throw status {st::bad_arguments, "Cannot edit interactively when no output is specified."}; |
| 213 | |
| 214 | if (opt.edit_interactively && (opt.delete_all || !opt.to_add.empty() || !opt.to_delete.empty())) |
| 215 | throw status {st::bad_arguments, "Cannot mix --edit with -adDsS."}; |
| 216 | |
| 217 | if (opt.cover_out == "-" && opt.path_out == "-") |
| 218 | throw status {st::bad_arguments, "Cannot specify standard output for both --output and --output-cover."}; |
| 219 | |
| 220 | if (opt.cover_out && opt.paths_in.size() > 1) |
| 221 | throw status {st::bad_arguments, "Cannot use --output-cover with multiple input files."}; |
| 222 | |
| 223 | if (opt.print_vendor && !read_only) |
| 224 | throw status {st::bad_arguments, "--vendor is only supported in read-only mode."}; |
| 225 | |
| 226 | if (set_cover) { |
| 227 | byte_string picture_data = ot::slurp_binary_file(set_cover->c_str()); |
| 228 | opt.to_delete.push_back(u8"METADATA_BLOCK_PICTURE"s); |
| 229 | opt.to_add.push_back(ot::make_cover(picture_data)); |
| 230 | } |
| 231 | |
| 232 | if (set_all) { |
| 233 | // Read comments from stdin and prepend them to opt.to_add. |
| 234 | std::list<std::u8string> comments = read_comments(comments_input, opt); |
| 235 | opt.to_add.splice(opt.to_add.begin(), std::move(comments)); |
| 236 | } |
| 237 | return opt; |
| 238 | } |
| 239 | |
| 240 | /** Format a UTF-8 string by adding tabulations (\t) after line feeds (\n) to mark continuation for |
| 241 | * multiline values. With -z, this behavior applies for embedded NUL characters instead of LF. */ |
| 242 | static std::u8string format_value(const std::u8string& source, const ot::options& opt) |
| 243 | { |
| 244 | auto newline_count = std::count(source.begin(), source.end(), opt.tag_delimiter); |
| 245 | |
| 246 | // General case: the value fits on a single line. Use std::string’s copy constructor for the |
| 247 | // most efficient copy we could hope for. |
| 248 | if (newline_count == 0) |
| 249 | return source; |
| 250 | |
| 251 | std::u8string formatted; |
| 252 | formatted.reserve(source.size() + newline_count); |
| 253 | for (auto c : source) { |
| 254 | formatted.push_back(c); |
| 255 | if (c == opt.tag_delimiter) |
| 256 | formatted.push_back(u8'\t'); |
| 257 | } |
| 258 | return formatted; |
| 259 | } |
| 260 | |
| 261 | /** |
| 262 | * Convert the comment from UTF-8 to the system encoding if relevant, and print it with a trailing |
| 263 | * line feed. |
| 264 | */ |
| 265 | static void puts_utf8(std::u8string_view str, FILE* output, const ot::options& opt) |
| 266 | { |
| 267 | if (opt.raw) { |
| 268 | fwrite(str.data(), 1, str.size(), output); |
| 269 | } else { |
| 270 | try { |
| 271 | std::string local = ot::decode_utf8(str); |
| 272 | fwrite(local.data(), 1, local.size(), output); |
| 273 | } catch (ot::status& rc) { |
| 274 | rc.message += " See --raw."; |
| 275 | throw; |
| 276 | } |
| 277 | } |
| 278 | putc(opt.tag_delimiter, output); |
| 279 | } |
| 280 | |
| 281 | /** |
| 282 | * Print comments in a human readable format that can also be read back in by #read_comment. |
| 283 | * |
| 284 | * To disambiguate between a newline embedded in a comment and a newline representing the start of |
| 285 | * the next tag, continuation lines always have a single TAB (^I) character added to the beginning. |
| 286 | */ |
| 287 | void ot::print_comments(const std::list<std::u8string>& comments, FILE* output, const ot::options& opt) |
| 288 | { |
| 289 | bool has_control = false; |
| 290 | for (const std::u8string& source_comment : comments) { |
| 291 | if (!has_control) { // Don’t bother analyzing comments if the flag is already up. |
| 292 | for (unsigned char c : source_comment) { |
| 293 | if (c < 0x20 && c != '\n') { |
| 294 | has_control = true; |
| 295 | break; |
| 296 | } |
| 297 | } |
| 298 | } |
| 299 | std::u8string utf8_comment = format_value(source_comment, opt); |
| 300 | puts_utf8(utf8_comment, output, opt); |
| 301 | } |
| 302 | if (has_control) |
| 303 | fputs("warning: Some tags contain control characters.\n", stderr); |
| 304 | } |
| 305 | |
| 306 | std::list<std::u8string> ot::read_comments(FILE* input, const ot::options& opt) |
| 307 | { |
| 308 | std::list<std::u8string> comments; |
| 309 | comments.clear(); |
| 310 | char* source_line = nullptr; |
| 311 | size_t buflen = 0; |
| 312 | ssize_t nread; |
| 313 | std::u8string* previous_comment = nullptr; |
| 314 | while ((nread = getdelim(&source_line, &buflen, opt.tag_delimiter, input)) != -1) { |
| 315 | if (nread > 0 && source_line[nread - 1] == opt.tag_delimiter) |
| 316 | --nread; // Chomp. |
| 317 | |
| 318 | std::u8string line; |
| 319 | if (opt.raw) { |
| 320 | line = std::u8string(reinterpret_cast<char8_t*>(source_line), nread); |
| 321 | } else { |
| 322 | try { |
| 323 | line = encode_utf8(std::string_view(source_line, nread)); |
| 324 | } catch (const ot::status& rc) { |
| 325 | free(source_line); |
| 326 | throw ot::status {ot::st::badly_encoded, "UTF-8 conversion error: " + rc.message}; |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | if (line.empty()) { |
| 331 | // Ignore empty lines. |
| 332 | previous_comment = nullptr; |
| 333 | } else if (line[0] == u8'#') { |
| 334 | // Ignore comments. |
| 335 | previous_comment = nullptr; |
| 336 | } else if (line[0] == u8'\t') { |
| 337 | // Continuation line: append the current line to the previous tag. |
| 338 | if (previous_comment == nullptr) { |
| 339 | ot::status rc = {ot::st::error, "Unexpected continuation line: " + std::string(source_line, nread)}; |
| 340 | free(source_line); |
| 341 | throw rc; |
| 342 | } else { |
| 343 | line[0] = opt.tag_delimiter; |
| 344 | previous_comment->append(line); |
| 345 | } |
| 346 | } else if (line.find(u8'=') == decltype(line)::npos) { |
| 347 | ot::status rc = {ot::st::error, "Malformed tag: " + std::string(source_line, nread)}; |
| 348 | free(source_line); |
| 349 | throw rc; |
| 350 | } else { |
| 351 | previous_comment = &comments.emplace_back(std::move(line)); |
| 352 | } |
| 353 | } |
| 354 | free(source_line); |
| 355 | return comments; |
| 356 | } |
| 357 | |
| 358 | void ot::delete_comments(std::list<std::u8string>& comments, const std::u8string& selector) |
| 359 | { |
| 360 | auto name = selector.data(); |
| 361 | auto equal = selector.find(u8'='); |
| 362 | auto value = (equal == std::u8string::npos ? nullptr : name + equal + 1); |
| 363 | auto name_len = value ? equal : selector.size(); |
| 364 | auto value_len = value ? selector.size() - equal - 1 : 0; |
| 365 | auto it = comments.begin(), end = comments.end(); |
| 366 | while (it != end) { |
| 367 | auto current = it++; |
| 368 | /** \todo Avoid using strncasecmp because it assumes the system locale is UTF-8. */ |
| 369 | bool name_match = current->size() > name_len + 1 && |
| 370 | (*current)[name_len] == '=' && |
| 371 | strncasecmp((const char*) current->data(), (const char*) name, name_len) == 0; |
| 372 | if (!name_match) |
| 373 | continue; |
| 374 | bool value_match = value == nullptr || |
| 375 | (current->size() == selector.size() && |
| 376 | memcmp(current->data() + equal + 1, value, value_len) == 0); |
| 377 | if (value_match) |
| 378 | comments.erase(current); |
| 379 | } |
| 380 | } |
| 381 | |
| 382 | /** Apply the modifications requested by the user to the opustags packet. */ |
| 383 | static void edit_tags(ot::opus_tags& tags, const ot::options& opt) |
| 384 | { |
| 385 | if (opt.set_vendor) |
| 386 | tags.vendor = *opt.set_vendor; |
| 387 | |
| 388 | if (opt.delete_all) { |
| 389 | tags.comments.clear(); |
| 390 | } else for (const std::u8string& name : opt.to_delete) { |
| 391 | ot::delete_comments(tags.comments, name); |
| 392 | } |
| 393 | |
| 394 | for (const std::u8string& comment : opt.to_add) |
| 395 | tags.comments.emplace_back(comment); |
| 396 | } |
| 397 | |
| 398 | /** Spawn VISUAL or EDITOR to edit the given tags. */ |
| 399 | static void edit_tags_interactively(ot::opus_tags& tags, const std::optional<std::string>& base_path, const ot::options& opt) |
| 400 | { |
| 401 | const char* editor = nullptr; |
| 402 | if (getenv("TERM") != nullptr) |
| 403 | editor = getenv("VISUAL"); |
| 404 | if (editor == nullptr) // without a terminal, or if VISUAL is unset |
| 405 | editor = getenv("EDITOR"); |
| 406 | if (editor == nullptr) |
| 407 | throw ot::status {ot::st::error, |
| 408 | "No editor specified in environment variable VISUAL or EDITOR."}; |
| 409 | |
| 410 | // Building the temporary tags file. |
| 411 | ot::status rc; |
| 412 | std::string tags_path = base_path.value_or("tags") + ".XXXXXX.opustags"; |
| 413 | int fd = mkstemps(const_cast<char*>(tags_path.data()), 9); |
| 414 | ot::file tags_file; |
| 415 | if (fd == -1 || (tags_file = fdopen(fd, "w")) == nullptr) |
| 416 | throw ot::status {ot::st::standard_error, |
| 417 | "Could not open '" + tags_path + "': " + strerror(errno)}; |
| 418 | ot::print_comments(tags.comments, tags_file.get(), opt); |
| 419 | tags_file.reset(); |
| 420 | |
| 421 | // Spawn the editor, and watch the modification timestamps. |
| 422 | timespec before = ot::get_file_timestamp(tags_path.c_str()); |
| 423 | ot::status editor_rc; |
| 424 | try { |
| 425 | ot::run_editor(editor, tags_path); |
| 426 | editor_rc = ot::st::ok; |
| 427 | } catch (const ot::status& rc) { |
| 428 | editor_rc = rc; |
| 429 | } |
| 430 | timespec after = ot::get_file_timestamp(tags_path.c_str()); |
| 431 | bool modified = (before.tv_sec != after.tv_sec || before.tv_nsec != after.tv_nsec); |
| 432 | if (editor_rc != ot::st::ok) { |
| 433 | if (modified) |
| 434 | fprintf(stderr, "warning: Leaving %s on the disk.\n", tags_path.c_str()); |
| 435 | else |
| 436 | remove(tags_path.c_str()); |
| 437 | throw editor_rc; |
| 438 | } else if (!modified) { |
| 439 | remove(tags_path.c_str()); |
| 440 | fputs("Cancelling edition because the tags file was not modified.\n", stderr); |
| 441 | throw ot::status {ot::st::cancel}; |
| 442 | } |
| 443 | |
| 444 | // Applying the new tags. |
| 445 | tags_file = fopen(tags_path.c_str(), "re"); |
| 446 | if (tags_file == nullptr) |
| 447 | throw ot::status {ot::st::standard_error, "Error opening " + tags_path + ": " + strerror(errno)}; |
| 448 | try { |
| 449 | tags.comments = ot::read_comments(tags_file.get(), opt); |
| 450 | } catch (const ot::status& rc) { |
| 451 | fprintf(stderr, "warning: Leaving %s on the disk.\n", tags_path.c_str()); |
| 452 | throw; |
| 453 | } |
| 454 | tags_file.reset(); |
| 455 | |
| 456 | // Remove the temporary tags file only on success, because unlike the |
| 457 | // partial Ogg file that is irrecoverable, the edited tags file |
| 458 | // contains user data, so let’s leave users a chance to recover it. |
| 459 | remove(tags_path.c_str()); |
| 460 | } |
| 461 | |
| 462 | static void output_cover(const ot::opus_tags& tags, const ot::options &opt) |
| 463 | { |
| 464 | std::optional<ot::picture> cover = extract_cover(tags); |
| 465 | if (!cover) { |
| 466 | fputs("warning: No cover found.\n", stderr); |
| 467 | return; |
| 468 | } |
| 469 | |
| 470 | ot::file output; |
| 471 | if (opt.cover_out == "-") { |
| 472 | output = stdout; |
| 473 | } else { |
| 474 | struct stat output_info; |
| 475 | if (stat(opt.cover_out->c_str(), &output_info) == 0) { |
| 476 | if (S_ISREG(output_info.st_mode) && !opt.overwrite) |
| 477 | throw ot::status {ot::st::error, "'" + opt.cover_out.value() + "' already exists. Use -y to overwrite."}; |
| 478 | } else if (errno != ENOENT) { |
| 479 | throw ot::status {ot::st::error, "Could not identify '" + opt.cover_out.value() + "': " + strerror(errno)}; |
| 480 | } |
| 481 | |
| 482 | output = fopen(opt.cover_out->c_str(), "w"); |
| 483 | if (output == nullptr) |
| 484 | throw ot::status {ot::st::standard_error, "Could not open '" + opt.cover_out.value() + "' for writing: " + strerror(errno)}; |
| 485 | } |
| 486 | |
| 487 | if (fwrite(cover->picture_data.data(), 1, cover->picture_data.size(), output.get()) < cover->picture_data.size()) |
| 488 | throw ot::status {ot::st::standard_error, "fwrite error: "s + strerror(errno)}; |
| 489 | } |
| 490 | |
| 491 | /** |
| 492 | * Main loop of opustags. Read the packets from the reader, and forwards them to the writer. |
| 493 | * Transform the OpusTags packet on the fly. |
| 494 | * |
| 495 | * The writer is optional. When writer is nullptr, opustags runs in read-only mode. |
| 496 | */ |
| 497 | static void process(ot::ogg_reader& reader, ot::ogg_writer* writer, const ot::options &opt) |
| 498 | { |
| 499 | bool focused = false; /*< the stream on which we operate is defined */ |
| 500 | int focused_serialno; /*< when focused, the serialno of the focused stream */ |
| 501 | |
| 502 | /** When the number of pages the OpusTags packet takes differs from the input stream to the |
| 503 | * output stream, we need to renumber all the succeeding pages. If the input stream |
| 504 | * contains gaps, the offset will naively reproduce the gaps: page numbers 0 (1) 2 4 will |
| 505 | * become 0 (1 2) 3 5, where (…) is the OpusTags packet, and not 0 (1 2) 3 4. */ |
| 506 | int pageno_offset = 0; |
| 507 | |
| 508 | while (reader.next_page()) { |
| 509 | auto serialno = ogg_page_serialno(&reader.page); |
| 510 | auto pageno = ogg_page_pageno(&reader.page); |
| 511 | if (!focused) { |
| 512 | focused = true; |
| 513 | focused_serialno = serialno; |
| 514 | } else if (serialno != focused_serialno) { |
| 515 | /** \todo Support mixed streams. */ |
| 516 | throw ot::status {ot::st::error, "Muxed streams are not supported yet."}; |
| 517 | } |
| 518 | if (reader.absolute_page_no == 0) { // Identification header |
| 519 | if (!ot::is_opus_stream(reader.page)) |
| 520 | throw ot::status {ot::st::error, "Not an Opus stream."}; |
| 521 | if (writer) |
| 522 | writer->write_page(reader.page); |
| 523 | } else if (reader.absolute_page_no == 1) { // Comment header |
| 524 | ot::opus_tags tags; |
| 525 | reader.process_header_packet([&tags](ogg_packet& p) { tags = ot::parse_tags(p); }); |
| 526 | if (opt.cover_out) |
| 527 | output_cover(tags, opt); |
| 528 | edit_tags(tags, opt); |
| 529 | if (writer) { |
| 530 | if (opt.edit_interactively) { |
| 531 | fflush(writer->file); // flush before calling the subprocess |
| 532 | edit_tags_interactively(tags, writer->path, opt); |
| 533 | } |
| 534 | auto packet = ot::render_tags(tags); |
| 535 | writer->write_header_packet(serialno, pageno, packet); |
| 536 | pageno_offset = writer->next_page_no - 1 - reader.absolute_page_no; |
| 537 | } else { |
| 538 | if (opt.cover_out != "-") { |
| 539 | if (opt.print_vendor) |
| 540 | puts_utf8(tags.vendor, stdout, opt); |
| 541 | else |
| 542 | ot::print_comments(tags.comments, stdout, opt); |
| 543 | } |
| 544 | break; |
| 545 | } |
| 546 | } else if (writer) { |
| 547 | ot::renumber_page(reader.page, pageno + pageno_offset); |
| 548 | writer->write_page(reader.page); |
| 549 | } |
| 550 | } |
| 551 | if (reader.absolute_page_no < 1) |
| 552 | throw ot::status {ot::st::error, "Expected at least 2 Ogg pages."}; |
| 553 | } |
| 554 | |
| 555 | static void run_single(const ot::options& opt, const std::string& path_in, const std::optional<std::string>& path_out) |
| 556 | { |
| 557 | ot::file input; |
| 558 | if (path_in == "-") |
| 559 | input = stdin; |
| 560 | else if ((input = fopen(path_in.c_str(), "re")) == nullptr) |
| 561 | throw ot::status {ot::st::standard_error, |
| 562 | "Could not open '" + path_in + "' for reading: " + strerror(errno)}; |
| 563 | ot::ogg_reader reader(input.get()); |
| 564 | |
| 565 | /* Read-only mode. */ |
| 566 | if (!path_out) { |
| 567 | process(reader, nullptr, opt); |
| 568 | return; |
| 569 | } |
| 570 | |
| 571 | /* Read-write mode. |
| 572 | * |
| 573 | * The output pointer is set to one of: |
| 574 | * - stdout for "-", |
| 575 | * - final_output.get() for special files like /dev/null, |
| 576 | * - temporary_output.get() for regular files. |
| 577 | * |
| 578 | * We use a temporary output file for the following reasons: |
| 579 | * 1. A partial .opus output would be seen by softwares like media players, but a .part |
| 580 | * (for partial) won’t. |
| 581 | * 2. If the process crashes badly, or the power cuts off, we don't want to leave a partial |
| 582 | * file at the final location. The temporary file is going to remain though. |
| 583 | * 3. If we're overwriting a regular file, we'd rather avoid wiping its content before we |
| 584 | * even started reading the input file. That way, the original file is always preserved |
| 585 | * on error or crash. |
| 586 | * 4. It is necessary for in-place editing. We can't reliably open the same file as both |
| 587 | * input and output. |
| 588 | */ |
| 589 | |
| 590 | FILE* output = nullptr; |
| 591 | ot::partial_file temporary_output; |
| 592 | ot::file final_output; |
| 593 | |
| 594 | struct stat output_info; |
| 595 | if (path_out == "-") { |
| 596 | output = stdout; |
| 597 | } else if (stat(path_out->c_str(), &output_info) == 0) { |
| 598 | /* The output file exists. */ |
| 599 | if (!S_ISREG(output_info.st_mode)) { |
| 600 | /* Special files are opened for writing directly. */ |
| 601 | if ((final_output = fopen(path_out->c_str(), "we")) == nullptr) |
| 602 | throw ot::status {ot::st::standard_error, |
| 603 | "Could not open '" + path_out.value() + "' for writing: " + strerror(errno)}; |
| 604 | output = final_output.get(); |
| 605 | } else if (opt.overwrite) { |
| 606 | temporary_output.open(path_out->c_str()); |
| 607 | output = temporary_output.get(); |
| 608 | } else { |
| 609 | throw ot::status {ot::st::error, "'" + path_out.value() + "' already exists. Use -y to overwrite."}; |
| 610 | } |
| 611 | } else if (errno == ENOENT) { |
| 612 | temporary_output.open(path_out->c_str()); |
| 613 | output = temporary_output.get(); |
| 614 | } else { |
| 615 | throw ot::status {ot::st::error, "Could not identify '" + path_out.value() + "': " + strerror(errno)}; |
| 616 | } |
| 617 | |
| 618 | ot::ogg_writer writer(output); |
| 619 | writer.path = path_out; |
| 620 | process(reader, &writer, opt); |
| 621 | |
| 622 | // Close the input file and finalize the output. When --in-place is specified, some file |
| 623 | // systems like SMB require that the input is closed first. |
| 624 | input.reset(); |
| 625 | temporary_output.commit(); |
| 626 | } |
| 627 | |
| 628 | void ot::run(const ot::options& opt) |
| 629 | { |
| 630 | if (opt.print_help) { |
| 631 | fputs(help_message, stdout); |
| 632 | return; |
| 633 | } |
| 634 | |
| 635 | ot::status global_rc = st::ok; |
| 636 | for (const auto& path_in : opt.paths_in) { |
| 637 | try { |
| 638 | run_single(opt, path_in, opt.in_place ? path_in : opt.path_out); |
| 639 | } catch (const ot::status& rc) { |
| 640 | global_rc = st::error; |
| 641 | if (!rc.message.empty()) |
| 642 | fprintf(stderr, "%s: error: %s\n", path_in.c_str(), rc.message.c_str()); |
| 643 | } |
| 644 | } |
| 645 | if (global_rc != st::ok) |
| 646 | throw global_rc; |
| 647 | } |