int sc_plugin_interface::buffer_write(uint32_t index, const char * filename, const char * header_format, const char * sample_format,
                                      uint32_t start, uint32_t frames, bool leave_open)
{
    SndBuf * buf = World_GetNRTBuf(&world, index);
    int format = headerFormatFromString(header_format) | sampleFormatFromString(sample_format);

    SndfileHandle sf(filename, SFM_WRITE, format, buf->channels, buf->samplerate);

    if (!sf)
        return -1;

    if (frames == 0xffffffff)
        frames = buf->frames;

    const uint32_t remain = uint32_t(buf->frames) > start ? buf->frames - start : 0;
    const uint32_t frames_to_write = std::min(remain, frames);

    if (frames_to_write)
        sf.writef(buf->data + start * buf->channels, frames_to_write);

    if (leave_open && !buf->sndfile)
        buf->sndfile = sf.takeOwnership();

    return 0;
}
static inline int sndfileFormatInfoFromStrings(struct SF_INFO *info, const char *headerFormatString, const char *sampleFormatString)
{
    int headerFormat = headerFormatFromString(headerFormatString);
    if (!headerFormat) return kSCErr_Failed;

    int sampleFormat = sampleFormatFromString(sampleFormatString);
    if (!sampleFormat) return kSCErr_Failed;

    info->format = (unsigned int)(headerFormat | sampleFormat);
    return kSCErr_None;
}