Recherche avancée

Médias (0)

Mot : - Tags -/organisation

Aucun média correspondant à vos critères n’est disponible sur le site.

Autres articles (38)

  • HTML5 audio and video support

    13 avril 2011, par

    MediaSPIP uses HTML5 video and audio tags to play multimedia files, taking advantage of the latest W3C innovations supported by modern browsers.
    The MediaSPIP player used has been created specifically for MediaSPIP and can be easily adapted to fit in with a specific theme.
    For older browsers the Flowplayer flash fallback is used.
    MediaSPIP allows for media playback on major mobile platforms with the above (...)

  • Contribute to translation

    13 avril 2011

    You can help us to improve the language used in the software interface to make MediaSPIP more accessible and user-friendly. You can also translate the interface into any language that allows it to spread to new linguistic communities.
    To do this, we use the translation interface of SPIP where the all the language modules of MediaSPIP are available. Just subscribe to the mailing list and request further informantion on translation.
    MediaSPIP is currently available in French and English (...)

  • Creating farms of unique websites

    13 avril 2011, par

    MediaSPIP platforms can be installed as a farm, with a single "core" hosted on a dedicated server and used by multiple websites.
    This allows (among other things) : implementation costs to be shared between several different projects / individuals rapid deployment of multiple unique sites creation of groups of like-minded sites, making it possible to browse media in a more controlled and selective environment than the major "open" (...)

Sur d’autres sites (4084)

  • FFmpeg avcodec_open2 throws -22 ("Invalid Argument")

    14 avril 2023, par stupidbutseeking

    I got stuck trying to write a simple video conversion using C++ and ffmpeg.

    


    When trying to convert a video using FFmpeg, calling avcodec_open2 fails with the code "-22" which seems to be an "Invalid Argument"-error.

    


    I can't figure out why it fails, nor what the invalid argument is. In the following snippet I create the output codec and pass its context the information from the source (code further down below).

    


    The check for the "outputCodec" works and does not throw an error. As far as I know an "AVDictionary"-argument is optional. So I guess the reason for the error is the context.

    


        const AVCodec* outputCodec = avcodec_find_encoder_by_name(codecName.c_str());

    if (!outputCodec)
    {
        std::cout << "Zielformat-Codec nicht gefunden" << std::endl;
        return -1;
    }

    AVCodecContext* outputCodecContext = avcodec_alloc_context3(outputCodec);
    outputCodecContext->bit_rate = bitRate;
    outputCodecContext->width = inputCodecContext->width;
    outputCodecContext->height = inputCodecContext->height;
    outputCodecContext->pix_fmt = outputCodec->pix_fmts[0];
    outputCodecContext->time_base = inputCodecContext->time_base;

    **int errorCode = avcodec_open2(outputCodecContext, outputCodec, NULL); //THIS RETURNS -22**
    if (errorCode != 0)
    {
        std::cout << "Fehler beim Öffnen des Zielformat-Codecs" << std::endl;
        return -1;
    }


    


    Here is the code for getting the input file & context :

    


        std::string inputFilename = "input_video.mp4";
    std::string outputFilename = "output.avi";
    std::string codecName = "mpeg4";
    int bitRate = 400000;

    AVFormatContext* inputFormatContext = NULL;
    if (avformat_open_input(&inputFormatContext, inputFilename.c_str(), NULL, NULL) != 0)
    {
        std::cout << "Fehler beim Öffnen der Eingabedatei" << std::endl;
        return -1;
    }

    [Do Video Stream Search)

    AVCodecParameters* inputCodecParameters = inputFormatContext->streams[videoStreamIndex]->codecpar;
    const AVCodec* inputCodec = avcodec_find_decoder(inputCodecParameters->codec_id);
    AVCodecContext* inputCodecContext = avcodec_alloc_context3(inputCodec);
    if (avcodec_parameters_to_context(inputCodecContext, inputCodecParameters) != 0)
    {
        std::cout << "Fehler beim Setzen des Eingabecodecs" << std::endl;
        return -1;
    }
    if (avcodec_open2(inputCodecContext, inputCodec, NULL) != 0)
    {
        std::cout << "Fehler beim Öffnen des Eingabecodecs" << std::endl;
        return -1;
    }


    


    The purpose was simply to get started with ffmpeg in an own C++ project.

    


    If it is of any need, I downloaded the ffmpeg libs from here. I used the gpl shared ones. The architecture is win x64. I referenced them through the project properties (additional libraries and so on).

    


    I tried to convert a .mp4 video to an .avi video with an "mpeg4" compression.
I also tried other compressions like "libx264" but none worked.

    


    I searched for the problem on stackoverflow but could not find the exact same problem. While its purpose is different this post is about the same error code when calling avcodec_open2. But its solution is not working for me. I inspected the watch for the "outputContext" while running the code and the codec_id, codec_type and format is set. I use the time_base from the input file. According to my understanding, this should be equal to the source. So I can not find out what I am missing.

    


    Thanks in advance and sorry for my english.

    


    And for completion, here is the whole method :

    


    int TestConvert()
{
    std::string inputFilename = "input_video.mp4";
    std::string outputFilename = "output.avi";
    std::string codecName = "mpeg4";
    int bitRate = 400000;

    AVFormatContext* inputFormatContext = NULL;
    if (avformat_open_input(&inputFormatContext, inputFilename.c_str(), NULL, NULL) != 0)
    {
        std::cout << "Fehler beim Öffnen der Eingabedatei" << std::endl;
        return -1;
    }

    int videoStreamIndex = -1;
    for (unsigned int i = 0; i < inputFormatContext->nb_streams; i++)
    {
        if (inputFormatContext->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
        {
            videoStreamIndex = i;
            break;
        }
    }

    AVCodecParameters* inputCodecParameters = inputFormatContext->streams[videoStreamIndex]->codecpar;
    const AVCodec* inputCodec = avcodec_find_decoder(inputCodecParameters->codec_id);
    AVCodecContext* inputCodecContext = avcodec_alloc_context3(inputCodec);
    if (avcodec_parameters_to_context(inputCodecContext, inputCodecParameters) != 0)
    {
        std::cout << "Fehler beim Setzen des Eingabecodecs" << std::endl;
        return -1;
    }
    if (avcodec_open2(inputCodecContext, inputCodec, NULL) != 0)
    {
        std::cout << "Fehler beim Öffnen des Eingabecodecs" << std::endl;
        return -1;
    }

    const AVCodec* outputCodec = avcodec_find_encoder_by_name(codecName.c_str());

    if (!outputCodec)
    {
        std::cout << "Zielformat-Codec nicht gefunden" << std::endl;
        return -1;
    }

    AVCodecContext* outputCodecContext = avcodec_alloc_context3(outputCodec);
    outputCodecContext->bit_rate = bitRate;
    outputCodecContext->width = inputCodecContext->width;
    outputCodecContext->height = inputCodecContext->height;
    outputCodecContext->pix_fmt = outputCodec->pix_fmts[0];
    outputCodecContext->time_base = inputCodecContext->time_base;

    int errorCode = avcodec_open2(outputCodecContext, outputCodec, NULL);
    if (errorCode != 0)
    {
        std::cout << "Fehler beim Öffnen des Zielformat-Codecs" << std::endl;
        return -1;
    }

    AVFormatContext* outputFormatContext = NULL;
    if (avformat_alloc_output_context2(&outputFormatContext, NULL, NULL, outputFilename.c_str()) != 0)
    {
        std::cout << "Fehler beim Erstellen des Ausgabe-Formats" << std::endl;
        return -1;
    }

    AVStream* outputVideoStream = avformat_new_stream(outputFormatContext, outputCodec);
    if (outputVideoStream == NULL)
    {
        std::cout << "Fehler beim Hinzufügen des Video-Streams zum Ausgabe-Format" << std::endl;
        return -1;
    }
    outputVideoStream->id = outputFormatContext->nb_streams - 1;
    AVCodecParameters* outputCodecParameters = outputVideoStream->codecpar;
    if (avcodec_parameters_from_context(outputCodecParameters, outputCodecContext) != 0)
    {
        std::cout << "Fehler beim Setzen des Ausgabe-Codecs" << std::endl;
        return -1;
    }

    if (!(outputFormatContext->oformat->flags & AVFMT_NOFILE))
    {
        if (avio_open(&outputFormatContext->pb, outputFilename.c_str(), AVIO_FLAG_WRITE) != 0)
        {
            std::cout << "Fehler beim Öffnen der Ausgabedatei" << std::endl;
            return -1;
        }
    }

    if (avformat_write_header(outputFormatContext, NULL) != 0)
    {
        std::cout << "Fehler beim Schreiben des Ausgabe-Formats in die Ausgabedatei" << std::endl;
        return -1;
    }

    AVPacket packet;
    int response;
    AVFrame* frame = av_frame_alloc();
    AVFrame* outputFrame = av_frame_alloc();
    while (av_read_frame(inputFormatContext, &packet) == 0)
    {
        if (packet.stream_index == videoStreamIndex)
        {
            response = avcodec_send_packet(inputCodecContext, &packet);
            while (response >= 0)
            {
                response = avcodec_receive_frame(inputCodecContext, frame);
                if (response == AVERROR(EAGAIN) || response == AVERROR_EOF)
                {
                    break;
                }
                else if (response < 0)
                {
                    std::cout << "Fehler beim Dekodieren des Video-Pakets" << std::endl;
                    return -1;
                }

                struct SwsContext* swsContext = sws_getContext(inputCodecContext->width, inputCodecContext->height, inputCodecContext->pix_fmt, outputCodecContext->width, outputCodecContext->height, outputCodecContext->pix_fmt, SWS_BILINEAR, NULL, NULL, NULL); if (!swsContext)
                {
                    std::cout << "Fehler beim Erstellen des SwsContext" << std::endl;
                    return -1;
                }
                sws_scale(swsContext, frame->data, frame->linesize, 0, inputCodecContext->height, outputFrame->data, outputFrame->linesize);
                sws_freeContext(swsContext);

                outputFrame->pts = frame->pts;
                outputFrame->pkt_dts = frame->pkt_dts;
                //outputFrame->pkt_duration = frame->pkt_duration;
                response = avcodec_send_frame(outputCodecContext, outputFrame);
                while (response >= 0)
                {
                    response = avcodec_receive_packet(outputCodecContext, &packet);
                    if (response == AVERROR(EAGAIN) || response == AVERROR_EOF)
                    {
                        break;
                    }
                    else if (response < 0)
                    {
                        std::cout << "Fehler beim Kodieren des Ausgabe-Frames" << std::endl;
                        return -1;
                    }

                    packet.stream_index = outputVideoStream->id;
                    av_packet_rescale_ts(&packet, outputCodecContext->time_base, outputVideoStream->time_base);
                    if (av_interleaved_write_frame(outputFormatContext, &packet) != 0)
                    {
                        std::cout << "Fehler beim Schreiben des Ausgabe-Pakets" << std::endl;
                        return -1;
                    }
                    av_packet_unref(&packet);
                }
            }
        }
        av_packet_unref(&packet);
    }

    av_write_trailer(outputFormatContext);
    avcodec_free_context(&inputCodecContext);
    avcodec_free_context(&outputCodecContext);
    avformat_close_input(&inputFormatContext);
    avformat_free_context(inputFormatContext);
    avformat_free_context(outputFormatContext);
    av_frame_free(&frame);
    av_frame_free(&outputFrame);

    return 0;

}


    


  • FFmpeg invalid data found when processing input with D3D11VA and DXVA2 hw acceleration

    6 mai 2023, par grill2010

    I'm currently porting my Android streaming app to Windows and for decoding the h264 video stream I use FFmpeg with possible hardware acceleration. Last two weeks I was reading a lot of documentation and studied a lot of examples on the internet. For my project I use JavaCV which is internally using FFmpeg 5.1.2. On Windows I support D3D11VA, DXVA2 and Cuvid for hardware acceleration (and software decoding as fallback). During testing I noticed that I get some strange artefacts when using D3D11VA or DXVA2 hw acceleration. Upon further investigation I saw that I receive a lot of

    


    "Invalid data found when processing input"

    


    errors when calling avcodec_send_packet. It seems this error only occurs on certain key frames. The error is reproducable all the time. The software decoder or cuvid decoder has absolutely no problem to process and to decode such a frame, so not sure why there should be an invalid data in the frame ? I played around a lot with the decoder configuration but nothing seems to help and at that point I think this is definitely not normal behaviour.

    


    I provided a reproducable example which can be downloaded from here. All the important part is in the App.java class. In addition an example of the code was posted below. The example is trying to decode a key frame. The keyframe data with sps and pps is read from a file in the resource folder of the project.

    


    To run the project just perform a .\gradlew build and afterwards a .\gradlew run. If you run the example the last log message shown in the terminal should be "SUCESS with HW decoding". The hardware decoder can be changed via the HW_DEVICE_TYPE variable in the App.java class. To disable hw acceleration just set the USE_HW_ACCEL to false.

    


    For me everything seems to be correct and I have no idea what could be wrong with the code. I looked a lot on the internet to find the root cause of the issue and I did not really found a solution but other sources which are related to (maybe) the same problem

    


    https://www.mail-archive.com/libav-user@ffmpeg.org/...

    


    https://stackoverflow.com/questions/67307397/ffmpeg-...

    


    I also found another streaming app on Windows which can use D3D11VA and DXVA2 hardware acceleration called Chiaki (it requires a PS4 or a PS5) which seems to have the exact same problem. I used the build provided here. It will fail to decode certain key frames as well when hardware acceleration with D3D11VA or DXVA2 is selected (e.g. the first key frame received by the stream). Chiaki can output the seemingly faulty frame but this is also possible with my example by setting the USE_AV_EF_EXPLODE to false.

    


    Are there any ffmpeg gurus around that can check what's the problem with D3D11VA or DXVA2 ? Anything else that needs to be done to make the D3D11VA and DXVA2 hardware decoder work ? I'm now completly out of ideas and I'm not even sure if this is fixable.

    


    I have Windows 11 installed on my test machine, and I have the latest Nvidea drivers installed.

    


    Edit : here is a shrinked complete example of my project (keyframe file which includes sps and pps can be downloaded from here. It's a hex string file and can be decoded with the provided HexUtil class)

    


    import javafx.application.Application;&#xA;import javafx.scene.Scene;&#xA;import javafx.scene.layout.Pane;&#xA;import javafx.stage.Stage;&#xA;import org.bytedeco.ffmpeg.avcodec.AVCodec;&#xA;import org.bytedeco.ffmpeg.avcodec.AVCodecContext;&#xA;import org.bytedeco.ffmpeg.avcodec.AVCodecHWConfig;&#xA;import org.bytedeco.ffmpeg.avcodec.AVPacket;&#xA;import org.bytedeco.ffmpeg.avutil.AVBufferRef;&#xA;import org.bytedeco.ffmpeg.avutil.AVDictionary;&#xA;import org.bytedeco.ffmpeg.avutil.AVFrame;&#xA;import org.bytedeco.javacpp.BytePointer;&#xA;import org.bytedeco.javacpp.IntPointer;&#xA;import org.bytedeco.javacv.FFmpegLogCallback;&#xA;import org.tinylog.Logger;&#xA;&#xA;import java.io.IOException;&#xA;import java.io.InputStream;&#xA;import java.nio.charset.StandardCharsets;&#xA;import java.util.Objects;&#xA;import java.util.function.Consumer;&#xA;&#xA;import static org.bytedeco.ffmpeg.avcodec.AVCodecContext.AV_EF_EXPLODE;&#xA;import static org.bytedeco.ffmpeg.avcodec.AVCodecContext.FF_THREAD_SLICE;&#xA;import static org.bytedeco.ffmpeg.global.avcodec.*;&#xA;import static org.bytedeco.ffmpeg.global.avutil.*;&#xA;&#xA;public class App extends Application {&#xA;&#xA;    /**** decoder variables ****/&#xA;&#xA;    private AVHWContextInfo hardwareContext;&#xA;&#xA;    private AVCodec decoder;&#xA;    private AVCodecContext m_VideoDecoderCtx;&#xA;&#xA;    private AVCodecContext.Get_format_AVCodecContext_IntPointer formatCallback;&#xA;    private final int streamResolutionX = 1920;&#xA;    private final int streamResolutionY = 1080;&#xA;&#xA;    // AV_HWDEVICE_TYPE_CUDA // example works with cuda&#xA;    // AV_HWDEVICE_TYPE_DXVA2 // producing Invalid data found on keyframe&#xA;    // AV_HWDEVICE_TYPE_D3D11VA // producing Invalid data found on keyframe&#xA;    private static final int HW_DEVICE_TYPE = AV_HWDEVICE_TYPE_DXVA2;&#xA;&#xA;    private static final boolean USE_HW_ACCEL = true;&#xA;&#xA;    private static final boolean USE_AV_EF_EXPLODE = true;&#xA;&#xA;    public static void main(final String[] args) {&#xA;        //System.setProperty("prism.order", "d3d,sw");&#xA;        System.setProperty("prism.vsync", "false");&#xA;        Application.launch(App.class);&#xA;    }&#xA;&#xA;    @Override&#xA;    public void start(final Stage primaryStage) {&#xA;        final Pane dummyPane = new Pane();&#xA;        dummyPane.setStyle("-fx-background-color: black");&#xA;        final Scene scene = new Scene(dummyPane, this.streamResolutionX, this.streamResolutionY);&#xA;        primaryStage.setScene(scene);&#xA;        primaryStage.show();&#xA;        primaryStage.setMinWidth(480);&#xA;        primaryStage.setMinHeight(360);&#xA;&#xA;        this.initializeFFmpeg(result -> {&#xA;            if (!result) {&#xA;                Logger.error("FFmpeg could not be initialized correctly, terminating program");&#xA;                System.exit(1);&#xA;                return;&#xA;            }&#xA;            this.performTestFramesFeeding();&#xA;        });&#xA;    }&#xA;&#xA;    private void initializeFFmpeg(final Consumer<boolean> finishHandler) {&#xA;        FFmpegLogCallback.setLevel(AV_LOG_DEBUG); // Increase log level until the first frame is decoded&#xA;        //FFmpegLogCallback.setLevel(AV_LOG_QUIET);&#xA;        this.decoder = avcodec_find_decoder(AV_CODEC_ID_H264); // usually decoder name is h264 and without hardware support it&#x27;s yuv420p otherwise nv12&#xA;&#xA;        if (this.decoder == null) {&#xA;            Logger.error("Unable to find decoder for format {}", "h264");&#xA;            finishHandler.accept(false);&#xA;            return;&#xA;        }&#xA;        Logger.info("Current decoder name: {}, {}", this.decoder.name().getString(), this.decoder.long_name().getString());&#xA;&#xA;        if (true) {&#xA;            for (; ; ) {&#xA;                this.m_VideoDecoderCtx = avcodec_alloc_context3(this.decoder);&#xA;                if (this.m_VideoDecoderCtx == null) {&#xA;                    Logger.error("Unable to find decoder for format AV_CODEC_ID_H264");&#xA;                    if (this.hardwareContext != null) {&#xA;                        this.hardwareContext.free();&#xA;                        this.hardwareContext = null;&#xA;                    }&#xA;                    continue;&#xA;                }&#xA;&#xA;                if (App.USE_HW_ACCEL) {&#xA;                    this.hardwareContext = this.createHardwareContext();&#xA;                    if (this.hardwareContext != null) {&#xA;                        Logger.info("Set hwaccel support");&#xA;                        this.m_VideoDecoderCtx.hw_device_ctx(this.hardwareContext.hwContext()); // comment to disable hwaccel&#xA;                    }&#xA;                } else {&#xA;                    Logger.info("Hwaccel manually disabled");&#xA;                }&#xA;&#xA;&#xA;                // Always request low delay decoding&#xA;                this.m_VideoDecoderCtx.flags(this.m_VideoDecoderCtx.flags() | AV_CODEC_FLAG_LOW_DELAY);&#xA;&#xA;                // Allow display of corrupt frames and frames missing references&#xA;                this.m_VideoDecoderCtx.flags(this.m_VideoDecoderCtx.flags() | AV_CODEC_FLAG_OUTPUT_CORRUPT);&#xA;                this.m_VideoDecoderCtx.flags2(this.m_VideoDecoderCtx.flags2() | AV_CODEC_FLAG2_SHOW_ALL);&#xA;&#xA;                if (App.USE_AV_EF_EXPLODE) {&#xA;                    // Report decoding errors to allow us to request a key frame&#xA;                    this.m_VideoDecoderCtx.err_recognition(this.m_VideoDecoderCtx.err_recognition() | AV_EF_EXPLODE);&#xA;                }&#xA;&#xA;                // Enable slice multi-threading for software decoding&#xA;                if (this.m_VideoDecoderCtx.hw_device_ctx() == null) { // if not hw accelerated&#xA;                    this.m_VideoDecoderCtx.thread_type(this.m_VideoDecoderCtx.thread_type() | FF_THREAD_SLICE);&#xA;                    this.m_VideoDecoderCtx.thread_count(2/*AppUtil.getCpuCount()*/);&#xA;                } else {&#xA;                    // No threading for HW decode&#xA;                    this.m_VideoDecoderCtx.thread_count(1);&#xA;                }&#xA;&#xA;                this.m_VideoDecoderCtx.width(this.streamResolutionX);&#xA;                this.m_VideoDecoderCtx.height(this.streamResolutionY);&#xA;                this.m_VideoDecoderCtx.pix_fmt(this.getDefaultPixelFormat());&#xA;&#xA;                this.formatCallback = new AVCodecContext.Get_format_AVCodecContext_IntPointer() {&#xA;                    @Override&#xA;                    public int call(final AVCodecContext context, final IntPointer pixelFormats) {&#xA;                        final boolean hwDecodingSupported = context.hw_device_ctx() != null &amp;&amp; App.this.hardwareContext != null;&#xA;                        final int preferredPixelFormat = hwDecodingSupported ?&#xA;                                App.this.hardwareContext.hwConfig().pix_fmt() :&#xA;                                context.pix_fmt();&#xA;                        int i = 0;&#xA;                        while (true) {&#xA;                            final int currentSupportedFormat = pixelFormats.get(i&#x2B;&#x2B;);&#xA;                            System.out.println("Supported pixel formats " &#x2B; currentSupportedFormat);&#xA;                            if (currentSupportedFormat == preferredPixelFormat) {&#xA;                                Logger.info("[FFmpeg]: pixel format in format callback is {}", currentSupportedFormat);&#xA;                                return currentSupportedFormat;&#xA;                            }&#xA;                            if (currentSupportedFormat == AV_PIX_FMT_NONE) {&#xA;                                break;&#xA;                            }&#xA;                        }&#xA;&#xA;                        i = 0;&#xA;                        while (true) { // try again and search for yuv&#xA;                            final int currentSupportedFormat = pixelFormats.get(i&#x2B;&#x2B;);&#xA;                            if (currentSupportedFormat == AV_PIX_FMT_YUV420P) {&#xA;                                Logger.info("[FFmpeg]: Not found in first match so use {}", AV_PIX_FMT_YUV420P);&#xA;                                return currentSupportedFormat;&#xA;                            }&#xA;                            if (currentSupportedFormat == AV_PIX_FMT_NONE) {&#xA;                                break;&#xA;                            }&#xA;                        }&#xA;&#xA;                        i = 0;&#xA;                        while (true) { // try again and search for nv12&#xA;                            final int currentSupportedFormat = pixelFormats.get(i&#x2B;&#x2B;);&#xA;                            if (currentSupportedFormat == AV_PIX_FMT_NV12) {&#xA;                                Logger.info("[FFmpeg]: Not found in second match so use {}", AV_PIX_FMT_NV12);&#xA;                                return currentSupportedFormat;&#xA;                            }&#xA;                            if (currentSupportedFormat == AV_PIX_FMT_NONE) {&#xA;                                break;&#xA;                            }&#xA;                        }&#xA;&#xA;                        Logger.info("[FFmpeg]: pixel format in format callback is using fallback {}", AV_PIX_FMT_NONE);&#xA;                        return AV_PIX_FMT_NONE;&#xA;                    }&#xA;                };&#xA;                this.m_VideoDecoderCtx.get_format(this.formatCallback);&#xA;&#xA;                final AVDictionary options = new AVDictionary(null);&#xA;                final int result = avcodec_open2(this.m_VideoDecoderCtx, this.decoder, options);&#xA;                if (result &lt; 0) {&#xA;                    Logger.error("avcodec_open2 was not successful");&#xA;                    finishHandler.accept(false);&#xA;                    return;&#xA;                }&#xA;                av_dict_free(options);&#xA;                break;&#xA;            }&#xA;        }&#xA;&#xA;        if (this.decoder == null || this.m_VideoDecoderCtx == null) {&#xA;            finishHandler.accept(false);&#xA;            return;&#xA;        }&#xA;        finishHandler.accept(true);&#xA;    }&#xA;&#xA;    private AVHWContextInfo createHardwareContext() {&#xA;        AVHWContextInfo result = null;&#xA;        for (int i = 0; ; i&#x2B;&#x2B;) {&#xA;            final AVCodecHWConfig config = avcodec_get_hw_config(this.decoder, i);&#xA;            if (config == null) {&#xA;                break;&#xA;            }&#xA;&#xA;            if ((config.methods() &amp; AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX) &lt; 0) {&#xA;                continue;&#xA;            }&#xA;            final int device_type = config.device_type();&#xA;            if (device_type != App.HW_DEVICE_TYPE) {&#xA;                continue;&#xA;            }&#xA;            final AVBufferRef hw_context = av_hwdevice_ctx_alloc(device_type);&#xA;            if (hw_context == null || av_hwdevice_ctx_create(hw_context, device_type, (String) null, null, 0) &lt; 0) {&#xA;                Logger.error("HW accel not supported for type {}", device_type);&#xA;                av_free(config);&#xA;                av_free(hw_context);&#xA;            } else {&#xA;                Logger.info("HW accel created for type {}", device_type);&#xA;                result = new AVHWContextInfo(config, hw_context);&#xA;            }&#xA;            break;&#xA;        }&#xA;&#xA;        return result;&#xA;    }&#xA;&#xA;    @Override&#xA;    public void stop() {&#xA;        this.releaseNativeResources();&#xA;    }&#xA;&#xA;    /************************/&#xA;    /*** video processing ***/&#xA;    /************************/&#xA;&#xA;&#xA;    private void performTestFramesFeeding() {&#xA;        final AVPacket pkt = av_packet_alloc();&#xA;        if (pkt == null) {&#xA;            return;&#xA;        }&#xA;        try (final BytePointer bp = new BytePointer(65_535 * 4)) {&#xA;            final byte[] frameData = AVTestFrames.h264KeyTestFrame;&#xA;&#xA;&#xA;            bp.position(0);&#xA;&#xA;            bp.put(frameData);&#xA;            bp.limit(frameData.length);&#xA;&#xA;            pkt.data(bp);&#xA;            pkt.capacity(bp.capacity());&#xA;            pkt.size(frameData.length);&#xA;            pkt.position(0);&#xA;            pkt.limit(frameData.length);&#xA;            final AVFrame avFrame = av_frame_alloc();&#xA;&#xA;            final int err = avcodec_send_packet(this.m_VideoDecoderCtx, pkt); // this will fail with D3D11VA and DXVA2&#xA;            if (err &lt; 0) {&#xA;                final BytePointer buffer = new BytePointer(512);&#xA;                av_strerror(err, buffer, buffer.capacity());&#xA;                final String string = buffer.getString();&#xA;                System.out.println("Error on decoding test frame " &#x2B; err &#x2B; " message " &#x2B; string);&#xA;                av_frame_free(avFrame);&#xA;                return;&#xA;            }&#xA;&#xA;            final int result = avcodec_receive_frame(this.m_VideoDecoderCtx, avFrame);&#xA;            final AVFrame decodedFrame;&#xA;            if (result == 0) {&#xA;                if (this.m_VideoDecoderCtx.hw_device_ctx() == null) {&#xA;                    decodedFrame = avFrame;&#xA;                    av_frame_unref(decodedFrame);&#xA;                    System.out.println("SUCESS with SW decoding");&#xA;                } else {&#xA;                    final AVFrame hwAvFrame = av_frame_alloc();&#xA;                    if (av_hwframe_transfer_data(hwAvFrame, avFrame, 0) &lt; 0) {&#xA;                        System.out.println("Failed to transfer frame from hardware");&#xA;                        av_frame_unref(hwAvFrame);&#xA;                        decodedFrame = avFrame;&#xA;                    } else {&#xA;                        av_frame_unref(avFrame);&#xA;                        decodedFrame = hwAvFrame;&#xA;                        System.out.println("SUCESS with HW decoding");&#xA;                    }&#xA;                    av_frame_unref(decodedFrame);&#xA;                }&#xA;            } else {&#xA;                final BytePointer buffer = new BytePointer(512);&#xA;                av_strerror(result, buffer, buffer.capacity());&#xA;                final String string = buffer.getString();&#xA;                System.out.println("error " &#x2B; result &#x2B; " message " &#x2B; string);&#xA;                av_frame_free(avFrame);&#xA;            }&#xA;        } finally {&#xA;            if (pkt.stream_index() != -1) {&#xA;                av_packet_unref(pkt);&#xA;            }&#xA;            pkt.releaseReference();&#xA;        }&#xA;    }&#xA;&#xA;    final Object releaseLock = new Object();&#xA;    private volatile boolean released = false;&#xA;&#xA;    private void releaseNativeResources() {&#xA;        if (this.released) {&#xA;            return;&#xA;        }&#xA;        this.released = true;&#xA;        synchronized (this.releaseLock) {&#xA;            // Close the video codec&#xA;            if (this.m_VideoDecoderCtx != null) {&#xA;                avcodec_free_context(this.m_VideoDecoderCtx);&#xA;                this.m_VideoDecoderCtx = null;&#xA;            }&#xA;&#xA;            // close the format callback&#xA;            if (this.formatCallback != null) {&#xA;                this.formatCallback.close();&#xA;                this.formatCallback = null;&#xA;            }&#xA;&#xA;            // close hw context&#xA;            if (this.hardwareContext != null) {&#xA;                this.hardwareContext.free();&#xA;            }&#xA;        }&#xA;    }&#xA;&#xA;    private int getDefaultPixelFormat() {&#xA;        return AV_PIX_FMT_YUV420P; // Always return yuv420p here&#xA;    }&#xA;&#xA;    public static final class HexUtil {&#xA;        private static final char[] hexArray = "0123456789ABCDEF".toCharArray();&#xA;&#xA;        private HexUtil() {&#xA;        }&#xA;&#xA;        public static String hexlify(final byte[] bytes) {&#xA;            final char[] hexChars = new char[bytes.length * 2];&#xA;&#xA;            for (int j = 0; j &lt; bytes.length; &#x2B;&#x2B;j) {&#xA;                final int v = bytes[j] &amp; 255;&#xA;                hexChars[j * 2] = HexUtil.hexArray[v >>> 4];&#xA;                hexChars[j * 2 &#x2B; 1] = HexUtil.hexArray[v &amp; 15];&#xA;            }&#xA;&#xA;            return new String(hexChars);&#xA;        }&#xA;&#xA;        public static byte[] unhexlify(final String argbuf) {&#xA;            final int arglen = argbuf.length();&#xA;            if (arglen % 2 != 0) {&#xA;                throw new RuntimeException("Odd-length string");&#xA;            } else {&#xA;                final byte[] retbuf = new byte[arglen / 2];&#xA;&#xA;                for (int i = 0; i &lt; arglen; i &#x2B;= 2) {&#xA;                    final int top = Character.digit(argbuf.charAt(i), 16);&#xA;                    final int bot = Character.digit(argbuf.charAt(i &#x2B; 1), 16);&#xA;                    if (top == -1 || bot == -1) {&#xA;                        throw new RuntimeException("Non-hexadecimal digit found");&#xA;                    }&#xA;&#xA;                    retbuf[i / 2] = (byte) ((top &lt;&lt; 4) &#x2B; bot);&#xA;                }&#xA;&#xA;                return retbuf;&#xA;            }&#xA;        }&#xA;    }&#xA;&#xA;    public static final class AVHWContextInfo {&#xA;        private final AVCodecHWConfig hwConfig;&#xA;        private final AVBufferRef hwContext;&#xA;&#xA;        private volatile boolean freed = false;&#xA;&#xA;        public AVHWContextInfo(final AVCodecHWConfig hwConfig, final AVBufferRef hwContext) {&#xA;            this.hwConfig = hwConfig;&#xA;            this.hwContext = hwContext;&#xA;        }&#xA;&#xA;        public AVCodecHWConfig hwConfig() {&#xA;            return this.hwConfig;&#xA;        }&#xA;&#xA;        public AVBufferRef hwContext() {&#xA;            return this.hwContext;&#xA;        }&#xA;&#xA;        public void free() {&#xA;            if (this.freed) {&#xA;                return;&#xA;            }&#xA;            this.freed = true;&#xA;            av_free(this.hwConfig);&#xA;            av_free(this.hwContext);&#xA;        }&#xA;&#xA;&#xA;        @Override&#xA;        public boolean equals(Object o) {&#xA;            if (this == o) return true;&#xA;            if (o == null || getClass() != o.getClass()) return false;&#xA;            AVHWContextInfo that = (AVHWContextInfo) o;&#xA;            return freed == that.freed &amp;&amp; Objects.equals(hwConfig, that.hwConfig) &amp;&amp; Objects.equals(hwContext, that.hwContext);&#xA;        }&#xA;&#xA;        @Override&#xA;        public int hashCode() {&#xA;            return Objects.hash(hwConfig, hwContext, freed);&#xA;        }&#xA;&#xA;        @Override&#xA;        public String toString() {&#xA;            return "AVHWContextInfo[" &#x2B;&#xA;                    "hwConfig=" &#x2B; this.hwConfig &#x2B; ", " &#x2B;&#xA;                    "hwContext=" &#x2B; this.hwContext &#x2B; &#x27;]&#x27;;&#xA;        }&#xA;&#xA;    }&#xA;&#xA;    public static final class AVTestFrames {&#xA;&#xA;        private AVTestFrames() {&#xA;&#xA;        }&#xA;&#xA;        static {&#xA;            InputStream inputStream = null;&#xA;            try {&#xA;                inputStream = AVTestFrames.class.getClassLoader().getResourceAsStream("h264_test_key_frame.txt");&#xA;                final byte[] h264TestFrameBuffer = inputStream == null ? new byte[0] : inputStream.readAllBytes();&#xA;                final String h264TestFrame = new String(h264TestFrameBuffer, StandardCharsets.UTF_8);&#xA;                AVTestFrames.h264KeyTestFrame = HexUtil.unhexlify(h264TestFrame);&#xA;            } catch (final IOException e) {&#xA;                Logger.error(e, "Could not parse test frame");&#xA;            } finally {&#xA;                if (inputStream != null) {&#xA;                    try {&#xA;                        inputStream.close();&#xA;                        inputStream = null;&#xA;                    } catch (final IOException e) {&#xA;                        Logger.error(e, "Could not close test frame input stream");&#xA;                    }&#xA;                }&#xA;            }&#xA;        }&#xA;&#xA;        public static byte[] h264KeyTestFrame;&#xA;    }&#xA;}&#xA;</boolean>

    &#xA;

    The build gradle of the project looks like this

    &#xA;

    plugins {&#xA;    id &#x27;application&#x27;&#xA;    id &#x27;org.openjfx.javafxplugin&#x27; version &#x27;0.0.13&#x27;&#xA;}&#xA;&#xA;group &#x27;com.test.example&#x27;&#xA;version &#x27;1.0.0&#x27;&#xA;&#xA;repositories {&#xA;    mavenCentral()&#xA;    mavenLocal()&#xA;    maven { url &#x27;https://jitpack.io&#x27; }&#xA;}&#xA;&#xA;dependencies {&#xA;    implementation group: &#x27;org.bytedeco&#x27;, name: &#x27;javacv-platform&#x27;, version: &#x27;1.5.8&#x27;&#xA;    implementation group: &#x27;com.github.oshi&#x27;, name: &#x27;oshi-core&#x27;, version: &#x27;3.4.3&#x27;&#xA;    implementation &#x27;org.tinylog:tinylog-api:2.1.0&#x27;&#xA;    implementation &#x27;org.tinylog:tinylog-impl:2.1.0&#x27;&#xA;    implementation &#x27;org.jcodec:jcodec:0.2.5&#x27;&#xA;}&#xA;&#xA;test {&#xA;    useJUnitPlatform()&#xA;}&#xA;&#xA;javafx {&#xA;    version = &#x27;17.0.6&#x27;&#xA;    modules = [&#x27;javafx.graphics&#x27;, &#x27;javafx.controls&#x27;, &#x27;javafx.fxml&#x27;, &#x27;javafx.base&#x27;]&#xA;}&#xA;&#xA;mainClassName = &#x27;com.test.example.App&#x27;&#xA;

    &#xA;

  • Call bash function in Java

    16 mai 2023, par ilie alexandru

    I have been using Java with bash in order to make some things easier, some examples :

    &#xA;

    From the main class to call a subclass in order to use bash commands :

    &#xA;

    Main classs :

    &#xA;

        //Checking if the server already has the user or not&#xA;    CheckUser checkUser = new CheckUser();&#xA;    int checuser= checkUser.CheckUserMethod(user);&#xA;    if( 1 != checuser) { // Yoda notation&#xA;&#xA;        //Making the directory for the user&#xA;        File userDirectory = new File(this.directory);&#xA;        userDirectory.mkdir();&#xA;    }&#xA;

    &#xA;

    The class that will call the ".sh" file :

    &#xA;

    public class CheckUser {&#xA;&#xA;protected int CheckUserMethod(String user){&#xA;    try {&#xA;&#xA;        Process p = Runtime.getRuntime().exec(new String[]{"bash", "-c", "cd ~/Final-Year-Spring/src/main/java/query &amp;&amp; ./checkuser.sh " &#x2B; user});&#xA;        BufferedReader srdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));&#xA;        String s =srdInput.readLine();&#xA;        if(s==null){&#xA;            return 0;&#xA;        }else {&#xA;            return Integer.parseInt(s);&#xA;        }&#xA;    }catch (Exception e){&#xA;        throw new RuntimeException(e);&#xA;    }&#xA;}&#xA;

    &#xA;

    &#xA;

    The bash file :

    &#xA;

    #!/bin/bash&#xA;&#xA;# shellcheck disable=SC2237&#xA;if ! [ -z "$1" ]&#xA;then&#xA;  cd ~/Final-Year-Spring/maps/ &amp;&amp; find "$1" -maxdepth 0 -type d -printf 1&#xA;fi&#xA;

    &#xA;

    Now you have a context.

    &#xA;

    I am trying to call a bash file that will execute a ffmpeg command. For instance, the same command when I am using the terminal :

    &#xA;

    ffmpeg -ss 00:00:00.75 -to 00:00:00.93 -i ~/IdeaProjects/Final-Year-Spring/datassets/Alex/check/5535415699068794046/00009.mp4 -ss 00:00:01.71 -to 00:00:01.82 -i ~/IdeaProjects/Final-Year-Spring/datassets/Alex/check/5535415699068794046/00009.mp4 ~/IdeaProjects/Final-Year-Spring/maps/output.mp4S&#xA;

    &#xA;

    Also a screenshot with the command in the cli :

    &#xA;

    enter image description here

    &#xA;

    The result of the cli command :

    &#xA;

    enter image description here

    &#xA;

    Now I am trying to do the same thing for multiple videos using Java and Bash.

    &#xA;

    The class that will create the input and the time :

    &#xA;

    public String CreateNewVideoMethod()

    &#xA;

    ArrayList<string> arrayList = new ArrayList&lt;>();&#xA;&#xA;MainSearch mainSearch = new MainSearch(this.array, this.search);&#xA;HashMap>>> map = new HashMap&lt;>();&#xA;        map = mainSearch.SearchInVideous();&#xA;&#xA;&#xA;HashMap>> file = new HashMap&lt;>();&#xA;file=map.get(this.array.get(1));&#xA;&#xA;file.forEach((k,v)->{&#xA;    StringBuilder stringBuilder = new StringBuilder(this.defaultpth);&#xA;    stringBuilder.append("/")&#xA;            .append(this.array.get(0))&#xA;            .append("/")&#xA;            .append(this.array.get(1))&#xA;            .append("/")&#xA;            .append(k)&#xA;            .append("/")&#xA;            .append("InfoVideo.txt");&#xA;&#xA;    GetVideoPath getVideoPath = new GetVideoPath();&#xA;    String videoPath = getVideoPath.GetVideoPathMethod(stringBuilder);&#xA;&#xA;    v.forEach((k1,v1)->{ // iterate though the words&#xA;        v1.forEach((k2,v2)->{ // iterate though the times&#xA;&#xA;            String doubleAsStringForKey = String.valueOf(k2);&#xA;            String[] arr = doubleAsStringForKey.split("\\.");&#xA;&#xA;            String doubleASStringForValue = String.valueOf(v2);&#xA;            String[] arr2 = doubleASStringForValue.split("\\.");&#xA;&#xA;            if(k2>10){&#xA;&#xA;                StringBuilder stringBuilder1 = new StringBuilder();&#xA;                stringBuilder1.append(" -ss ")&#xA;                        .append("00:00:")&#xA;                        .append(arr[0])&#xA;                        .append(".")&#xA;                        .append(arr[1])&#xA;                        .append(" -to ")&#xA;                        .append(" 00:00:")&#xA;                        .append(arr2[0])&#xA;                        .append(".")&#xA;                        .append(arr2[1])&#xA;                        .append(" -i ")&#xA;                        .append(videoPath);&#xA;                arrayList.add(String.valueOf(stringBuilder1));&#xA;            }&#xA;                else{&#xA;&#xA;                    StringBuilder stringBuilder1 = new StringBuilder();&#xA;                    stringBuilder1.append(" -ss ")&#xA;                            .append("00:00:0")&#xA;                            .append(arr[0])&#xA;                            .append(".")&#xA;                            .append(arr[1])&#xA;                            .append(" -to ")&#xA;                            .append("00:00:0")&#xA;                            .append(arr2[0])&#xA;                            .append(".")&#xA;                            .append(arr2[1])&#xA;                            .append(" -i ")&#xA;                            .append(videoPath);&#xA;                    arrayList.add(String.valueOf(stringBuilder1));&#xA;                }&#xA;&#xA;        });&#xA;    });&#xA;&#xA;});&#xA;&#xA;BashFIleForCreatingNewVideo bashFIleForCreatingNewVideo = new BashFIleForCreatingNewVideo();&#xA;bashFIleForCreatingNewVideo.BashFileForCreatingNewVideo(arrayList);&#xA;</string>

    &#xA;

    The class that must call the ".sh" file :

    &#xA;

    public class BashFIleForCreatingNewVideo {&#xA;&#xA;    protected String BashFileForCreatingNewVideo(ArrayList<string> arrayList){&#xA;        try {&#xA;&#xA;        StringBuilder stringBuilder = new StringBuilder();&#xA;&#xA;        for(String str : arrayList){&#xA;            stringBuilder.append(str);&#xA;        }&#xA;        Process p = Runtime.getRuntime().exec(new String[]{"bash", "-c", "cd ~/IdeaProjects/Final-Year-Spring/src/main/java/com/FinalYearProjectServer/Get_Requests/CreateNewVideo &amp;&amp; ./createNewVideo.sh ", String.valueOf(stringBuilder), String.valueOf(arrayList.size()-1), "./maps/outputstream.mp4"});&#xA;        BufferedReader srdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));&#xA;        String s =srdInput.readLine();&#xA;&#xA;        if(s==null){&#xA;            return "Error";&#xA;        }else {&#xA;            System.out.println(s);&#xA;            return s;&#xA;        }&#xA;&#xA;        } catch (IOException e) {&#xA;            throw new RuntimeException(e);&#xA;        }&#xA;&#xA;    }&#xA;}&#xA;</string>

    &#xA;

    The script file :

    &#xA;

    #!/bin/bash&#xA;&#xA;arr=( "$@" )&#xA;&#xA;echo "${arr[*]}"&#xA;&#xA;ffmpeg "${arr[0]}" -filter_complex concat=n="${arr[1]}":v=1:a=1 "${arr[2]}"&#xA;

    &#xA;

    What is passed to the script, small exaple, this is a string :

    &#xA;

     -ss 00:00:00.75 -to 00:00:00.93 -i ~/IdeaProjects/Final-Year-Spring/datassets/Alex/check/5535415699068794046/00009.mp4 -ss 00:00:01.71 -to 00:00:01.82 -i ~/IdeaProjects/Final-Year-Spring/datassets/Alex/check/5535415699068794046/00009.mp4 -ss 00:00:00.09 -to 00:00:00.34 -i ~/IdeaProjects/Final-Year-Spring/datassets/Alex/check/5535415699068794046/00027.mp4&#xA;

    &#xA;

    The next parameter is the number of videos that must concatenate and the last parameter is where the output must be.

    &#xA;

    My problem is the Bash file is not executing even the echo command or doing something. Do you have any suggestion, because I thing is about the way of how I am passing the array to the Bash file.

    &#xA;

    Ok so I am trying to use ProcessBuilder :

    &#xA;

            String[] command = {"bash","ffmpeg", String.valueOf(stringBuilder), "-filter_complex concat=n="&#x2B;String.valueOf(arrayList.size()-1)&#x2B;":v=1:a=1", "~/IdeaProjects/Final-Year-Spring/maps/output1.mp4"};&#xA;        ProcessBuilder p = new ProcessBuilder(command);&#xA;        Process p2 = p.start();&#xA;        BufferedReader srdInput;&#xA;        srdInput = new BufferedReader(new InputStreamReader(p2.getInputStream()));&#xA;        String s =srdInput.readLine();&#xA;

    &#xA;