Recherche avancée

Médias (16)

Mot : - Tags -/mp3

Sur d’autres sites (333)

  • Generating DASH manifest with ffmpeg works in Docker exec shell but not in os.exec golang

    22 février 2023, par Inquisitor

    I am trying to generate a DASH manifest with ffmpeg using this command

    


    /usr/bin/ffmpeg -f webm_dash_manifest -i ./480.webm -f webm_dash_manifest -i ./audio.webm -c copy -map 0:0 -map 1:0 -y -f webm_dash_manifest -adaptation_sets "id=0,streams=0 id=1,streams=1" ./manifest.mpd -loglevel repeat+level+verbose


    


    I run this in go, in a docker container as shown :

    


    func runFFmpeg(arguments []string) {
    arguments = append(arguments, "-loglevel", "repeat+level+verbose")
    cmd := exec.Command("ffmpeg", arguments...)

    fmt.Printf("cmd: %v\n", cmd)

    var out bytes.Buffer
    var stderr bytes.Buffer
    cmd.Stdout = &out
    cmd.Stderr = &stderr
    err := cmd.Run()

    if err != nil {
        log.Println(err)
        log.Println(stderr.String())
    }
}
runFFmpeg([]string{"-f", "webm_dash_manifest", "-i", "./480.webm", "-f", "webm_dash_manifest", "-i", "./audio.webm", "-c", "copy", "-map", "0:0", "-map", "1:0", "-y", "-f", "webm_dash_manifest", "-adaptation_sets", "\"id=0,streams=0 id=1,streams=1\"", "./manifest.mpd"})


    


    But I get this output :

    


     cmd: /usr/bin/ffmpeg -f webm_dash_manifest -i ./480.webm -f webm_dash_manifest -i ./audio.webm -c copy -map 0:0 -map 1:0 -y -copy_unknown -f webm_dash_manifest -adaptation_sets "id=0,streams=0 id=1,streams=1" ./manifest.mpd -loglevel repeat+level+verbose
 2023/02/22 04:45:17 exit status 1
 2023/02/22 04:45:17 [info] ffmpeg version 5.1.2 Copyright (c) 2000-2022 the FFmpeg developers
 [info]   built with gcc 12.2.1 (Alpine 12.2.1_git20220924-r3) 20220924
 [info]   configuration: --prefix=/usr --enable-avfilter --enable-libfontconfig --enable-libfreetype --enable-libfribidi --enable-gnutls --enable-gpl --enable-libass --enable-libmp3lame --enable-libpulse --enable-libvorbis --enable-libvpx --enable-libxvid --enable-libx264 --enable-libx265 --enable-libtheora --enable-libv4l2 --enable-libdav1d --enable-lto --enable-postproc --enable-pic --enable-pthreads --enable-shared --enable-libxcb --enable-librist --enable-libsrt --enable-libssh --enable-libvidstab --disable-stripping --disable-static --disable-librtmp --disable-lzma --enable-libaom --enable-libopus --enable-libsoxr --enable-libwebp --enable-vaapi --enable-vdpau --enable-vulkan --enable-libdrm --enable-libzmq --optflags=-O2 --disable-debug --enable-libsvtav1
 [info]   libavutil      57. 28.100 / 57. 28.100
 [info]   libavcodec     59. 37.100 / 59. 37.100
 [info]   libavformat    59. 27.100 / 59. 27.100
 [info]   libavdevice    59.  7.100 / 59.  7.100
 [info]   libavfilter     8. 44.100 /  8. 44.100
 [info]   libswscale      6.  7.100 /  6.  7.100
 [info]   libswresample   4.  7.100 /  4.  7.100
 [info]   libpostproc    56.  6.100 / 56.  6.100
 [webm_dash_manifest @ 0x7fcec2836100] [warning] Could not find codec parameters for stream 0 (Video: vp9, 1 reference frame, none(tv, progressive, left), 640x480): unspecified pixel format
 Consider increasing the value for the 'analyzeduration' (0) and 'probesize' (5000000) options
 [info] Input #0, webm_dash_manifest, from './480.webm':
 [info]   Metadata:
 [info]     title           : Big Buck Bunny, Sunflower version
 [info]     GENRE           : Animation
 [info]     MAJOR_BRAND     : isom
 [info]     MINOR_VERSION   : 1
 [info]     COMPATIBLE_BRANDS: isomavc1
 [info]     COMPOSER        : Sacha Goedegebure
 [info]     ARTIST          : Blender Foundation 2008, Janus Bager Kristensen 2013
 [info]     COMMENT         : Creative Commons Attribution 3.0 - http://bbb3d.renderfarming.net
 [info]     ENCODER         : Lavf59.27.100
 [info]   Duration: 00:10:34.60, bitrate: 352 kb/s
 [info]   Stream #0:0: Video: vp9, 1 reference frame, none(tv, progressive, left), 640x480, SAR 853:640 DAR 853:480, 30 fps, 30 tbr, 1k tbn (default)
 [info]     Metadata:
 [info]       HANDLER_NAME    : GPAC ISO Video Handler
 [info]       VENDOR_ID       : [0][0][0][0]
 [info]       ENCODER         : Lavc59.37.100 libvpx-vp9
 [info]       DURATION        : 00:10:34.600000000
 [info]       webm_dash_manifest_duration: 634600
 [info]       webm_dash_manifest_initialization_range: 889
 [info]       webm_dash_manifest_file_name: 480.webm
 [info]       webm_dash_manifest_track_number: 1
 [info]       webm_dash_manifest_cues_start: 27924928
 [info]       webm_dash_manifest_cues_end: 27927508
 [info]       webm_dash_manifest_bandwidth: 738287
 [info]       webm_dash_manifest_cluster_keyframe: 1
 [info]       webm_dash_manifest_cue_timestamps: 67,5067,10067,15067,20067,25067,30067,35067,40067,45067,50067,55067,60067,65067,70067,75067,80067,85067,90067,95067,100067,105067,110067,115067,120067,125067,130067,135067,140067,145067,150067,155067,160067,165067,170067,175067,180067,185067,190067,195067
 [info] Input #1, webm_dash_manifest, from './audio.webm':
 [info]   Metadata:
 [info]     title           : Big Buck Bunny, Sunflower version
 [info]     GENRE           : Animation
 [info]     MAJOR_BRAND     : isom
 [info]     MINOR_VERSION   : 1
 [info]     COMPATIBLE_BRANDS: isomavc1
 [info]     COMPOSER        : Sacha Goedegebure
 [info]     ARTIST          : Blender Foundation 2008, Janus Bager Kristensen 2013
 [info]     COMMENT         : Creative Commons Attribution 3.0 - http://bbb3d.renderfarming.net
 [info]     ENCODER         : Lavf59.27.100
 [info]   Duration: 00:05:35.91, bitrate: 120 kb/s
 [info]   Stream #1:0: Audio: vorbis, 48000 Hz, 5.1, fltp (default)
 [info]     Metadata:
 [info]       HANDLER_NAME    : GPAC ISO Audio Handler
 [info]       VENDOR_ID       : [0][0][0][0]
 [info]       ENCODER         : Lavc59.37.100 libvorbis
 [info]       DURATION        : 00:05:35.907000000
 [info]       webm_dash_manifest_duration: 335907
 [info]       webm_dash_manifest_initialization_range: 7411
 [info]       webm_dash_manifest_file_name: audio.webm
 [info]       webm_dash_manifest_track_number: 1
 [info]       webm_dash_manifest_cues_start: 5047497
 [info]       webm_dash_manifest_cues_end: 5048846
 [info]       webm_dash_manifest_bandwidth: 126994
 [info]       webm_dash_manifest_cluster_keyframe: 1
 [info]       webm_dash_manifest_cue_timestamps: 0,4986,9980,14962,19959,24956,29946,34930,39916,44911,49908,54892,59874,64868,69858,74858,79855,84847,89834,94834,99826,104826,109826,114818,119812,124799,129780,134770,139756,144743,149727,154719,159714,164706,169698,174687,179668,184667,189658,194650,19
 HERE'S THE ERROR --> [error] Could not write header for output file #0 (incorrect codec parameters ?): Operation not permitted
 [error] Error initializing output stream 0:1 -- 
 [info] Stream mapping:
 [info]   Stream #0:0 -> #0:0 (copy)
 [info]   Stream #1:0 -> #0:1 (copy)
 [error] 
 [AVIOContext @ 0x7fcebe23a840] [verbose] Statistics: 0 bytes written, 0 seeks, 0 writeouts
 [AVIOContext @ 0x7fcebe23a980] [verbose] Statistics: 5940786 bytes read, 133 seeks
 [AVIOContext @ 0x7fcebe23acc0] [verbose] Statistics: 2260628 bytes read, 72 seeks


    


    It works perfectly however if I run it within docker exec (exec into the container and run the command in bash). Also, note in the last output that the command is well formed when I print it out from go. File permissions are also not the problem since the command to create the video variants works with os.exec i.e

    


    runFFmpeg([]string{"-i", originalFilePath, "-c:v", "libvpx-vp9", "-keyint_min", "150", "-g", "150", "-tile-columns", "4", "-frame-parallel", "1", "-f", "webm", "-dash", "1", "-an", "-vf", fmt.Sprintf("scale=%s:%s", width, height), "-b:v", bitRate, "-dash", "1", "-y", destinationFilePath})


    


  • Error : ffmpeg : Failed to download resource "sqlite"

    22 février 2023, par nour

    i am trying to download ffmpeg but I am getting this error ! could anyone help ? I am using paperclip gem to add images and videos. I am getting this error on heroku when i try to add a new video Av::UnableToDetect (Unable to detect any supported library so that's why im trying to download ffmpeg. could someone help please ! thanks in advance

    


    brew install ffmpeg

    


    curl: (60) SSL certificate problem: certificate has expired
More details here: https://curl.haxx.se/docs/sslcerts.html

curl performs SSL certificate verification by default, using a "bundle"
 of Certificate Authority (CA) public keys (CA certs). If the default
 bundle file isn't adequate, you can specify an alternate file
 using the --cacert option.
If this HTTPS server uses a certificate signed by a CA represented in
 the bundle, the certificate verification probably failed due to a
 problem with the certificate (it might be expired, or the name might
 not match the domain name in the URL).
If you'd like to turn off curl's verification of the certificate, use
 the -k (or --insecure) option.
HTTPS-proxy has similar options --proxy-cacert and --proxy-insecure.
Error: ffmpeg: Failed to download resource "sqlite"
Download failed: https://sqlite.org/2022/sqlite-autoconf-3400100.tar.gz


    


    when i add a new video to my website on heroku I got this error

    


    2023-02-22T06:23:03.207072+00:00 app[web.1]: User Load (0.8ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
2023-02-22T06:23:03.208471+00:00 app[web.1]: Steptation Load (0.7ms)  SELECT  "steptations".* FROM "steptations" WHERE "steptations"."id" = $1 LIMIT 1  [["id", 1802]]
2023-02-22T06:23:03.210118+00:00 app[web.1]: [paperclip] Trying to link /tmp/RackMultipart20230222-2-1i28xon.mp4 to /tmp/847606d3771b12aa2d91db7647fe3a4920230222-2-165fycl.mp4
2023-02-22T06:23:03.210923+00:00 app[web.1]: [paperclip] Trying to link /tmp/847606d3771b12aa2d91db7647fe3a4920230222-2-165fycl.mp4 to /tmp/847606d3771b12aa2d91db7647fe3a4920230222-2-p6icfm.mp4
2023-02-22T06:23:03.211217+00:00 app[web.1]: Command :: file -b --mime '/tmp/847606d3771b12aa2d91db7647fe3a4920230222-2-p6icfm.mp4'
2023-02-22T06:23:03.218799+00:00 app[web.1]: [AV] Running command: if command -v avprobe 2>/dev/null; then echo "true"; else echo "false"; fi
2023-02-22T06:23:03.221000+00:00 app[web.1]: [AV] Running command: if command -v ffmpeg 2>/dev/null; then echo "true"; else echo "false"; fi
2023-02-22T06:23:03.222208+00:00 heroku[router]: at=info method=POST path= "/step_images?id=1802" host=www.mobileimplantlab.ca request_id=39f2b001-ab36-4a59-ae94-1f300d386a40 fwd="207.216.102.221" dyno=web.1 connect=0ms service=900ms status=500 bytes=234 protocol=https
2023-02-22T06:23:03.222987+00:00 app[web.1]: Completed 500 Internal Server Error in 18ms (ActiveRecord: 1.6ms)
2023-02-22T06:23:03.223510+00:00 app[web.1]: 
2023-02-22T06:23:03.223511+00:00 app[web.1]: Av::UnableToDetect (Unable to detect any supported library):
2023-02-22T06:23:03.223511+00:00 app[web.1]: app/controllers/step_images_controller.rb:15:in `create'
2023-02-22T06:23:03.223512+00:00 app[web.1]: 
2023-02-22T06:23:03.223512+00:00 app[web.1]: 
2023-02-22T06:23:14.356278+00:00 app[web.1]: Started POST "/step_images?id=1802" for 207.216.102.221 at 2023-02-22 06:23:14 +0000
2023-02-22T06:23:14.357993+00:00 app[web.1]: Processing by StepImagesController#create as HTML
2023-02-22T06:23:14.358067+00:00 app[web.1]: Parameters: {"utf8"=>"✓", "authenticity_token"=>"PgRtPGgyOSPP8lQlbf9fAgOSZre/XlYcKBKJhe81oOz9Ge81GZZzEfc4Xcnz0zzZ35S7PpsfKOse3Q73mxhjEA==", "step_image"=>{"product_id"=>"4", "text"=>"", "text2"=>"", "text3"=>"", "text4"=>"", "text5"=>"", "video"=>#, @original_filename="IMG_2826.mp4", @content_type="video/mp4", @headers="Content-Disposition: form-data; name=\"step_image[video]\"; filename=\"IMG_2826.mp4\"\r\nContent-Type: video/mp4\r\n">, "text6"=>"test", "user_id"=>"73", "case_id"=>"311", "step_id"=>"3"}, "commit"=>"Submit", "id"=>"1802"}
2023-02-22T06:23:14.359735+00:00 app[web.1]: User Load (0.8ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
2023-02-22T06:23:14.360954+00:00 app[web.1]: Steptation Load (0.7ms)  SELECT  "steptations".* FROM "steptations" WHERE "steptations"."id" = $1 LIMIT 1  [["id", 1802]]
2023-02-22T06:23:14.362132+00:00 app[web.1]: [paperclip] Trying to link /tmp/RackMultipart20230222-2-1stq4d4.mp4 to /tmp/847606d3771b12aa2d91db7647fe3a4920230222-2-1jq0dqp.mp4
2023-02-22T06:23:14.362719+00:00 app[web.1]: [paperclip] Trying to link /tmp/847606d3771b12aa2d91db7647fe3a4920230222-2-1jq0dqp.mp4 to /tmp/847606d3771b12aa2d91db7647fe3a4920230222-2-9hfi7z.mp4
2023-02-22T06:23:14.362932+00:00 app[web.1]: Command :: file -b --mime '/tmp/847606d3771b12aa2d91db7647fe3a4920230222-2-9hfi7z.mp4'
2023-02-22T06:23:14.370045+00:00 app[web.1]: [AV] Running command: if command -v avprobe 2>/dev/null; then echo "true"; else echo "false"; fi
2023-02-22T06:23:14.372073+00:00 app[web.1]: [AV] Running command: if command -v ffmpeg 2>/dev/null; then echo "true"; else echo "false"; fi
2023-02-22T06:23:14.374070+00:00 app[web.1]: Completed 500 Internal Server Error in 16ms (ActiveRecord: 1.5ms)
2023-02-22T06:23:14.374254+00:00 heroku[router]: at=info method=POST path= "/step_images?id=1802" host=www.mobileimplantlab.ca request_id=4a0702a2-8d14-454a-9f1f-edf154e140fc fwd="207.216.102.221" dyno=web.1 connect=0ms service=267ms status=500 bytes=234 protocol=https
2023-02-22T06:23:14.374720+00:00 app[web.1]: 
2023-02-22T06:23:14.374721+00:00 app[web.1]: Av::UnableToDetect (Unable to detect any supported library):


    


    in my gem file

    


    source 'https://rubygems.org'


# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.11.1'
# Use postgresql as the database for Active Record
gem 'pg', '~> 0.20.0'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.1.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
gem 'pry', '~> 0.13.1'
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc

# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Unicorn as the app server
# gem 'unicorn'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development


group :development do
  # Access an IRB console on exception pages or by using <%= console %> in views
  gem 'web-console', '~> 2.0'

  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
end

gem 'devise'
group :development, :test do
  gem "interactive_editor"
  gem "hirb"
  gem "awesome_print"
  gem 'byebug'
end
group :production do
  gem 'rails_12factor'
  gem 'puma'
end
gem 'mail_form'
gem 'font-awesome-sass', '~> 5.12.0'

gem 'bootsnap', '>= 1.1.0', require: false
gem 'bootstrap-sass', '~>3.2.0'

gem 'paperclip'

gem 'aws-sdk-s3'
gem 'aws-sdk', '< 2.0'

gem 'thor', '0.19.1'
gem 'omniauth-google-oauth2'
gem "recaptcha", require: "recaptcha/rails"
gem 'friendly_id', '~> 5.4.0'

gem 'activeadmin'

gem 'cocoon'
gem 'bigdecimal', '1.3.5'
gem 'bundler', '1.17.3'
gem 'paperclip-av-transcoder'
gem "paperclip-ffmpeg", "~> 1.2.0"
gem "will_paginate", "~> 3.0.4" 
gem 'rails-erd'
gem 'rails_autolink'

gem 'rails-erd', group: :development


    


    in the model

    


      has_attached_file :video, :styles => {
     :medium => { :geometry => "500x500", :format => 'jpg' },
     :thumb => { :geometry => "100x100", :format => 'jpg' }
  }, :processors => [:transcoder]

  validates_attachment_content_type :video,
    :content_type => [
      "video/mp4", 
      "video/quicktime",
      "video/3gpp",
      "video/x-ms-wmv",
      "video/mov",
      "video/flv",
      
      ]


    


  • Using PyAV to encode mono audio to file, params match docs, but still causes Errno 22

    20 février 2023, par andrew8088

    While 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):&#xA;&#xA;  File "Dev/multichan_recording/av_encode.py", line 147, in <module>&#xA;    ret_data, ret_flag = rec_callback(buffer, ci, {}, 1)&#xA;&#xA;  File "Dev/multichan_recording/av_encode.py", line 121, in rec_callback&#xA;    for out_packet in ostream.encode(frame):&#xA;&#xA;  File "av/stream.pyx", line 153, in av.stream.Stream.encode&#xA;&#xA;  File "av/codec/context.pyx", line 484, in av.codec.context.CodecContext.encode&#xA;&#xA;  File "av/audio/codeccontext.pyx", line 42, in av.audio.codeccontext.AudioCodecContext._prepare_frames_for_encode&#xA;&#xA;  File "av/audio/resampler.pyx", line 101, in av.audio.resampler.AudioResampler.resample&#xA;&#xA;  File "av/filter/graph.pyx", line 211, in av.filter.graph.Graph.push&#xA;&#xA;  File "av/filter/context.pyx", line 89, in av.filter.context.FilterContext.push&#xA;&#xA;  File "av/error.pyx", line 336, in av.error.err_check&#xA;&#xA;ValueError: [Errno 22] Invalid argument&#xA;&#xA;</module>

    &#xA;

    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.

    &#xA;

    After a brief glance in av/filter/context.pyx the exception must come from a bad return value from res = lib.av_buffersrc_write_frame(self.ptr, frame.ptr)
    &#xA;Trying to dig into av_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.

    &#xA;

    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.

    &#xA;

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

    &#xA;

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

    &#xA;