using System; using System.Collections; using System.Collections.Generic; using System.IO.MemoryMappedFiles; using UnityEngine; public class CameraServerMemory : MonoBehaviour { public Camera[] CameraSources; public string StreamFileName = "CameraStream"; public float ScanTime = 0.04f; private MemoryMappedViewAccessor mapView; private MemoryMappedFile mapFile; private List grabbedImages = new List(); private List imagePointers = new List(); private List imageSizes = new List(); private int HeaderSize; private bool isStreamingEnable = true; //--------------------------------------------------------------------------------- public void StreamingEnable(bool value) { this.isStreamingEnable = value; foreach (var c in CameraSources) { c.enabled = value; } } //--------------------------------------------------------------------------------- void Start () { int totalimagesize = 0; foreach (var c in CameraSources) { grabbedImages.Add(new Texture2D(c.targetTexture.width, c.targetTexture.height, TextureFormat.RGB24, false)); imagePointers.Add(totalimagesize); var imagesize = 3 * c.targetTexture.height * c.targetTexture.width; imageSizes.Add(imagesize); totalimagesize += imagesize; } HeaderSize = sizeof(Int32) + sizeof(Int32) * 2 * CameraSources.Length; mapFile = MemoryMappedFile.CreateOrOpen(StreamFileName, totalimagesize + HeaderSize); mapView = mapFile.CreateViewAccessor(0, totalimagesize + HeaderSize); mapView.Write(0, CameraSources.Length); for(int i = 0; i < CameraSources.Length; i++) { mapView.Write(4 + 8*i , CameraSources[i].targetTexture.width); mapView.Write(8 + 8*i , CameraSources[i].targetTexture.height); } StartCoroutine(Cameraframeloop()); } //--------------------------------------------------------------------------------- IEnumerator Cameraframeloop() { int i = 0; while (Application.isPlaying) { if (ScanTime > 0) yield return new WaitForSecondsRealtime(ScanTime); else yield return new WaitForEndOfFrame(); if (!this.isStreamingEnable) continue; RenderTexture.active = CameraSources[i].targetTexture; grabbedImages[i].ReadPixels(new Rect(0, 0, RenderTexture.active.width, RenderTexture.active.height), 0, 0); mapView.WriteArray( HeaderSize + imagePointers[i], grabbedImages[i].GetRawTextureData(), 0, imageSizes[i] ); i++; if (i == CameraSources.Length) i = 0; } } }