microsoft/DirectXTex

Allow callers to provide their own I/O routines

0xC0000054 opened this issue · 3 comments

This is another advanced feature that I implemented in the DirectXTex fork that my Paint.NET DDS plugin uses.
It allows me to have an adapter to make DirectXTex work with a .NET Stream, instead of having to use a temporary file or store the entire file in memory.

The proposed API is:

class IOHandler
{
public:
    enum class SeekOrigin
    {
        Begin,
        Current,
        End
    };

    virtual HRESULT __cdecl GetSize(int64_t& size) const noexcept = 0;

    virtual HRESULT __cdecl Read(void* buffer, size_t count) const noexcept = 0;

    virtual HRESULT __cdecl Seek(int64_t position, SeekOrigin origin) const noexcept = 0;

    virtual HRESULT __cdecl Write(const void* buffer, size_t count) const noexcept = 0;
};

DDS, HDR and TGA would have new methods for loading, saving and retrieving metadata using an IOHandler.
The WIC methods are currently excluded, but it may be possible to write an IStream implementation on top of the IOHandler.

HRESULT __cdecl GetMetadataFromDDSIOHandler(
_In_ const IOHandler& handler, _Out_ TexMetadata& metadata) noexcept;

HRESULT __cdecl LoadFromDDSIOHandler(
_In_ const IOHandler& handler,
_In_ DDS_FLAGS flags,
_Out_opt_ TexMetadata* metadata, _Out_ ScratchImage& image) noexcept;

HRESULT __cdecl SaveToDDSIOHandler
_In_ const Image& image, _In_ DDS_FLAGS flags, _In_ const IOHandler& handler) noexcept;

// Repeat for HDR and TGA.

This could also be used to simplify the various LoadFrom*File and SaveTo*File routines by wrapping the platform-specific code in an IOHandler, which would be used to call the appropriateIOHandler method.

Since DirectXTex does a lot of file parsing, I'm particularly sensitive to changes that might induce security bugs. This looks like it would be fairly invasive to the existing code, and require a some investment in additional testing.

I'm also not convinced that this is really necessarily. Why not just use .NET functions to load the image file into memory and then use the FromMemory methods to parse it?

Why not just use .NET functions to load the image file into memory and then use the FromMemory methods to parse it?

I originally did that, but it significantly increased the memory usage when loading and saving images.

Since DirectXTex does a lot of file parsing, I'm particularly sensitive to changes that might induce security bugs. This looks like it would be fairly invasive to the existing code, and require a some investment in additional testing.

Should I submit a draft PR with a prototype implementation?

After prototyping an implementation, I have decided that this is too specialized a request for the main DirectXTex library.
It adds a lot of code and complexity for a feature that very few people will probably use.