from pathlib import Path
import sys
p=Path(sys.argv[1])/'libavcodec/dstdec.c'
s=p.read_text()
if 'Widephase raw DSD output' not in s:
    old='        memcpy(frame->data[0], avpkt->data + 1, FFMIN(avpkt->size - 1, frame->nb_samples * channels));'
    assert old in s
    s=s.replace(old, '''        if (avpkt->size - 1 != frame->nb_samples * channels)
            return AVERROR_INVALIDDATA;
        for (i = 0; i < frame->nb_samples * channels; i++)
            dsd[i * 4] = avpkt->data[i + 1];''')
    old='dsd:\n    for (i = 0; i < channels; i++) {'
    assert old in s
    s=s.replace(old, '''dsd:
    /* Widephase raw DSD output: an opaque flag requests lossless MSB bytes.
       The normal allocation remains FLT-sized because arithmetic decoding uses
       a four-byte stride. Compact only after the entire frame is decoded. */
    if (avctx->opaque) {
        for (i = 0; i < frame->nb_samples * channels; i++)
            dsd[i] = dsd[i * 4];
        frame->format = AV_SAMPLE_FMT_U8;
        *got_frame_ptr = 1;
        return avpkt->size;
    }
    for (i = 0; i < channels; i++) {''')
    p.write_text(s)
