|
| 1 | +/* |
| 2 | + * SPDX-FileCopyrightText: 2024 Espressif Systems (Shanghai) CO LTD |
| 3 | + * |
| 4 | + * SPDX-License-Identifier: Apache-2.0 |
| 5 | + */ |
| 6 | + |
| 7 | +#include <string.h> |
| 8 | +#include "esp_log.h" |
| 9 | +#include "esp_heap_caps.h" |
| 10 | +#include "message_utils.h" |
| 11 | + |
| 12 | +static const char *TAG = "message_utils"; |
| 13 | + |
| 14 | +received_msg_t *esp_webrtc_create_buffer_for_msg(int capacity) |
| 15 | +{ |
| 16 | + ESP_LOGI(TAG, "Creating buffer of capacity %d", capacity); |
| 17 | + received_msg_t *msg = (received_msg_t *) calloc(1, sizeof(received_msg_t)); |
| 18 | + if (!msg) { |
| 19 | + ESP_LOGE(TAG, "Failed allocation of message structure"); |
| 20 | + return NULL; |
| 21 | + } |
| 22 | + |
| 23 | + msg->buf = heap_caps_malloc_prefer(capacity, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT, MALLOC_CAP_INTERNAL); |
| 24 | + if (!msg->buf) { |
| 25 | + ESP_LOGE(TAG, "Failed allocation of buffer size %d", capacity); |
| 26 | + free(msg); |
| 27 | + return NULL; |
| 28 | + } |
| 29 | + msg->capacity = capacity; |
| 30 | + msg->data_size = 0; |
| 31 | + return msg; |
| 32 | +} |
| 33 | + |
| 34 | +esp_err_t esp_webrtc_append_msg_to_existing(received_msg_t *dst_msg, void *data_ptr, int data_len, bool is_fin) |
| 35 | +{ |
| 36 | + ESP_LOGI(TAG, "Appending message of size %d at %d location, is_fin: %d", data_len, dst_msg->data_size, is_fin); |
| 37 | + |
| 38 | + if (!is_fin) { |
| 39 | + if (dst_msg->data_size + data_len > dst_msg->capacity) { |
| 40 | + ESP_LOGE(TAG, "Cannot fit all the data in %d size buffer. current_filled: %d, incoming_data: %d", |
| 41 | + dst_msg->capacity, dst_msg->data_size, data_len); |
| 42 | + dst_msg->data_size = dst_msg->capacity + 1; /* Overflow the limit forcefully */ |
| 43 | + return ESP_FAIL; |
| 44 | + } else { /* Gather fragmented message */ |
| 45 | + memcpy(dst_msg->buf + dst_msg->data_size, data_ptr, data_len); |
| 46 | + dst_msg->data_size += data_len; |
| 47 | + return ESP_ERR_NOT_FINISHED; |
| 48 | + } |
| 49 | + } else if (dst_msg->data_size == 0) { /* non-fragmented message */ |
| 50 | + memcpy(dst_msg->buf + dst_msg->data_size, data_ptr, data_len); |
| 51 | + dst_msg->data_size += data_len; |
| 52 | + return ESP_OK; |
| 53 | + } else { /* final part of the fragment */ |
| 54 | + if (dst_msg->data_size + data_len <= dst_msg->capacity) { /* valid fragmented gathered message */ |
| 55 | + /* Copy last piece */ |
| 56 | + memcpy(dst_msg->buf + dst_msg->data_size, data_ptr, data_len); |
| 57 | + dst_msg->data_size += data_len; |
| 58 | + /* Process now... */ |
| 59 | + return ESP_OK; |
| 60 | + } else { |
| 61 | + ESP_LOGW(TAG, "Discarding the message which could not be fit"); |
| 62 | + dst_msg->data_size = 0; |
| 63 | + return ESP_FAIL; |
| 64 | + } |
| 65 | + } |
| 66 | + return ESP_FAIL; |
| 67 | +} |
0 commit comments