Android平台如何实现屏幕数据采集并推送至RTMP服务器

简介: 随着无纸化、智慧教室等场景的普及,好多企业或者开发者开始寻求更高效稳定低延迟的RTMP同屏方案,本文以大牛直播SDK(Github)的同屏demo(对应工程:SmartServicePublisherV2)为例,介绍下如何采集编码推送RTMP数据到流媒体服务器。

随着无纸化、智慧教室等场景的普及,好多企业或者开发者开始寻求更高效稳定低延迟的RTMP同屏方案,本文以大牛直播SDK(Github)的同屏demo(对应工程:SmartServicePublisherV2)为例,介绍下如何采集编码推送RTMP数据到流媒体服务器。


系统要求:Android 5.0及以上系统。


废话不多说,上代码:


获取screen windows宽高,如需缩放,按照一定的比例缩放即可:

    private void createScreenEnvironment() {
        sreenWindowWidth = mWindowManager.getDefaultDisplay().getWidth();
        screenWindowHeight = mWindowManager.getDefaultDisplay().getHeight();
        Log.i(TAG, "screenWindowWidth: " + sreenWindowWidth + ",screenWindowHeight: "
                + screenWindowHeight);
        if (sreenWindowWidth > 800)
        {
            if (screenResolution == SCREEN_RESOLUTION_STANDARD)
            {
                scale_rate = SCALE_RATE_HALF;
                sreenWindowWidth = align(sreenWindowWidth / 2, 16);
                screenWindowHeight = align(screenWindowHeight / 2, 16);
            }
            else if(screenResolution == SCREEN_RESOLUTION_LOW)
            {
                scale_rate = SCALE_RATE_TWO_FIFTHS;
                sreenWindowWidth = align(sreenWindowWidth * 2 / 5, 16);
            }
        }
        Log.i(TAG, "After adjust mWindowWidth: " + sreenWindowWidth + ", mWindowHeight: " + screenWindowHeight);
        int pf = mWindowManager.getDefaultDisplay().getPixelFormat();
        Log.i(TAG, "display format:" + pf);
        DisplayMetrics displayMetrics = new DisplayMetrics();
        mWindowManager.getDefaultDisplay().getMetrics(displayMetrics);
        mScreenDensity = displayMetrics.densityDpi;
        mImageReader = ImageReader.newInstance(sreenWindowWidth,
                screenWindowHeight, 0x1, 6);
        mMediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
    }

获取到image数据后,传递到processScreenImage()处理:

   private void setupMediaProjection() {
        mMediaProjection = mMediaProjectionManager.getMediaProjection(
                MainActivity.mResultCode, MainActivity.mResultData);
    }
    private void setupVirtualDisplay() {
        mVirtualDisplay = mMediaProjection.createVirtualDisplay(
                "ScreenCapture", sreenWindowWidth, screenWindowHeight,
                mScreenDensity,
                DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
                mImageReader.getSurface(), null, null);
        mImageReader.setOnImageAvailableListener(
                new ImageReader.OnImageAvailableListener() {
                    @Override
                    public void onImageAvailable(ImageReader reader) {
                        Image image = mImageReader.acquireLatestImage();
                        if (image != null) {
                            processScreenImage(image);
                            //image.close();
                        }
                    }
                }, null);
    }

数据放到image list里面:

    private void  pushImage(Image image)
    {
        if ( null ==image )
            return;
        final int image_list_max_count = 1;
        LinkedList<Image> close_images = null;
        synchronized (image_list_lock)
        {
            if (image_list.size() > image_list_max_count )
            {
                close_images = new LinkedList();
                while ( image_list.size() > image_list_max_count)
                {
                    close_images.add(image_list.poll());
                }
            }
            image_list.add(image);
        }
        if ( close_images != null )
        {
            while( !close_images.isEmpty() ) {
                Image i = close_images.poll();
                if ( i != null )
                {
                    i.close();
                    //Log.i("PushImage", "drop image");
                }
            }
        }
    }

调用大牛直播SDK的RTMP初始化和参数设置接口:

        libPublisher = new SmartPublisherJniV2();    
        private void InitAndSetConfig() {
        //开始要不要采集音频或视频,请自行设置
        publisherHandle = libPublisher.SmartPublisherOpen(this.getApplicationContext(),
                audio_opt, video_opt, sreenWindowWidth,
                screenWindowHeight);
        if ( publisherHandle == 0 )
        {
            return;
        }
        Log.i(TAG, "publisherHandle=" + publisherHandle);
        libPublisher.SetSmartPublisherEventCallbackV2(publisherHandle, new EventHandeV2());
        if(videoEncodeType == 1)
        {
            int h264HWKbps = setHardwareEncoderKbps(true, sreenWindowWidth,
                    screenWindowHeight);
            Log.i(TAG, "h264HWKbps: " + h264HWKbps);
            int isSupportH264HWEncoder = libPublisher
                    .SetSmartPublisherVideoHWEncoder(publisherHandle, h264HWKbps);
            if (isSupportH264HWEncoder == 0) {
                Log.i(TAG, "Great, it supports h.264 hardware encoder!");
            }
        }
        else if (videoEncodeType == 2)
        {
            int hevcHWKbps = setHardwareEncoderKbps(false, sreenWindowWidth,
                    screenWindowHeight);
            Log.i(TAG, "hevcHWKbps: " + hevcHWKbps);
            int isSupportHevcHWEncoder = libPublisher
                    .SetSmartPublisherVideoHevcHWEncoder(publisherHandle, hevcHWKbps);
            if (isSupportHevcHWEncoder == 0) {
                Log.i(TAG, "Great, it supports hevc hardware encoder!");
            }
        }
        if(is_sw_vbr_mode)
        {
            int is_enable_vbr = 1;
            int video_quality = CalVideoQuality(sreenWindowWidth,
                    screenWindowHeight, true);
            int vbr_max_bitrate = CalVbrMaxKBitRate(sreenWindowWidth,
                    screenWindowHeight);
            libPublisher.SmartPublisherSetSwVBRMode(publisherHandle, is_enable_vbr, video_quality, vbr_max_bitrate);
        }
        //音频相关可以参考SmartPublisher工程
    /*
    if (!is_speex)
    {
      // set AAC encoder
      libPublisher.SmartPublisherSetAudioCodecType(publisherHandle, 1);
    }
    else
    {
      // set Speex encoder
      libPublisher.SmartPublisherSetAudioCodecType(publisherHandle, 2);
      libPublisher.SmartPublisherSetSpeexEncoderQuality(publisherHandle, 8);
    }
    libPublisher.SmartPublisherSetNoiseSuppression(publisherHandle, is_noise_suppression ? 1
        : 0);
    libPublisher.SmartPublisherSetAGC(publisherHandle, is_agc ? 1 : 0);
    */
        // libPublisher.SmartPublisherSetClippingMode(publisherHandle, 0);
        //libPublisher.SmartPublisherSetSWVideoEncoderProfile(publisherHandle, sw_video_encoder_profile);
        //libPublisher.SmartPublisherSetSWVideoEncoderSpeed(publisherHandle, sw_video_encoder_speed);
        // libPublisher.SetRtmpPublishingType(publisherHandle, 0);
         libPublisher.SmartPublisherSetFPS(publisherHandle, 18);    //帧率可调
         libPublisher.SmartPublisherSetGopInterval(publisherHandle, 18*3);
         //libPublisher.SmartPublisherSetSWVideoBitRate(publisherHandle, 1200, 2400); //针对软编码有效,一般最大码率是平均码率的二倍
         libPublisher.SmartPublisherSetSWVideoEncoderSpeed(publisherHandle, 3);
         //libPublisher.SmartPublisherSaveImageFlag(publisherHandle, 1);
    }

初始化、参数设置后,设置RTMP推送的URL,并调用SartPublisher()接口,开始推送:

        //如果同时推送和录像,设置一次就可以
        InitAndSetConfig();
        if ( publisherHandle == 0 )
        {
            stopScreenCapture();
            return;
        }
        if(push_type == PUSH_TYPE_RTMP)
        {
            String publishURL = intent.getStringExtra("PUBLISHURL");
            Log.i(TAG, "publishURL: " + publishURL);
            if (libPublisher.SmartPublisherSetURL(publisherHandle, publishURL) != 0) {
                stopScreenCapture();
                Log.e(TAG, "Failed to set publish stream URL..");
                if (publisherHandle != 0) {
                    if (libPublisher != null) {
                        libPublisher.SmartPublisherClose(publisherHandle);
                        publisherHandle = 0;
                    }
                }
                return;
            }
        }
        //启动传递数据线程
        post_data_thread = new Thread(new DataRunnable());
        Log.i(TAG, "new post_data_thread..");
        is_post_data_thread_alive = true;
        post_data_thread.start();
  int startRet = libPublisher.SmartPublisherStartPublisher(publisherHandle);
            if (startRet != 0) {
                isPushingRtmp = false;
                Log.e(TAG, "Failed to start push rtmp stream..");
                return;
            }
  //如果同时推送和录像,Audio启动一次就可以了
  CheckInitAudioRecorder();

开始推送后,传递数据到底层SDK:

    public class DataRunnable implements Runnable{
        private final static String TAG = "DataRunnable==> ";
        @Override
        public void run() {
            // TODO Auto-generated method stub
            Log.i(TAG, "post data thread is running..");
            ByteBuffer last_buffer = null;
            Image last_image = null;
            long last_post_time = System.currentTimeMillis();
            while (is_post_data_thread_alive)
            {
                boolean is_skip = false;
                /*
                synchronized (data_list_lock)
                {
                    if ( data_list.isEmpty())
                    {
                        if((System.currentTimeMillis() - last_post_time) > frame_added_interval_setting)
                        {
                            if(last_buffer != null)
                            {
                                Log.i(TAG, "补帧中..");
                            }
                            else
                            {
                                is_skip = true;
                            }
                        }
                        else
                        {
                           is_skip = true;
                        }
                    }
                    else
                    {
                        last_buffer = data_list.get(0);
                        data_list.remove(0);
                    }
                }
                */
                Image new_image = popImage();
                if ( new_image == null )
                {
                    if((System.currentTimeMillis() - last_post_time) > frame_added_interval_setting)
                    {
                        if(last_image != null)
                        {
                            Log.i(TAG, "补帧中..");
                        }
                        else
                        {
                            is_skip = true;
                        }
                    }
                    else
                    {
                        is_skip = true;
                    }
                }
                else
                {
                    if ( last_image != null )
                    {
                        last_image.close();
                    }
                    last_image = new_image;
                }
                if( is_skip )
                {
                    // Log.i("OnScreenImage", "is_skip");
                    try {
                        Thread.sleep(5);   //休眠5ms
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                else
                {
                    //if( last_buffer != null && publisherHandle != 0 && (isPushing || isRecording || isRTSPPublisherRunning) )
                    if( last_image != null && publisherHandle != 0 && (isPushingRtmp || isRecording || isRTSPPublisherRunning) )
                    {
                        long post_begin_time = System.currentTimeMillis();
                        final Image.Plane[] planes = last_image.getPlanes();
                        if ( planes != null && planes.length > 0 )
                        {
                            libPublisher.SmartPublisherOnCaptureVideoRGBAData(publisherHandle, planes[0].getBuffer(), planes[0].getRowStride(),
                                    last_image.getWidth(), last_image.getHeight());
                        }
                        last_post_time = System.currentTimeMillis();
                        long post_cost_time = last_post_time - post_begin_time;
                        if ( post_cost_time >=0 && post_cost_time < 10 )
                        {
                            try {
                                Thread.sleep(10-post_cost_time);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        /*
                        libPublisher.SmartPublisherOnCaptureVideoRGBAData(publisherHandle, last_buffer, row_stride_,
                                width_, height_);
                                */
                        /*
                        //实际裁剪比例,可酌情自行调整
                        int left = 100;
                        int cliped_left = 0;
                        int top = 0;
                        int cliped_top = 0;
                        int cliped_width = width_;
                        int cliped_height = height_;
                        if(scale_rate == SCALE_RATE_HALF)
                        {
                            cliped_left = left / 2;
                            cliped_top = top / 2;
                            //宽度裁剪后,展示3/4比例
                            cliped_width = (width_ *3)/4;
                            //高度不做裁剪
                            cliped_height = height_;
                        }
                        else if(scale_rate == SCALE_RATE_TWO_FIFTHS)
                        {
                            cliped_left = left * 2 / 5;
                            cliped_top = top * 2 / 5;
                            //宽度裁剪后,展示3/4比例
                            cliped_width = (width_ *3)/4;
                            //高度不做裁剪
                            cliped_height = height_;
                        }
                        if(cliped_width % 2 != 0)
                        {
                            cliped_width = cliped_width + 1;
                        }
                        if(cliped_height % 2 != 0)
                        {
                            cliped_height = cliped_height + 1;
                        }
                        if ( (cliped_left + cliped_width) > width_)
                        {
                            Log.e(TAG, " invalid cliped region settings, cliped_left: " + cliped_left + " cliped_width:" + cliped_width + " width:" + width_);
                            return;
                        }
                        if ( (cliped_top + cliped_height) > height_)
                        {
                            Log.e(TAG, "invalid cliped region settings, cliped_top: " + cliped_top + " cliped_height:" + cliped_height + " height:" + height_);
                            return;
                        }
                        //Log.i(TAG, " clipLeft: " + cliped_left + " clipTop: " + cliped_top +  " clipWidth: " + cliped_width + " clipHeight: " + cliped_height);
                        libPublisher.SmartPublisherOnCaptureVideoClipedRGBAData(publisherHandle, last_buffer, row_stride_,
                                width_, height_, cliped_left, cliped_top, cliped_width, cliped_height );
                        */
                       // Log.i(TAG, "post data: " + last_post_time + " cost:" + post_cost_time);
                    }
                    else
                    {
                        try {
                            Thread.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            if ( last_image != null)
            {
                last_image.close();
                last_image = null;
            }
        }
    }

关闭采集推送:

    public void onDestroy() {
        // TODO Auto-generated method stub
        Log.i(TAG, "Service stopped..");
        stopScreenCapture();
        clearAllImages();
        if( is_post_data_thread_alive && post_data_thread != null )
        {
            Log.i(TAG, "onDestroy close post_data_thread++");
            is_post_data_thread_alive = false;
            try {
                post_data_thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            post_data_thread = null;
            Log.i(TAG, "onDestroy post_data_thread closed--");
        }
        if (isPushingRtmp || isRecording || isRTSPPublisherRunning)
        {
            if (audioRecord_ != null) {
                Log.i(TAG, "surfaceDestroyed, call StopRecording..");
                audioRecord_.Stop();
                if (audioRecordCallback_ != null) {
                    audioRecord_.RemoveCallback(audioRecordCallback_);
                    audioRecordCallback_ = null;
                }
                audioRecord_ = null;
            }
            stopPush();
            isPushingRtmp = false;
            stopRecorder();
            isRecording = false;
            stopRtspPublisher();
            isRTSPPublisherRunning = false;
            stopRtspService();
            isRTSPServiceRunning = false;
            if (publisherHandle != 0) {
                if (libPublisher != null) {
                    libPublisher.SmartPublisherClose(publisherHandle);
                    publisherHandle = 0;
                }
            }
        }
        libPublisher.UnInitRtspServer();
        super.onDestroy();
    }

以上就是Android平台数据采集、编码并推送的大概流程,感兴趣的开发者可参考下。

目录
打赏
0
0
0
0
70
分享
相关文章
Android平台如何不推RTMP|不发布RTSP流|不实时录像|不回传GB28181数据时实时快照?
本文介绍了一种在Android平台上实现实时截图快照的方法,尤其适用于无需依赖系统接口的情况,如在RTMP推送、RTSP服务或GB28181设备接入等场景下进行截图。通过底层模块(libSmartPublisher.so)实现了截图功能,封装了`SnapShotImpl.java`类来管理截图流程。此外,提供了关键代码片段展示初始化SDK实例、执行截图、以及在Activity销毁时释放资源的过程。此方案还考虑到了快照数据的灵活处理需求,符合GB/T28181-2022的技术规范。对于寻求更灵活快照机制的开发者来说,这是一个值得参考的设计思路。
152 1
安卓手机远程连接登录Windows服务器教程
安卓手机远程连接登录Windows服务器教程
951 4
搭建rtmp流媒体服务器的步骤
网络上很多问文章介绍使用ffmpeg推送和拉流,经常遗漏安装rtsp-simple-server的步骤,执行推流命令:
372 0
termux+anlinux+Rvnc viewer来使安卓手机(平板)变成linux服务器
本文介绍了如何在Android设备上安装Termux和AnLinux,并通过这些工具运行Ubuntu系统和桌面环境。
864 2
termux+anlinux+Rvnc viewer来使安卓手机(平板)变成linux服务器
Android平台一对一音视频通话方案大比拼:WebRTC VS RTMP VS RTSP,谁才是王者?
【9月更文挑战第4天】本文详细对比了在Android平台上实现一对一音视频通话时常用的WebRTC、RTMP及RTSP三种技术方案。从技术原理、性能表现与开发难度等方面进行了深入分析,并提供了示例代码。WebRTC适合追求低延迟和高质量的场景,但开发成本较高;RTMP和RTSP则在简化开发流程的同时仍能保持较好的传输效果,适用于不同需求的应用场景。
471 1
Android平台RTMP推送|轻量级RTSP服务如何实现麦克风|扬声器声音采集切换
Android平台扬声器播放声音的采集,在无纸化同屏等场景下,意义很大,早期低版本的Android设备,是没法直接采集扬声器audio的(从Android 10开始支持),所以,如果需要采集扬声器audio,需要先做系统版本判断,添加相应的权限。
183 0
Android平台实现屏幕录制(屏幕投影)|音频播放采集|麦克风采集并推送RTMP或轻量级RTSP服务
Android平台屏幕采集、音频播放声音采集、麦克风采集编码打包推送到RTMP和轻量级RTSP服务的相关技术实现,做成高稳定低延迟的同屏系统,还需要有配套好的RTMP、RTSP直播播放器
118 0
Android平台RTMP推送|轻量级RTSP服务|GB28181接入之文字、png图片水印的精进之路
本文探讨了Android平台上推流模块中添加文字与PNG水印的技术演进。自2015年起,为了满足应急指挥及安防领域的需求,逐步发展出三代水印技术:第一代为静态文字与图像水印;第二代实现了动态更新水印内容的能力,例如实时位置与时间信息;至第三代,则优化了数据传输效率,直接使用Bitmap对象传递水印数据至JNI层,减少了内存拷贝次数。这些迭代不仅提升了用户体验和技术效率,也体现了开发者追求极致与不断创新的精神。
Android平台如何实现多路低延迟RTSP|RTMP播放?
本文档详细介绍了大牛直播SDK在Android平台上实现RTSP与RTMP流媒体播放及录像功能的技术细节。早在2015年,SDK的第一版就已经支持了多实例播放,并且通过简单的实例封装就能轻松实现。文档中提供了代码示例,展示了如何开启播放、停止播放以及开始和停止录像等功能。此外,SDK还提供了丰富的配置选项,例如设置录像目录、文件大小限制、转码选项等。总结部分列出了该SDK的关键特性,包括但不限于高稳定性和低延迟的播放能力、多实例支持、事件回调、硬解码支持、网络状态监控以及复杂的网络环境处理等。这些功能使得SDK能够应对各种应用场景,特别是在对延迟和稳定性有极高要求的情况下表现优异。
184 5
穿越数字洪流,揭秘Unity3d中的视频魔法!Windows、Android和iOS如何征服RTSP与RTMP的终极指南!
【8月更文挑战第15天】在数字媒体的海洋中,实时视频流是连接世界的桥梁。对于那些渴望在Unity3d中搭建这座桥梁的开发者来说,本文将揭示如何在Windows、Android和iOS平台上征服RTSP与RTMP的秘密。我们将深入探讨这两种协议的特性,以及在不同平台上实现流畅播放的技巧。无论你是追求稳定性的RTSP拥趸,还是低延迟的RTMP忠实粉丝,这里都有你需要的答案。让我们一起穿越数字洪流,探索Unity3d中视频魔法的世界吧!
188 2

热门文章

最新文章

下一篇
oss创建bucket
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等