Category Archives: Programming

Converting a C++ code base from boost::filesystem to std::filesystem

My project MKVToolNix has used the boost::filesystem library for a long time. It allows for easy path manipulation (e.g. “what’s the parent directory”, “does the named entry exist & is a file” or “create all directories for this path that don’t exist yet”). The central class of the library is boost::filesystem::path which encodes an absolute or relative part of an entry in the file system and offers various functions for modifying, querying or formatting it. All utility functions such as the aforementioned “create all directories” take path instances as arguments.

All of this worked mostly fine.

After release v53 of MKVToolNix a user reported an issue with using Emojis in file names. Turns out this wasn’t trivial to debug and is likely a bug in boost::filesystem or in the way I handled character encoding (more on that later).

This motivated me to look into converting MKVToolNix from boost::filesystem to std::filesystem which had been added to the C++ Standard Library with C++17. Its design is based heavily on boost::filesystem: a lot of the classes & functions are named identically within the two namespaces and most of their semantics match. As I’m eager to reduce the number of third-party libraries by using C++ standard libraries where it makes sense, converting my code base seemed the obvious step.

I mean, how hard could it be? Right?

Easy changes

A lot of changes were trivial: simply replacing boost::filesystem:: with std::filesystem:: got me pretty far.

Another easy change was to replace deprecated function names with the current ones, e.g. branch_path() with parent_path(): look up the deprecated function name in for boost::filesystem, take its replacement & swap the namespace — done.

Encodings & character set conversions

The most glaring difference in my opinion between the two libraries is how they handle encodings/character set conversions for the path classes. In both libraries the path class offer constructors for instances of std::string and std::wstring. Internally the classes use either std::string or std::wstring for storage depending on the operating system they’re compiled for: wide strings (std::wstring) for Windows and narrow ones (std::string) everywhere else.

This means that the constructors taking the string type that doesn’t match the storage type (std::string on Windows, std::wstring everywhere else) must do character set conversion, either from narrow to wide (Windows) or wide to narrow (Linux). This is where things get really dicey.

boost::filesystem solves this by letting the user imbue the whole boost::filesystem::path class with a C++ locale object. That locale object is used for the conversion. The programmer has to set this up once per program invocation, and that’s it. Easy.

MKVToolNix’s internal string handling uses UTF-8 encoded narrow strings everywhere. For file names, too[1]Yes, I know that’s bad as file systems on Unix aren’t guaranteed to have any type of encoding; file names might contain something that isn’t valid according to any encoding etc. etc.. Therefore the logical choice was to imbue boost::filesystem::path with an UTF-8 character set conversion locale. It would convert between UTF-8 encoded narrow strings and wide strings.

std::filesystem does not do it that way. At all. For the constructor taking char-based narrow strings (pointer-to-char or std::string) conversion from the native narrow encoding is done. On POSIX systems this means no conversion which matches how MKVToolNix is coded: std::filesystem::path receives a UTF-8 encoded narrow string & stores it as-is internally.

On Windows, though, this means that conversion is done from a character set such as Windows-1252 on a German Windows. Oooh boy, this is bad, as that isn’t at all how MKVToolNix encodes narrow strings. So what happens when an UTF-8 encoded narrow string containing non-ASCII characters is passed to std::filesystem::path? Mangled non-ASCII characters, of course. German Umlaute, French accents, Asian characters, Emojis — doesn’t matter. Encodings don’t match, conversion does bad things, file names are messed up.

In effect this means that I must never, ever use the narrow string constructor of std::filesystem::path on Windows except for when I know the narrow string only contains ASCII characters.

Implicit conversion

This thing wouldn’t be so bad for me if the constructors std::filesystem::path were explicit. They’re not, though, meaning string-to-path can hide in various places and are hard to spot. For example:

void do_stuff(const std::filesystem::path &p) {
  // do something with p
}

void chunky_bacon(const std::string &file_name) {
  // do chunky things
  do_stuff(file_name);
  // do bacon things
}

Here’s one of those conversions that absolutely must not happen on Windows, due to the implicit constructor.

Another example:

std::filesystem::path dir;
// set dir somehow
auto full_file_name = dir / sub_dir / "index.txt";

Is this OK? Well, depends on the type of sub_dir, actually. If it is a path already, it’s OK; if it’s a wide string, it’s OK, too, but all narrow string types (char arrays, std::string)? Not so much. And this is really hard to spot or grep for.[2]The "index.txt" argument is fine. Even though it’s a narrow string, it solely consists of ASCII characters that’ll convert properly to wide strings no matter what Windows’ native … Continue reading

I’d really appreciate if my compiler was able to help me out here. Having the constructors explicit would mean neither of these examples would compile and I’d need to add an explicit conversion myself. But the C++ committee didn’t make them explicit, probably for a reason.

Solutions

My solution was to ban the use of the constructors[3]C++20 will improve this situation with the introduction of char8_t. The constructor taking a char8_t-based narrow string will always convert from UTF-8, avoiding this mess.. Instead I introduced helper functions to_path() that take both narrow & wide strings & assume narrow strings are UTF-8 encoded. These helper functions work differently depending on whether I’m compiling for Windows or other systems.

Let’s take the second example from above. I’d convert it as follows:

auto full_file_name = dir / mtx::fs::to_path(sub_dir) / "index.txt";

Ugly as sin.

Bugs in the C++ Standard Library

std::filesystem is rather new, being added in C++17. I was prepared for bugs to rear their ugly heads. But I wasn’t prepared for how broken certain parts of the gcc standard C++ library are on Windows wrt. to UNC paths[4]I use a gcc/mingw cross-compiler from the MXE project for cross-compiling from Linux to Windows. The same issues would happen compiling with mingw on Windows itself.. A UNC path might look like this: \\server\share\sub_dir\file.txt Without any particular order, here are a couple of issues I ran into (this is with gcc 10.2.0, the latest release at the time of writing):

  1. On Windows the std::filesystem::file_size function was implemented by calling 32-bit functions that use signed 32-bit variables for storing the file size. Needless to say, this doesn’t work too well with files larger than 2 GB. The corresponding gcc bug 95749 has already been fixed upstream, but it isn’t part of a release yet. My workaround: I cherry-picked the commit fixing the issue into my own copy of gcc I’m using for building MKVToolNix.
  2. std::filesystem::exists doesn’t work correctly with all UNC paths. It works with e.g. \\server\share\sub_dir\file.txt but not the share \\server\share itself. I’ve reported this as gcc bug 99311. My workaround: I don’t use std::filesystem::exists; instead I test for the type I expect (e.g. std::filesystem::is_directory or std::filesystem::is_regular_file) as those functions do work correctly. Even with UNC paths.
  3. As a consequence std::filesystem::create_directories doesn’t work with UNC paths either. It thinks that neither \\server nor \\server\share exist and tries to create them. That fails, obviously, and create_directories aborts at the first failure. My workaround: I NIH’ed my own create_directories function that uses std::filesystem::is_directory for testing for existence. Only on Windows, of course. Reported in the same bug as the one above.
  4. std::filesystem::absolute and std::filesystem::path::is_absolute don’t work on UNC paths. They think those paths aren’t absolute and will do funky things such as return C:\server\share\file.txt when asked for the absolute path to \\server\share\file.txt. Of course I reported this, too; it’s gcc bug 99333 where I was told that it was actually a bug in the std::filesystem::path::has_root_name function. My workaround: I NIH’ed some more functions that treat paths starting with \\ or // as absolute.
  5. UNC paths using forward slashes are only supported if the program is compiled with the cygwin gcc compiler. My workaround: in my NIH’ed functions I normalize forward slashes to backslashes.
  6. UNC device paths starting with \\?\… such as \\?\C:\Path\File.mkv or \\?\UNC\server\share\file.opus don’t work at all. Functions such as std::filesystem::exists() don’t work, and even my workaround from above (using std::filesystem::is_directory() or std::filesystem::is_regular_file()) doesn’t work with these paths. I’ve filed gcc bug 99430 for this. My workaround: at the moment I haven’t implemented one. I might replace \\?\… with \\.\… in my conversion functions as those seem to fare better.

As I wrote above, this is gcc 10.2.0. Your compiler might fare better, of course. I suspect that Microsoft’s Visual C++ has fewer of those Windows-specific issues, simply due to the amount of experience its developers have with Windows’s peculiarities.

Bugs in MKVToolNix

Most bugs that were actually bugs in MKVToolNix instead of the standard C++ library turned out to be due to using the implicit conversion of narrow strings to path objects that I’ve talked about in length above.

There was one bug that was due to changed semantics between the two libraries: what happens if your path is at the root already (e.g. C:\ on Windows) and you call parent_path() on it? boost::filesystem will return an empty path object whereas std::filesystem will return the same path again. This means that loops checking the file system from a point to root have to have their conditions changed. Instead of e.g. while (!path.empty()) you’ll have to do something like while (path.parent_path() != path). It gets even nastier wrt. to UNC paths; see this chart for details. I definitely forgot to fix a couple of these cases leading to endless loops.

macOS woes & older Linux versions

One problem on macOS is that different macOS versions have different levels of support for C++17. Until this change I used to build for macOS 10.14 “Mojave” and newer, as those supported all C++17 features I used. However, std::filesystem, while being a C++17 feature, is only supported on macOS 10.15 “Catalina” and the current 11.0 “Big Sur”. One of the drawbacks of using current technology.

This is a bit different to older Linux distributions. Let’s take CentOS 7, a rather old distribution. I can still compile current MKVToolNix releases there by installing the latest developer toolset which comes with a current gcc & libc++. For macOS the compiler version doesn’t suffice, though: even if I install a recent XCode version on macOS 10.14, I cannot build code using std::filesystem for it as the standard C++ library on macOS 10.14 doesn’t contain that functionality. I haven’t bothered investigating if it’s possible to include a newer standard C++ library itself in the MKVToolNix disk image.

And on Linux? Was it worth it?

Well… I haven’t had a single issue with so far with the conversion on Linux.

And as to the question whether or not it was worth it: hmm… meh. I really like to reduce my number of external dependencies. That is a tangible gain. It simplifies the build process & reduces build times in various situations where Boost isn’t available as I’m now down to solely using header-only libraries from Boost. And I actively take part in improving the gcc standard C++ library implementation. This is still Open Source, after all; you’re expected to give back & help out. This is how all of our projects grow.

Footnotes

Footnotes
1 Yes, I know that’s bad as file systems on Unix aren’t guaranteed to have any type of encoding; file names might contain something that isn’t valid according to any encoding etc. etc.
2 The "index.txt" argument is fine. Even though it’s a narrow string, it solely consists of ASCII characters that’ll convert properly to wide strings no matter what Windows’ native narrow encoding is. I hope.
3 C++20 will improve this situation with the introduction of char8_t. The constructor taking a char8_t-based narrow string will always convert from UTF-8, avoiding this mess.
4 I use a gcc/mingw cross-compiler from the MXE project for cross-compiling from Linux to Windows. The same issues would happen compiling with mingw on Windows itself.

Speeding up MKVToolNix compilation speed with zapcc

Compiling MKVToolNix can take quite a bit of time. It’s a C++ application, it uses a lot of template code, and it doesn’t make use of the pimpl idiom as much as it could. For years I’ve been using the usual several techniques trying to keep the time down: parallel compilation and pre-compiled headers. However, it still takes quite a lot of time, and that’s a bother during development.[1]I’m also caching compilation results using ccache so that re-compiling is super fast, but that doesn’t help with initial compilation times or if something in one of the central header … Continue reading

That’s why I was instantly stoked when reading about an announcement earlier this weak: zapcc, a clang-based C/C++ compiler heavily tuned towards performance, is being open-sourced. Having more Open Source options in the compiler world is great, having someone working on speed is even better.

zapcc’s web site has some outrageous numbers, toting 40x speedup during re-compilation. That sure sounds like marketing numbers. So how much better is it for my use case, compiling MKVToolNix? Well, look at this:

chart of compilation time of different compilers with different options

This sure looks nice! Here are the actual numbers:

Compiler drake -j1 drake -j5
gcc 8.1.1, no precompiled headers 39:49 15:21
gcc 8.1.1, with precompiled headers 24:34 09:23
clang 6.0.0, no precompiled headers 29:11 12:27
clang 6.0.0, with precompiled headers 18:27 07:05
zapcc revision c2b11ba7 07:16 03:05

Now those numbers explore the whole range between “no help at all” (no pre-compiled headers, no parallelism during compilation, slowest compiler) and “bells and whistles” (maximum parallelism, fastest compiler). A realistic comparison is between my usual setup and the fastest zapcc variant. Those two numbers are the bold ones above: clang using pre-compiled headers with five running compilers in parallel vs. zapcc with five running compilers in parallel.[2]zapcc doesn’t support pre-compiled headers, hence only one line for zapcc And this is quite remarkable: from seven minutes down to three, down to 43% of the original time. Yes, this does make quite a difference during development.

So if you’re looking for a way to speed up your C++ compilation time, take a look at zapcc. I’m just glad people focus on different aspects of compilers, and us users can profit from them thanks to the compilers being Open Source. A big thanks to all compiler developers!

All tests were done on my Arch Linux installation:

  • MKVToolNix revision 7008661ed951e79c9cc6b7dc167137e84bed8805
  • CFLAGS=-fno-omit-frame-pointer CXXFLAGS=-fno-omit-frame-pointer ./configure --enable-debug --enable-optimization
  • gcc & clang from Arch’s repositories
  • zapcc compiled from git
  • Intel i5-4690K (four real cores, no hyperthreading)
  • 32 GB RAM DDR-3 1600 MHz
  • Samsung EVO 850 SSD
  • no swap space
  • all compiled binaries pass my test suite

Footnotes

Footnotes
1 I’m also caching compilation results using ccache so that re-compiling is super fast, but that doesn’t help with initial compilation times or if something in one of the central header files that’s included all over the place changes.
2 zapcc doesn’t support pre-compiled headers, hence only one line for zapcc

MKVToolNix 5.6.0 released

Hey,

I’ve released v5.6.0. It fixes a couple of important issues with the new --split parts: functionality. Other bugs were fixed as well. A Polish translation of the programs has been added as well as a Spanish translation of mmg’s guide.

Here are the usual links: the home page, the source code and the Windows installer and 7zip archive.

All of the binaries that I provide myself are already available.

Here’s the full ChangeLog since release 5.5.0:

  • 2012-05-27 Moritz Bunkus <moritz@bunkus.org>
    • Released v5.6.0.
    • documentation: Added Spanish translation of mmg’s guide by Israel Lucas Torrijos (see AUTHORS).
  • 2012-05-20 Moritz Bunkus <moritz@bunkus.org>
    • mkvmerge: bug fix: SRT subtitle entries with colons as the decimal separator are accepted. Fix for issue 754.
  • 2012-05-13 Moritz Bunkus <moritz@bunkus.org>
    • mkvmerge: bug fix: XML tag files with <Simple> tags that only contained a name and nested <Simple> were wrongfully rejected as invalid. Fixes issue 752.
    • mkvmerge: enhancement: mkvmerge was optimizied to keep cluster timecodes strictly increasing in most situations.
  • 2012-04-24 Moritz Bunkus <moritz@bunkus.org>
    • all: Added a translation to Polish by Daniel (see AUTHORS).
  • 2012-04-16 Moritz Bunkus <moritz@bunkus.org>
    • mkvextract: bug fix: Extraction of AVC/h.264 was completely broken after 2012-04-09 resulting in files with a length of 0 bytes.
  • 2012-04-09 Moritz Bunkus <moritz@bunkus.org>
    • mmg: new feature: When adding a Matroska file that has either the "previous segment UID" or the "next segment UID" set then mmg will copy those two and the source file’s segment UID into the corresponding controls on the "globla" tab if they haven’t been set before. Implements ticket 733.
    • mkvmerge: new feature: The verbose identification mode for Matroska files will now includes the "segment UID", the "next segment UID" and "previous segment UID" elements.
    • mkvmerge: enhancement: In "–split parts:" mode mkvmerge will use the output file name as it is instead of adding a running number to it if all the ranges to be kept are to be written into a single output file. Implements ticket 743.
    • mkvextract: bug fix: mkvextract will no longer abort extracing h.264 tracks if it encounters a NAL smaller than its size field. Instead it will warn about it and drop the NAL.
  • 2012-04-08 Moritz Bunkus <moritz@bunkus.org>
    • mkvmerge: bug fix: Writing more than two parts into the same file with "–split parts:" resulted in the timecodes of the third and all following parts to be wrong. Fixes ticket 740.
    • mkvmerge: bug fix: The "–split parts:" functionality was not taking dropped ranges into account when calculating the segment duration for files that more than one range was written to. Fixes ticket 738.
    • mkvmerge: bug fix: The "–split parts:" functionality was producing a small gap between the first part’s last packet’s timecode and the second part’s first packet’s timecode if two parts are written to the same file. Fixes ticket 742.
  • 2012-04-07 Moritz Bunkus <moritz@bunkus.org>
    • mkvmerge: bug fix: The "–split parts:" functionality was writing a superfluous and empty first part if the first range starts at 00:00:00. Fixes ticket 737.
  • 2012-04-07 Moritz Bunkus <moritz@bunkus.org>
    • mmg, build system: Fixed building with wxWidgets 2.9.3.

MKVToolNix v5.0.1 released

Hey,

I’ve released mkvtoolnix v5.0.1. It’s a release with a few improvements/bug fixes and one important fix for a regression introduced in v5.0.0 regarding PGS subtitles.

There were no changes that concern package maintainers.

Here are the usual links: the home page, the source code and the Windows installer and 7zip archive.

All of the binaries that I provide myself are already available.

Here’s the full ChangeLog since release 5.0.0:

  • 2011-10-09 Moritz Bunkus <moritz@bunkus.org>
    • Released v5.0.1.
  • 2011-10-08 Moritz Bunkus <moritz@bunkus.org>
    • build system: Updated the Debian/Ubuntu files to debhelper v7/quilt 3.0 format.
    • mkvmerge: enhancement: Implemented support for yet another way of storing EAC3 and DTS in MPEG transport streams.
  • 2011-10-05 Moritz Bunkus <moritz@bunkus.org>
    • mkvinfo: bug fix: Track information was not reset when opening more than one file in the GUI.
  • 2011-10-03 Moritz Bunkus <moritz@bunkus.org>
    • mkvmerge: bug fix: The PGS subtitle output module was not outputting any packet in certain cases due to uninitialized variables.
  • 2011-09-27 Moritz Bunkus <moritz@bunkus.org>
    • mkvmerge: bug fix: Fixed mkvmerge not finding any track in TS streams whose first PMT packet could not be parsed (e.g. invalid CRC).
    • mkvmerge: bug fix: Fixed detection of TS streams that only contain one PAT or PMT packet within the first few KB but no others within the first 10 MB.

Have fun.