class_docstr: WebGear_RTC is similar to WeGear API in many aspects but utilizes WebRTC technology under the hood instead of Motion JPEG, which
  makes it suitable for building powerful video-streaming solutions for all modern browsers as well as native clients available on
  all major platforms.
  
  WebGear_RTC is implemented with the help of aiortc library which is built on top of asynchronous I/O framework for Web Real-Time
  Communication (WebRTC) and Object Real-Time Communication (ORTC) and supports many features like SDP generation/parsing, Interactive
  Connectivity Establishment with half-trickle and mDNS support, DTLS key and certificate generation, DTLS handshake, etc.
  
  WebGear_RTC can handle multiple consumers seamlessly and provides native support for ICE (Interactive Connectivity Establishment)
  protocol, STUN (Session Traversal Utilities for NAT), and TURN (Traversal Using Relays around NAT) servers that help us to easily
  establish direct media connection with the remote peers for uninterrupted data flow. It also allows us to define our custom Server
  as a source to transform frames easily before sending them across the network(see this doc example).
  
  WebGear_RTC API works in conjunction with Starlette ASGI application and can also flexibly interact with Starlette's ecosystem of
  shared middleware, mountable applications, Response classes, Routing tables, Static Files, Templating engine(with Jinja2), etc.
  
  Additionally, WebGear_RTC API also provides internal wrapper around VideoGear, which itself provides internal access to both
  CamGear and PiGear APIs.
class_docstr_tok: ["WebGear_RTC","is","similar","to","WeGear","API","in","many","aspects","but","utilizes","WebRTC","technology","under","the","hood","instead","of","Motion","JPEG",",","which","makes","it","suitable","for","building","powerful","video-streaming","solutions","for","all","modern","browsers","as","well","as","native","clients","available","on","all","major","platforms",".","WebGear_RTC","is","implemented","with","the","help","of","aiortc","library","which","is","built","on","top","of","asynchronous","I\/O","framework","for","Web","Real-Time","Communication","(","WebRTC",")","and","Object","Real-Time","Communication","(","ORTC",")","and","supports","many","features","like","SDP","generation\/parsing",",","Interactive","Connectivity","Establishment","with","half-trickle","and","mDNS","support",",","DTLS","key","and","certificate","generation",",","DTLS","handshake",",","etc",".","WebGear_RTC","can","handle","multiple","consumers","seamlessly","and","provides","native","support","for","ICE","(","Interactive","Connectivity","Establishment",")","protocol",",","STUN","(","Session","Traversal","Utilities","for","NAT",")",",","and","TURN","(","Traversal","Using","Relays","around","NAT",")","servers","that","help","us","to","easily","establish","direct","media","connection","with","the","remote","peers","for","uninterrupted","data","flow",".","It","also","allows","us","to","define","our","custom","Server","as","a","source","to","transform","frames","easily","before","sending","them","across","the","network","(","see","this","doc","example",")",".","WebGear_RTC","API","works","in","conjunction","with","Starlette","ASGI","application","and","can","also","flexibly","interact","with","Starlette","'s","ecosystem","of","shared","middleware",",","mountable","applications",",","Response","classes",",","Routing","tables",",","Static","Files",",","Templating","engine","(","with","Jinja2",")",",","etc",".","Additionally",",","WebGear_RTC","API","also","provides","internal","wrapper","around","VideoGear",",","which","itself","provides","internal","access","to","both","CamGear","and","PiGear","APIs","."]
docstr: This constructor method initializes the object state and attributes of the WebGear_RTC class.
  
  Parameters:
      enablePiCamera (bool): provide access to PiGear(if True) or CamGear(if False) APIs respectively.
      stabilize (bool): enable access to Stabilizer Class for stabilizing frames.
      camera_num (int): selects the camera module index which will be used as Rpi source.
      resolution (tuple): sets the resolution (i.e. `(width,height)`) of the Rpi source.
      framerate (int/float): sets the framerate of the Rpi source.
      source (based on input): defines the source for the input stream.
      stream_mode (bool): controls the exclusive YouTube Mode.
      backend (int): selects the backend for OpenCV's VideoCapture class.
      colorspace (str): selects the colorspace of the input stream.
      logging (bool): enables/disables logging.
      time_delay (int): time delay (in sec) before start reading the frames.
      options (dict): provides ability to alter Tweak Parameters of WebGear_RTC, CamGear, PiGear & Stabilizer.
docstr_tok: ["This","constructor","method","initializes","the","object","state","and","attributes","of","the","WebGear_RTC","class",".","Parameters",":","enablePiCamera","(","bool",")",":","provide","access","to","PiGear","(","if","True",")","or","CamGear","(","if","False",")","APIs","respectively",".","stabilize","(","bool",")",":","enable","access","to","Stabilizer","Class","for","stabilizing","frames",".","camera_num","(","int",")",":","selects","the","camera","module","index","which","will","be","used","as","Rpi","source",".","resolution","(","tuple",")",":","sets","the","resolution","(","i.e",".","`","(","width",",","height",")","`",")","of","the","Rpi","source",".","framerate","(","int\/float",")",":","sets","the","framerate","of","the","Rpi","source",".","source","(","based","on","input",")",":","defines","the","source","for","the","input","stream",".","stream_mode","(","bool",")",":","controls","the","exclusive","YouTube","Mode",".","backend","(","int",")",":","selects","the","backend","for","OpenCV","'s","VideoCapture","class",".","colorspace","(","str",")",":","selects","the","colorspace","of","the","input","stream",".","logging","(","bool",")",":","enables\/disables","logging",".","time_delay","(","int",")",":","time","delay","(","in","sec",")","before","start","reading","the","frames",".","options","(","dict",")",":","provides","ability","to","alter","Tweak","Parameters","of","WebGear_RTC",",","CamGear",",","PiGear","&","Stabilizer","."]
code: def __init__(
      self,
      enablePiCamera=False,
      stabilize=False,
      source=None,
      camera_num=0,
      stream_mode=False,
      backend=0,
      colorspace=None,
      resolution=(640, 480),
      framerate=25,
      logging=False,
      time_delay=0,
      **options,
  ):
      """
      This constructor method initializes the object state and attributes of the WebGear_RTC class.
  
      Parameters:
          enablePiCamera (bool): provide access to PiGear(if True) or CamGear(if False) APIs respectively.
          stabilize (bool): enable access to Stabilizer Class for stabilizing frames.
          camera_num (int): selects the camera module index which will be used as Rpi source.
          resolution (tuple): sets the resolution (i.e. `(width,height)`) of the Rpi source.
          framerate (int/float): sets the framerate of the Rpi source.
          source (based on input): defines the source for the input stream.
          stream_mode (bool): controls the exclusive YouTube Mode.
          backend (int): selects the backend for OpenCV's VideoCapture class.
          colorspace (str): selects the colorspace of the input stream.
          logging (bool): enables/disables logging.
          time_delay (int): time delay (in sec) before start reading the frames.
          options (dict): provides ability to alter Tweak Parameters of WebGear_RTC, CamGear, PiGear & Stabilizer.
      """
      # raise error(s) for critical Class imports
      import_dependency_safe("starlette" if starlette is None else "")
      import_dependency_safe("aiortc" if aiortc is None else "")
  
      # initialize global params
      self.__logging = logging
  
      custom_data_location = (
          ""  # path to save data-files to custom location
      )
      data_path = ""  # path to WebGear_RTC data-files
      overwrite_default = False
      self.__relay = None  # act as broadcaster
  
      # reformat dictionary
      options = {str(k).strip(): v for k, v in options.items()}
  
      # assign values to global variables if specified and valid
      if options:
          if "custom_data_location" in options:
              value = options["custom_data_location"]
              if isinstance(value, str):
                  assert os.access(
                      value, os.W_OK
                  ), "[WebGear_RTC:ERROR] :: Permission Denied!, cannot write WebGear_RTC data-files to '{}' directory!".format(
                      value
                  )
                  assert os.path.isdir(
                      os.path.abspath(value)
                  ), "[WebGear_RTC:ERROR] :: `custom_data_location` value must be the path to a directory and not to a file!"
                  custom_data_location = os.path.abspath(value)
              else:
                  logger.warning(
                      "Skipped invalid `custom_data_location` value!"
                  )
              del options["custom_data_location"]  # clean
  
          if "overwrite_default_files" in options:
              value = options["overwrite_default_files"]
              if isinstance(value, bool):
                  overwrite_default = value
              else:
                  logger.warning(
                      "Skipped invalid `overwrite_default_files` value!"
                  )
              del options["overwrite_default_files"]  # clean
  
          if "enable_live_broadcast" in options:
              value = options["enable_live_broadcast"]
              if isinstance(value, bool):
                  if value:
                      self.__relay = MediaRelay()
                      options[
                          "enable_infinite_frames"
                      ] = True  # enforce infinite frames
                      logger.critical(
                          "Enabled live broadcasting for Peer connection(s)."
                      )
                  else:
                      None
              else:
                  logger.warning(
                      "Skipped invalid `enable_live_broadcast` value!"
                  )
              del options["enable_live_broadcast"]  # clean
  
      # check if custom certificates path is specified
      if custom_data_location:
          data_path = generate_webdata(
              custom_data_location,
              c_name="webgear_rtc",
              overwrite_default=overwrite_default,
              logging=logging,
          )
      else:
          # otherwise generate suitable path
          data_path = generate_webdata(
              os.path.join(expanduser("~"), ".vidgear"),
              c_name="webgear_rtc",
              overwrite_default=overwrite_default,
              logging=logging,
          )
  
      # log it
      self.__logging and logger.debug(
          "`{}` is the default location for saving WebGear_RTC data-files.".format(
              data_path
          )
      )
  
      # define Jinja2 templates handler
      self.__templates = Jinja2Templates(
          directory="{}/templates".format(data_path)
      )
  
      # define custom exception handlers
      self.__exception_handlers = {
          404: self.__not_found,
          500: self.__server_error,
      }
      # define routing tables
      self.routes = [
          Route("/", endpoint=self.__homepage),
          Route("/offer", self.__offer, methods=["GET", "POST"]),
          Mount(
              "/static",
              app=StaticFiles(directory="{}/static".format(data_path)),
              name="static",
          ),
      ]
  
      # define middleware support
      self.middleware = []
  
      # Handle RTC video server
      if "custom_stream" in options or not (source is None):
          # Handle video source
          self.__default_rtc_server = RTC_VideoServer(
              enablePiCamera=enablePiCamera,
              stabilize=stabilize,
              source=source,
              camera_num=camera_num,
              stream_mode=stream_mode,
              backend=backend,
              colorspace=colorspace,
              resolution=resolution,
              framerate=framerate,
              logging=logging,
              time_delay=time_delay,
              **options,
          )
          # add exclusive reset connection node
          self.routes.append(
              Route(
                  "/close_connection",
                  self.__reset_connections,
                  methods=["POST"],
              )
          )
      else:
          raise ValueError(
              "[WebGear_RTC:ERROR] :: Source cannot be NoneType without Custom Stream(`custom_stream`) defined!"
          )
  
      # copying original routing tables for further validation
      self.__rt_org_copy = self.routes[:]
      # collects peer RTC connections
      self.__pcs = set()
  
file_path: vidgear/vidgear/gears/asyncio/webgear_rtc.py
imports: import os
  import time
  import fractions
  import asyncio
  import logging
  from os.path import expanduser
  from .helper import reducer, generate_webdata, create_blank_frame
  from ..helper import logger_handler, retrieve_best_interpolation, import_dependency_safe, logcurr_vidgear_ver
  from ..videogear import VideoGear
label_desc: Use image node_id 1 to create a new WebGear_RTC object  with example: obj = WebGear_RTC(enablePiCamera, stabilize, source, camera_num, stream_mode, backend, colorspace, resolution, framerate, logging, time_delay)