Search code examples
c++gstreamer

Properly close the pipeline to save image of udpsrc (currently my image is empty)


I would like to save one image of my updsrc. When the user click on a button the code bellow is running. But when I look at my image, it is empty. I try a lot of "way" to stop the pipeline but I think that I did not closed the pipeline properly.

Does anyone have any idea ?

    GstElement* snappipe;
    GError* error = NULL;
    GstElement* source;
    GstElement* filesink;
    GstCaps* caps = gst_caps_new_simple("application/x-rtp",
        "media", G_TYPE_STRING, "video",
        "payload", G_TYPE_INT, 96,
        "encoding-name", G_TYPE_STRING, "H264",
        NULL);

    m_strPathNameSave += CreateFileName("png");    
   
    snappipe = gst_parse_launch("udpsrc name=source num-buffers=1 !rtph264depay !h264parse !avdec_h264 !autovideoconvert ! pngenc ! filesink name=mysink", &error);
    if (!snappipe) {
        g_print("Parse error: %s\n", error->message);
        exit(1);
    }

    filesink = gst_bin_get_by_name(GST_BIN(snappipe), "mysink");
    g_object_set(filesink, "location", m_strPathNameSave.c_str(), NULL);

    source = gst_bin_get_by_name(GST_BIN(snappipe), "source");
    g_object_set(G_OBJECT(source), "caps", caps, NULL);
    g_object_set(G_OBJECT(source), "port", m_port, NULL);

    gst_element_set_state(snappipe, GST_STATE_PLAYING);
    GstBus* bus = gst_element_get_bus(snappipe);
    gst_object_unref(bus);

    Sleep(10000);

    gst_element_set_state(snappipe, GST_STATE_NULL);
    gst_object_unref(snappipe);

Solution

  • I solve the problem like that :

    std::string strPathImage = "\\image.png";
    
    GstCaps* caps;
    GstSample* from_sample, * to_sample;
    GError* err = NULL;
    GstBuffer* buf;
    GstMapInfo map_info;
    
    
    g_object_get((*ptrstats).sink, "last-sample", &from_sample, NULL);
    if (from_sample == NULL) {
        GST_ERROR("Error getting last sample form sink");
        return;
    }
    
    caps = gst_caps_from_string("image/png");
    to_sample = gst_video_convert_sample(from_sample, caps, GST_CLOCK_TIME_NONE, &err);
    
    gst_caps_unref(caps);
    gst_sample_unref(from_sample);
    
    if (to_sample == NULL && err) {
        GST_ERROR("Error converting frame: %s", err->message);
        g_error_free(err);
        return;
    }
    
    buf = gst_sample_get_buffer(to_sample);
    if (gst_buffer_map(buf, &map_info, GST_MAP_READ)) {
        if (!g_file_set_contents(strPathImage.c_str(), (const char*)map_info.data,
            map_info.size, &err)) {
            GST_WARNING("Could not save thumbnail: %s", err->message);
            g_error_free(err);
        }
    }
    
    gst_sample_unref(to_sample);
    gst_buffer_unmap(buf, &map_info);