技術背景
隨著Unity3D的應用范圍越來越廣,越來越多的行業開始基于Unity3D開發產品,如傳統行業中虛擬仿真教育、航空工業、室內設計、城市規劃、工業仿真等領域,
基于此,好多開發者苦于在Unity環境下,沒有低延遲的推拉流解決方案,前幾年,我們在Unity環境下推出了跨平臺低延遲的RTMP|RTSP直播播放器,很好的解決了好多對延遲要求苛刻的使用場景,
隨著時間的推移,越來越多的開發者聯系我們,希望我們能推出Unity環境下的RTMP推送模塊,獲取到unity的實時資料,更低延遲更高效率的實作資料傳輸推送,基于此,我們發布了Unity環境下的RTMP推送模塊,
本文以Windows平臺為例,資料源分別為Unity的視窗、攝像頭或整個螢屏,編碼傳輸模塊,還是呼叫大牛直播SDK(官方)的原生介面,簡單界面先睹為快:

技術實作
1. 基礎初始化
private bool InitSDK()
{
if (!is_pusher_sdk_init_)
{
// 設定日志路徑(請確保目錄存在)
String log_path = "D:\\pulisherlog";
NTSmartLog.NT_SL_SetPath(log_path);
UInt32 isInited = NTSmartPublisherSDK.NT_PB_Init(0, IntPtr.Zero);
if (isInited != 0)
{
Debug.Log("呼叫NT_PB_Init失敗..");
return false;
}
is_pusher_sdk_init_ = true;
}
return true;
}
2. 呼叫Open()介面,獲取推送實體
public bool OpenPublisherHandle(uint video_option, uint audio_option)
{
if (publisher_handle_ != IntPtr.Zero)
{
return true;
}
publisher_handle_count_ = 0;
if (NTBaseCodeDefine.NT_ERC_OK != NTSmartPublisherSDK.NT_PB_Open(out publisher_handle_,
video_option, audio_option, 0, IntPtr.Zero))
{
return false;
}
if (publisher_handle_ != IntPtr.Zero)
{
pb_event_call_back_ = new NT_PB_SDKEventCallBack(PbEventCallBack);
NTSmartPublisherSDK.NT_PB_SetEventCallBack(publisher_handle_, IntPtr.Zero, pb_event_call_back_);
return true;
}
else
{
return false;
}
}
3. 初始化引數配置
這里需要注意下,如果要采集unity視窗,需要設定圖層模式,先填充一層RGBA黑色背景,然后再添加一層,用于疊加外部資料,
private void SetCommonOptionToPublisherSDK()
{
if (!IsPublisherHandleAvailable())
{
Debug.Log("SetCommonOptionToPublisherSDK, publisher handle with null..");
return;
}
NTSmartPublisherSDK.NT_PB_ClearLayersConfig(publisher_handle_, 0,
0, IntPtr.Zero);
if (video_option == NTSmartPublisherDefine.NT_PB_E_VIDEO_OPTION.NT_PB_E_VIDEO_OPTION_LAYER)
{
// 第0層填充RGBA矩形, 目的是保證幀率, 顏色就填充全黑
int red = 0;
int green = 0;
int blue = 0;
int alpha = 255;
NT_PB_RGBARectangleLayerConfig rgba_layer_c0 = new NT_PB_RGBARectangleLayerConfig();
rgba_layer_c0.base_.type_ = (Int32)NTSmartPublisherDefine.NT_PB_E_LAYER_TYPE.NT_PB_E_LAYER_TYPE_RGBA_RECTANGLE;
rgba_layer_c0.base_.index_ = 0;
rgba_layer_c0.base_.enable_ = 1;
rgba_layer_c0.base_.region_.x_ = 0;
rgba_layer_c0.base_.region_.y_ = 0;
rgba_layer_c0.base_.region_.width_ = video_width_;
rgba_layer_c0.base_.region_.height_ = video_height_;
rgba_layer_c0.base_.offset_ = Marshal.OffsetOf(rgba_layer_c0.GetType(), "base_").ToInt32();
rgba_layer_c0.base_.cb_size_ = (uint)Marshal.SizeOf(rgba_layer_c0);
rgba_layer_c0.red_ = System.BitConverter.GetBytes(red)[0];
rgba_layer_c0.green_ = System.BitConverter.GetBytes(green)[0];
rgba_layer_c0.blue_ = System.BitConverter.GetBytes(blue)[0];
rgba_layer_c0.alpha_ = System.BitConverter.GetBytes(alpha)[0];
IntPtr rgba_conf = Marshal.AllocHGlobal(Marshal.SizeOf(rgba_layer_c0));
Marshal.StructureToPtr(rgba_layer_c0, rgba_conf, true);
UInt32 rgba_r = NTSmartPublisherSDK.NT_PB_AddLayerConfig(publisher_handle_, 0,
rgba_conf, (int)NTSmartPublisherDefine.NT_PB_E_LAYER_TYPE.NT_PB_E_LAYER_TYPE_RGBA_RECTANGLE,
0, IntPtr.Zero);
Marshal.FreeHGlobal(rgba_conf);
NT_PB_ExternalVideoFrameLayerConfig external_layer_c1 = new NT_PB_ExternalVideoFrameLayerConfig();
external_layer_c1.base_.type_ = (Int32)NTSmartPublisherDefine.NT_PB_E_LAYER_TYPE.NT_PB_E_LAYER_TYPE_EXTERNAL_VIDEO_FRAME;
external_layer_c1.base_.index_ = 1;
external_layer_c1.base_.enable_ = 1;
external_layer_c1.base_.region_.x_ = 0;
external_layer_c1.base_.region_.y_ = 0;
external_layer_c1.base_.region_.width_ = video_width_;
external_layer_c1.base_.region_.height_ = video_height_;
external_layer_c1.base_.offset_ = Marshal.OffsetOf(external_layer_c1.GetType(), "base_").ToInt32();
external_layer_c1.base_.cb_size_ = (uint)Marshal.SizeOf(external_layer_c1);
IntPtr external_layer_conf = Marshal.AllocHGlobal(Marshal.SizeOf(external_layer_c1));
Marshal.StructureToPtr(external_layer_c1, external_layer_conf, true);
UInt32 external_r = NTSmartPublisherSDK.NT_PB_AddLayerConfig(publisher_handle_, 0,
external_layer_conf, (int)NTSmartPublisherDefine.NT_PB_E_LAYER_TYPE.NT_PB_E_LAYER_TYPE_EXTERNAL_VIDEO_FRAME,
0, IntPtr.Zero);
Marshal.FreeHGlobal(external_layer_conf);
}
else if (video_option == NTSmartPublisherDefine.NT_PB_E_VIDEO_OPTION.NT_PB_E_VIDEO_OPTION_CAMERA)
{
CameraInfo camera = cameras_[cur_sel_camera_index_];
NT_PB_VideoCaptureCapability cap = camera.capabilities_[cur_sel_camera_resolutions_index_];
SetVideoCaptureDeviceBaseParameter(camera.id_.ToString(), (UInt32)cap.width_, (UInt32)cap.height_);
}
SetFrameRate((UInt32)CalBitRate(edit_key_frame_, video_width_, video_height_));
Int32 type = 0; //軟編碼
Int32 encoder_id = 1;
UInt32 codec_id = (UInt32)NTCommonMediaDefine.NT_MEDIA_CODEC_ID.NT_MEDIA_CODEC_ID_H264;
Int32 param1 = 0;
SetVideoEncoder(type, encoder_id, codec_id, param1);
SetVideoQualityV2(CalVideoQuality(video_width_, video_height_, is_h264_encoder));
SetVideoMaxBitRate((CalMaxKBitRate(edit_key_frame_, video_width_, video_height_, false)));
SetVideoKeyFrameInterval((edit_key_frame_));
if (is_h264_encoder)
{
SetVideoEncoderProfile(1);
}
SetVideoEncoderSpeed(CalVideoEncoderSpeed(video_width_, video_height_, is_h264_encoder));
// 音頻相關設定
SetAuidoInputDeviceId(0);
SetPublisherAudioCodecType(1);
SetPublisherMute(is_mute);
SetEchoCancellation(0, 0);
SetNoiseSuppression(0);
SetAGC(0);
SetVAD(0);
SetInputAudioVolume(Convert.ToSingle(edit_audio_input_volume_));
}
4. 資料采集
攝像頭和螢屏的資料采集,還是呼叫原生的SDK介面,本文不再贅述,如果需要采集Unity表單的資料,可以用參考以下代碼:
if ( texture_ == null || video_width_ != Screen.width || video_height_ != Screen.height)
{
Debug.Log("OnPostRender screen changed++ scr_width: " + Screen.width + " scr_height: " + Screen.height);
if (screen_image_ != IntPtr.Zero)
{
Marshal.FreeHGlobal(screen_image_);
screen_image_ = IntPtr.Zero;
}
if (texture_ != null)
{
UnityEngine.Object.Destroy(texture_);
texture_ = null;
}
video_width_ = Screen.width;
video_height_ = Screen.height;
texture_ = new Texture2D(video_width_, video_height_, TextureFormat.BGRA32, false);
screen_image_ = Marshal.AllocHGlobal(video_width_ * 4 * video_height_);
Debug.Log("OnPostRender screen changed--");
return;
}
texture_.ReadPixels(new Rect(0, 0, video_width_, video_height_), 0, 0, false);
texture_.Apply();
從 texture里面,通過呼叫 GetRawTextureData(),獲取到原始資料,
5. 資料對接
獲取到資料后,通過呼叫 OnPostRGBAData()介面,傳遞給SDK層,
6. 本地資料預覽
public bool StartPreview()
{
if(CheckPublisherHandleAvailable() == false)
return false;
video_preview_image_callback_ = new NT_PB_SDKVideoPreviewImageCallBack(SDKVideoPreviewImageCallBack);
NTSmartPublisherSDK.NT_PB_SetVideoPreviewImageCallBack(publisher_handle_, (int)NTSmartPublisherDefine.NT_PB_E_IMAGE_FORMAT.NT_PB_E_IMAGE_FORMAT_RGB32, IntPtr.Zero, video_preview_image_callback_);
if (NTBaseCodeDefine.NT_ERC_OK != NTSmartPublisherSDK.NT_PB_StartPreview(publisher_handle_, 0, IntPtr.Zero))
{
if (0 == publisher_handle_count_)
{
NTSmartPublisherSDK.NT_PB_Close(publisher_handle_);
publisher_handle_ = IntPtr.Zero;
}
return false;
}
publisher_handle_count_++;
is_previewing_ = true;
return true;
}
設定preview后,處理preview的資料回呼
//預覽資料回呼
public void SDKVideoPreviewImageCallBack(IntPtr handle, IntPtr user_data, IntPtr image)
{
NT_PB_Image pb_image = (NT_PB_Image)Marshal.PtrToStructure(image, typeof(NT_PB_Image));
NT_VideoFrame pVideoFrame = new NT_VideoFrame();
pVideoFrame.width_ = pb_image.width_;
pVideoFrame.height_ = pb_image.height_;
pVideoFrame.stride_ = pb_image.stride_[0];
Int32 argb_size = pb_image.stride_[0] * pb_image.height_;
pVideoFrame.plane_data_ = new byte[argb_size];
if (argb_size > 0)
{
Marshal.Copy(pb_image.plane_[0],pVideoFrame.plane_data_,0, argb_size);
}
{
cur_image_ = pVideoFrame;
}
}
7. 相關event回呼處理
private void PbEventCallBack(IntPtr handle, IntPtr user_data,
UInt32 event_id,
Int64 param1,
Int64 param2,
UInt64 param3,
UInt64 param4,
[MarshalAs(UnmanagedType.LPStr)] String param5,
[MarshalAs(UnmanagedType.LPStr)] String param6,
IntPtr param7)
{
String event_log = "";
switch (event_id)
{
case (uint)NTSmartPublisherDefine.NT_PB_E_EVENT_ID.NT_PB_E_EVENT_ID_CONNECTING:
event_log = "連接中";
if (!String.IsNullOrEmpty(param5))
{
event_log = event_log + " url:" + param5;
}
break;
case (uint)NTSmartPublisherDefine.NT_PB_E_EVENT_ID.NT_PB_E_EVENT_ID_CONNECTION_FAILED:
event_log = "連接失敗";
if (!String.IsNullOrEmpty(param5))
{
event_log = event_log + " url:" + param5;
}
break;
case (uint)NTSmartPublisherDefine.NT_PB_E_EVENT_ID.NT_PB_E_EVENT_ID_CONNECTED:
event_log = "已連接";
if (!String.IsNullOrEmpty(param5))
{
event_log = event_log + " url:" + param5;
}
break;
case (uint)NTSmartPublisherDefine.NT_PB_E_EVENT_ID.NT_PB_E_EVENT_ID_DISCONNECTED:
event_log = "斷開連接";
if (!String.IsNullOrEmpty(param5))
{
event_log = event_log + " url:" + param5;
}
break;
default:
break;
}
if(OnLogEventMsg != null) OnLogEventMsg.Invoke(event_id, event_log);
}
8. 開始推送、停止推送
public bool StartPublisher(String url)
{
if (CheckPublisherHandleAvailable() == false) return false;
if (publisher_handle_ == IntPtr.Zero)
{
return false;
}
if (!String.IsNullOrEmpty(url))
{
NTSmartPublisherSDK.NT_PB_SetURL(publisher_handle_, url, IntPtr.Zero);
}
if (NTBaseCodeDefine.NT_ERC_OK != NTSmartPublisherSDK.NT_PB_StartPublisher(publisher_handle_, IntPtr.Zero))
{
if (0 == publisher_handle_count_)
{
NTSmartPublisherSDK.NT_PB_Close(publisher_handle_);
publisher_handle_ = IntPtr.Zero;
}
is_publishing_ = false;
return false;
}
publisher_handle_count_++;
is_publishing_ = true;
return true;
}
public void StopPublisher()
{
if (is_publishing_ == false) return;
publisher_handle_count_--;
NTSmartPublisherSDK.NT_PB_StopPublisher(publisher_handle_);
if (0 == publisher_handle_count_)
{
NTSmartPublisherSDK.NT_PB_Close(publisher_handle_);
publisher_handle_ = IntPtr.Zero;
}
is_publishing_ = false;
}
9. 關閉實體
public void Close()
{
if (0 == publisher_handle_count_)
{
NTSmartPublisherSDK.NT_PB_Close(publisher_handle_);
publisher_handle_ = IntPtr.Zero;
}
}
總結
經測驗,Unity環境下,通過高效率的資料采集、編碼和推送,配合SmartPlayer播放器播放,整體延遲可控制在毫秒級,可適用于大多數Unity環境下對延遲和穩定性要求苛刻的場景,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/287003.html
標籤:其他
上一篇:關于公轉與自轉的相關代碼
下一篇:C語言——三子棋
