Blame view

trunk/research/players/srs_publisher/src/srs_publisher.as 20.7 KB
winlin authored
1 2 3
package
{
    import flash.display.Sprite;
winlin authored
4 5 6 7 8 9 10 11 12
    import flash.display.StageAlign;
    import flash.display.StageScaleMode;
    import flash.events.Event;
    import flash.events.NetStatusEvent;
    import flash.external.ExternalInterface;
    import flash.media.Camera;
    import flash.media.H264Profile;
    import flash.media.H264VideoStreamSettings;
    import flash.media.Microphone;
13 14 15
    import flash.media.MicrophoneEnhancedMode;
    import flash.media.MicrophoneEnhancedOptions;
    import flash.media.SoundCodec;
winlin authored
16 17 18
    import flash.media.Video;
    import flash.net.NetConnection;
    import flash.net.NetStream;
19 20
    import flash.system.Security;
    import flash.system.SecurityPanel;
winlin authored
21
    import flash.ui.ContextMenu;
22
    import flash.ui.ContextMenuItem;
winlin authored
23
    import flash.utils.setTimeout;
winlin authored
24 25 26
    
    public class srs_publisher extends Sprite
    {
winlin authored
27 28 29 30 31
        // user set id.
        private var js_id:String = null;
        // user set callback
        private var js_on_publisher_ready:String = null;
        private var js_on_publisher_error:String = null;
32
        private var js_on_publisher_warn:String = null;
winlin authored
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
        
        // publish param url.
        private var user_url:String = null;
        // play param, user set width and height
        private var user_w:int = 0;
        private var user_h:int = 0;
        private var user_vcodec:Object = {};
        private var user_acodec:Object = {};
        
        // media specified.
        private var media_conn:NetConnection = null;
        private var media_stream:NetStream = null;
        private var media_video:Video = null;
        private var media_camera:Camera = null;
        private var media_microphone:Microphone = null;
        
        // error code.
50 51 52
        private const error_camera_get:int = 100;
        private const error_microphone_get:int = 101;
        private const error_camera_muted:int = 102;
53 54
        private const error_connection_closed:int = 103;
        private const error_connection_failed:int = 104;
winlin authored
55
        
winlin authored
56 57
        public function srs_publisher()
        {
winlin authored
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
            if (!this.stage) {
                this.addEventListener(Event.ADDED_TO_STAGE, this.system_on_add_to_stage);
            } else {
                this.system_on_add_to_stage(null);
            }
        }
        
        /**
         * system event callback, when this control added to stage.
         * the main function.
         */
        private function system_on_add_to_stage(evt:Event):void {
            this.removeEventListener(Event.ADDED_TO_STAGE, this.system_on_add_to_stage);
            
            this.stage.align = StageAlign.TOP_LEFT;
            this.stage.scaleMode = StageScaleMode.NO_SCALE;
            
            this.contextMenu = new ContextMenu();
            this.contextMenu.hideBuiltInItems();
            
            var flashvars:Object = this.root.loaderInfo.parameters;
            
            if (!flashvars.hasOwnProperty("id")) {
                throw new Error("must specifies the id");
            }
            
            this.js_id = flashvars.id;
            this.js_on_publisher_ready = flashvars.on_publisher_ready;
            this.js_on_publisher_error = flashvars.on_publisher_error;
87
            this.js_on_publisher_warn = flashvars.on_publisher_warn;
winlin authored
88
            
89 90 91 92 93 94 95 96 97 98 99 100
            // initialized size.
            this.user_w = flashvars.width;
            this.user_h = flashvars.height;
            
            // try to get the camera, if muted, alert the security and requires user to open it.
            var c:Camera = Camera.getCamera();
            if (c.muted) {
                Security.showSettings(SecurityPanel.PRIVACY);
            }
            
            __show_local_camera(c);
            
winlin authored
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
            flash.utils.setTimeout(this.system_on_js_ready, 0);
        }
        
        /**
         * system callack event, when js ready, register callback for js.
         * the actual main function.
         */
        private function system_on_js_ready():void {
            if (!flash.external.ExternalInterface.available) {
                trace("js not ready, try later.");
                flash.utils.setTimeout(this.system_on_js_ready, 100);
                return;
            }
            
            flash.external.ExternalInterface.addCallback("__publish", this.js_call_publish);
            flash.external.ExternalInterface.addCallback("__stop", this.js_call_stop);
            
            var cameras:Array = Camera.names;
            var microphones:Array = Microphone.names;
            trace("retrieve system cameras(" + cameras + ") and microphones(" + microphones + ")");
            
            flash.external.ExternalInterface.call(this.js_on_publisher_ready, this.js_id, cameras, microphones);
        }
        
        /**
        * notify the js an error occur.
        */
        private function system_error(code:int, desc:String):void {
            trace("system error, code=" + code + ", error=" + desc);
            flash.external.ExternalInterface.call(this.js_on_publisher_error, this.js_id, code);
        }
132 133 134 135
        private function system_warn(code:int, desc:String):void {
            trace("system warn, code=" + code + ", error=" + desc);
            flash.external.ExternalInterface.call(this.js_on_publisher_warn, this.js_id, code);
        }
winlin authored
136
        
137 138
        // srs infos
        private var srs_server:String = null;
139 140
        private var srs_primary:String = null;
        private var srs_authors:String = null;
141
        private var srs_id:String = null;
142
        private var srs_pid:String = null;
143
        private var srs_server_ip:String = null;
144 145 146 147 148 149
        private function update_context_items():void {
            // for context menu
            var customItems:Array = [new ContextMenuItem("SrsPlayer")];
            if (srs_server != null) {
                customItems.push(new ContextMenuItem("Server: " + srs_server));
            }
150
            if (srs_primary != null) {
winlin authored
151
                customItems.push(new ContextMenuItem("Primary: " + srs_primary));
152 153 154
            }
            if (srs_authors != null) {
                customItems.push(new ContextMenuItem("Authors: " + srs_authors));
155
            }
156 157 158
            if (srs_server_ip != null) {
                customItems.push(new ContextMenuItem("SrsIp: " + srs_server_ip));
            }
159 160 161
            if (srs_pid != null) {
                customItems.push(new ContextMenuItem("SrsPid: " + srs_pid));
            }
162 163 164 165 166 167
            if (srs_id != null) {
                customItems.push(new ContextMenuItem("SrsId: " + srs_id));
            }
            contextMenu.customItems = customItems;
        }
        
winlin authored
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
        /**
         * publish stream to server.
         * @param url a string indicates the rtmp url to publish.
         * @param _width, the player width.
         * @param _height, the player height.
         * @param vcodec an object contains the video codec info.
         * @param acodec an object contains the audio codec info.
         */
        private function js_call_publish(url:String, _width:int, _height:int, vcodec:Object, acodec:Object):void {
            trace("start to publish to " + url + ", vcodec " + JSON.stringify(vcodec) + ", acodec " + JSON.stringify(acodec));
            
            this.user_url = url;
            this.user_w = _width;
            this.user_h = _height;
            this.user_vcodec = vcodec;
            this.user_acodec = acodec;
            
            this.js_call_stop();
            
            // microphone and camera
188 189 190 191 192 193
            var microphone:Microphone = null;
            //microphone = Microphone.getEnhancedMicrophone(acodec.device_code);
            if (!microphone) {
                microphone = Microphone.getMicrophone(acodec.device_code);
            }
            if(microphone == null){
194 195
                this.system_error(this.error_microphone_get, "failed to open microphone " + acodec.device_code + "(" + acodec.device_name + ")");
                return;
winlin authored
196
            }
197
            // ignore muted, for flash will require user to access it.
winlin authored
198 199
            
            // Remark: the name is the index!
200 201
            var camera:Camera = Camera.getCamera(vcodec.device_code);
            if(camera == null){
202
                this.system_error(this.error_camera_get, "failed to open camera " + vcodec.device_code + "(" + vcodec.device_name + ")");
winlin authored
203 204
                return;
            }
205 206
            // ignore muted, for flash will require user to access it.
            // but we still warn user.
207
            if(camera && camera.muted){
208 209
                this.system_warn(this.error_camera_muted, "Access Denied, camera " + vcodec.device_code + "(" + vcodec.device_name + ") is muted");
            }
winlin authored
210
            
211 212
            this.media_camera = camera;
            this.media_microphone = microphone;
winlin authored
213 214 215 216 217 218 219
            
            this.media_conn = new NetConnection();
            this.media_conn.client = {};
            this.media_conn.client.onBWDone = function():void {};
            this.media_conn.addEventListener(NetStatusEvent.NET_STATUS, function(evt:NetStatusEvent):void {
                trace ("NetConnection: code=" + evt.info.code);
                
220 221
                if (evt.info.hasOwnProperty("data") && evt.info.data) {
                    if (evt.info.data.hasOwnProperty("srs_server")) {
222
                        srs_server = evt.info.data.srs_server;
223
                    }
224 225 226 227 228
                    if (evt.info.data.hasOwnProperty("srs_primary")) {
                        srs_primary = evt.info.data.srs_primary;
                    }
                    if (evt.info.data.hasOwnProperty("srs_authors")) {
                        srs_authors = evt.info.data.srs_authors;
229 230 231
                    }
                    if (evt.info.data.hasOwnProperty("srs_id")) {
                        srs_id = evt.info.data.srs_id;
232
                    }
233 234 235
                    if (evt.info.data.hasOwnProperty("srs_pid")) {
                        srs_pid = evt.info.data.srs_pid;
                    }
236 237 238
                    if (evt.info.data.hasOwnProperty("srs_server_ip")) {
                        srs_server_ip = evt.info.data.srs_server_ip;
                    }
239
                    update_context_items();
240
                }
241 242 243 244 245 246 247 248 249 250 251

                if (evt.info.code == "NetConnection.Connect.Closed") {
                    js_call_stop();
                    system_error(error_connection_closed, "server closed the connection");
                    return;
                }
                if (evt.info.code == "NetConnection.Connect.Failed") {
                    js_call_stop();
                    system_error(error_connection_failed, "connect to server failed");
                    return;
                }
252
                
winlin authored
253 254 255 256 257 258 259 260 261 262 263 264 265
                // TODO: FIXME: failed event.
                if (evt.info.code != "NetConnection.Connect.Success") {
                    return;
                }
                
                media_stream = new NetStream(media_conn);
                media_stream.client = {};
                media_stream.addEventListener(NetStatusEvent.NET_STATUS, function(evt:NetStatusEvent):void {
                    trace ("NetStream: code=" + evt.info.code);
                    
                    // TODO: FIXME: failed event.
                });
                
266 267
                __build_video_codec(media_stream, camera, vcodec);
                __build_audio_codec(media_stream, microphone, acodec);
winlin authored
268 269
                
                if (media_microphone) {
270
                    media_stream.attachAudio(microphone);
winlin authored
271 272
                }
                if (media_camera) {
273
                    media_stream.attachCamera(camera);
winlin authored
274 275 276 277 278
                }
                
                var streamName:String = url.substr(url.lastIndexOf("/"));
                media_stream.publish(streamName);
                
279
                __show_local_camera(media_camera);
winlin authored
280 281 282 283 284 285 286 287 288 289 290
            });
            
            var tcUrl:String = this.user_url.substr(0, this.user_url.lastIndexOf("/"));
            this.media_conn.connect(tcUrl);
        }
        
        /**
         * function for js to call: to stop the stream. ignore if not publish.
         */
        private function js_call_stop():void {
            if (this.media_stream) {
291 292
                this.media_stream.attachAudio(null);
                this.media_stream.attachCamera(null);
winlin authored
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
                this.media_stream.close();
                this.media_stream = null;
            }
            if (this.media_conn) {
                this.media_conn.close();
                this.media_conn = null;
            }
        }
        
        private function __build_audio_codec(stream:NetStream, m:Microphone, acodec:Object):void {
            if (!m) {
                return;
            }
            
            // if no microphone, donot set the params.
            if(m == null){
                return;
            }
            
            // use default values.
            var microEncodeQuality:int = 8;
            var microRate:int = 22; // 22 === 22050 Hz
            
            trace("[Publish] audio encoding parameters: " 
winlin authored
317
                + "audio(microphone) codec=" + acodec.codec + "encodeQuality=" + microEncodeQuality
winlin authored
318 319 320 321 322 323 324 325 326 327 328 329
                + ", rate=" + microRate + "(22050Hz)"
            );
            
            // The encoded speech quality when using the Speex codec. Possible values are from 0 to 10. The default value is 6. Higher numbers 
            // represent higher quality but require more bandwidth, as shown in the following table. The bit rate values that are listed represent 
            // net bit rates and do not include packetization overhead.
            m.encodeQuality = microEncodeQuality;
            
            // The rate at which the microphone is capturing sound, in kHz. Acceptable values are 5, 8, 11, 22, and 44. The default value is 8 kHz 
            // if your sound capture device supports this value. Otherwise, the default value is the next available capture level above 8 kHz that 
            // your sound capture device supports, usually 11 kHz.
            m.rate = microRate;
330 331
            
            // see: http://www.adobe.com/cn/devnet/flashplayer/articles/acoustic-echo-cancellation.html
winlin authored
332 333 334 335 336 337 338 339 340
            if (acodec.codec == "nellymoser") {
                m.codec = SoundCodec.NELLYMOSER;
            } else if (acodec.codec == "pcma") {
                m.codec = SoundCodec.PCMA;
            } else if (acodec.codec == "pcmu") {
                m.codec = SoundCodec.PCMU;
            } else {
                m.codec = SoundCodec.SPEEX;
            }
341
            m.framesPerPacket = 1;
winlin authored
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
        }
        private function __build_video_codec(stream:NetStream, c:Camera, vcodec:Object):void {
            if (!c) {
                return;
            }
            
            if(vcodec.codec == "vp6"){
                trace("use VP6, donot use H.264 publish encoding.");
                return;
            }

            var x264profile:String = (vcodec.profile == "main") ? H264Profile.MAIN : H264Profile.BASELINE;
            var x264level:String = vcodec.level;
            var cameraFps:Number = Number(vcodec.fps);
            var x264KeyFrameInterval:int = int(vcodec.gop * cameraFps);
            var cameraWidth:int = String(vcodec.size).split("x")[0];
            var cameraHeight:int = String(vcodec.size).split("x")[1];
            var cameraBitrate:int = int(vcodec.bitrate);
            
            // use default values.
            var cameraQuality:int = 85;
            
            trace("[Publish] video h.264(x264) encoding parameters: " 
                + "profile=" + x264profile 
                + ", level=" + x264level
                + ", keyFrameInterval(gop)=" + x264KeyFrameInterval
                + "; video(camera) width=" + cameraWidth
                + ", height=" + cameraHeight
                + ", fps=" + cameraFps
                + ", bitrate=" + cameraBitrate
                + ", quality=" + cameraQuality
            );
            
            var h264Settings:H264VideoStreamSettings = new H264VideoStreamSettings();
            // we MUST set its values first, then set the NetStream.videoStreamSettings, or it will keep the origin values.
            h264Settings.setProfileLevel(x264profile, x264level); 
            stream.videoStreamSettings = h264Settings;
            // the setKeyFrameInterval/setMode/setQuality use the camera settings.
            // http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/media/VideoStreamSettings.html
            // Note This feature will be supported in future releases of Flash Player and AIR, for now, Camera parameters are used.
            //
            //h264Settings.setKeyFrameInterval(4);
            //h264Settings.setMode(800, 600, 15);
            //h264Settings.setQuality(500, 0);
            
            // set the camera and microphone.
            
            // setKeyFrameInterval(keyFrameInterval:int):void
            // 	keyFrameInterval:int — A value that specifies which video frames are transmitted in full (as keyframes) instead of being 
            //		interpolated by the video compression algorithm. A value of 1 means that every frame is a keyframe, a value of 3 means 
            //		that every third frame is a keyframe, and so on. Acceptable values are 1 through 48.
            c.setKeyFrameInterval(x264KeyFrameInterval);
            
            // setMode(width:int, height:int, fps:Number, favorArea:Boolean = true):void
            //  width:int — The requested capture width, in pixels. The default value is 160.
            //  height:int — The requested capture height, in pixels. The default value is 120.
            //  fps:Number — The requested rate at which the camera should capture data, in frames per second. The default value is 15.
            c.setMode(cameraWidth, cameraHeight, cameraFps);
            
            // setQuality(bandwidth:int, quality:int):void
            //  bandwidth:int — Specifies the maximum amount of bandwidth that the current outgoing video feed can use, in bytes per second. 
            //		To specify that the video can use as much bandwidth as needed to maintain the value of quality, pass 0 for bandwidth. 
            //		The default value is 16384.
            //  quality:int — An integer that specifies the required level of picture quality, as determined by the amount of compression 
            // 		being applied to each video frame. Acceptable values range from 1 (lowest quality, maximum compression) to 100 
            //		(highest quality, no compression). To specify that picture quality can vary as needed to avoid exceeding bandwidth, 
            //		pass 0 for quality.
            //  winlin:
410
            //		bandwidth is in Bps not kbps. 
winlin authored
411
            //		quality=1 is lowest quality, 100 is highest quality.
412
            c.setQuality(cameraBitrate / 8.0 * 1000, cameraQuality);
winlin authored
413
        }
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
        
        private function __show_local_camera(c:Camera):void {
            if (this.media_video) {
                this.media_video.attachCamera(null);
                this.removeChild(this.media_video);
                this.media_video = null;
            }
            
            // show local camera
            media_video = new Video();
            media_video.attachCamera(c);
            media_video.smoothing = true;
            addChild(media_video);
            
            // rescale the local camera.
            var cw:Number = user_h * c.width / c.height;
            if (cw > user_w) {
                var ch:Number = user_w * c.height / c.width;
                media_video.width = user_w;
                media_video.height = ch;
            } else {
                media_video.width = cw;
                media_video.height = user_h;
            }
            media_video.x = (user_w - media_video.width) / 2;
            media_video.y = (user_h - media_video.height) / 2;
            
            __draw_black_background(user_w, user_h);
            
            // lowest layer, for mask to cover it.
            setChildIndex(media_video, 0);
        }
        
        /**
         * draw black background and draw the fullscreen mask.
         */
        private function __draw_black_background(_width:int, _height:int):void {
            // draw black bg.
            this.graphics.beginFill(0x00, 1.0);
            this.graphics.drawRect(0, 0, _width, _height);
            this.graphics.endFill();
            
            // draw the fs mask.
            //this.control_fs_mask.graphics.beginFill(0xff0000, 0);
            //this.control_fs_mask.graphics.drawRect(0, 0, _width, _height);
            //this.control_fs_mask.graphics.endFill();
        }
winlin authored
461 462
    }
}