Проблема при использовании моей Picamera для потоковой передачи - PullRequest
1 голос
/ 21 апреля 2019

У меня сервир на малиновом ру, который транслирует видео с PiCamera.Однако, когда соединение с клиентом потеряно, я попытался открыть его снова, чтобы клиент мог снова подключиться.Но при этом я получаю эту ошибку:

mmal: mmal_vc_port_enable: failed to enable port vc.null_sink:in:0(OPQV): ENOSPC
mmal: mmal_port_enable: failed to enable connected port (vc.null_sink:in:0(OPQV))0x70804730 (ENOSPC)
mmal: mmal_connection_enable: output port couldn't be enabled
Exception in thread Thread-2:
Traceback (most recent call last):
  File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.5/threading.py", line 862, in run
    self._target(*self._args, **self._kwargs)
  File "/media/pi/INSTINCT/bubbabot4/client/serveur_video.py", line 38, in _connection_avec_client
    self._envoit_image()
  File "/media/pi/INSTINCT/bubbabot4/client/serveur_video.py", line 43, in _envoit_image
    camera=picamera.PiCamera()
  File "/usr/lib/python3/dist-packages/picamera/camera.py", line 433, in __init__
    self._init_preview()
  File "/usr/lib/python3/dist-packages/picamera/camera.py", line 513, in _init_preview
    self, self._camera.outputs[self.CAMERA_PREVIEW_PORT])
  File "/usr/lib/python3/dist-packages/picamera/renderers.py", line 558, in __init__
    self.renderer.inputs[0].connect(source).enable()
  File "/usr/lib/python3/dist-packages/picamera/mmalobj.py", line 2212, in enable
    prefix="Failed to enable connection")
  File "/usr/lib/python3/dist-packages/picamera/exc.py", line 184, in mmal_check
    raise PiCameraMMALError(status, prefix)
picamera.exc.PiCameraMMALError: Failed to enable connection: Out of resources

Я пытался очистить все varaible, чтобы получить некоторые ресурсы, но это не сработало.

# -*-coding:utf-8  -*
import io
import socket
import struct
import time
import picamera
from threading import Thread
import gc

class ControleurStreamingVideo():

    def __init__(self):
        self.adresse='0.0.0.0'
        self.port=8000

        self._serveur_socket = socket.socket()
        self._serveur_socket.bind((self.adresse, self.port))
        self._connection = None

        self._thread=None
        self._fermer_serveur=False
        self._output=None

    def ouvrir_serveur(self):
        self._thread = Thread(target=self._connection_avec_client)
        self._thread.start()

    def _connection_avec_client(self):
        try:
            print("Serveur en attente d'une connection... port={} adresse={}".format(self.port, self.adresse))
            self._serveur_socket.listen(5)
            self._connection = self._serveur_socket.accept()[0].makefile('wb')
            print("Connection réussi, début de la vidéo")

        except Exception as e:
            repr(e)

        self._envoit_image()



    def _envoit_image(self):
        camera=picamera.PiCamera()
        camera.resolution='VGA'
        camera.framerate=30
        try:
            self._output = SplitFrames(self._connection, self)
            time.sleep(2)  #warmup la caméra
            camera.start_recording(self._output, format='mjpeg', quality=30)

            while self._fermer_serveur==False:
                camera.wait_recording(1)
            camera.stop_recording()
            camera.close()
            self._serveur_socket.close()
            self._connection.close()

        except Exception as e:
            self._serveur_socket.close()
            del camera
            del self._output
            del self._connection
            del self._thread
            print("Connection avec le client perdu...")
            gc.collect()
            self.ouvrir_serveur()

    def fermer_serveur(self):
        self._fermer_serveur=True
        print("Serveur fermer")

    def _reouvrir_serveur(self):
        print("reouverture du serveur...")
        self.ouvrir_serveur()


class SplitFrames(object):

    def __init__(self, connection, controleur_vid):
        self.connection = connection
        self.controleur_vid=controleur_vid
        self.stream = io.BytesIO()
        self._erreur=False

    def write(self, buf):
        if buf.startswith(b'\xff\xd8'):
            # Start of new frame; send the old one's length
            # then the data
            size = self.stream.tell()
            if size > 0:
                self.connection.write(struct.pack('<L', size))
                self.connection.flush()
                self.stream.seek(0)
                self.connection.write(self.stream.read(size))
                self.stream.seek(0)
            self.stream.write(buf)
...