Recherche avancée
Médias (91)
-
MediaSPIP Simple : futur thème graphique par défaut ?
26 septembre 2013, par
Mis à jour : Octobre 2013
Langue : français
Type : Video
-
avec chosen
13 septembre 2013, par
Mis à jour : Septembre 2013
Langue : français
Type : Image
-
sans chosen
13 septembre 2013, par
Mis à jour : Septembre 2013
Langue : français
Type : Image
-
config chosen
13 septembre 2013, par
Mis à jour : Septembre 2013
Langue : français
Type : Image
-
SPIP - plugins - embed code - Exemple
2 septembre 2013, par
Mis à jour : Septembre 2013
Langue : français
Type : Image
-
GetID3 - Bloc informations de fichiers
9 avril 2013, par
Mis à jour : Mai 2013
Langue : français
Type : Image
Sur d’autres sites (346)
-
Using PyAV to encode mono audio to file, params match docs, but still causes Errno 22
20 février 2023, par andrew8088While trying to use PyAV to encode live mono audio from a microphone to a compressed audio stream (using mp2 or flac as encoder), the program kept raising an exception
ValueError: [Errno 22] Invalid argument
.

To remove the live microphone source as a cause of the problem, and to make the problematic code easier for others to run/test, I have removed the mic source and now just generate a pure tone as a sequence of input buffers.


All attempts to figure out the missing or mismatched or incorrect argument have just resulted in seeing documentation and examples that are the same as my code.


I would like to know from someone who has used PyAV successfully for mono audio what the correct method and parameters are for encoding mono frames into the mono stream.


The package used is av 10.0.0 installed with

pip3 install av --no-binary av

so it uses my package-manager provided ffmpeg library, which is version 4.2.7.

The problematic python code is :


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Recreating an error 22 when encoding sound with PyAV.

Created on Sun Feb 19 08:10:29 2023
@author: andrewm
"""
import typing
import sys
import math
import fractions

import av
from av import AudioFrame

""" Ensure some PyAudio constants are still defined without changing 
 the PyAudio recording callback function and without depending 
 on PyAudio simply for reproducing the PyAV bug [Errno 22] thrown in 
 File "av/filter/context.pyx", line 89, in av.filter.context.FilterContext.push
"""
class PA_Stub():
 paContinue = True
 paComplete= False

pyaudio = PA_Stub()


"""Generate pure tone at given frequency with amplitude 0...1.0 at 
 sampling frewuency fs and beginning at phase offset 'phase'.
 Returns the new phase after the sinusoid has cycled over the 
 sampling window length.
"""
def generate_tone(
 freq:int, phase:float, amp:float, fs, samp_fmt, buffer:bytearray
) -> float:
 assert samp_fmt == "s16", "Only s16 supported atm"
 samp_size_bytes = 2
 n_samples = int(len(buffer)/samp_size_bytes)
 window = [int(0) for i in range(n_samples)]
 theta = phase
 phase_inc = 2*math.pi * freq / fs
 for i in range(n_samples):
 v = amp * math.sin(theta)
 theta += phase_inc
 s = int((2**15-1)*v)
 window[i] = s
 for sample_i in range(len(window)):
 byte_i = sample_i * samp_size_bytes
 enc = window[sample_i].to_bytes(
 2, byteorder=sys.byteorder, signed=True
 )
 buffer[byte_i] = enc[0]
 buffer[byte_i+1] = enc[1]
 return theta


channels = 1
fs = 44100 # Record at 44100 samples per second
fft_size_samps = 256
chunk_samps = fft_size_samps * 10 # Record in chunks that are multiples of fft windows.

# print(f"fft_size_samps={fft_size_samps}\nchunk_samps={chunk_samps}")

seconds = 3.0
out_filename = "testoutput.wav"

# Store data in chunks for 3 seconds
sample_limit = int(fs * seconds)
sample_len = 0
frames = [] # Initialize array to store frames

ffmpeg_codec_name = 'mp2' # flac, mp3, or libvorbis make same error.

sample_size_bytes = 2
buffer = bytearray(int(chunk_samps*sample_size_bytes))
chunkperiod = chunk_samps / fs
total_chunks = int(math.ceil(seconds / chunkperiod))
phase = 0.0

### uncomment if you want to see the synthetic data being used as a mic input.
# with open("test.raw","wb") as raw_out:
# for ci in range(total_chunks):
# phase = generate_tone(2600, phase, 0.8, fs, "s16", buffer)
# raw_out.write(buffer)
# print("finished gen test")
# sys.exit(0)
# #---- 

# Using mp2 or mkv as the container format gets the same error.
with av.open(out_filename+'.mp2', "w", format="mp2") as output_con:
 output_con.metadata["title"] = "My title"
 output_con.metadata["key"] = "value"
 channel_layout = "mono"
 sample_fmt = "s16p"

 ostream = output_con.add_stream(ffmpeg_codec_name, fs, layout=channel_layout)
 assert ostream is not None, "No stream!"
 cctx = ostream.codec_context
 cctx.sample_rate = fs
 cctx.time_base = fractions.Fraction(numerator=1,denominator=fs)
 cctx.format = sample_fmt
 cctx.channels = channels
 cctx.layout = channel_layout
 print(cctx, f"layout#{cctx.channel_layout}")
 
 # Define PyAudio-style callback for recording plus PyAV transcoding.
 def rec_callback(in_data, frame_count, time_info, status):
 global sample_len
 global ostream
 frames.append(in_data)
 nsamples = int(len(in_data) / (channels*sample_size_bytes))
 
 frame = AudioFrame(format=sample_fmt, layout=channel_layout, samples=nsamples)
 frame.sample_rate = fs
 frame.time_base = fractions.Fraction(numerator=1,denominator=fs)
 frame.pts = sample_len
 frame.planes[0].update(in_data)
 print(frame, len(in_data))
 
 for out_packet in ostream.encode(frame):
 output_con.mux(out_packet)
 for out_packet in ostream.encode(None):
 output_con.mux(out_packet)
 
 sample_len += nsamples
 retflag = pyaudio.paContinue if sample_lencode>


If you uncomment the RAW output part you will find the generated data can be imported as PCM s16 Mono 44100Hz into Audacity and plays the expected tone, so the generated audio data does not seem to be the problem.


The normal program console output up until the exception is :


mp2 at 0x7f8e38202cf0> layout#4
Beginning
 5120
. 5120



The stack trace is :


Traceback (most recent call last):

 File "Dev/multichan_recording/av_encode.py", line 147, in <module>
 ret_data, ret_flag = rec_callback(buffer, ci, {}, 1)

 File "Dev/multichan_recording/av_encode.py", line 121, in rec_callback
 for out_packet in ostream.encode(frame):

 File "av/stream.pyx", line 153, in av.stream.Stream.encode

 File "av/codec/context.pyx", line 484, in av.codec.context.CodecContext.encode

 File "av/audio/codeccontext.pyx", line 42, in av.audio.codeccontext.AudioCodecContext._prepare_frames_for_encode

 File "av/audio/resampler.pyx", line 101, in av.audio.resampler.AudioResampler.resample

 File "av/filter/graph.pyx", line 211, in av.filter.graph.Graph.push

 File "av/filter/context.pyx", line 89, in av.filter.context.FilterContext.push

 File "av/error.pyx", line 336, in av.error.err_check

ValueError: [Errno 22] Invalid argument

</module>


edit : It's interesting that the error happens on the 2nd AudioFrame, as apparently the first one was encoded okay, because they are given the same attribute values aside from the Presentation Time Stamp (pts), but leaving this out and letting PyAV/ffmpeg generate the PTS by itself does not fix the error, so an incorrect PTS does not seem the cause.


After a brief glance in
av/filter/context.pyx
the exception must come from a bad return value fromres = lib.av_buffersrc_write_frame(self.ptr, frame.ptr)

Trying to dig intoav_buffersrc_write_frame
from the ffmpeg source it is not clear what could be causing this error. The only obvious one is a mismatch between channel layouts, but my code is setting the layout the same in the Stream and the Frame. That problem had been found by an old question pyav - cannot save stream as mono and their answer (that one parameter required is undocumented) is the only reason the code now has the layout='mono' argument when making the stream.

The program output shows layout #4 is being used, and from https://github.com/FFmpeg/FFmpeg/blob/release/4.2/libavutil/channel_layout.h you can see this is the value for symbol AV_CH_FRONT_CENTER which is the only channel in the MONO layout.


The mismatch is surely some other object property or an undocumented parameter requirement.


How do you encode mono audio to a compressed stream with PyAV ?


-
What permission ffmpeg-static need in AWS Lambda ?
17 février 2023, par JánosI have this code. It download a image, made a video from it and upload it to S3. It runs on Lambda. Added packages, intalled, zipped, uploaded.


npm install --production
zip -r my-lambda-function.zip ./



But get an
error code 126


2023-02-17T09:27:55.236Z 5c845bb6-02c1-41b0-8759-4459591b57b0 INFO Error: ffmpeg exited with code 126
 at ChildProcess.<anonymous> (/var/task/node_modules/fluent-ffmpeg/lib/processor.js:182:22)
 at ChildProcess.emit (node:events:513:28)
 at ChildProcess._handle.onexit (node:internal/child_process:291:12)
2023-02-17T09:27:55.236Z 5c845bb6-02c1-41b0-8759-4459591b57b0 INFO Error: ffmpeg exited with code 126 at ChildProcess.<anonymous> (/var/task/node_modules/fluent-ffmpeg/lib/processor.js:182:22) at ChildProcess.emit (node:events:513:28) at ChildProcess._handle.onexit (node:internal/child_process:291:12)
</anonymous></anonymous>


Do I need to set a specific premission for ffmpeg ?


import { PutObjectCommand, S3Client } from '@aws-sdk/client-s3'
import { fromNodeProviderChain } from '@aws-sdk/credential-providers'
import axios from 'axios'
import pathToFfmpeg from 'ffmpeg-static'
import ffmpeg from 'fluent-ffmpeg'
import fs from 'fs'
ffmpeg.setFfmpegPath(pathToFfmpeg)
const credentials = fromNodeProviderChain({
 clientConfig: {
 region: 'eu-central-1',
 },
})
const client = new S3Client({ credentials })

export const handler = async (event, context) => {
 try {
 let body
 let statusCode = 200
 const query = event?.queryStringParameters
 if (!query?.imgId && !query?.video1Id && !query?.video2Id) {
 return
 }

 const imgId = query?.imgId
 const video1Id = query?.video1Id
 const video2Id = query?.video2Id
 console.log(
 `Parameters received, imgId: ${imgId}, video1Id: ${video1Id}, video2Id: ${video2Id}`
 )
 const imgURL = getFileURL(imgId)
 const video1URL = getFileURL(`${video1Id}.mp4`)
 const video2URL = getFileURL(`${video2Id}.mp4`)
 const imagePath = `/tmp/${imgId}`
 const video1Path = `/tmp/${video1Id}.mp4`
 const video2Path = `/tmp/${video2Id}.mp4`
 const outputPath = `/tmp/${imgId}.mp4`
 await Promise.all([
 downloadFile(imgURL, imagePath),
 downloadFile(video1URL, video1Path),
 downloadFile(video2URL, video2Path),
 ])
 await new Promise((resolve, reject) => {
 console.log('Input files downloaded')
 ffmpeg()
 .input(imagePath)
 .inputFormat('image2')
 .inputFPS(30)
 .loop(1)
 .size('1080x1080')
 .videoCodec('libx264')
 .format('mp4')
 .outputOptions([
 '-tune animation',
 '-pix_fmt yuv420p',
 '-profile:v baseline',
 '-level 3.0',
 '-preset medium',
 '-crf 23',
 '-movflags +faststart',
 '-y',
 ])
 .output(outputPath)
 .on('end', () => {
 console.log('Output file generated')
 resolve()
 })
 .on('error', (e) => {
 console.log(e)
 reject()
 })
 .run()
 
 })
 await uploadFile(outputPath, imgId + '.mp4')
 .then((url) => {
 body = JSON.stringify({
 url,
 })
 })
 .catch((error) => {
 console.error(error)
 statusCode = 400
 body = error?.message ?? error
 })
 console.log(`File uploaded to S3`)
 const headers = {
 'Content-Type': 'application/json',
 'Access-Control-Allow-Headers': 'Content-Type',
 'Access-Control-Allow-Origin': 'https://tikex.com, https://borespiac.hu',
 'Access-Control-Allow-Methods': 'GET',
 }
 return {
 statusCode,
 body,
 headers,
 }
 } catch (error) {
 console.error(error)
 return {
 statusCode: 500,
 body: JSON.stringify('Error fetching data'),
 }
 }
}

const downloadFile = async (url, path) => {
 try {
 console.log(`Download will start: ${url}`)
 const response = await axios(url, {
 responseType: 'stream',
 })
 if (response.status !== 200) {
 throw new Error(
 `Failed to download file, status code: ${response.status}`
 )
 }
 response.data
 .pipe(fs.createWriteStream(path))
 .on('finish', () => console.log(`File downloaded to ${path}`))
 .on('error', (e) => {
 throw new Error(`Failed to save file: ${e}`)
 })
 } catch (e) {
 console.error(`Error downloading file: ${e}`)
 }
}
const uploadFile = async (path, id) => {
 const buffer = fs.readFileSync(path)
 const params = {
 Bucket: 't44-post-cover',
 ACL: 'public-read',
 Key: id,
 ContentType: 'video/mp4',
 Body: buffer,
 }
 await client.send(new PutObjectCommand(params))
 return getFileURL(id)
}
const getFileURL = (id) => {
 const bucket = 't44-post-cover'
 const url = `https://${bucket}.s3.eu-central-1.amazonaws.com/${id}`
 return url
}



Added
AWSLambdaBasicExecutionRole-16e770c8-05fa-4c42-9819-12c468cb5b49
permission, with policy :

{
 "Version": "2012-10-17",
 "Statement": [
 {
 "Effect": "Allow",
 "Action": "logs:CreateLogGroup",
 "Resource": "arn:aws:logs:eu-central-1:634617701827:*"
 },
 {
 "Effect": "Allow",
 "Action": [
 "logs:CreateLogStream",
 "logs:PutLogEvents"
 ],
 "Resource": [
 "arn:aws:logs:eu-central-1:634617701827:log-group:/aws/lambda/promo-video-composer-2:*"
 ]
 },
 {
 "Effect": "Allow",
 "Action": [
 "s3:GetObject",
 "s3:PutObject",
 "s3:ListBucket"
 ],
 "Resource": [
 "arn:aws:s3:::example-bucket",
 "arn:aws:s3:::example-bucket/*"
 ]
 },
 {
 "Effect": "Allow",
 "Action": [
 "logs:CreateLogGroup",
 "logs:CreateLogStream",
 "logs:PutLogEvents"
 ],
 "Resource": [
 "arn:aws:logs:*:*:*"
 ]
 },
 {
 "Effect": "Allow",
 "Action": [
 "ec2:DescribeNetworkInterfaces"
 ],
 "Resource": [
 "*"
 ]
 },
 {
 "Effect": "Allow",
 "Action": [
 "sns:*"
 ],
 "Resource": [
 "*"
 ]
 },
 {
 "Effect": "Allow",
 "Action": [
 "cloudwatch:*"
 ],
 "Resource": [
 "*"
 ]
 },
 {
 "Effect": "Allow",
 "Action": [
 "kms:Decrypt"
 ],
 "Resource": [
 "*"
 ]
 }
 ]
}



What do I miss ?


janoskukoda@Janoss-MacBook-Pro promo-video-composer-2 % ls -l $(which ffmpeg)
lrwxr-xr-x 1 janoskukoda admin 35 Feb 10 12:50 /opt/homebrew/bin/ffmpeg -> ../Cellar/ffmpeg/5.1.2_4/bin/ffmpeg



-
What is Multi-Touch Attribution ? (And How To Get Started)
2 février 2023, par Erin — Analytics Tips