About release the buffer or caps or structure resources in appsink callback function

Hello everyone, I want to know in the callback function of the appsink. Do I need to release the resources of the buffer and some Gst* I called. For example:

GstFlowReturn GstreamerStreamDecoder::on_new_image_static(GstAppSink *Myappsink, gpointer user_data){
    // entity the appsink simple
    GstSample *sample = gst_app_sink_pull_sample(Myappsink);
    if (!sample) {
        ERROR("Failed to pull sample from appsink.")
        return GST_FLOW_ERROR;
    }

    // add GstCaps of appsink
    GstCaps *caps = gst_sample_get_caps(sample);
    if (!caps) {
        ERROR("Failed to get caps from sample.")
        gst_sample_unref(sample);
        return GST_FLOW_ERROR;
    }

    // get the structure of the cap
    GstStructure *structure = gst_caps_get_structure(caps, 0);
    if (!structure) {
        ERROR("Failed to get structure from caps.")
        gst_sample_unref(sample);
        return GST_FLOW_ERROR;
    }

    // get the image width and height
    int width, height;
    if (!gst_structure_get_int(structure, "width", &width) || !gst_structure_get_int(structure, "height", &height)) {
        ERROR("Failed to get width/height from structure." )
        gst_sample_unref(sample);
        return GST_FLOW_ERROR;
    }

    GstBuffer *buffer = gst_sample_get_buffer(sample);
    GstMapInfo map;
    gst_buffer_map(buffer, &map, GST_MAP_READ);

    auto image = std::make_shared<cv::Mat>(cv::Size(width, height), CV_8UC3, (char*)map.data, cv::Mat::AUTO_STEP);

    gst_buffer_unmap(buffer, &map);
    gst_sample_unref(sample);
    return GST_FLOW_OK;
}

Do I need to unref the buffer/caps/structure to ensure the memory leak?

No, this is correct. You have to unref the sample, and you have to unmap the buffer after mapping. The buffer/caps are only borrowed from the sample (the sample owns it and you get that same reference which is valid for as long as the sample is), and the structure is borrowed from the caps.

Check the API documentation for all these functions. The most interesting part there is the transfer none and transfer full annotation for parameters and return values, which tells you about ownership transfer.

1 Like

Thank you very much for your reply! I will have a look!