浏览代码

Detach live-stream frames before sending to the browser

SybexXx 1 天之前
父节点
当前提交
87818361b7
共有 1 个文件被更改,包括 120 次插入 和 71 次删除
  1. 120 71
      code/components/jomjol_controlcamera/ClassControllCamera.cpp

+ 120 - 71
code/components/jomjol_controlcamera/ClassControllCamera.cpp

@@ -1299,45 +1299,38 @@ esp_err_t CCamera::CaptureToHTTP(httpd_req_t *req, int delay, bool previewCaptur
 
 
 esp_err_t CCamera::CaptureToStream(httpd_req_t *req, bool FlashlightOn)
 esp_err_t CCamera::CaptureToStream(httpd_req_t *req, bool FlashlightOn)
 {
 {
-    esp_err_t res = ESP_OK;
-    size_t fb_len = 0;
-    int64_t fr_start = 0;
-    char part_buf[64];
+    if (req == NULL) return ESP_ERR_INVALID_ARG;
 
 
     {
     {
-        ScopedCameraLock settingsLock(m_cameraMutex);
-        if (!settingsLock.acquired()) return ESP_ERR_TIMEOUT;
+        ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
+        if (!operationLock.acquired()) return ESP_ERR_TIMEOUT;
         const esp_err_t restoreResult = RestoreCommittedSettingsIfNeeded();
         const esp_err_t restoreResult = RestoreCommittedSettingsIfNeeded();
         if (restoreResult != ESP_OK) return restoreResult;
         if (restoreResult != ESP_OK) return restoreResult;
     }
     }
 
 
     LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Live stream started");
     LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Live stream started");
-    if (FlashlightOn)
-    {
-        LEDOnOff(true);
-        LightOnOff(true);
-    }
+    ScopedCameraCaptureIndicators indicators(*this, FlashlightOn, FlashlightOn);
 
 
-    res = httpd_resp_set_type(req, _STREAM_CONTENT_TYPE);
-    if (res == ESP_OK)
+    esp_err_t result = httpd_resp_set_type(req, _STREAM_CONTENT_TYPE);
+    if (result == ESP_OK)
     {
     {
-        res = httpd_resp_send_chunk(req, _STREAM_BOUNDARY, strlen(_STREAM_BOUNDARY));
+        result = httpd_resp_send_chunk(req, _STREAM_BOUNDARY, strlen(_STREAM_BOUNDARY));
     }
     }
 
 
-    // Discard one initial frame so that exposure and white balance can settle.
-    if (res == ESP_OK)
+    // One warmup frame lets exposure and white balance settle before streaming.
+    if (result == ESP_OK)
     {
     {
-        ScopedCameraOperationLock warmupLease(m_cameraOperationMutex);
-        if (!warmupLease.acquired())
+        ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
+        if (!operationLock.acquired())
         {
         {
-            res = ESP_ERR_TIMEOUT;
+            result = ESP_ERR_TIMEOUT;
         }
         }
         else
         else
         {
         {
-            ScopedCameraLock warmupLock(m_cameraMutex);
-            if (!warmupLock.acquired())
+            ScopedCameraLock cameraLock(m_cameraMutex);
+            if (!cameraLock.acquired())
             {
             {
-                res = ESP_ERR_TIMEOUT;
+                result = ESP_ERR_TIMEOUT;
             }
             }
             else
             else
             {
             {
@@ -1346,79 +1339,135 @@ esp_err_t CCamera::CaptureToStream(httpd_req_t *req, bool FlashlightOn)
         }
         }
     }
     }
 
 
-    while (res == ESP_OK)
+    char partBuffer[64];
+    while (result == ESP_OK)
     {
     {
-        fr_start = esp_timer_get_time();
-        ScopedCameraOperationLock frameLease(m_cameraOperationMutex);
-        if (!frameLease.acquired())
-        {
-            res = ESP_ERR_TIMEOUT;
-        }
-        else
+        const int64_t frameStart = esp_timer_get_time();
+        uint8_t *frameData = NULL;
+        size_t frameLength = 0;
+        bool frameDataInPsram = false;
+
         {
         {
-            ScopedCameraFrame frame;
+            // Reserve the camera only long enough to acquire and detach a frame.
+            // Network transmission below uses the independent copy and owns no
+            // camera-driver or framebuffer resources.
+            ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
+            if (!operationLock.acquired())
             {
             {
-                // Only serialize access to the camera driver while acquiring the frame.
-                // Keep the framebuffer lease, not the driver mutex, during network I/O.
-                ScopedCameraLock frameLock(m_cameraMutex);
-                if (!frameLock.acquired())
-                {
-                    res = ESP_ERR_TIMEOUT;
-                }
-                else
+                result = ESP_ERR_TIMEOUT;
+            }
+            else
+            {
+                camera_fb_t *fb = NULL;
                 {
                 {
-                    frame.set(esp_camera_fb_get());
-                    if (frame.get() == NULL)
+                    ScopedCameraLock cameraLock(m_cameraMutex);
+                    if (!cameraLock.acquired())
+                    {
+                        result = ESP_ERR_TIMEOUT;
+                    }
+                    else
                     {
                     {
-                        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToStream: Camera framebuffer not available");
-                        res = ESP_FAIL;
+                        fb = esp_camera_fb_get();
                     }
                     }
                 }
                 }
-            }
 
 
-            if (res == ESP_OK)
-            {
-                camera_fb_t *fb = frame.get();
-                fb_len = fb->len;
-                const int headerLength = snprintf(part_buf, sizeof(part_buf), _STREAM_PART,
-                                                   static_cast<unsigned int>(fb_len));
-                if (headerLength < 0 || static_cast<size_t>(headerLength) >= sizeof(part_buf))
+                if (result == ESP_OK && fb == NULL)
                 {
                 {
-                    res = ESP_FAIL;
+                    LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToStream: Camera framebuffer not available");
+                    result = ESP_FAIL;
                 }
                 }
-                else
+
+                if (result == ESP_OK)
                 {
                 {
-                    res = httpd_resp_send_chunk(req, part_buf, static_cast<size_t>(headerLength));
+                    ScopedCameraFrame frame(fb, m_cameraMutex);
+                    if (fb->format == PIXFORMAT_JPEG)
+                    {
+                        if (fb->buf == NULL || fb->len == 0)
+                        {
+                            result = ESP_FAIL;
+                        }
+                        else
+                        {
+                            frameData = static_cast<uint8_t *>(malloc_psram_heap(
+                                "Live stream JPEG copy", fb->len, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
+                            if (frameData == NULL)
+                            {
+                                LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToStream: JPEG copy allocation failed");
+                                result = ESP_ERR_NO_MEM;
+                            }
+                            else
+                            {
+                                memcpy(frameData, fb->buf, fb->len);
+                                frameLength = fb->len;
+                                frameDataInPsram = true;
+                            }
+                        }
+                    }
+                    else if (!frame2jpg(fb, 80, &frameData, &frameLength) ||
+                             frameData == NULL || frameLength == 0)
+                    {
+                        if (frameData != NULL)
+                        {
+                            free(frameData);
+                            frameData = NULL;
+                        }
+                        result = ESP_FAIL;
+                    }
+
+                    frame.release();
                 }
                 }
+            }
+        }
+
+        // All camera resources are released before any potentially blocking
+        // socket operation. A slow or disconnected client cannot starve the flow.
+        if (result == ESP_OK)
+        {
+            const int headerLength = snprintf(partBuffer, sizeof(partBuffer), _STREAM_PART,
+                                               static_cast<unsigned int>(frameLength));
+            if (headerLength < 0 || static_cast<size_t>(headerLength) >= sizeof(partBuffer))
+            {
+                result = ESP_FAIL;
+            }
+            else
+            {
+                result = httpd_resp_send_chunk(req, partBuffer, static_cast<size_t>(headerLength));
+            }
 
 
-                if (res == ESP_OK) res = httpd_resp_send_chunk(req, (const char *)fb->buf, fb_len);
-                if (res == ESP_OK) res = httpd_resp_send_chunk(req, _STREAM_BOUNDARY, strlen(_STREAM_BOUNDARY));
+            if (result == ESP_OK)
+            {
+                result = httpd_resp_send_chunk(req, reinterpret_cast<const char *>(frameData),
+                                               static_cast<ssize_t>(frameLength));
+            }
+            if (result == ESP_OK)
+            {
+                result = httpd_resp_send_chunk(req, _STREAM_BOUNDARY, strlen(_STREAM_BOUNDARY));
             }
             }
         }
         }
 
 
-        if (res != ESP_OK)
+        if (frameData != NULL)
         {
         {
-            break;
+            if (frameDataInPsram) free_psram_heap("Live stream JPEG copy", frameData);
+            else free(frameData);
         }
         }
 
 
-        const int64_t fr_end = esp_timer_get_time();
-        ESP_LOGD(TAG, "JPG: %dKB %dms", (int)(fb_len / 1024), (int)((fr_end - fr_start) / 1000));
-        const int64_t fr_delta_ms = (fr_end - fr_start) / 1000;
-        if (CAM_LIVESTREAM_REFRESHRATE > fr_delta_ms)
+        if (result != ESP_OK) break;
+
+        const int64_t frameEnd = esp_timer_get_time();
+        ESP_LOGD(TAG, "Stream frame: %uKB %ums",
+                 static_cast<unsigned int>(frameLength / 1024),
+                 static_cast<unsigned int>((frameEnd - frameStart) / 1000));
+        const int64_t frameDurationMs = (frameEnd - frameStart) / 1000;
+        if (CAM_LIVESTREAM_REFRESHRATE > frameDurationMs)
         {
         {
-            const TickType_t xDelay = pdMS_TO_TICKS(CAM_LIVESTREAM_REFRESHRATE - fr_delta_ms);
-            ESP_LOGD(TAG, "Stream: sleep for: %lu ticks", (unsigned long)xDelay);
-            vTaskDelay(xDelay);
+            const TickType_t delayTicks =
+                pdMS_TO_TICKS(CAM_LIVESTREAM_REFRESHRATE - frameDurationMs);
+            vTaskDelay(delayTicks);
         }
         }
     }
     }
 
 
-    if (FlashlightOn)
-    {
-        LEDOnOff(false);
-        LightOnOff(false);
-    }
     LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Live stream stopped");
     LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Live stream stopped");
-    return res;
+    return result;
 }
 }
 
 
 void CCamera::UpdateFlashOutputLocked(void)
 void CCamera::UpdateFlashOutputLocked(void)