Segmentation fault at nvds_obj_enc_finish()

Setup:

• Hardware Platform (Jetson / GPU) Jetson Nano
• DeepStream Version 6.0.1

Issue:
I met an issue: I refer saving a whole image from How to encode multiple images using the same objectMeta inside obj_meta_list - #6 by chinthy2 but the error Segmentation fault at nvds_obj_enc_finish ((NvDsObjEncCtxHandle)ctx);

This is my code:

#include <gst/gst.h>
#include "main.hpp"
#include <time.h>
#include <yaml-cpp/yaml.h>
#include <chrono>
#include "gstnvdsmeta.h"
#include "nvbufsurface.h"
#include "nvds_obj_encode.h"

#include "file_source_bin.hpp"
#include "file_sink_bin.hpp"
#include "rtsp_sink_bin.hpp"
#include "webcam_source_bin.hpp"

Pipeline g_pipeline_program;


void handle_sigint(int sig) {
    if (g_pipeline_program.pipeline) {
        g_print("Caught SIGINT, sending EOS...\n");
        gst_element_send_event(g_pipeline_program.pipeline, gst_event_new_eos());
    }
}

static gchar *
get_absolute_file_path(gchar *cfg_file_path, gchar *file_path)
{
    gchar abs_cfg_path[PATH_MAX + 1];
    gchar *abs_file_path;
    gchar *delim;

    if (file_path && file_path[0] == '/')
    {
        return file_path;
    }

    if (!realpath(cfg_file_path, abs_cfg_path))
    {
        g_free(file_path);
        return NULL;
    }

    // Return absolute path of config file if file_path is NULL.
    if (!file_path)
    {
        abs_file_path = g_strdup(abs_cfg_path);
        return abs_file_path;
    }

    delim = g_strrstr(abs_cfg_path, "/");
    *(delim + 1) = '\0';

    abs_file_path = g_strconcat(abs_cfg_path, file_path, NULL);
    g_free(file_path);

    return abs_file_path;
}

static gboolean
bus_call(G_GNUC_UNUSED GstBus *bus, GstMessage *msg, gpointer data)
{
    GMainLoop *loop = (GMainLoop *)data;
    switch (GST_MESSAGE_TYPE(msg))
    {
    case GST_MESSAGE_EOS:
        g_print("End of stream\n");
        g_main_loop_quit(loop);
        break;
    case GST_MESSAGE_ERROR:
    {
        gchar *debug;
        GError *error;
        gst_message_parse_error(msg, &error, &debug);
        g_printerr("ERROR from element %s: %s\n",
                   GST_OBJECT_NAME(msg->src), error->message);
        if (debug)
            g_printerr("Error details: %s\n", debug);
        g_free(debug);
        g_error_free(error);
        g_main_loop_quit(loop);
        break;
    }
    default:
        break;
    }
    return TRUE;
}

// Pad probe function
static GstPadProbeReturn
nvdsosd_sink_pad_buffer_probe(G_GNUC_UNUSED GstPad *pad,
                              GstPadProbeInfo *info,
                              gpointer ctx)
{
    static int frame_num = 0;
    static time_t start_time = 0;
    static int fps_frame_count = 0;

    GstBuffer *buf = (GstBuffer *) info->data;
    GstMapInfo inmap = GST_MAP_INFO_INIT;
    if (!gst_buffer_map (buf, &inmap, GST_MAP_READ)) {
        GST_ERROR ("input buffer mapinfo failed");
        return GST_PAD_PROBE_OK;
    }
    NvBufSurface *ip_surf = (NvBufSurface *) inmap.data;
    gst_buffer_unmap (buf, &inmap);

    if (start_time == 0)
    {
        start_time = time(NULL);
    }

    frame_num++; // Increment once per batch
    fps_frame_count++; // Increment FPS frame count

    time_t current_time = time(NULL);
    double elapsed_time = difftime(current_time, start_time);

    if (elapsed_time >= 1.0)
    {
        double fps = fps_frame_count / elapsed_time;
        g_print("FPS: %.2f\n", fps);
        fps_frame_count = 0;
        start_time = current_time;
    }

    if (frame_num % 1 == 0)
        g_print("Frame number at sink pad of nvdsosd: %d\n", frame_num);

    NvDsBatchMeta *batch_meta = gst_buffer_get_nvds_batch_meta(buf);
    if (!batch_meta)
        return GST_PAD_PROBE_OK;

    // Map to store colors for each object_id and maintain a list for recent IDs
    static GHashTable *color_map = NULL;
    static GQueue *recent_ids = NULL;
    if (!color_map)
    {
        color_map = g_hash_table_new(g_int_hash, g_int_equal);
        recent_ids = g_queue_new();
    }

    for (NvDsMetaList *frame_list = batch_meta->frame_meta_list;
         frame_list != NULL;
         frame_list = frame_list->next)
    {
        NvDsFrameMeta *frame_meta = (NvDsFrameMeta *)(frame_list->data);
        if (!frame_meta || !frame_meta->obj_meta_list)
            continue;

        NvDsDisplayMeta *display_meta = nvds_acquire_display_meta_from_pool(batch_meta);
        if (!display_meta)
            continue;
        // gboolean save_image = FALSE;
        for (NvDsMetaList *obj_list = frame_meta->obj_meta_list;
             obj_list != NULL;
             obj_list = obj_list->next)
        {
            NvDsObjectMeta *obj_meta = (NvDsObjectMeta *)(obj_list->data);
            if (!obj_meta)
                continue;

            gpointer color_ptr = g_hash_table_lookup(color_map, &(obj_meta->object_id));
            gfloat *color = (gfloat *)color_ptr;
            
            // save_image = TRUE;
            if (!color)
            {
                if (g_queue_get_length(recent_ids) >= 100)
                {
                    gpointer old_id = g_queue_pop_head(recent_ids);
                    g_hash_table_remove(color_map, old_id);
                    g_free(old_id);
                }

                gfloat *new_color = g_new(gfloat, 4);
                new_color[0] = g_random_double(); // Red
                new_color[1] = g_random_double(); // Green
                new_color[2] = g_random_double(); // Blue
                new_color[3] = 1.0;               // Alpha

                gint *id_copy = g_new(gint, 1);
                *id_copy = obj_meta->object_id;
                g_hash_table_insert(color_map, id_copy, new_color);
                g_queue_push_tail(recent_ids, id_copy);
                color = new_color;
            }

            obj_meta->rect_params.border_color.red = color[0];
            obj_meta->rect_params.border_color.green = color[1];
            obj_meta->rect_params.border_color.blue = color[2];
            obj_meta->rect_params.border_color.alpha = color[3];
        }

        nvds_add_display_meta_to_frame(frame_meta, display_meta);

        NvDsObjectMeta newMeta;
        NvDsObjEncUsrArgs userData = { 0 };
        /* To be set by user */
        userData.saveImg = TRUE;
        /* Set if Image scaling Required */
        userData.scaleImg = FALSE;
        userData.scaledWidth = 0;
        userData.scaledHeight = 0;
        /* Preset */
        userData.objNum = 1;
        /* Quality */
        userData.quality = 80;
        newMeta.rect_params.width = frame_meta->source_frame_width;
        newMeta.rect_params.height = frame_meta->source_frame_height;
        newMeta.rect_params.top = 0.0f;
        newMeta.rect_params.left = 0.0f;
        static int i = 1;
        char sbuf[32] = {0};
        sprintf(userData.fileNameImg, "%d.jpg", i++);
        /*Main Function Call */
        g_print("nvds_obj_enc_process before\n");
        nvds_obj_enc_process ((NvDsObjEncCtxHandle)ctx, &userData, ip_surf, &newMeta, frame_meta);
        g_print("nvds_obj_enc_process after\n");
    }
    
    g_print("nvds_obj_enc_finish before\n");
    nvds_obj_enc_finish ((NvDsObjEncCtxHandle)ctx);
    g_print("nvds_obj_enc_finish\n");
    return GST_PAD_PROBE_OK;
}

// Pad probe function
// static GstPadProbeReturn
// nvdsosd_src_pad_buffer_probe(G_GNUC_UNUSED GstPad *pad,
//                               GstPadProbeInfo *info,
//                               gpointer ctx)
// {
//     GstBuffer *buf = (GstBuffer *) info->data;
//     NvDsBatchMeta *batch_meta = gst_buffer_get_nvds_batch_meta (buf);

//     for (NvDsMetaList *frame_list = batch_meta->frame_meta_list;
//         frame_list != NULL;
//         frame_list = frame_list->next)
//    {
//         NvDsFrameMeta *frame_meta = (NvDsFrameMeta *)(frame_list->data);
//         if (!frame_meta || !frame_meta->obj_meta_list)
//             continue;

//         FILE *file;
//         char fileFrameNameString[FILE_NAME_SIZE];
//         NvDsUserMetaList *usrMetaList = frame_meta->frame_user_meta_list;
//         while (usrMetaList != NULL) {
//             NvDsUserMeta *usrMetaData = (NvDsUserMeta *) usrMetaList->data;
//             if (TRUE) 
//             {
//                 // Save image
//                 snprintf (fileFrameNameString, FILE_NAME_SIZE, "frame_%d.jpg", frame_meta->frame_num);
                    
//                 NvDsObjEncOutParams *enc_jpeg_image =
//                     (NvDsObjEncOutParams *) usrMetaData->user_meta_data;

//                 /* Write to File */
//                 file = fopen (fileFrameNameString, "wb");
//                 fwrite (enc_jpeg_image->outBuffer, sizeof (uint8_t),
//                     enc_jpeg_image->outLen, file);
//                 fclose (file);

//                 break;
//             }
//         }
//     }
//     return GST_PAD_PROBE_OK;
// }

static gboolean
set_tracker_properties(GstElement *nvtracker, gchar *tracker_config_file)
{
    gboolean ret = FALSE;
    GError *error = NULL;
    gchar **keys = NULL;
    gchar **key = NULL;
    GKeyFile *key_file = g_key_file_new();

    if (!g_key_file_load_from_file(key_file, tracker_config_file, G_KEY_FILE_NONE,
                                   &error))
    {
        g_printerr("Failed to load config file: %s\n", error->message);
        return FALSE;
    }

    keys = g_key_file_get_keys(key_file, CONFIG_GROUP_TRACKER, NULL, &error);
    CHECK_ERROR(error);

    for (key = keys; *key; key++)
    {
        if (!g_strcmp0(*key, CONFIG_GROUP_TRACKER_WIDTH))
        {
            gint width =
                g_key_file_get_integer(key_file, CONFIG_GROUP_TRACKER,
                                       CONFIG_GROUP_TRACKER_WIDTH, &error);
            CHECK_ERROR(error);
            g_object_set(G_OBJECT(nvtracker), "tracker-width", width, NULL);
        }
        else if (!g_strcmp0(*key, CONFIG_GROUP_TRACKER_HEIGHT))
        {
            gint height =
                g_key_file_get_integer(key_file, CONFIG_GROUP_TRACKER,
                                       CONFIG_GROUP_TRACKER_HEIGHT, &error);
            CHECK_ERROR(error);
            g_object_set(G_OBJECT(nvtracker), "tracker-height", height, NULL);
        }
        else if (!g_strcmp0(*key, CONFIG_GPU_ID))
        {
            guint gpu_id =
                g_key_file_get_integer(key_file, CONFIG_GROUP_TRACKER,
                                       CONFIG_GPU_ID, &error);
            CHECK_ERROR(error);
            g_object_set(G_OBJECT(nvtracker), "gpu_id", gpu_id, NULL);
        }
        else if (!g_strcmp0(*key, CONFIG_GROUP_TRACKER_LL_CONFIG_FILE))
        {
            char *ll_config_file = get_absolute_file_path(tracker_config_file,
                                                          g_key_file_get_string(key_file,
                                                                                CONFIG_GROUP_TRACKER,
                                                                                CONFIG_GROUP_TRACKER_LL_CONFIG_FILE, &error));
            CHECK_ERROR(error);
            g_object_set(G_OBJECT(nvtracker), "ll-config-file", ll_config_file, NULL);
        }
        else if (!g_strcmp0(*key, CONFIG_GROUP_TRACKER_LL_LIB_FILE))
        {
            char *ll_lib_file = get_absolute_file_path(tracker_config_file,
                                                       g_key_file_get_string(key_file,
                                                                             CONFIG_GROUP_TRACKER,
                                                                             CONFIG_GROUP_TRACKER_LL_LIB_FILE, &error));
            CHECK_ERROR(error);
            g_object_set(G_OBJECT(nvtracker), "ll-lib-file", ll_lib_file, NULL);
        }
        else
        {
            g_printerr("Unknown key '%s' for group [%s]", *key,
                       CONFIG_GROUP_TRACKER);
        }
    }

    ret = TRUE;
done:
    if (error)
    {
        g_error_free(error);
    }
    if (keys)
    {
        g_strfreev(keys);
    }
    if (!ret)
    {
        g_printerr("%s failed", __func__);
    }
    return ret;
}

void init_config(Pipeline *g_pipeline_program, string deepstream_config_file_path)
{
    YAML::Node config = YAML::LoadFile(deepstream_config_file_path);

    // This is for source node =================================================
    YAML::Node source = config["source"];
    SrcBin *src_bin = new SrcBin();
    src_bin->bin = gst_bin_new("source-bin");
    src_bin->nvstreammux = gst_element_factory_make("nvstreammux", "nvstream-mux");
    g_object_set(G_OBJECT(src_bin->nvstreammux),
                 "batch-size",
                 1,
                 "width",
                 1920,
                 "height",
                 1080,
                 "batched-push-timeout",
                 40000,
                 NULL);
    gst_bin_add(GST_BIN(src_bin->bin), src_bin->nvstreammux);

    GstPad *srcpad_nvstreamux =
        gst_element_get_static_pad(src_bin->nvstreammux, "src");
    src_bin->ghost_pad = gst_ghost_pad_new("src", srcpad_nvstreamux);
    gst_pad_set_active(src_bin->ghost_pad, TRUE);

    if (!gst_element_add_pad(src_bin->bin, src_bin->ghost_pad))
    {
        g_printerr("Failed to add ghost pad in file source bin\n");
    }

    for (YAML::const_iterator it = source.begin(); it != source.end(); ++it)
    {
        string key = it->first.as<string>();
        if (key == "filesrc")
        {
            FileSrcBin *file_src_bin = new FileSrcBin();
            setup_file_src_bin(file_src_bin, src_bin, it->second["location"].as<string>());
        }
        else if (key == "webcam")
        {
            WebcamSrcBin *webcam_src_bin = new WebcamSrcBin();
            setup_webcam_src_bin(webcam_src_bin, src_bin, it->second["device"].as<string>());
        }
    }
    gst_bin_add(GST_BIN(g_pipeline_program->pipeline), src_bin->bin);
    g_pipeline_program->src_bin = src_bin;
    g_print("Source node initialized\n");
    // End of source node ============================================================

    // This is for process node ======================================================
    ProcessBin *process_bin = new ProcessBin();
    process_bin->bin = gst_bin_new("process-bin");

    // This is for inference
    YAML::Node inference = config["nvinfer"];
    string config_file_path = inference["config-file-path"].as<string>();
    process_bin->nvinfer = gst_element_factory_make("nvinfer", "nv-infer");

    // This is for tracker
    YAML::Node tracker = config["nvtracker"];
    string tracker_config_file_path = tracker["config-file-path"].as<string>();
    process_bin->nvtracker = gst_element_factory_make("nvtracker", "nvtracker");

    // Define the rest of the elements
    process_bin->nvvidconv = gst_element_factory_make("nvvideoconvert", "nvvideo-convert");
    process_bin->nvdsosd = gst_element_factory_make("nvdsosd", "nvdsosd");
    process_bin->nvvidconv2 = gst_element_factory_make("nvvideoconvert", "nvvideo-convert-2");
    process_bin->encoder = gst_element_factory_make("nvv4l2h264enc", "nvv4l2h264enc");

    // Set properties
    g_object_set(G_OBJECT(process_bin->nvinfer), "config-file-path", config_file_path.c_str(), NULL);
    if (!set_tracker_properties(process_bin->nvtracker, (gchar *)tracker_config_file_path.c_str()))
    {
         g_printerr("Failed to set tracker properties. Exiting.\n");
         return;
    }

    gst_bin_add_many(GST_BIN(process_bin->bin),
                     process_bin->nvinfer,
                     process_bin->nvtracker,
                     process_bin->nvvidconv,
                     process_bin->nvdsosd,
                     process_bin->nvvidconv2,
                     process_bin->encoder,
                     NULL);
    gst_element_link_many(process_bin->nvinfer,
                          process_bin->nvtracker,
                          process_bin->nvvidconv,
                          process_bin->nvdsosd,
                          process_bin->nvvidconv2,
                          NULL);
    if (!gst_element_link(process_bin->nvvidconv2, process_bin->encoder))
    {
        g_printerr("Failed to link. Exiting.\n");
        return;
    }


    /*Creat Context for Object Encoding */
    NvDsObjEncCtxHandle obj_ctx_handle = nvds_obj_enc_create_context ();
    if (!obj_ctx_handle) {
        g_print ("Unable to create context\n");
        return;
    }

    // Attach pad probe to the sink pad of nvdsosd
    GstPad *nvdsosd_sink_pad =
        gst_element_get_static_pad(process_bin->nvdsosd, "sink");
    if (!nvdsosd_sink_pad)
    {
        g_printerr("Unable to get nvdsosd sink pad\n");
    }
    else
    {
        gst_pad_add_probe(nvdsosd_sink_pad,
                          GST_PAD_PROBE_TYPE_BUFFER,
                          nvdsosd_sink_pad_buffer_probe,
                          (gpointer) obj_ctx_handle,
                          NULL);
    }
    gst_object_unref(nvdsosd_sink_pad);

    // Attach pad probe to the src pad of nvdsosd
    // GstPad *nvdsosd_src_pad =
    //     gst_element_get_static_pad(process_bin->nvdsosd, "src");
    // if (!nvdsosd_src_pad)
    // {
    //     g_printerr("Unable to get nvdsosd sink pad\n");
    // }
    // else
    // {
    //     gst_pad_add_probe(nvdsosd_src_pad,
    //                       GST_PAD_PROBE_TYPE_BUFFER,
    //                       nvdsosd_src_pad_buffer_probe,
    //                       (gpointer) obj_ctx_handle,
    //                       NULL);
    // }
    // gst_object_unref(nvdsosd_src_pad);

    // Add src ghost pad to process bin
    GstPad *srcpad_encoder = gst_element_get_static_pad(process_bin->encoder, "src");
    process_bin->src_ghost_pad = gst_ghost_pad_new("src", srcpad_encoder);
    gst_pad_set_active(process_bin->src_ghost_pad, TRUE);
    if (!gst_element_add_pad(process_bin->bin, process_bin->src_ghost_pad))
    {
        g_printerr("Failed to add src_ghost_pad to process_bin \n");
    }

    // Add sink ghost pad to process bin
    GstPad *sinkpad_nvinfer = gst_element_get_static_pad(process_bin->nvinfer, "sink");
    process_bin->sink_ghost_pad = gst_ghost_pad_new("sink", sinkpad_nvinfer);
    gst_pad_set_active(process_bin->sink_ghost_pad, TRUE);
    if (!gst_element_add_pad(process_bin->bin, process_bin->sink_ghost_pad))
    {
        g_printerr("Failed to add sink_ghost_pad to process_bin \n");
    }

    gst_bin_add(GST_BIN(g_pipeline_program->pipeline), process_bin->bin);
    g_pipeline_program->process_bin = process_bin;
    g_print("Process node initialized\n");
    // End of process node ==============================================================

    // This is for sink node ============================================================
    SinkBin *sink_bin = new SinkBin();
    sink_bin->bin = gst_bin_new("sink-bin");
    sink_bin->tee = gst_element_factory_make("tee", "tee");

    gst_bin_add(GST_BIN(sink_bin->bin), sink_bin->tee);

    GstPad *sinkpad_tee =
        gst_element_get_static_pad(sink_bin->tee, "sink");
    sink_bin->sink_ghost_pad = gst_ghost_pad_new("sink", sinkpad_tee);
    gst_pad_set_active(sink_bin->sink_ghost_pad, TRUE);

    if (!gst_element_add_pad(sink_bin->bin, sink_bin->sink_ghost_pad))
    {
        g_printerr("Failed to add sink_ghost_pad in sink bin\n");
    }

    YAML::Node sink = config["sink"];
    for (YAML::const_iterator it = sink.begin(); it != sink.end(); ++it)
    {
        string key = it->first.as<string>();
        if (key == "filesink")
        {
            FileSinkBin *file_sink_bin = new FileSinkBin();
            setup_file_sink_bin(file_sink_bin, sink_bin, it->second["location"].as<string>());
        }
        else if (key == "rtsp")
        {
            RTSPSinkBin *rtsp_sink_bin = new RTSPSinkBin();
            setup_rtsp_sink_bin(rtsp_sink_bin, sink_bin, it->second["ip"].as<string>(), it->second["port"].as<int>());
        }
    }
    gst_bin_add(GST_BIN(g_pipeline_program->pipeline), sink_bin->bin);
    g_pipeline_program->sink_bin = sink_bin;
    g_print("Sink node initialized\n");
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        g_printerr("Need syntax: %s <config_pipeline.yml>\n", argv[0]);
        return -1;
    }
    else
    {
        g_print("Using config file: %s\n", argv[1]);
    }

    gst_init(&argc, &argv);


    g_pipeline_program.pipeline = gst_pipeline_new("pipeline-0");


    // Set up the SIGINT handler
    signal(SIGINT, handle_sigint);

    init_config(&g_pipeline_program, argv[1]);

    // Link ghost_pad of source bin vs sink_ghost_pad of process bin
    if (gst_pad_link(g_pipeline_program.src_bin->ghost_pad, g_pipeline_program.process_bin->sink_ghost_pad) != 0)
    {
        g_printerr("Failed to link src_ghost_pad to sink_ghost_pad. Exiting.\n");
    }

    // Link src_ghost_pad of process bin vs sink_ghost_pad of sink bin
    if (gst_pad_link(g_pipeline_program.process_bin->src_ghost_pad, g_pipeline_program.sink_bin->sink_ghost_pad) != 0)
    {
        g_printerr("Failed to link src_ghost_pad to sink_ghost_pad. Exiting.\n");
    }

    GMainLoop *main_loop;
    main_loop = g_main_loop_new(NULL, FALSE);
    GstBus *bus;
    bus = gst_element_get_bus(g_pipeline_program.pipeline);
    G_GNUC_UNUSED guint bus_watch_id = gst_bus_add_watch(bus, bus_call, main_loop);
    gst_object_unref(bus);

    GST_DEBUG_BIN_TO_DOT_FILE(
        GST_BIN(g_pipeline_program.pipeline), GST_DEBUG_GRAPH_SHOW_ALL, "pipeline");

    // Calculate time (seconds) to run the pipeline
    auto start = std::chrono::high_resolution_clock::now();

    // Start playing
    gst_element_set_state(g_pipeline_program.pipeline, GST_STATE_PLAYING);
    g_main_loop_run(main_loop);
    
    /* Destroy context for Object Encoding */
    // nvds_obj_enc_destroy_context (obj_ctx_handle);

    // Free resources
    g_main_loop_unref(main_loop);
    gst_object_unref(bus);
    gst_element_set_state(g_pipeline_program.pipeline, GST_STATE_NULL);
    gst_object_unref(g_pipeline_program.pipeline);

    auto end = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> elapsed = end - start;
    g_print("Time taken to run the pipeline: %f seconds\n", elapsed.count());

    return 0;
}

Output terminal

jetson@jetson-desktop:~/hai/_my-app$ GST_DEBUG=3 ./build/main2 configs/pipeline_config.txt
Using config file: configs/pipeline_config.txt
Source node initialized
Unknown key 'enable-batch-process' for group [tracker]Process node initialized
Sink node initialized
Opening in BLOCKING MODE 
0:00:00.722129232 31605   0x55a39dfb30 WARN                    v4l2 gstv4l2object.c:2388:gst_v4l2_object_add_interlace_mode:0x55a39cec40 Failed to determine interlace mode
0:00:00.722225067 31605   0x55a39dfb30 WARN                    v4l2 gstv4l2object.c:2388:gst_v4l2_object_add_interlace_mode:0x55a39cec40 Failed to determine interlace mode
0:00:00.722285433 31605   0x55a39dfb30 WARN                    v4l2 gstv4l2object.c:2388:gst_v4l2_object_add_interlace_mode:0x55a39cec40 Failed to determine interlace mode
0:00:00.722341944 31605   0x55a39dfb30 WARN                    v4l2 gstv4l2object.c:2388:gst_v4l2_object_add_interlace_mode:0x55a39cec40 Failed to determine interlace mode
0:00:00.722551792 31605   0x55a39dfb30 WARN                    v4l2 gstv4l2object.c:4476:gst_v4l2_object_probe_caps:<nvv4l2h264enc:src> Failed to probe pixel aspect ratio with VIDIOC_CROPCAP: Unknown error -1
Opening in BLOCKING MODE 
0:00:00.835991169 31605   0x55a39dfb30 WARN                    v4l2 gstv4l2object.c:4476:gst_v4l2_object_probe_caps:<nvv4l2-decoder:src> Failed to probe pixel aspect ratio with VIDIOC_CROPCAP: Unknown error -1
0:00:00.836049607 31605   0x55a39dfb30 WARN                    v4l2 gstv4l2object.c:2388:gst_v4l2_object_add_interlace_mode:0x55a360b7e0 Failed to determine interlace mode
0:00:00.836099869 31605   0x55a39dfb30 WARN                    v4l2 gstv4l2object.c:2388:gst_v4l2_object_add_interlace_mode:0x55a360b7e0 Failed to determine interlace mode
0:00:00.836147682 31605   0x55a39dfb30 WARN                    v4l2 gstv4l2object.c:2388:gst_v4l2_object_add_interlace_mode:0x55a360b7e0 Failed to determine interlace mode
0:00:00.836189506 31605   0x55a39dfb30 WARN                    v4l2 gstv4l2object.c:2388:gst_v4l2_object_add_interlace_mode:0x55a360b7e0 Failed to determine interlace mode
0:00:00.836237059 31605   0x55a39dfb30 WARN                    v4l2 gstv4l2object.c:2388:gst_v4l2_object_add_interlace_mode:0x55a360b7e0 Failed to determine interlace mode
gstnvtracker: Loading low-level lib at //home/jetson/hai/_my-app/bytetrack/libByteTracker.so
[BYTETrack Initialized]
gstnvtracker: Batch processing is OFF
gstnvtracker: Past frame output is OFF
0:00:00.883882241 31605   0x55a39dfb30 WARN                 nvinfer gstnvinfer.cpp:635:gst_nvinfer_logger:<nv-infer> NvDsInferContext[UID 1]: Warning from NvDsInferContextImpl::initialize() <nvdsinfer_context_impl.cpp:1161> [UID = 1]: Warning, OpenCV has been deprecated. Using NMS for clustering instead of cv::groupRectangles with topK = 20 and NMS Threshold = 0.5
0:00:10.163062063 31605   0x55a39dfb30 INFO                 nvinfer gstnvinfer.cpp:638:gst_nvinfer_logger:<nv-infer> NvDsInferContext[UID 1]: Info from NvDsInferContextImpl::deserializeEngineAndBackend() <nvdsinfer_context_impl.cpp:1900> [UID = 1]: deserialized trt engine from :/home/jetson/hai/_my-app/yolov8/models/yolo11n_b1_gpu0_fp16.engine
INFO: [Implicit Engine Info]: layers num: 2
0   INPUT  kFLOAT input           3x640x640       
1   OUTPUT kFLOAT output          8400x6          

0:00:10.164341620 31605   0x55a39dfb30 INFO                 nvinfer gstnvinfer.cpp:638:gst_nvinfer_logger:<nv-infer> NvDsInferContext[UID 1]: Info from NvDsInferContextImpl::generateBackendContext() <nvdsinfer_context_impl.cpp:2004> [UID = 1]: Use deserialized engine model: /home/jetson/hai/_my-app/yolov8/models/yolo11n_b1_gpu0_fp16.engine
0:00:10.411164525 31605   0x55a39dfb30 INFO                 nvinfer gstnvinfer_impl.cpp:313:notifyLoadModelStatus:<nv-infer> [UID 1]: Load new model:configs/config_infer_primary_yoloV8.txt sucessfully
0:00:10.411832872 31605   0x55a39dfb30 WARN                 basesrc gstbasesrc.c:3583:gst_base_src_start_complete:<file-source> pad not activated yet
0:00:10.414299536 31605   0x55a3918320 WARN                 qtdemux qtdemux_types.c:233:qtdemux_type_get: unknown QuickTime node type sgpd
0:00:10.414348704 31605   0x55a3918320 WARN                 qtdemux qtdemux_types.c:233:qtdemux_type_get: unknown QuickTime node type sbgp
0:00:10.414375058 31605   0x55a3918320 WARN                 qtdemux qtdemux_types.c:233:qtdemux_type_get: unknown QuickTime node type pasp
0:00:10.414413965 31605   0x55a3918320 WARN                 qtdemux qtdemux.c:3031:qtdemux_parse_trex:<demuxer> failed to find fragment defaults for stream 1
0:00:10.414603813 31605   0x55a3918320 WARN                 qtdemux qtdemux.c:3031:qtdemux_parse_trex:<demuxer> failed to find fragment defaults for stream 2
Failed to link demuxer and parser.
Demuxer and parser linked.
NvMMLiteOpen : Block : BlockType = 261 
NVMEDIA: Reading vendor.tegra.display-size : status: 6 
NvMMLiteBlockCreate : Block : BlockType = 261 
0:00:10.526396957 31605   0x55a3918320 WARN                    v4l2 gstv4l2object.c:4476:gst_v4l2_object_probe_caps:<nvv4l2-decoder:src> Failed to probe pixel aspect ratio with VIDIOC_CROPCAP: Unknown error -1
0:00:10.526527481 31605   0x55a3918320 WARN                    v4l2 gstv4l2object.c:2388:gst_v4l2_object_add_interlace_mode:0x55a360b7e0 Failed to determine interlace mode
0:00:10.526590138 31605   0x55a3918320 WARN                    v4l2 gstv4l2object.c:2388:gst_v4l2_object_add_interlace_mode:0x55a360b7e0 Failed to determine interlace mode
0:00:10.526651129 31605   0x55a3918320 WARN                    v4l2 gstv4l2object.c:2388:gst_v4l2_object_add_interlace_mode:0x55a360b7e0 Failed to determine interlace mode
0:00:10.526706391 31605   0x55a3918320 WARN                    v4l2 gstv4l2object.c:2388:gst_v4l2_object_add_interlace_mode:0x55a360b7e0 Failed to determine interlace mode
0:00:10.526763527 31605   0x55a3918320 WARN                    v4l2 gstv4l2object.c:2388:gst_v4l2_object_add_interlace_mode:0x55a360b7e0 Failed to determine interlace mode
NvMMLiteOpen : Block : BlockType = 4 
===== NVMEDIA: NVENC =====
NvMMLiteBlockCreate : Block : BlockType = 4 
0:00:10.540400522 31605   0x55a3918320 WARN          v4l2bufferpool gstv4l2bufferpool.c:1087:gst_v4l2_buffer_pool_start:<nvv4l2h264enc:pool:src> Uncertain or not enough buffers, enabling copy threshold
0:00:10.541566066 31605   0x55a3918320 WARN            v4l2videodec gstv4l2videodec.c:1755:gst_v4l2_video_dec_decide_allocation:<nvv4l2-decoder> Duration invalid, not setting latency
0:00:10.544840611 31605   0x55a3918320 WARN          v4l2bufferpool gstv4l2bufferpool.c:1087:gst_v4l2_buffer_pool_start:<nvv4l2-decoder:pool:src> Uncertain or not enough buffers, enabling copy threshold
0:00:10.562903997 31605   0x7f2000b630 WARN          v4l2bufferpool gstv4l2bufferpool.c:1536:gst_v4l2_buffer_pool_dqbuf:<nvv4l2-decoder:pool:src> Driver should never set v4l2_buffer.field to ANY
Frame number at sink pad of nvdsosd: 1
nvds_obj_enc_process before
nvds_obj_enc_process after
nvds_obj_enc_finish before
Segmentation fault (core dumped)

Can you do a preliminary analysis with gdb first?

$gdb --args <your command>
$r
#after the crash
$bt

This is my output, please check it. Thanks

jetson@jetson-desktop:~/hai/_my-app$ GST_DEBUG=3 gdb --args ./build/main2 configs/pipeline_config.txt
GNU gdb (Ubuntu 8.1.1-0ubuntu1) 8.1.1
Copyright (C) 2018 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "aarch64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./build/main2...(no debugging symbols found)...done.
(gdb) r
Starting program: /home/jetson/hai/_my-app/build/main2 configs/pipeline_config.txt
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/aarch64-linux-gnu/libthread_db.so.1".
[New Thread 0x7fb3cac080 (LWP 12223)]
[New Thread 0x7fb34ab080 (LWP 12224)]
[New Thread 0x7fb2caa080 (LWP 12225)]
[New Thread 0x7fb24a9080 (LWP 12226)]
[New Thread 0x7f9ffff080 (LWP 12227)]
Using config file: configs/pipeline_config.txt
Source node initialized
Unknown key 'enable-batch-process' for group [tracker]Process node initialized
Sink node initialized
Opening in BLOCKING MODE 
0:00:02.684298377 12209   0x5555c91b30 WARN                    v4l2 gstv4l2object.c:2388:gst_v4l2_object_add_interlace_mode:0x5555c80800 Failed to determine interlace mode
0:00:02.684403692 12209   0x5555c91b30 WARN                    v4l2 gstv4l2object.c:2388:gst_v4l2_object_add_interlace_mode:0x5555c80800 Failed to determine interlace mode
0:00:02.684454943 12209   0x5555c91b30 WARN                    v4l2 gstv4l2object.c:2388:gst_v4l2_object_add_interlace_mode:0x5555c80800 Failed to determine interlace mode
0:00:02.684500049 12209   0x5555c91b30 WARN                    v4l2 gstv4l2object.c:2388:gst_v4l2_object_add_interlace_mode:0x5555c80800 Failed to determine interlace mode
0:00:02.684709324 12209   0x5555c91b30 WARN                    v4l2 gstv4l2object.c:4476:gst_v4l2_object_probe_caps:<nvv4l2h264enc:src> Failed to probe pixel aspect ratio with VIDIOC_CROPCAP: Unknown error -1
[New Thread 0x7f89859080 (LWP 12248)]
Opening in BLOCKING MODE 
0:00:03.321272059 12209   0x5555c91b30 WARN                    v4l2 gstv4l2object.c:4476:gst_v4l2_object_probe_caps:<nvv4l2-decoder:src> Failed to probe pixel aspect ratio with VIDIOC_CROPCAP: Unknown error -1
0:00:03.321332425 12209   0x5555c91b30 WARN                    v4l2 gstv4l2object.c:2388:gst_v4l2_object_add_interlace_mode:0x55558bc970 Failed to determine interlace mode
0:00:03.321426489 12209   0x5555c91b30 WARN                    v4l2 gstv4l2object.c:2388:gst_v4l2_object_add_interlace_mode:0x55558bc970 Failed to determine interlace mode
0:00:03.321474980 12209   0x5555c91b30 WARN                    v4l2 gstv4l2object.c:2388:gst_v4l2_object_add_interlace_mode:0x55558bc970 Failed to determine interlace mode
0:00:03.321511543 12209   0x5555c91b30 WARN                    v4l2 gstv4l2object.c:2388:gst_v4l2_object_add_interlace_mode:0x55558bc970 Failed to determine interlace mode
0:00:03.321553263 12209   0x5555c91b30 WARN                    v4l2 gstv4l2object.c:2388:gst_v4l2_object_add_interlace_mode:0x55558bc970 Failed to determine interlace mode
[New Thread 0x7f88ee9080 (LWP 12249)]
gstnvtracker: Loading low-level lib at //home/jetson/hai/_my-app/bytetrack/libByteTracker.so
[BYTETrack Initialized]
gstnvtracker: Batch processing is OFF
gstnvtracker: Past frame output is OFF
[New Thread 0x7f83fff080 (LWP 12250)]
0:00:03.743809639 12209   0x5555c91b30 WARN                 nvinfer gstnvinfer.cpp:635:gst_nvinfer_logger:<nv-infer> NvDsInferContext[UID 1]: Warning from NvDsInferContextImpl::initialize() <nvdsinfer_context_impl.cpp:1161> [UID = 1]: Warning, OpenCV has been deprecated. Using NMS for clustering instead of cv::groupRectangles with topK = 20 and NMS Threshold = 0.5
0:00:14.756361830 12209   0x5555c91b30 INFO                 nvinfer gstnvinfer.cpp:638:gst_nvinfer_logger:<nv-infer> NvDsInferContext[UID 1]: Info from NvDsInferContextImpl::deserializeEngineAndBackend() <nvdsinfer_context_impl.cpp:1900> [UID = 1]: deserialized trt engine from :/home/jetson/hai/_my-app/yolov8/models/yolo11n_b1_gpu0_fp16.engine
INFO: [Implicit Engine Info]: layers num: 2
0   INPUT  kFLOAT input           3x640x640       
1   OUTPUT kFLOAT output          8400x6          

0:00:14.757646755 12209   0x5555c91b30 INFO                 nvinfer gstnvinfer.cpp:638:gst_nvinfer_logger:<nv-infer> NvDsInferContext[UID 1]: Info from NvDsInferContextImpl::generateBackendContext() <nvdsinfer_context_impl.cpp:2004> [UID = 1]: Use deserialized engine model: /home/jetson/hai/_my-app/yolov8/models/yolo11n_b1_gpu0_fp16.engine
[New Thread 0x7f69af6080 (LWP 12287)]
[New Thread 0x7f4f306080 (LWP 12288)]
[New Thread 0x7f4eb05080 (LWP 12289)]
0:00:15.065408090 12209   0x5555c91b30 INFO                 nvinfer gstnvinfer_impl.cpp:313:notifyLoadModelStatus:<nv-infer> [UID 1]: Load new model:configs/config_infer_primary_yoloV8.txt sucessfully
0:00:15.065854663 12209   0x5555c91b30 WARN                 basesrc gstbasesrc.c:3583:gst_base_src_start_complete:<file-source> pad not activated yet
[New Thread 0x7f4e304080 (LWP 12290)]
0:00:15.070436743 12209   0x5555bc9320 WARN                 qtdemux qtdemux_types.c:233:qtdemux_type_get: unknown QuickTime node type sgpd
0:00:15.070497994 12209   0x5555bc9320 WARN                 qtdemux qtdemux_types.c:233:qtdemux_type_get: unknown QuickTime node type sbgp
0:00:15.070531485 12209   0x5555bc9320 WARN                 qtdemux qtdemux_types.c:233:qtdemux_type_get: unknown QuickTime node type pasp
0:00:15.070622320 12209   0x5555bc9320 WARN                 qtdemux qtdemux.c:3031:qtdemux_parse_trex:<demuxer> failed to find fragment defaults for stream 1
0:00:15.070778886 12209   0x5555bc9320 WARN                 qtdemux qtdemux.c:3031:qtdemux_parse_trex:<demuxer> failed to find fragment defaults for stream 2
Failed to link demuxer and parser.
Demuxer and parser linked.
NvMMLiteOpen : Block : BlockType = 261 
NVMEDIA: Reading vendor.tegra.display-size : status: 6 
[New Thread 0x7f4db03080 (LWP 12291)]
[New Thread 0x7f4d302080 (LWP 12292)]
[New Thread 0x7f4cb01080 (LWP 12293)]
NvMMLiteBlockCreate : Block : BlockType = 261 
[New Thread 0x7f3ffff080 (LWP 12294)]
0:00:15.187003695 12209   0x5555bc9320 WARN                    v4l2 gstv4l2object.c:4476:gst_v4l2_object_probe_caps:<nvv4l2-decoder:src> Failed to probe pixel aspect ratio with VIDIOC_CROPCAP: Unknown error -1
0:00:15.187062499 12209   0x5555bc9320 WARN                    v4l2 gstv4l2object.c:2388:gst_v4l2_object_add_interlace_mode:0x55558bc970 Failed to determine interlace mode
0:00:15.187100364 12209   0x5555bc9320 WARN                    v4l2 gstv4l2object.c:2388:gst_v4l2_object_add_interlace_mode:0x55558bc970 Failed to determine interlace mode
0:00:15.187135625 12209   0x5555bc9320 WARN                    v4l2 gstv4l2object.c:2388:gst_v4l2_object_add_interlace_mode:0x55558bc970 Failed to determine interlace mode
0:00:15.187167084 12209   0x5555bc9320 WARN                    v4l2 gstv4l2object.c:2388:gst_v4l2_object_add_interlace_mode:0x55558bc970 Failed to determine interlace mode
0:00:15.187197554 12209   0x5555bc9320 WARN                    v4l2 gstv4l2object.c:2388:gst_v4l2_object_add_interlace_mode:0x55558bc970 Failed to determine interlace mode
NvMMLiteOpen : Block : BlockType = 4 
===== NVMEDIA: NVENC =====
NvMMLiteBlockCreate : Block : BlockType = 4 
0:00:15.200771656 12209   0x5555bc9320 WARN          v4l2bufferpool gstv4l2bufferpool.c:1087:gst_v4l2_buffer_pool_start:<nvv4l2h264enc:pool:src> Uncertain or not enough buffers, enabling copy threshold
[New Thread 0x7f3dd19080 (LWP 12295)]
0:00:15.202905140 12209   0x5555bc9320 WARN            v4l2videodec gstv4l2videodec.c:1755:gst_v4l2_video_dec_decide_allocation:<nvv4l2-decoder> Duration invalid, not setting latency
0:00:15.203308639 12209   0x5555bc9320 WARN          v4l2bufferpool gstv4l2bufferpool.c:1087:gst_v4l2_buffer_pool_start:<nvv4l2-decoder:pool:src> Uncertain or not enough buffers, enabling copy threshold
[New Thread 0x7f3d518080 (LWP 12296)]
0:00:15.220842985 12209   0x7f4400b630 WARN          v4l2bufferpool gstv4l2bufferpool.c:1536:gst_v4l2_buffer_pool_dqbuf:<nvv4l2-decoder:pool:src> Driver should never set v4l2_buffer.field to ANY
[New Thread 0x7f3cd17080 (LWP 12297)]
[New Thread 0x7f1baff080 (LWP 12316)]
Frame number at sink pad of nvdsosd: 1
nvds_obj_enc_process before
[New Thread 0x7f1b2fe080 (LWP 12317)]
nvds_obj_enc_process after
nvds_obj_enc_finish before

Thread 22 "pool" received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7f1b2fe080 (LWP 12317)]
0x0000007f899843fc in jpeg_write_raw_data () from /usr/lib/aarch64-linux-gnu/tegra/libnvjpeg.so
(gdb) bt
#0  0x0000007f899843fc in jpeg_write_raw_data () at /usr/lib/aarch64-linux-gnu/tegra/libnvjpeg.so
#1  0x0000007fb7b91100 in  () at /opt/nvidia/deepstream/deepstream-6.0/lib/libnvds_batch_jpegenc.so
#2  0x0000007fb7d08558 in  () at /usr/lib/aarch64-linux-gnu/libglib-2.0.so.0
#3  0x0000007fb7d9ce80 in  () at /usr/lib/aarch64-linux-gnu/libglib-2.0.so.0

@yuweiw please check it! Thank you very much

Let’s first confirm that there is no problem with our sample. Could you try to use our deepstream-image-meta-test to save the whole image first?
You can refer to the modified source code below. It can save the whole image with bbox.
deepstream_image_meta_test.c (21.4 KB)

Your code is fine, saving the whole frame.
This code crashes after frame 1, but before the modification, it was the same, only able to run frame 1. Is there a problem with my Jetson?

jetson@jetson-desktop:/opt/nvidia/deepstream/deepstream/sources/apps/sample_apps/deepstream-image-meta-test$ sudo ./deepstream-image-meta-test file:///opt/nvidia/deepstream/deepstream/samples/streams/sample_720p.mp4
Now playing: file:///opt/nvidia/deepstream/deepstream/samples/streams/sample_720p.mp4,
0:00:00.207198537  1122   0x5579b60010 WARN                 nvinfer gstnvinfer.cpp:635:gst_nvinfer_logger:<primary-nvinference-engine> NvDsInferContext[UID 1]: Warning from NvDsInferContextImpl::initialize() <nvdsinfer_context_impl.cpp:1161> [UID = 1]: Warning, OpenCV has been deprecated. Using NMS for clustering instead of cv::groupRectangles with topK = 20 and NMS Threshold = 0.5
0:00:00.208042668  1122   0x5579b60010 INFO                 nvinfer gstnvinfer.cpp:638:gst_nvinfer_logger:<primary-nvinference-engine> NvDsInferContext[UID 1]: Info from NvDsInferContextImpl::buildModel() <nvdsinfer_context_impl.cpp:1914> [UID = 1]: Trying to create engine from model files
0:01:11.484014345  1122   0x5579b60010 INFO                 nvinfer gstnvinfer.cpp:638:gst_nvinfer_logger:<primary-nvinference-engine> NvDsInferContext[UID 1]: Info from NvDsInferContextImpl::buildModel() <nvdsinfer_context_impl.cpp:1947> [UID = 1]: serialize cuda engine to file: /opt/nvidia/deepstream/deepstream-6.0/samples/models/Primary_Detector/resnet10.caffemodel_b1_gpu0_fp16.engine successfully
INFO: [Implicit Engine Info]: layers num: 3
0   INPUT  kFLOAT input_1         3x368x640       
1   OUTPUT kFLOAT conv2d_bbox     16x23x40        
2   OUTPUT kFLOAT conv2d_cov/Sigmoid 4x23x40         

0:01:11.617077882  1122   0x5579b60010 INFO                 nvinfer gstnvinfer_impl.cpp:313:notifyLoadModelStatus:<primary-nvinference-engine> [UID 1]: Load new model:ds_image_meta_pgie_config.txt sucessfully
Running...
Opening in BLOCKING MODE 
NvMMLiteOpen : Block : BlockType = 261 
NVMEDIA: Reading vendor.tegra.display-size : status: 6 
NvMMLiteBlockCreate : Block : BlockType = 261 
Frame Number = 1 Number of objects = 9 Vehicle Count = 6 Person Count = 3
0:01:13.125016539  1122   0x557981fb20 WARN                 nvinfer gstnvinfer.cpp:2288:gst_nvinfer_output_loop:<primary-nvinference-engine> error: Internal data stream error.
0:01:13.125065394  1122   0x557981fb20 WARN                 nvinfer gstnvinfer.cpp:2288:gst_nvinfer_output_loop:<primary-nvinference-engine> error: streaming stopped, reason error (-5)
ERROR from element primary-nvinference-engine: Internal data stream error.
Error details: /dvs/git/dirty/git-master_linux/deepstream/sdk/src/gst-plugins/gst-nvinfer/gstnvinfer.cpp(2288): gst_nvinfer_output_loop (): /GstPipeline:ds-image-meta-test-pipeline/GstNvInfer:primary-nvinference-engine:
streaming stopped, reason error (-5)
Exiting...

This is my CMakeList file, I think it ok:

# add_subdirectory(yaml-cpp)

cmake_minimum_required(VERSION 3.2.1)

project(MyGStreamerProject LANGUAGES CXX)

# Set C++ standard
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# Define DeepStream version and paths
set(DEEPSTREAM_VERSION 6.0)
set(DEEPSTREAM_DIR /opt/nvidia/deepstream/deepstream-${DEEPSTREAM_VERSION})
set(DEEPSTREAM_LIBRARIES_DIR ${DEEPSTREAM_DIR}/lib)
set(DEEPSTREAM_SOURCES_INCLUDES_DIR ${DEEPSTREAM_DIR}/sources/includes)
set(DEEPSTREAM_APPS_COMMON_INCLUDES_DIR ${DEEPSTREAM_DIR}/sources/apps/apps-common/includes)
set(CUDA_TOOLKIT_ROOT_DIR /usr/local/cuda-10.2)
set(CUDA_INCLUDE_DIRS ${CUDA_TOOLKIT_ROOT_DIR}/targets/aarch64-linux/include)
set(CUDA_LIBRARIES ${CUDA_TOOLKIT_ROOT_DIR}/targets/aarch64-linux/lib/libcudart.so)

# Find required packages
find_package(PkgConfig REQUIRED)
# set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "/usr/local/include/yaml-cpp")
# find_package(yaml-cpp REQUIRED)

pkg_check_modules(GST REQUIRED gstreamer-1.0)
pkg_check_modules(GLIB REQUIRED glib-2.0)
pkg_check_modules(GSTRTSP REQUIRED gstreamer-rtsp-server-1.0)

# Display configuration details
message(STATUS "GStreamer RTSP Server version: ${GSTRTSP_VERSION}")
message(STATUS "GStreamer RTSP Server libraries: ${GSTRTSP_LIBRARIES}")
message(STATUS "GStreamer RTSP Server include dirs: ${GSTRTSP_INCLUDE_DIRS}")
message(STATUS "DEEPSTREAM libraries dir: ${DEEPSTREAM_LIBRARIES_DIR}")
message(STATUS "DEEPSTREAM include dirs: ${DEEPSTREAM_SOURCES_INCLUDES_DIR}")
message(STATUS "DEEPSTREAM app common include dirs: ${DEEPSTREAM_APPS_COMMON_INCLUDES_DIR}")

# Include directories
include_directories(
    # ${YAML_CPP_INCLUDE_DIR}
    ${CMAKE_SOURCE_DIR}/utils
    ${CMAKE_SOURCE_DIR}
    ${GST_INCLUDE_DIRS}
    ${GLIB_INCLUDE_DIRS}
    ${DEEPSTREAM_SOURCES_INCLUDES_DIR}
    ${DEEPSTREAM_APPS_COMMON_INCLUDES_DIR}
    ${GSTRTSP_INCLUDE_DIRS}
    ${CUDA_INCLUDE_DIRS}
)

# Source files
file(GLOB_RECURSE SRC_FILES
    main2.cpp
    utils/*.cpp
)

# Define executable
add_executable(
    main2
    ${SRC_FILES}
)

# Link libraries
target_link_libraries(
    main2 PRIVATE yaml-cpp
    # ${YAML_CPP_LIBRARIES}
    ${GST_LIBRARIES}
    ${GLIB_LIBRARIES}
    ${GSTRTSP_LIBRARIES}
    ${DEEPSTREAM_LIBRARIES_DIR}/libnvds_meta.so
    ${DEEPSTREAM_LIBRARIES_DIR}/libnvdsgst_meta.so
    ${DEEPSTREAM_LIBRARIES_DIR}/libnvdsgst_helper.so
    ${DEEPSTREAM_LIBRARIES_DIR}/libnvds_batch_jpegenc.so
    ${DEEPSTREAM_LIBRARIES_DIR}/libnvbufsurface.so
    ${CUDA_LIBRARIES}
)

# Compiler options
target_compile_options(
    main2
    PRIVATE
    -Wall
    -Wextra
    -Wpedantic
)

# Final status message
message(STATUS "Configuration complete. Ready to build ${PROJECT_NAME}")

and this is structure folder, you want I upload file for you, please comment:

Since our sample is fine, could you customized based on this step by step? This makes it easier to rule out which part of your customization is causing the problem.

How can I customize step by step, because the part save image I copied from your example code? Or I develope my app from you example code? Can you suggest me more (I’m fresher in Deepstream)

I mean you can add your implement step by step from our sample that is already running successfully. This makes it easy to analyze which customized code introduces the problem.

Or you can provide a simplified, executable version of your demo and attach the detailed steps. We can try to reproduce it on our side.

This is a simpler version that you can help me check, the error is similar. Because DS Forum does not allow me to upload a .cpp file, therefore, I rename .txt (please rename .cpp after download)
Command run:

mkdir build
cd build
cmake ..
make -j2
./main2

CMakeLists.txt (1.0 KB)
main2.txt (9.7 KB)

Output in my computer:

jetson@jetson-desktop:~/hai/develop/build$ ./main2 
Decoder linked to stream muxer.All elements linked.Now playing
Opening in BLOCKING MODE 
Opening in BLOCKING MODE 
0:00:10.117347181 15209   0x55a5be40a0 INFO                 nvinfer gstnvinfer.cpp:638:gst_nvinfer_logger:<nv-infer> NvDsInferContext[UID 1]: Info from NvDsInferContextImpl::deserializeEngineAndBackend() <nvdsinfer_context_impl.cpp:1900> [UID = 1]: deserialized trt engine from :/opt/nvidia/deepstream/deepstream-6.0/samples/models/Primary_Detector/resnet10.caffemodel_b1_gpu0_fp16.engine
INFO: [Implicit Engine Info]: layers num: 3
0   INPUT  kFLOAT input_1         3x368x640       
1   OUTPUT kFLOAT conv2d_bbox     16x23x40        
2   OUTPUT kFLOAT conv2d_cov/Sigmoid 4x23x40         

0:00:10.118645385 15209   0x55a5be40a0 INFO                 nvinfer gstnvinfer.cpp:638:gst_nvinfer_logger:<nv-infer> NvDsInferContext[UID 1]: Info from NvDsInferContextImpl::generateBackendContext() <nvdsinfer_context_impl.cpp:2004> [UID = 1]: Use deserialized engine model: /opt/nvidia/deepstream/deepstream-6.0/samples/models/Primary_Detector/resnet10.caffemodel_b1_gpu0_fp16.engine
0:00:10.446981138 15209   0x55a5be40a0 INFO                 nvinfer gstnvinfer_impl.cpp:313:notifyLoadModelStatus:<nv-infer> [UID 1]: Load new model:/opt/nvidia/deepstream/deepstream/sources/apps/sample_apps/deepstream-test1/dstest1_pgie_config.txt sucessfully
Demuxer and parser linked.
NvMMLiteOpen : Block : BlockType = 261 
NVMEDIA: Reading vendor.tegra.display-size : status: 6 
NvMMLiteBlockCreate : Block : BlockType = 261 
NvMMLiteOpen : Block : BlockType = 4 
===== NVMEDIA: NVENC =====
NvMMLiteBlockCreate : Block : BlockType = 4 
Before nvds_obj_enc_process
After nvds_obj_enc_process
Before nvds_obj_enc_finish
Segmentation fault (core dumped)

@yuweiw This is an urgent job at my university. Can you help me as soon as possible? Thank you very much.

Sure. If you just want to save the image, please set the userData.attachUsrMeta = FALSE;.

Beside set userData.attachUsrMeta = FALSE;
Can you explain why if I save the image after nvdsosd, that Segmentation fault. Else, not error

Some plugins in DeepStream can break the structure of the batch, like nvstreamtiler, nvstreamdemux, etc… After these plugins, it may not find the corresponding meta, so you cannot attach the raw data to it. We recommend that you take a quick look at our Guide before implementing your feature.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.