Implementing RTMP streaming in C language

ghz 8months ago ⋅ 142 views

Using the librtmp Library on M300 PSDK with Linux,Calling the function RTMP_Write() multiple times results in an error and program termination。

input: const uint8_t *buf(data stream), uint32_t len(data length)

function: rtmp_buf = (char *)malloc(len * sizeof(char)); memcpy(rtmp_buf, buf, len);

output: RTMP_Write(rtmp, rtmp_buf, len) free(rtmp_buf)`

Answers

It seems like you're encountering issues with memory management when using the librtmp library on the M300 PSDK with Linux. The issue might be related to memory allocation and deallocation.

Here's a potential approach to address the problem:

  1. Check Memory Allocation: Make sure that memory allocation (malloc()) is successful before proceeding with writing data into the buffer.

  2. Ensure Proper Buffer Management: Ensure that you're managing the buffer properly, including allocating memory for it before writing data and freeing it after use to avoid memory leaks.

  3. Error Handling: Check the return value of RTMP_Write() to handle any errors gracefully.

Here's an example of how you might modify your code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <librtmp/rtmp.h>

int main() {
    // Initialize librtmp
    RTMP *rtmp = RTMP_Alloc();
    if (!rtmp) {
        fprintf(stderr, "Error: Failed to allocate RTMP structure.\n");
        return 1;
    }

    // Initialize RTMP connection
    if (!RTMP_Init(rtmp)) {
        fprintf(stderr, "Error: Failed to initialize RTMP.\n");
        RTMP_Free(rtmp);
        return 1;
    }

    // Connect to server
    if (!RTMP_SetupURL(rtmp, "rtmp://your_server_url")) {
        fprintf(stderr, "Error: Failed to set RTMP URL.\n");
        RTMP_Free(rtmp);
        return 1;
    }
    RTMP_EnableWrite(rtmp);

    // Connect to server
    if (!RTMP_Connect(rtmp, NULL)) {
        fprintf(stderr, "Error: Failed to connect to RTMP server.\n");
        RTMP_Free(rtmp);
        return 1;
    }

    // Create and write data
    const uint8_t *buf = /* your data */;
    uint32_t len = /* length of your data */;
    char *rtmp_buf = (char *)malloc(len * sizeof(char));
    if (!rtmp_buf) {
        fprintf(stderr, "Error: Failed to allocate memory for RTMP buffer.\n");
        RTMP_Free(rtmp);
        return 1;
    }
    memcpy(rtmp_buf, buf, len);

    // Write data to RTMP stream
    if (RTMP_Write(rtmp, rtmp_buf, len) <= 0) {
        fprintf(stderr, "Error: Failed to write data to RTMP stream.\n");
    }

    // Free memory and close connection
    free(rtmp_buf);
    RTMP_Close(rtmp);
    RTMP_Free(rtmp);

    return 0;
}

Make sure to replace "rtmp://your_server_url" with the actual RTMP server URL you are using.

This code snippet includes error handling for memory allocation and RTMP operations to help identify and address any issues that may occur during execution.