Technical illustration: Audio ingestion checks the host and address, bounds received bytes, decodes the audio and saves a new immutable output.
Original technical illustration for this runnable lab.

A music API returns a download URL and a successful status. The object at that URL can still be an error page, an incomplete file or a file outside the formats your player accepts. Passing it straight into the public media directory turns a provider response into a publishing decision without checking the bytes.

This exercise separates URL admission, bounded download and local decoding. You will run a small Python validator against a generated WAV and deliberately invalid responses. The HTTP tests use injected DNS and connection objects; they never contact a provider, an internal address or a public IP.

MusicFlow's inspected Node.js code already separates constrained audio downloading from ffprobe and ffmpeg checks. The tutorial uses Python's standard library to make an independent implementation easy to inspect. Its synthetic host, limits and file policy belong to the exercise, not to a claim that a particular provider has been integrated successfully.

Install the two media tools, then run the fixture

Download the audio-ingestion lab. It requires Python, ffprobe and ffmpeg available on PATH. The package records the exact versions used in verification. Check your installation before running the tests.

python3 --version
ffprobe -version
ffmpeg -version
python3 -B -m unittest discover -v
python3 ingest.py

The demo creates two seconds of synthetic WAV data, probes it, decodes its audio stream and reports its size, duration and SHA-256 hash. The temporary directory is removed afterward. It is test data, not an AI music sample.

The tests also pass HTML bytes into the same validator and truncate a WAV after its header. Both must fail, and their temporary files must disappear. Renaming either object to .mp3 does not change the result because the decision uses the bytes and decoder output.

Admit a provider host and pin the checked address

The URL policy accepts HTTPS on port 443, requires an exact allowed hostname and rejects embedded credentials and fragments. DNS answers are checked before opening the connection. If any returned address is non-global, the whole answer set is rejected.

def resolve(url,allowed_hosts,resolver=None):
    u=urlsplit(url)
    if u.scheme!='https' or u.username or u.password or u.fragment or u.port not in (None,443) or u.hostname not in allowed_hosts:
        raise ValueError('URL outside allowed provider hosts')
    if resolver is None:
        resolver=lambda h:[v[4][0] for v in socket.getaddrinfo(h,443,type=socket.SOCK_STREAM)]
    addresses=resolver(u.hostname)
    if not addresses or any(not ipaddress.ip_address(a).is_global or '%' in a for a in addresses):
        raise ValueError('non-global address')
    return u,addresses[0]

The default connection class opens the socket to the already checked IP while keeping the original hostname for TLS certificate verification. This avoids performing an unrelated second hostname lookup after validating the first result. It also means that the allowlist and certificate hostname are separate checks.

class PinnedHTTPS(http.client.HTTPSConnection):
    def __init__(self,host,ip):super().__init__(host,timeout=5);self.ip=ip
    def connect(self):
        raw=socket.create_connection((self.ip,443),self.timeout)
        try:self.sock=ssl.create_default_context().wrap_socket(raw,server_hostname=self.host)
        except BaseException:raw.close();raise

The exercise's connector test records the hostname and IP passed into this class. It verifies the handoff between policy and transport. It does not establish real-network TLS behavior or provide a security audit. A deployed service should additionally control network egress and run untrusted media processing with an appropriately isolated service account or container.

Count actual bytes even when headers are absent

The downloader accepts only a 200 response. It does not follow redirects. A redirect would create another destination requiring the same validation, so rejecting it keeps this example's destination policy small and explicit.

def download(url,allowed_hosts,resolver=None,connector=PinnedHTTPS,limit=1024*1024):
    u,ip=resolve(url,allowed_hosts,resolver);connection=connector(u.hostname,ip)
    try:
        connection.request('GET',(u.path or '/')+('?' + u.query if u.query else ''),headers={'Accept':'audio/*'})
        response=connection.getresponse()
        if response.status!=200:raise ValueError('response is not 200; redirects are not followed')
        declared=response.getheader('Content-Length')
        if declared is not None and (not declared.isdigit() or int(declared)>limit):raise ValueError('invalid or oversized declared length')
        data=bytearray()
        while chunk:=response.read(65536):
            data.extend(chunk)
            if len(data)>limit:raise ValueError('stream exceeds limit')
        if declared is not None and len(data)!=int(declared):raise ValueError('truncated response')
        return bytes(data)
    finally:connection.close()

The body limit is one MiB in this exercise. A declared length above that limit is rejected immediately. The code also counts the bytes actually read, which catches a streamed response without Content-Length. When a length is declared, a shorter body is treated as truncation.

The connector uses a five-second socket timeout. That is not a full-job deadline, and this program does not claim protection against every slow-response pattern. A production worker needs a total execution budget, cancellation behavior and resource limits around the transport as well as the decoder.

Probe and decode before exposing the output

The validator writes into a temporary file in the intended output directory. It restricts the media tools to local file/pipe protocols and WAV/MP3 formats, checks that the reported duration is between one and ten seconds, then asks ffmpeg to decode the selected audio stream without producing a new public file.

Only after those checks does it create the output name using a same-filesystem hard link. That operation refuses to replace an existing file, including one created by another process after the initial existence check. The temporary name is removed in a finally block on success and failure.

def validate(data,output):
    output=Path(output)
    if output.exists():raise FileExistsError('choose a new output path')
    output.parent.mkdir(parents=True,exist_ok=True)
    fd,name=tempfile.mkstemp(prefix='.audio-',dir=output.parent)
    try:
        with os.fdopen(fd,'wb') as f:f.write(data)
        r=subprocess.run(['ffprobe','-v','error','-protocol_whitelist','file,pipe','-format_whitelist','wav,mp3','-show_entries','format=duration,format_name:stream=codec_type','-of','json',name],check=True,capture_output=True,text=True,timeout=5)
        info=json.loads(r.stdout);fmt=info.get('format',{});duration=float(fmt.get('duration',0))
        if fmt.get('format_name') not in ['wav','mp3'] or not 1<=duration<=10 or not any(s.get('codec_type')=='audio' for s in info.get('streams',[])):
            raise ValueError('unsupported audio or duration')
        subprocess.run(['ffmpeg','-v','error','-xerror','-nostdin','-protocol_whitelist','file,pipe','-format_whitelist','wav,mp3','-i',name,'-map','0:a:0','-f','null','-'],check=True,capture_output=True,timeout=10)
        # Same-filesystem link refuses replacement if another process won the name.
        os.link(name,output)
        return {'bytes':len(data),'sha256':hashlib.sha256(data).hexdigest(),'seconds':duration,'format':fmt['format_name']}
    finally:Path(name).unlink(missing_ok=True)

The whitelist keeps this lab focused on two file formats; it is not an antivirus engine. Tool versions, decoder sandboxing, disk quotas and host permissions remain deployment concerns. Longer musical works would require a different duration policy, and the accepted format should match the actual delivery contract.

Audio ingestion checks the host and address, bounds received bytes, decodes the audio and saves a new immutable output.
Independent teaching model. Install ffprobe and ffmpeg on PATH before running.

A URL can have a query without an explicit path. The request target must still begin with /; the regression fixture checks that https://host?token=abc becomes /?token=abc, not just a bare query.

Keep the release decision separate

Ten tests passed after extracting the final archive into a fresh directory. They cover host admission, mixed DNS answers, checked-address handoff, rejected redirects, oversized streams, truncation, valid audio, invalid HTML and temporary-file cleanup. Real HTTPS connections and provider accounts were not exercised.

A valid WAV can still be unsuitable for a customer's project. These checks say that the supplied data fits the lab's technical format policy. They say nothing about musical quality, authorship, sample clearance or whether downstream licensing is permitted.

Fone MusicFlow places generation results, source information, review and publication in separate records. When commissioning a music platform, ask to see the rejected-file path as well as a successful result. The operator should be able to trace the original attempt, retain a useful failure reason and keep invalid media out of the public catalog.

The ffprobe documentation describes the machine-readable format information used here. The exact local program and its tests are in the download, so changing a format or size limit can be reviewed as an executable policy change.