Recherche avancée

Médias (3)

Mot : - Tags -/Valkaama

Autres articles (9)

  • Organiser par catégorie

    17 mai 2013, par

    Dans MédiaSPIP, une rubrique a 2 noms : catégorie et rubrique.
    Les différents documents stockés dans MédiaSPIP peuvent être rangés dans différentes catégories. On peut créer une catégorie en cliquant sur "publier une catégorie" dans le menu publier en haut à droite ( après authentification ). Une catégorie peut être rangée dans une autre catégorie aussi ce qui fait qu’on peut construire une arborescence de catégories.
    Lors de la publication prochaine d’un document, la nouvelle catégorie créée sera proposée (...)

  • Les thèmes de MediaSpip

    4 juin 2013

    3 thèmes sont proposés à l’origine par MédiaSPIP. L’utilisateur MédiaSPIP peut rajouter des thèmes selon ses besoins.
    Thèmes MediaSPIP
    3 thèmes ont été développés au départ pour MediaSPIP : * SPIPeo : thème par défaut de MédiaSPIP. Il met en avant la présentation du site et les documents média les plus récents ( le type de tri peut être modifié - titre, popularité, date) . * Arscenic : il s’agit du thème utilisé sur le site officiel du projet, constitué notamment d’un bandeau rouge en début de page. La structure (...)

  • Déploiements possibles

    31 janvier 2010, par

    Deux types de déploiements sont envisageable dépendant de deux aspects : La méthode d’installation envisagée (en standalone ou en ferme) ; Le nombre d’encodages journaliers et la fréquentation envisagés ;
    L’encodage de vidéos est un processus lourd consommant énormément de ressources système (CPU et RAM), il est nécessaire de prendre tout cela en considération. Ce système n’est donc possible que sur un ou plusieurs serveurs dédiés.
    Version mono serveur
    La version mono serveur consiste à n’utiliser qu’une (...)

Sur d’autres sites (2816)

  • How to install ffmpeg on a Windows Dockerhub image ?

    18 janvier, par Youssef Kharoufi

    I have a program that executes a ffmpeg command to a video input, copies this video and pastes is in an output directory.

    


    Here is my code in case you would want to duplicate it :

    


        using Renderer.Models;&#xA;using System;&#xA;using System.IO;&#xA;using System.Text.Json;&#xA;using System.Threading.Tasks;&#xA;&#xA;public class Program&#xA;{&#xA;    public static async Task Main(string[] args)&#xA;    {&#xA;        var result = new DockerTaskResult();&#xA;        try&#xA;        {&#xA;            // Path to the JSON input file&#xA;            string jsonInputPath = @"C:\Users\ykharoufi\source\repos\Renderer\Renderer\Json\task.json";&#xA;&#xA;            // Check if the JSON file exists&#xA;            if (!File.Exists(jsonInputPath))&#xA;            {&#xA;                throw new FileNotFoundException($"JSON input file not found at path: {jsonInputPath}");&#xA;            }&#xA;&#xA;            // Read the JSON content&#xA;            string jsonContent = File.ReadAllText(jsonInputPath);&#xA;&#xA;            try&#xA;            {&#xA;                // Deserialize the JSON into a DockerTask object&#xA;                DockerTask task = JsonSerializer.Deserialize<dockertask>(jsonContent);&#xA;                if (task == null)&#xA;                {&#xA;                    throw new Exception("Failed to deserialize the task from JSON.");&#xA;                }&#xA;&#xA;                // Validate the input paths&#xA;                if (string.IsNullOrEmpty(task.InputFileRepoPath) || !File.Exists(task.InputFileRepoPath))&#xA;                {&#xA;                    throw new Exception($"Input file path is invalid or does not exist: {task.InputFileRepoPath}");&#xA;                }&#xA;&#xA;                if (string.IsNullOrEmpty(task.OutputFileRepoPath) || !Directory.Exists(task.OutputFileRepoPath))&#xA;                {&#xA;                    throw new Exception($"Output directory path is invalid or does not exist: {task.OutputFileRepoPath}");&#xA;                }&#xA;&#xA;                // Initialize the Docker worker and run the task&#xA;                var worker = new DockerWorker();&#xA;                var success = await worker.RunDockerTaskAsync(task);&#xA;&#xA;                if (success.Success)&#xA;                {&#xA;                    result.Success = true;&#xA;                    result.Message = "Command executed successfully!";&#xA;&#xA;                    // Check the output directory for files&#xA;                    if (Directory.Exists(task.OutputFileRepoPath))&#xA;                    {&#xA;                        result.OutputFiles = Directory.GetFiles(task.OutputFileRepoPath);&#xA;                    }&#xA;                }&#xA;                else&#xA;                {&#xA;                    result.Success = false;&#xA;                    result.Message = "Failed to execute the command.";&#xA;                    result.ErrorDetails = success.ErrorDetails;&#xA;                }&#xA;            }&#xA;            catch (JsonException)&#xA;            {&#xA;                // Handle invalid JSON format&#xA;                result.Success = false;&#xA;                result.Message = "Invalid JSON format.";&#xA;                result.ErrorDetails = "Invalid data entry";&#xA;            }&#xA;        }&#xA;        catch (Exception ex)&#xA;        {&#xA;            result.Success = false;&#xA;            result.Message = "An error occurred during execution.";&#xA;            result.ErrorDetails = ex.Message;&#xA;        }&#xA;        finally&#xA;        {&#xA;            // Serialize the result to JSON and write to console&#xA;            string outputJson = JsonSerializer.Serialize(result, new JsonSerializerOptions { WriteIndented = true });&#xA;            Console.WriteLine(outputJson);&#xA;        }&#xA;    }&#xA;}&#xA;&#xA;    using System;&#xA;using System.Collections.Generic;&#xA;using System.IO;&#xA;using System.Text.Json;&#xA;using System.Threading.Tasks;&#xA;using Docker.DotNet;&#xA;using Docker.DotNet.Models;&#xA;using Renderer.Models;&#xA;&#xA;public class DockerWorker&#xA;{&#xA;    private readonly DockerClient _dockerClient;&#xA;&#xA;    public DockerWorker()&#xA;    {&#xA;        Console.WriteLine("Initializing Docker client...");&#xA;        _dockerClient = new DockerClientConfiguration(&#xA;            new Uri("npipe://./pipe/docker_engine")) // Windows Docker URI&#xA;            .CreateClient();&#xA;        Console.WriteLine("Docker client initialized.");&#xA;    }&#xA;&#xA;    public async Task<dockertaskresult> RunDockerTaskAsync(DockerTask task)&#xA;    {&#xA;        var result = new DockerTaskResult();&#xA;&#xA;        try&#xA;        {&#xA;            Console.WriteLine("Starting Docker task...");&#xA;            Console.WriteLine($"Image: {task.ImageNaming}");&#xA;            Console.WriteLine($"Container: {task.ContainerNaming}");&#xA;            Console.WriteLine($"Input Path: {task.InputFileRepoPath}");&#xA;            Console.WriteLine($"Output Path: {task.OutputFileRepoPath}");&#xA;            Console.WriteLine($"Command: {task.CommandDef}");&#xA;&#xA;            // Ensure the Docker image exists&#xA;            Console.WriteLine("Checking if Docker image exists...");&#xA;            var imageCheckResult = await EnsureImageExists(task.ImageNaming);&#xA;            if (!imageCheckResult.Success)&#xA;            {&#xA;                result.Success = false;&#xA;                result.Message = imageCheckResult.Message;&#xA;                result.ErrorDetails = imageCheckResult.ErrorDetails;&#xA;                return result;&#xA;            }&#xA;            Console.WriteLine("Docker image verified.");&#xA;&#xA;            // Determine platform&#xA;            var platform = await GetImagePlatform(task.ImageNaming);&#xA;            Console.WriteLine($"Detected image platform: {platform}");&#xA;&#xA;            // Translate paths&#xA;            string inputVolume, outputVolume;&#xA;            if (platform == "linux")&#xA;            {&#xA;                inputVolume = $"{task.InputFileRepoPath.Replace("C:\\", "/mnt/c/").Replace("\\", "/")}:/app/input";&#xA;                outputVolume = $"{task.OutputFileRepoPath.Replace("C:\\", "/mnt/c/").Replace("\\", "/")}:/app/output";&#xA;            }&#xA;            else if (platform == "windows")&#xA;            {&#xA;                string inputDir = Path.GetFullPath(Path.GetDirectoryName(task.InputFileRepoPath)).TrimEnd(&#x27;\\&#x27;);&#xA;                string outputDir = Path.GetFullPath(task.OutputFileRepoPath).TrimEnd(&#x27;\\&#x27;);&#xA;&#xA;                if (!Directory.Exists(inputDir))&#xA;                {&#xA;                    throw new Exception($"Input directory does not exist: {inputDir}");&#xA;                }&#xA;                if (!Directory.Exists(outputDir))&#xA;                {&#xA;                    throw new Exception($"Output directory does not exist: {outputDir}");&#xA;                }&#xA;&#xA;                inputVolume = $"{inputDir}:C:\\app\\input";&#xA;                outputVolume = $"{outputDir}:C:\\app\\output";&#xA;&#xA;                Console.WriteLine($"Input volume: {inputVolume}");&#xA;                Console.WriteLine($"Output volume: {outputVolume}");&#xA;            }&#xA;            else&#xA;            {&#xA;                throw new Exception($"Unsupported platform: {platform}");&#xA;            }&#xA;&#xA;            // Create container&#xA;            Console.WriteLine("Creating Docker container...");&#xA;            var containerResponse = await _dockerClient.Containers.CreateContainerAsync(new CreateContainerParameters&#xA;            {&#xA;                Image = task.ImageNaming,&#xA;                Name = task.ContainerNaming,&#xA;                HostConfig = new HostConfig&#xA;                {&#xA;                    Binds = new List<string> { inputVolume, outputVolume },&#xA;                    AutoRemove = true&#xA;                },&#xA;                Cmd = new[] { platform == "linux" ? "bash" : "cmd.exe", "/c", task.CommandDef }&#xA;            });&#xA;&#xA;            if (string.IsNullOrEmpty(containerResponse.ID))&#xA;            {&#xA;                throw new Exception("Failed to create Docker container.");&#xA;            }&#xA;            Console.WriteLine($"Container created with ID: {containerResponse.ID}");&#xA;&#xA;            // Start container&#xA;            Console.WriteLine("Starting container...");&#xA;            bool started = await _dockerClient.Containers.StartContainerAsync(containerResponse.ID, new ContainerStartParameters());&#xA;            if (!started)&#xA;            {&#xA;                throw new Exception($"Failed to start container: {task.ContainerNaming}");&#xA;            }&#xA;&#xA;            // Wait for container to finish&#xA;            Console.WriteLine("Waiting for container to finish...");&#xA;            var waitResponse = await _dockerClient.Containers.WaitContainerAsync(containerResponse.ID);&#xA;&#xA;            if (waitResponse.StatusCode != 0)&#xA;            {&#xA;                Console.WriteLine($"Container exited with error code: {waitResponse.StatusCode}");&#xA;                await FetchContainerLogs(containerResponse.ID);&#xA;                throw new Exception($"Container exited with non-zero status code: {waitResponse.StatusCode}");&#xA;            }&#xA;&#xA;            // Fetch logs&#xA;            Console.WriteLine("Fetching container logs...");&#xA;            await FetchContainerLogs(containerResponse.ID);&#xA;&#xA;            result.Success = true;&#xA;            result.Message = "Docker task completed successfully.";&#xA;            return result;&#xA;        }&#xA;        catch (Exception ex)&#xA;        {&#xA;            Console.WriteLine($"Error: {ex.Message}");&#xA;            result.Success = false;&#xA;            result.Message = "An error occurred during execution.";&#xA;            result.ErrorDetails = ex.Message;&#xA;            return result;&#xA;        }&#xA;    }&#xA;&#xA;    private async Task<string> GetImagePlatform(string imageName)&#xA;    {&#xA;        try&#xA;        {&#xA;            Console.WriteLine($"Inspecting Docker image: {imageName}...");&#xA;            var imageDetails = await _dockerClient.Images.InspectImageAsync(imageName);&#xA;            Console.WriteLine($"Image platform: {imageDetails.Os}");&#xA;            return imageDetails.Os.ToLower();&#xA;        }&#xA;        catch (Exception ex)&#xA;        {&#xA;            throw new Exception($"Failed to inspect image: {ex.Message}");&#xA;        }&#xA;    }&#xA;&#xA;    private async Task<dockertaskresult> EnsureImageExists(string imageName)&#xA;    {&#xA;        var result = new DockerTaskResult();&#xA;        try&#xA;        {&#xA;            Console.WriteLine($"Pulling Docker image: {imageName}...");&#xA;            await _dockerClient.Images.CreateImageAsync(&#xA;                new ImagesCreateParameters { FromImage = imageName, Tag = "latest" },&#xA;                null,&#xA;                new Progress<jsonmessage>()&#xA;            );&#xA;            result.Success = true;&#xA;            result.Message = "Docker image is available.";&#xA;        }&#xA;        catch (Exception ex)&#xA;        {&#xA;            result.Success = false;&#xA;            result.Message = $"Failed to pull Docker image: {imageName}";&#xA;            result.ErrorDetails = ex.Message;&#xA;        }&#xA;        return result;&#xA;    }&#xA;&#xA;    private async Task FetchContainerLogs(string containerId)&#xA;    {&#xA;        try&#xA;        {&#xA;            Console.WriteLine($"Fetching logs for container: {containerId}...");&#xA;            var logs = await _dockerClient.Containers.GetContainerLogsAsync(&#xA;                containerId,&#xA;                new ContainerLogsParameters { ShowStdout = true, ShowStderr = true });&#xA;&#xA;            using (var reader = new StreamReader(logs))&#xA;            {&#xA;                string logLine;&#xA;                while ((logLine = await reader.ReadLineAsync()) != null)&#xA;                {&#xA;                    Console.WriteLine(logLine);&#xA;                }&#xA;            }&#xA;        }&#xA;        catch (Exception ex)&#xA;        {&#xA;            Console.WriteLine($"Failed to fetch logs: {ex.Message}");&#xA;        }&#xA;    }&#xA;}&#xA;&#xA;    {&#xA;  "ImageNaming": "khuser/windowsimage:latest",&#xA;  "ContainerNaming": "custom-worker-container",&#xA;  "InputFileRepoPath": "C:/Users/user/source/repos/Renderer/Renderer/wwwroot/audio.mp4",&#xA;  "OutputFileRepoPath": "C:/Users/user/Desktop/output/",&#xA;  "CommandDef": "ffmpeg -i C:\\app\\input\\audio.mp4 -c copy C:\\app\\output\\copiedAudio.mp4"&#xA;</jsonmessage></dockertaskresult></string></string></dockertaskresult></dockertask>

    &#xA;

    }. My problem is what I get in the output of my program : Initializing Docker client... Docker client initialized. Starting Docker task... Image: khyoussef/windowsimage:latest Container: custom-worker-container Input Path: C:/Users/ykharoufi/source/repos/Renderer/Renderer/wwwroot/audio.mp4 Output Path: C:/Users/ykharoufi/Desktop/output/ Command: ffmpeg -i C:\app\input\audio.mp4 -c copy C:\app\output\copiedAudio.mp4 Checking if Docker image exists... Pulling Docker image: khyoussef/windowsimage:latest... Docker image verified. Inspecting Docker image: khyoussef/windowsimage:latest... Image platform: windows Detected image platform: windows Input volume: C:\Users\ykharoufi\source\repos\Renderer\Renderer\wwwroot:C:\app\input Output volume: C:\Users\ykharoufi\Desktop\output:C:\app\output Creating Docker container... Container created with ID: 1daca99b3c76bc8c99c1aed7d2c546ae75aedd9aa1feb0f5002e54769390248e Starting container... Waiting for container to finish... Container exited with error code: 1 Fetching logs for container: 1daca99b3c76bc8c99c1aed7d2c546ae75aedd9aa1feb0f5002e54769390248e... @&#x27;ffmpeg&#x27; is not recognized as an internal or external command, !operable program or batch file. Error: Container exited with non-zero status code: 1 { "Success": false, "Message": "Failed to execute the command.", "ErrorDetails": "Container exited with non-zero status code: 1", "OutputFiles": null }, This is the Dockerfile I am working with :

    &#xA;

    `# Use Windows Server Core as the base image&#xA;FROM mcr.microsoft.com/windows/server:ltsc2022&#xA;&#xA;# Set the working directory&#xA;WORKDIR /app&#xA;&#xA;# Install required tools (FFmpeg and Visual C&#x2B;&#x2B; Redistributable)&#xA;RUN powershell -Command \&#xA;    $ErrorActionPreference = &#x27;Stop&#x27;; \&#xA;    # Install Visual C&#x2B;&#x2B; Redistributable&#xA;    Invoke-WebRequest -Uri https://aka.ms/vs/16/release/vc_redist.x64.exe -OutFile vc_redist.x64.exe; \&#xA;    Start-Process -FilePath vc_redist.x64.exe -ArgumentList &#x27;/install&#x27;, &#x27;/quiet&#x27;, &#x27;/norestart&#x27; -NoNewWindow -Wait; \&#xA;    Remove-Item -Force vc_redist.x64.exe; \&#xA;    # Download FFmpeg&#xA;    Invoke-WebRequest -Uri https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-n7.1-latest-win64-gpl-7.1.zip -OutFile ffmpeg.zip; \&#xA;    # Extract FFmpeg&#xA;    Expand-Archive -Path ffmpeg.zip -DestinationPath C:\ffmpeg; \&#xA;    Remove-Item -Force ffmpeg.zip; \&#xA;    # Debug step: Verify FFmpeg extraction&#xA;    Write-Output "FFmpeg extracted to C:\\ffmpeg"; \&#xA;    dir C:\ffmpeg; \&#xA;    dir C:\ffmpeg\ffmpeg-n7.1-latest-win64-gpl-7.1\bin&#xA;&#xA;# Add FFmpeg to PATH permanently&#xA;ENV PATH="C:\\ffmpeg\\ffmpeg-n7.1-latest-win64-gpl-7.1\\bin;${PATH}"&#xA;&#xA;# Verify FFmpeg installation&#xA;RUN ["cmd", "/S", "/C", "ffmpeg -version"]&#xA;&#xA;# Copy required files to the container&#xA;COPY ./ /app/&#xA;&#xA;# Default to a PowerShell session&#xA;CMD ["C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe", "-NoExit"]&#xA;`&#xA;

    &#xA;

    . I did build it using this command : docker build -t khuser/windowsimage:latest -f Dockerfile .

    &#xA;

  • C++ ffmpeg - export to wav error : Invalid PCM packet, data has size 2 but at least a size of 4 was expected

    9 septembre 2024, par Chris P

    C++ code :

    &#xA;

    AudioSegment AudioSegment::from_file(const std::string&amp; file_path, const std::string&amp; format, const std::string&amp; codec,&#xA;    const std::map&amp; parameters, int start_second, int duration) {&#xA;&#xA;    avformat_network_init();&#xA;    av_log_set_level(AV_LOG_ERROR); // Adjust logging level as needed&#xA;&#xA;    AVFormatContext* format_ctx = nullptr;&#xA;    if (avformat_open_input(&amp;format_ctx, file_path.c_str(), nullptr, nullptr) != 0) {&#xA;        std::cerr &lt;&lt; "Error: Could not open audio file." &lt;&lt; std::endl;&#xA;        return AudioSegment();  // Return an empty AudioSegment on failure&#xA;    }&#xA;&#xA;    if (avformat_find_stream_info(format_ctx, nullptr) &lt; 0) {&#xA;        std::cerr &lt;&lt; "Error: Could not find stream information." &lt;&lt; std::endl;&#xA;        avformat_close_input(&amp;format_ctx);&#xA;        return AudioSegment();&#xA;    }&#xA;&#xA;    int audio_stream_index = -1;&#xA;    for (unsigned int i = 0; i &lt; format_ctx->nb_streams; i&#x2B;&#x2B;) {&#xA;        if (format_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {&#xA;            audio_stream_index = i;&#xA;            break;&#xA;        }&#xA;    }&#xA;&#xA;    if (audio_stream_index == -1) {&#xA;        std::cerr &lt;&lt; "Error: Could not find audio stream." &lt;&lt; std::endl;&#xA;        avformat_close_input(&amp;format_ctx);&#xA;        return AudioSegment();&#xA;    }&#xA;&#xA;    AVCodecParameters* codec_par = format_ctx->streams[audio_stream_index]->codecpar;&#xA;    const AVCodec* my_codec = avcodec_find_decoder(codec_par->codec_id);&#xA;    AVCodecContext* codec_ctx = avcodec_alloc_context3(my_codec);&#xA;&#xA;    if (!codec_ctx) {&#xA;        std::cerr &lt;&lt; "Error: Could not allocate codec context." &lt;&lt; std::endl;&#xA;        avformat_close_input(&amp;format_ctx);&#xA;        return AudioSegment();&#xA;    }&#xA;&#xA;    if (avcodec_parameters_to_context(codec_ctx, codec_par) &lt; 0) {&#xA;        std::cerr &lt;&lt; "Error: Could not initialize codec context." &lt;&lt; std::endl;&#xA;        avcodec_free_context(&amp;codec_ctx);&#xA;        avformat_close_input(&amp;format_ctx);&#xA;        return AudioSegment();&#xA;    }&#xA;&#xA;    if (avcodec_open2(codec_ctx, my_codec, nullptr) &lt; 0) {&#xA;        std::cerr &lt;&lt; "Error: Could not open codec." &lt;&lt; std::endl;&#xA;        avcodec_free_context(&amp;codec_ctx);&#xA;        avformat_close_input(&amp;format_ctx);&#xA;        return AudioSegment();&#xA;    }&#xA;&#xA;    SwrContext* swr_ctx = swr_alloc();&#xA;    if (!swr_ctx) {&#xA;        std::cerr &lt;&lt; "Error: Could not allocate SwrContext." &lt;&lt; std::endl;&#xA;        avcodec_free_context(&amp;codec_ctx);&#xA;        avformat_close_input(&amp;format_ctx);&#xA;        return AudioSegment();&#xA;    }&#xA;    codec_ctx->sample_rate = 44100;&#xA;    // Set up resampling context to convert to S16 format with 2 bytes per sample&#xA;    av_opt_set_chlayout(swr_ctx, "in_chlayout", &amp;codec_ctx->ch_layout, 0);&#xA;    av_opt_set_int(swr_ctx, "in_sample_rate", codec_ctx->sample_rate, 0);&#xA;    av_opt_set_sample_fmt(swr_ctx, "in_sample_fmt", codec_ctx->sample_fmt, 0);&#xA;&#xA;    AVChannelLayout dst_ch_layout;&#xA;    av_channel_layout_copy(&amp;dst_ch_layout, &amp;codec_ctx->ch_layout);&#xA;    av_channel_layout_uninit(&amp;dst_ch_layout);&#xA;    av_channel_layout_default(&amp;dst_ch_layout, 2);&#xA;&#xA;    av_opt_set_chlayout(swr_ctx, "out_chlayout", &amp;dst_ch_layout, 0);&#xA;    av_opt_set_int(swr_ctx, "out_sample_rate", codec_ctx->sample_rate, 0);  // Match input sample rate&#xA;    av_opt_set_sample_fmt(swr_ctx, "out_sample_fmt", AV_SAMPLE_FMT_S16, 0);  // Force S16 format&#xA;&#xA;    if (swr_init(swr_ctx) &lt; 0) {&#xA;        std::cerr &lt;&lt; "Error: Failed to initialize the resampling context" &lt;&lt; std::endl;&#xA;        swr_free(&amp;swr_ctx);&#xA;        avcodec_free_context(&amp;codec_ctx);&#xA;        avformat_close_input(&amp;format_ctx);&#xA;        return AudioSegment();&#xA;    }&#xA;&#xA;    AVPacket packet;&#xA;    AVFrame* frame = av_frame_alloc();&#xA;    if (!frame) {&#xA;        std::cerr &lt;&lt; "Error: Could not allocate frame." &lt;&lt; std::endl;&#xA;        swr_free(&amp;swr_ctx);&#xA;        avcodec_free_context(&amp;codec_ctx);&#xA;        avformat_close_input(&amp;format_ctx);&#xA;        return AudioSegment();&#xA;    }&#xA;&#xA;    std::vector<char> output;&#xA;    while (av_read_frame(format_ctx, &amp;packet) >= 0) {&#xA;        if (packet.stream_index == audio_stream_index) {&#xA;            if (avcodec_send_packet(codec_ctx, &amp;packet) == 0) {&#xA;                while (avcodec_receive_frame(codec_ctx, frame) == 0) {&#xA;                    if (frame->pts != AV_NOPTS_VALUE) {&#xA;                        frame->pts = av_rescale_q(frame->pts, codec_ctx->time_base, format_ctx->streams[audio_stream_index]->time_base);&#xA;                    }&#xA;&#xA;                    uint8_t* output_buffer;&#xA;                    int output_samples = av_rescale_rnd(&#xA;                        swr_get_delay(swr_ctx, codec_ctx->sample_rate) &#x2B; frame->nb_samples,&#xA;                        codec_ctx->sample_rate, codec_ctx->sample_rate, AV_ROUND_UP);&#xA;&#xA;                    int output_buffer_size = av_samples_get_buffer_size(&#xA;                        nullptr, 2, output_samples, AV_SAMPLE_FMT_S16, 1);&#xA;&#xA;                    output_buffer = (uint8_t*)av_malloc(output_buffer_size);&#xA;&#xA;                    if (output_buffer) {&#xA;                        memset(output_buffer, 0, output_buffer_size); // Zero padding to avoid random noise&#xA;                        int converted_samples = swr_convert(swr_ctx, &amp;output_buffer, output_samples,&#xA;                            (const uint8_t**)frame->extended_data, frame->nb_samples);&#xA;&#xA;                        if (converted_samples >= 0) {&#xA;                            output.insert(output.end(), output_buffer, output_buffer &#x2B; output_buffer_size);&#xA;                        }&#xA;                        else {&#xA;                            std::cerr &lt;&lt; "Error: Failed to convert audio samples." &lt;&lt; std::endl;&#xA;                        }&#xA;                        // Make sure output_buffer is valid before freeing&#xA;                        if (output_buffer != nullptr) {&#xA;                            av_free(output_buffer);&#xA;                            output_buffer = nullptr; // Prevent double-free&#xA;                        }&#xA;                    }&#xA;                    else {&#xA;                        std::cerr &lt;&lt; "Error: Could not allocate output buffer." &lt;&lt; std::endl;&#xA;                    }&#xA;                }&#xA;            }&#xA;            else {&#xA;                std::cerr &lt;&lt; "Error: Failed to send packet to codec context." &lt;&lt; std::endl;&#xA;            }&#xA;        }&#xA;        av_packet_unref(&amp;packet);&#xA;    }&#xA;&#xA;    int frame_width = av_get_bytes_per_sample(AV_SAMPLE_FMT_S16) * 2;  // Use 2 bytes per sample and 2 channels&#xA;&#xA;    std::map metadata = {&#xA;        {"sample_width", 2},  // S16 format has 2 bytes per sample&#xA;        {"frame_rate", codec_ctx->sample_rate},  // Use the input sample rate&#xA;        {"channels", 2},  // Assuming stereo output&#xA;        {"frame_width", frame_width}&#xA;    };&#xA;&#xA;    av_frame_free(&amp;frame);&#xA;    swr_free(&amp;swr_ctx);&#xA;    avcodec_free_context(&amp;codec_ctx);&#xA;    avformat_close_input(&amp;format_ctx);&#xA;&#xA;    return AudioSegment(static_cast<const>(output.data()), output.size(), metadata);&#xA;}&#xA;&#xA;std::ofstream AudioSegment::export_segment_to_wav_file(const std::string&amp; out_f) {&#xA;    std::cout &lt;&lt; this->get_channels() &lt;&lt; std::endl;&#xA;    av_log_set_level(AV_LOG_ERROR);&#xA;    AVCodecContext* codec_ctx = nullptr;&#xA;    AVFormatContext* format_ctx = nullptr;&#xA;    AVStream* stream = nullptr;&#xA;    AVFrame* frame = nullptr;&#xA;    AVPacket* pkt = nullptr;&#xA;    int ret;&#xA;&#xA;    // Initialize format context for WAV&#xA;    if (avformat_alloc_output_context2(&amp;format_ctx, nullptr, "wav", out_f.c_str()) &lt; 0) {&#xA;        throw std::runtime_error("Could not allocate format context.");&#xA;    }&#xA;&#xA;    // Find encoder for PCM&#xA;    const AVCodec* codec_ptr = avcodec_find_encoder(AV_CODEC_ID_PCM_S16LE);&#xA;    if (!codec_ptr) {&#xA;        throw std::runtime_error("PCM encoder not found.");&#xA;    }&#xA;&#xA;    // Add stream&#xA;    stream = avformat_new_stream(format_ctx, codec_ptr);&#xA;    if (!stream) {&#xA;        throw std::runtime_error("Failed to create new stream.");&#xA;    }&#xA;&#xA;    // Allocate codec context&#xA;    codec_ctx = avcodec_alloc_context3(codec_ptr);&#xA;    if (!codec_ctx) {&#xA;        throw std::runtime_error("Could not allocate audio codec context.");&#xA;    }&#xA;&#xA;    // Set codec parameters for PCM&#xA;    codec_ctx->bit_rate = 128000;  // Bitrate&#xA;    codec_ctx->sample_rate = this->get_frame_rate();  // Use correct sample rate&#xA;    codec_ctx->ch_layout.nb_channels = this->get_channels();  // Set the correct channel count&#xA;&#xA;    // Set the channel layout: stereo or mono&#xA;    if (this->get_channels() == 2) {&#xA;        av_channel_layout_default(&amp;codec_ctx->ch_layout, 2);  // Stereo layout&#xA;    }&#xA;    else {&#xA;        av_channel_layout_default(&amp;codec_ctx->ch_layout, 1);  // Mono layout&#xA;    }&#xA;&#xA;    codec_ctx->sample_fmt = AV_SAMPLE_FMT_S16;  // PCM 16-bit format&#xA;&#xA;    // Open codec&#xA;    if (avcodec_open2(codec_ctx, codec_ptr, nullptr) &lt; 0) {&#xA;        throw std::runtime_error("Could not open codec.");&#xA;    }&#xA;&#xA;    // Set codec parameters to the stream&#xA;    if (avcodec_parameters_from_context(stream->codecpar, codec_ctx) &lt; 0) {&#xA;        throw std::runtime_error("Could not initialize stream codec parameters.");&#xA;    }&#xA;&#xA;    // Open output file&#xA;    std::ofstream out_file(out_f, std::ios::binary);&#xA;    if (!out_file) {&#xA;        throw std::runtime_error("Failed to open output file.");&#xA;    }&#xA;&#xA;    if (!(format_ctx->oformat->flags &amp; AVFMT_NOFILE)) {&#xA;        if (avio_open(&amp;format_ctx->pb, out_f.c_str(), AVIO_FLAG_WRITE) &lt; 0) {&#xA;            throw std::runtime_error("Could not open output file.");&#xA;        }&#xA;    }&#xA;&#xA;    // Write file header&#xA;    if (avformat_write_header(format_ctx, nullptr) &lt; 0) {&#xA;        throw std::runtime_error("Error occurred when writing file header.");&#xA;    }&#xA;&#xA;    // Initialize packet&#xA;    pkt = av_packet_alloc();&#xA;    if (!pkt) {&#xA;        throw std::runtime_error("Could not allocate AVPacket.");&#xA;    }&#xA;&#xA;    // Initialize frame&#xA;    frame = av_frame_alloc();&#xA;    if (!frame) {&#xA;        throw std::runtime_error("Could not allocate AVFrame.");&#xA;    }&#xA;&#xA;    // Set the frame properties&#xA;    frame->format = codec_ctx->sample_fmt;&#xA;    frame->ch_layout = codec_ctx->ch_layout;&#xA;&#xA;    // Number of audio samples available in the data buffer&#xA;    int total_samples = data_.size() / (av_get_bytes_per_sample(AV_SAMPLE_FMT_S16) * codec_ctx->ch_layout.nb_channels);&#xA;    int samples_read = 0;&#xA;&#xA;    // Set the number of samples per frame dynamically based on the input data&#xA;    while (samples_read &lt; total_samples) {&#xA;        // Determine how many samples to read in this iteration (don&#x27;t exceed the total sample count)&#xA;        int num_samples = std::min(codec_ctx->frame_size, total_samples - samples_read);&#xA;        if (num_samples == 0) {&#xA;            num_samples = 1024;&#xA;            codec_ctx->frame_size = 1024;&#xA;        }&#xA;        // Ensure num_samples is not zero&#xA;        if (num_samples &lt;= 0) {&#xA;            throw std::runtime_error("Invalid number of samples in frame.");&#xA;        }&#xA;&#xA;        // Set the number of samples in the frame&#xA;        frame->nb_samples = num_samples;&#xA;&#xA;        // Allocate the frame buffer based on the number of samples&#xA;        ret = av_frame_get_buffer(frame, 0);&#xA;        if (ret &lt; 0) {&#xA;            std::cerr &lt;&lt; "Error allocating frame buffer: " &lt;&lt; ret &lt;&lt; std::endl;&#xA;            throw std::runtime_error("Could not allocate audio data buffers.");&#xA;        }&#xA;&#xA;        // Copy the audio data into the frame&#x27;s buffer (interleaving if necessary)&#xA;        /*if (codec_ctx->ch_layout.nb_channels == 2) {&#xA;            // If stereo, interleave planar data into packed format&#xA;            for (int i = 0; i &lt; num_samples; &#x2B;&#x2B;i) {&#xA;                ((int16_t*)frame->data[0])[2 * i] = ((int16_t*)data_.data())[i];                // Left channel&#xA;                ((int16_t*)frame->data[0])[2 * i &#x2B; 1] = ((int16_t*)data_.data())[total_samples &#x2B; i]; // Right channel&#xA;            }&#xA;        }&#xA;        else {&#xA;            // For mono or packed data, directly copy the samples&#xA;            std::memcpy(frame->data[0], data_.data() &#x2B; samples_read * av_get_bytes_per_sample(AV_SAMPLE_FMT_S16) * codec_ctx->ch_layout.nb_channels,&#xA;                num_samples * av_get_bytes_per_sample(AV_SAMPLE_FMT_S16) * codec_ctx->ch_layout.nb_channels);&#xA;        }&#xA;        */&#xA;        std::memcpy(frame->data[0], data_.data() &#x2B; samples_read * av_get_bytes_per_sample(AV_SAMPLE_FMT_S16) * codec_ctx->ch_layout.nb_channels,&#xA;            num_samples * av_get_bytes_per_sample(AV_SAMPLE_FMT_S16) * codec_ctx->ch_layout.nb_channels);&#xA;&#xA;        // Send the frame for encoding&#xA;        ret = avcodec_send_frame(codec_ctx, frame);&#xA;        if (ret &lt; 0) {&#xA;            std::cerr &lt;&lt; "Error sending frame for encoding: " &lt;&lt; ret &lt;&lt; std::endl;&#xA;            throw std::runtime_error("Error sending frame for encoding.");&#xA;        }&#xA;&#xA;        // Receive and write encoded packets&#xA;        while (ret >= 0) {&#xA;            ret = avcodec_receive_packet(codec_ctx, pkt);&#xA;            if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {&#xA;                break;&#xA;            }&#xA;            else if (ret &lt; 0) {&#xA;                throw std::runtime_error("Error during encoding.");&#xA;            }&#xA;&#xA;            out_file.write(reinterpret_cast(pkt->data), pkt->size);&#xA;            av_packet_unref(pkt);&#xA;        }&#xA;&#xA;        samples_read &#x2B;= num_samples;&#xA;    }&#xA;&#xA;    // Flush the encoder&#xA;    if (avcodec_send_frame(codec_ctx, nullptr) &lt; 0) {&#xA;        throw std::runtime_error("Error flushing the encoder.");&#xA;    }&#xA;&#xA;    while (avcodec_receive_packet(codec_ctx, pkt) >= 0) {&#xA;        out_file.write(reinterpret_cast(pkt->data), pkt->size);&#xA;        av_packet_unref(pkt);&#xA;    }&#xA;&#xA;    // Write file trailer&#xA;    av_write_trailer(format_ctx);&#xA;&#xA;    // Cleanup&#xA;    av_frame_free(&amp;frame);&#xA;    av_packet_free(&amp;pkt);&#xA;    avcodec_free_context(&amp;codec_ctx);&#xA;&#xA;    if (!(format_ctx->oformat->flags &amp; AVFMT_NOFILE)) {&#xA;        avio_closep(&amp;format_ctx->pb);&#xA;    }&#xA;    avformat_free_context(format_ctx);&#xA;&#xA;    out_file.close();&#xA;    return out_file;&#xA;}&#xA;&#xA;</const></char>

    &#xA;

    Run code :

    &#xA;

    #include "audio_segment.h"&#xA;#include "effects.h"&#xA;#include "playback.h"&#xA;#include "cppaudioop.h"&#xA;#include "exceptions.h"&#xA;#include "generators.h"&#xA;#include "silence.h"&#xA;#include "utils.h"&#xA;&#xA;#include <iostream>&#xA;#include <filesystem>&#xA;&#xA;using namespace cppdub;&#xA;&#xA;int main() {&#xA;    try {&#xA;        // Load the source audio file&#xA;        AudioSegment seg_1 = AudioSegment::from_file("../data/test10.mp3");&#xA;        std::string out_file_name = "ah-ah-ah.wav";&#xA;&#xA;        // Export the audio segment to a new file with specified settings&#xA;        //seg_1.export_segment(out_file_name, "mp3");&#xA;        seg_1.export_segment_to_wav_file(out_file_name);&#xA;&#xA;&#xA;        // Optionally play the audio segment to verify&#xA;        // play(seg_1);&#xA;&#xA;        // Load the exported audio file&#xA;        AudioSegment seg_2 = AudioSegment::from_file(out_file_name);&#xA;&#xA;        // Play segments&#xA;        //play(seg_1);&#xA;        play(seg_2);&#xA;    }&#xA;    catch (const std::exception&amp; e) {&#xA;        std::cerr &lt;&lt; "An error occurred: " &lt;&lt; e.what() &lt;&lt; std::endl;&#xA;    }&#xA;&#xA;    return 0;&#xA;}&#xA;</filesystem></iostream>

    &#xA;

    Error in second call of from_file function :

    &#xA;

    [pcm_s16le @ 000002d82ca5bfc0] Invalid PCM packet, data has size 2 but at least a size of 4 was expected

    &#xA;

    The process continue, i call hear the seg_2 with play(seg_2) call, but i can't directly play seg_2 export wav file (from windows explorer).

    &#xA;

    I had a guess that error may be because packed vs plannar formats missmatch but i am not quit sure. Maybe a swr_convert is necessary.

    &#xA;

  • Java uses FFmpegRecoder to encode frames into H264 streams

    5 septembre 2024, par zhang1973

    I want to obtain the Frame from the video stream, process it, use FFmpegRecoder to encode it into an H264 stream, and transmit it to the front-end. But I found that the AVPacket obtained directly using grabber.grabAVPacket can be converted into H264 stream and played normally. The H264 stream encoded using FFmpegRecoder cannot be played.

    &#xA;

    Here is my Code :

    &#xA;

        private FFmpegFrameRecorder recorder;&#xA;    private ByteArrayOutputStream outputStream =  new ByteArrayOutputStream();;&#xA;    private boolean createRecoder(Frame frame){&#xA;        recorder = new FFmpegFrameRecorder(outputStream, frame.imageWidth, frame.imageHeight);&#xA;        recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264);&#xA;        recorder.setFormat("h264");  //"h264"); //&#xA;        recorder.setFrameRate(30);&#xA;        recorder.setPixelFormat(avutil.AV_PIX_FMT_YUV420P);&#xA;        recorder.setVideoBitrate(4000 * 1000); // 设置比特率为4000 kbps&#xA;        recorder.setVideoOption("preset", "ultrafast"); // 设置编码器预设,"ultrafast"是最快的,"veryslow"是最慢但质量最好&#xA;        recorder.setAudioChannels(0);&#xA;&#xA;        try {&#xA;            recorder.start();&#xA;            return recorderStatus = true;&#xA;        } catch (org.bytedeco.javacv.FrameRecorder.Exception e1) {&#xA;            log.info("启动转码录制器失败", e1);&#xA;            MediaService.cameras.remove(cameraDto.getMediaKey());&#xA;            e1.printStackTrace();&#xA;        }&#xA;&#xA;        return recorderStatus = false;&#xA;    }&#xA;&#xA;    private boolean slow = false;&#xA;    protected void transferStream2H264() throws FFmpegFrameGrabber.Exception {&#xA;&#xA;        // 初始化和拉去图像的方法&#xA;        log.info(" create grabber  ");&#xA;        if (!createGrabber()) {&#xA;            log.error("   == > ");&#xA;            return;&#xA;        }&#xA;        transferFlag = true;&#xA;&#xA;        if(!createRecoder(grabber.grab())){&#xA;            return;&#xA;        }&#xA;&#xA;        try {&#xA;            grabber.flush();&#xA;        } catch (Exception e) {&#xA;            log.info("清空拉流器缓存失败", e);&#xA;            e.printStackTrace();&#xA;        }&#xA;&#xA;        if (header == null) {&#xA;            header = bos.toByteArray();&#xA;            slow = true;&#xA;//          System.out.println("Header1");&#xA;//          System.out.println(header);&#xA;            bos.reset();&#xA;        }else{&#xA;            System.out.println("Header2");&#xA;            System.out.println(header);&#xA;        }&#xA;&#xA;        running = true;&#xA;&#xA;        // 事实更新所有的连接数&#xA;        listenClient();&#xA;&#xA;        long startTime = 0;&#xA;        long videoTS = 0;&#xA;&#xA;        for (; running &amp;&amp; grabberStatus;) {&#xA;            try {&#xA;                if (transferFlag) {&#xA;                    long startGrab = System.currentTimeMillis();&#xA;                    //视频采集器&#xA;//                  AVPacket pkt = grabber.grabPacket();&#xA;                    Frame frame = grabber.grab();&#xA;                    recorder.record(frame);&#xA;                    byte[] videoData = outputStream.toByteArray();&#xA;                    if ((System.currentTimeMillis() - startGrab) > 5000) {&#xA;                        log.info("\r\n{}\r\n视频流网络异常>>>", cameraDto.getUrl());&#xA;                        closeMedia();&#xA;                        break;&#xA;                    }&#xA;&#xA;                        videoTS = 1000 * (System.currentTimeMillis() - startTime);&#xA;&#xA;&#xA;                            if (startTime == 0) {&#xA;                                startTime = System.currentTimeMillis();&#xA;                            }&#xA;                            videoTS = 1000 * (System.currentTimeMillis() - startTime);&#xA;&#xA;                                byte[] rbuffer = videoData;&#xA;                                readSize = videoData.length;&#xA;&#xA;                                if(spsdata == null || ppsdata == null){&#xA;                                    movePos = 0;&#xA;                                    lastPos = 0;&#xA;                                    isNewPack = true;&#xA;                                    while(movePos &lt; readSize){&#xA;                                        if (rbuffer[movePos] == 0 &amp;&amp; rbuffer[movePos &#x2B; 1] == 0 &amp;&amp; rbuffer[movePos &#x2B; 2] == 1) {&#xA;                                            findCode = true;&#xA;                                            skipLen = 3;&#xA;                                            mCurFrameFirstByte = (int)(0xff &amp; rbuffer[movePos &#x2B; skipLen]);&#xA;                                        } else if (rbuffer[movePos] == 0 &amp;&amp; rbuffer[movePos &#x2B; 1] == 0 &amp;&amp; rbuffer[movePos &#x2B; 2] == 0 &amp;&amp; rbuffer[movePos &#x2B; 3] == 1) {&#xA;                                            findCode = true;&#xA;                                            skipLen = 4;&#xA;                                            mCurFrameFirstByte = (int)(0xff &amp; rbuffer[movePos &#x2B; skipLen]);&#xA;                                        } else {&#xA;                                            skipLen = 1;&#xA;                                        }&#xA;&#xA;                                        if(!isFirstFind &amp;&amp; isNewPack &amp;&amp; findCode){&#xA;                                            mFrameFirstByte = mCurFrameFirstByte;&#xA;                                            findCode = false;&#xA;                                            isNewPack = false;&#xA;                                            mNaluType          = mFrameFirstByte &amp; 0x1f;&#xA;                                            if(mNaluType != MediaConstant.NALU_TYPE_SEI &amp;&amp;&#xA;                                                    mNaluType != MediaConstant.NALU_TYPE_SPS &amp;&amp;&#xA;                                                    mNaluType != MediaConstant.NALU_TYPE_PPS &amp;&amp;&#xA;                                                    mNaluType != MediaConstant.NALU_TYPE_IDR){&#xA;                                                startCounter&#x2B;&#x2B;;&#xA;                                                break;&#xA;                                            }&#xA;                                        }&#xA;&#xA;                                        if(isFirstFind){&#xA;                                            isFirstFind = false;&#xA;                                            findCode = false;&#xA;                                            mFrameFirstByte = mCurFrameFirstByte;&#xA;                                        }&#xA;&#xA;                                        if(findCode){&#xA;                                            startCounter&#x2B;&#x2B;;&#xA;                                            mNaluType          = mFrameFirstByte &amp; 0x1f;&#xA;&#xA;                                            findCode = false;&#xA;                                            mFrameLen = (movePos - lastPos);&#xA;                                            if(mNaluType == MediaConstant.NALU_TYPE_IDR){&#xA;                                                mFrameLen = readSize - movePos;&#xA;                                            }&#xA;&#xA;                                            if(mNaluType != MediaConstant.NALU_TYPE_SEI &amp;&amp;&#xA;                                                    mNaluType != MediaConstant.NALU_TYPE_SPS &amp;&amp;&#xA;                                                    mNaluType != MediaConstant.NALU_TYPE_PPS &amp;&amp;&#xA;                                                    mNaluType != MediaConstant.NALU_TYPE_IDR){&#xA;                                                System.out.println("  one packe many frames --->  type: " &#x2B; mNaluType &#x2B; " jump out ");&#xA;                                                break;&#xA;                                            }&#xA;                                            if(mNaluType == MediaConstant.NALU_TYPE_SPS){&#xA;                                                if(null == spsdata){&#xA;                                                    spsdata = new byte[mFrameLen];&#xA;                                                    System.arraycopy(rbuffer, lastPos, spsdata, 0, mFrameLen);&#xA;                                                }&#xA;                                            }&#xA;                                            if(mNaluType == MediaConstant.NALU_TYPE_PPS){&#xA;&#xA;                                                if(null == ppsdata){&#xA;                                                    ppsdata = new byte[mFrameLen];&#xA;                                                    System.arraycopy(rbuffer, lastPos, ppsdata, 0, mFrameLen);&#xA;                                                }&#xA;                                            }&#xA;&#xA;                                            lastPos = movePos;&#xA;                                            mFrameFirstByte = mCurFrameFirstByte;&#xA;                                            mNaluType          = mFrameFirstByte &amp; 0x1f;&#xA;                                            if(mNaluType == MediaConstant.NALU_TYPE_IDR){&#xA;                                                mFrameLen = readSize - movePos;&#xA;                                                startCounter&#x2B;&#x2B;;&#xA;&#xA;                                                break;&#xA;                                            }&#xA;                                        }&#xA;&#xA;                                        movePos &#x2B;= skipLen;&#xA;                                        isNewPack = false;&#xA;                                    }&#xA;                                }&#xA;&#xA;                                sendFrameData(rbuffer);&#xA;//                          }&#xA;//                          av_packet_unref(pkt);&#xA;//                      }&#xA;&#xA;//                  }&#xA;                } else {&#xA;                }&#xA;            } catch (Exception e) {&#xA;                grabberStatus = false;&#xA;                MediaService.cameras.remove(cameraDto.getMediaKey());&#xA;            } catch (FFmpegFrameRecorder.Exception e) {&#xA;                throw new RuntimeException(e);&#xA;            }&#xA;        }&#xA;&#xA;        try {&#xA;            grabber.close();&#xA;            bos.close();&#xA;        } catch (org.bytedeco.javacv.FrameRecorder.Exception e) {&#xA;            e.printStackTrace();&#xA;        } catch (Exception e) {&#xA;            e.printStackTrace();&#xA;        } catch (IOException e) {&#xA;            e.printStackTrace();&#xA;        } finally {&#xA;            closeMedia();&#xA;        }&#xA;        log.info("关闭媒体流-javacv,{} ", cameraDto.getUrl());&#xA;    }&#xA;

    &#xA;