events {
    worker_connections 1024;
}

error_log /dev/stdout info;

http {
    sendfile off;                           # on|off. Toggles the use of sendfile. Default=off. For optimal HLS delivery disable this.
    tcp_nodelay on;                         # on|off. Forces a socket to send the data in its buffer, whatever the packet size. Default=on.
    tcp_nopush on;                          # on|off. Sends the response header and beginning of a file in one packet. Default=off.
    server_tokens off;                      # on|off|build. Toggles showing nginx version in the response header field. Default=on.
    keepalive_timeout 65;                   # A keep-alive client connection will stay open for .. on the server side. Use 0 to disable. Default=75s
    types_hash_max_size 2048;               # Sets the maximum size of the types hash tables. Default=1024.
    server_name_in_redirect off;            # Toggles the use of the primary server name, specified by the server_name directive. Default=off.
    server_names_hash_bucket_size 64;       # Sets the bucket size for the server names hash tables depending on processor's cache line, 32|64|128.
    default_type application/octet-stream;  # Emit this MIME type for all requests.

    access_log /dev/stdout;

    ## Include configuration files from these locations ##
    include /etc/nginx/mime.types;

    gzip off;               # on|off. Compresses responses using gzip method. Helps to reduce size of transmitted data by half or more. Default=off
    # gzip_vary on;         # More info on zip variables is found here: https://nginx.org/en/docs/http/ngx_http_gzip_module.html
    gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    server {
        listen 18080;

        location = /stat {
            rtmp_stat all;
            #rtmp_stat_stylesheet stat.xsl;
            #auth_basic Restricted Content;         # Create a valid .htpasswd before uncommenting this.
            #auth_basic_user_file .htpasswd;        # Create a valid .htpasswd before uncommenting this.
 
        }

        location = /control {
            rtmp_control all;
            #add_header Access-Control-Allow-Origin * always;
        }
    }

    server {
        listen 8080;

        location / {
            proxy_pass http://frontend:5001;
            include /etc/nginx/mime.types;
        }

        location /fallback {
            root /www;
            add_header Cache-Control no-cache;
            add_header Access-Control-Allow-Origin *;
        }

        location /hls {
            types {
                application/vnd.apple.mpegurl m3u8;
                video/mp2t ts;
            }
            root /tmp;
 
            add_header Cache-Control no-cache;
 
            autoindex on;
            #alias /www/hls;                      # << Take note of this line. Change it when required.
 
            # To avoid issues with cross-domain HTTP requests (e.g. during development)
            add_header 'Access-Control-Allow-Origin' '*' always;
 
            expires -1;
            add_header Strict-Transport-Security "max-age=63072000";
            add_header 'Access-Control-Expose-Headers' 'Content-Length';
            if ($request_method = 'OPTIONS') {
                add_header 'Access-Control-Allow-Origin' '*';
                add_header 'Access-Control-Max-Age' 1728000;
                add_header 'Content-Type' 'text/plain charset=UTF-8';
                add_header 'Content-Length' 0;
                return 204;
            }
        }
 
        location /flv {
            flv_live on;
            add_header Access-Control-Allow-Origin *;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

    }
}

rtmp {
    access_log /dev/stdout;
    server {
        listen 1935; # Listen on standard RTMP port

        application live {      # Name it whatever you prefer. You will need at least one application, you can have many more.
            live on;                # on|off. Enables this application and allowing live streaming to it. Default=on.
            # max_streams 32;       # Sets maximum number of RTMP streams. Default value is 32 which is usually ok for most cases. Default=32.
            # max_connections 100;  # Sets maximum number of connections for rtmp engine. Default=off.
            meta on;                # on|copy|off. Receive metadata packets containing predefined fields like width, height etc. Default=on.
            interleave off;         # on|off. Audio and video data is transmitted on the same RTMP chunk stream. Default=off.
            wait_key on;            # on|off. Makes video stream start with a key frame. Default=off.
            wait_video off;         # on|off. Disable audio until first video frame is sent (can cause delay). Default=off.
            drop_idle_publisher 10s;# Drop publisher that has been idle for this time. Only works when connection is in publish mode. Default=off
            sync 300ms;             # When timestamp difference exceeds the value specifiedan absolute frame is sent fixing that. Default=300ms.
            play_restart off;       # on|off. If enabled sends "NetStream.Play.Start" and "NetStream.Play.Stop" every time publishing starts or stops. Default=off.
            idle_streams on;        # on|off. If disabled prevents viewers from connecting to idle/nonexistent streams and disconnects all. Default=on.

            ## NOTIFICATIONS  - This section has too many options to include in this example config. ##
            ## Notifications use HTTP callback to inform subscribers that stream has started. You will need a website that can handle these. ##
            ## These option go beyond the scope of this configuration file as it contains lots of info. Please visit this url for more info: ##
            ## https://github.com/arut/nginx-rtmp-module/wiki/Directives#notify ##
            publish_notify on;     ## on|off. Send "NetStream.Play.PublishNotify" & "NetStream.Play.UnpublishNotify" to subscribers. Default=off
            on_publish http://auth:8081/;
            notify_method get;
            # on_play http://www.example.com/plugin/Live/on_play.php;
            # on_record_done http://www.example.com/plugin/Live/on_record_done.php';

            ## PUBLISHING ##
            allow 127.0.0.1;            # If you decice to harden these rules, it is adviced to uncomment this line.
            allow publish all;          # Anybody from any location can stream to this application. Comment this out if you want to use deny publish.
            #deny publish all;          # Nobody can stream to the server except those that you've set in previous lines.

            ## PLAYING  ##
            allow play 127.0.0.1;       # Localhost can play the stream from this application. Must be set if you decide to use push later on!
            #allow play all;            # Anybody can play the RTMP livestream directly. Comment this out if you decide to use the next option.
            deny play all;              # Nobody can play the RTMP stream except those that we've set in lines above it.

            ## RECORDING
            record off;                     # off|all|audio|video|keyframes|manual. These options sorta speak for themselves.
            record_path /tmp/recordings; # Folder location that will be used to store the recordings. YOU SHOULD CHANGE THIS TO YOUR PREFERENCE!
            record_suffix -%d-%b-%y-%T.flv; # Added to recorded filenames. Example uses 'strftime' format results: -24-Apr-13-18:23:38.flv. Default=.flv
            record_unique on;               # on|off. Appends timestamp to recorded files. Otherwise the same file is re-written each time. Default=-off
            record_append off;              # on|off. When turned on recorder appends new data to the old file with no gap. Default=off
            record_lock off;                # on|off. When turned on recorded file gets locked with 'fcntl' call. Default=off.
            record_notify off;              # on|off. Toggles sending "NetStream.Record.Start" and "NetStream.Record.Stop" status messages. Default=off.
            # record_max_size 128K;         # Set maximum file size of the recorded files. No default.
            # record_max_frames 200;        # Sets maximum number of video frames per recorded file. No default.
            # record_interval 15m;          # Restart recording after this number of (milli)seconds/minutes. Zero means no delay. Default=off.
            # recorder name {}              # Create recorder{} block. Multiple recorders can be created withing single application. Example:
            recorder audio {
                record audio;
                record_suffix .audio.flv;
                record_path /tmp/recordings/audio;
                }
            ## This will automatically convert your .flv recordings to mp4 when the stream/recording is stopped. WARNING! This will cause high CPU usage!! ##
            # exec_record_done ffmpeg -i $path -f mp4 /tmp/recordings/$basename.mp4;

            ## RELAYING ##
            ## PULLING STREAMS ##
            ## For more info please visit:  https://github.com/arut/nginx-rtmp-module/wiki/Directives#relay ##
            ## pull url [key=value]*        # Creates pull relay. A stream is pulled from remote machine and becomes available locally. ##
            ## URL Syntax:                  [rtmp://]host[:port][/app[/playpath]] ##
            # pull rtmp://cdn.example.com/live/ch?id=1234 name=channel_a;           # This is an example. Visit above url for more info.
            # session_relay off;            # on|off. On=relay is destroyed when connection is closed. Off=relay is destroyed when stream is closed. Default=off.

            ## PUSHING STREAMS ##
            ## Push has the same syntax as pull. Unlike pull, push directive publishes stream to remote server. ##
            ## This will push the stream from incoming /live application to these below to create HLS and/or Dash streams, or to record or transcode automatically. ##
            ## Only enable HLS push if you are not using ABS options earlier or by using the encoder application ##
            push rtmp://localhost/hls;      # Remember to enable an app called HLS! Disable it if you use transcoding using variable bitrates.

            ## YOUTUBE PUSH OPTIONS ##
            # push rmtp://localhost/youtube; # Uncomment this to use application on localhost (MUST BE SPECIFIED). OR simply use the following line:
            # push rtmp://a.rtmp.youtube.com/live2 /YOUR-LIVE-STREAM-KEY;   # Your RTMP stream will be pushed as it is to Youtube as an RTMP stream.
            ## TWITCH PUSH OPTIONS ##
            # push rmtp://localhost/twitch;  # Uncomment this to use application on localhost (MUST BE SPECIFIED). OR simply use the following line:
            # push rtmp://live-ams.twitch.tv/app /live_YOUR-LIVE-STREAM-KEY;        # Your RTMP stream will be pushed as it is to Twitch as an RTMP stream.
        } 

        application hls {                   # We enabled pushing stream from 'live' application to 'hls' we need to define it of course.
            allow publish 127.0.0.1;
            deny publish all;
            live on;                        # on|off. Enables this application and allowing live streaming to it. Default=on.
            hls on;                         # on|off. Toggles HLS on or off for this application.
            hls_type live;                  # live|event. Live plays from the current live position. Event plays from the start of the playlist. Default=live.
            hls_path /tmp/hls;              # Location to store the video fragment files. Will be created if it doesn't exist.
            hls_fragment 10s;               # Sets HLS fragment length in seconds or minutes. Default=5s.
            hls_playlist_length 5m;         # Sets HLS playlist length in seconds or minutes. Default=30s.
            hls_sync 2ms;                   # Timestamp sync threshold. Prevents crackling noise after conversion from low-res (1KHz) to high-res(90KHz). Default=2ms.
            hls_continuous off;             # on|off. In this mode HLS sequence number is started from where it stopped last time. Old fragments are kept. Default=off.
            hls_nested on;                  # on|off. In this mode a subdirectory of hls_path is created for each stream. Default=off.
            hls_cleanup on;                 # on|off. Nginx cache manager process removes old HLS fragments and playlist files from hls_path. Default=on.
            hls_fragment_naming system;     # system = use system time. sequential = use increasing integers. timestamp = use stream timestamp. Default=sequential.
            hls_fragment_slicing plain;     # plain|aligned. Plain: switch fragment when target duration is reached. Aligned: switch fragment when incoming timestamp is a
                                            # multiple of fragment duration. Makes it possible to generate identical fragments on different nginx instances. Default=plain.
            ## ENCRYPTION KEYS     ## !! Only works if you have certificates defined in your HTTP server block (Usually a seperate file in /sites-available/yourfile.conf)
            # hls_keys on;                          # on|off. Enables HLS encryption. AES-128 method is used to encrypt the HLS fragments. Requires ssl module. Default=off.
            # hls_key_path /tmp/keys;    # Sets the directory where auto-generated HLS keys are saved. Default= hls_path.
            # hls_key_url https://foo.bar/keys;     # Sets url for HLS key file entries. When empty it assumes hls_path. Default= empty.
            # hls_fragments_per_key 100;            # Sets the number of HLS fragments encrypted with the same key. 0 means only one key is created at the publish start and
                                                    # all fragments within the session are encrypted with this key. Default=0.

            ## HLS_VARIANT - Used for variable bitrate streaming. Please read: https://github.com/arut/nginx-rtmp-module/wiki/Directives#hls_variant ##
            ## When hls_variant suffix is matched on stream name then variant playlist is created for the current stream with all entries specified by hls_variant
            ## directives in current application. Stripped name without suffix is used as variant stream name. The original stream is processed as usual.
            ## Optional parameters following the suffix are appended to EXT-X-STREAM-INF in m3u8 playlist. See HLS spec 3.3.10. EXT-X-STREAM-INF for full list.
            #       hls_variant _low BANDWIDTH=288000;      # _low          - Low bitrate, sub-SD resolution
            #       hls_variant _mid BANDWIDTH=448000;      # _mid          - Medium bitrate, SD resolution
            #       hls_variant _high BANDWIDTH=1152000;    # _high         - Higher-than-SD resolution
            #       hls_variant _higher BANDWIDTH=2048000;  # _higher       - High bitrate, HD 720p resolution
            #       hls_variant _src BANDWIDTH=4096000;     # _src          - Source bitrate, source resolution
        }

    }
}

