Suck the cat with code! This paper is participating in[Cat Essay Campaign].
See nuggets official launched a “suction cat” essay activities, I as a pseudo shovel excretion officer whim to try it, after all, the reward is the best keyboard in the hearts of programmersHHKB
Well, although it is a salt fish, but the dream still has to have.
Simply draw a cat with CSS? The feeling is not what depth, and this kind of behavior is more like water article, and there is no competitiveness. Since I don’t write front-end pages and I don’t know how to deeply learn related knowledge, the only thing left is Agora’s live SDK. I used Agora’s AndroidSDK a few years ago to encapsulate the live broadcast room, and now use it to simply run a Demo should not be a big problem? But on the other hand, using mobile phones to broadcast live is certainly not able to withstand the mobile phone, not to mention the serious problem of hot mobile phone, just the battery power problem is enough to eat a pot. So today, let’s live in a different way, live on the computer, let alone 24 hours, even if it’s a month without a problem. When it comes to computer broadcast, we will certainly think of OBS, after all, the anchors of major broadcast platforms are using this software to broadcast, because OBS-Studio project is open source and free, and supports various plug-ins to customize their own live broadcast room, it is really sweet. But if I’m using OBS and I don’t have any knowledge of the code, it doesn’t work, it doesn’t meet the requirements of the Nuggets, so what? I have to start from the bottom. We all know that the bottom layer of audio and video is C, and the best use of audio and video is FFMPEG, and because it is 24h uninterrupted live, then in nas, or the server above the stream, more energy saving, so today we will first use FFMPEG to achieve a simple stream function.
After checking the wiki on the official website and the blog of the big guy, we found that we want to push the streaming video to the streaming media server, so we need to build a streaming media server first, the most popular one on the Internet is to use Nginx to do it.
The Nginx + RTMP server is installed on the MAC
Naginx is a lightweight web service that uses less memory and resources than Apache. Nginx processes requests asynchronously and non-blocking, while Apache is blocking. Nginx is a good choice for HLS or RTMP streaming media servers because of its ability to maintain low resource and low consumption performance under high concurrency.
Install Nginx using Homebrow
(1) Execute clone command,github project (Github.com/denji/homeb…)
brew tap denji/nginx
!!!!!!!!! Brew tap Homebrew /nginx error: Homebrew /nginx is deprecated. They were migrated according to their original values. They were migrated according to their original values. Error: Homebrew /nginx was deprecated.
(2) Run the following installation commands:
brew install nginx-full --with-rtmp-module
Now that the nginx and RTMP modules are installed, it is time to configure the RTMP module for nginx
brew info nginx-full
Copy the code
Nginx installation location:
/usr/local/opt/nginx-full/bin/nginx
Copy the code
Nginx configuration file location:
/usr/local/etc/nginx/nginx.conf
Copy the code
(3) Run the following command to start nginx:
sudo nginx
Copy the code
Two, test:
Open the following address in your browser: http://localhost:8080Copy the code
If the preceding page is displayed, the installation is successful.
If the terminal prompts
Nginx: [emerg] Bind () to 0.0.0.0:8080 Failed (48: Address already in use)Copy the code
If port 8080 is occupied, check the PORT PID
lsof -i tcp:8080
Copy the code
Kill Kill the PID that occupies port 8080
Kill 9603 (replace with PID occupying port 8080)Copy the code
Reload the nginx configuration file
RTMP copy nginx configuration file to nginx.conf file:
vi /usr/local/etc/nginx/nginx.conf
Copy the code
(2) Execute the above command will directly edit, or directly go to the current file with notepad open. Scroll to the end (after the last}, not in {}), add some code, configure, and save.
rtmp { server { listen 1935; Application rtmplive {live on; Set the maximum number of connections for the RTMP engine. Default value: off MAX_connections 1024; } application hls{ live on; hls on; hls_path /usr/local/var/www/hls; hls_fragment 1s; }}}Copy the code
(3) After editing, run the following command to reload the configuration file:
sudo nginx -s reload
Copy the code
Nginx: [alert] could not open error log file: open() "/usr/local/var/log/nginx/error.log" failed (13: Permission denied)
After the command is executed, a dialog box is displayed asking you whether to allow nginx to join the network.
(4) Restart nginx
sudo /usr/local/opt/nginx-full/bin/nginx -s reload
Copy the code
If you did not install nginx on sudo nginx -s reload, you are advised to uninstall nginx and re-install nginx on sudo nginx -s reload. nginx: [emerg] unknown directive “rtmp” in /usr/local/etc/nginx/nginx.conf:119
Nginx:
Reload the configuration file: nginx -s reload log: nginx -s reopen the scene of a stop nginx: nginx -s stop Nginx: nginx -s quitCopy the code
Add sudo before the command if an error message indicating insufficient permission is displayed
Install the FFMEPG tool
brew install ffmpeg
Copy the code
The figure above shows ffMEPG installation completed
Five, local push flow
(1) Set up local video live broadcasting. For example, there are many movies on the computer, and we can achieve real-time live broadcasting by pushing the stream:
A: push flow content playback on your computer Install a support RTMP protocol of video player, Mac can use VLC VLC or use open source projects IINA local download a video file path to/Users/iOS002 / Desktop/loginmovie. Mp4 executing the following command
ffmpeg -re -i /Users/iOS002/Desktop/loginmovie.mp4 -vcodec libx264 -acodec aac -strict -2 -f flv rtmp://localhost:1935/rtmplive/room
Copy the code
Then Open file — Open Network in VLC and type the URL directly in the code:
rtmp://localhost:1935/rtmplive/room
Copy the code
That is, VLC can be used to play the RTMP stream pushed from the terminal in real time.
The effect is shown in figure
B: Watch the stream of computer through mobile phone. Change the address into the stream address by integrating ijkPlayer: The player side uses iJkPlayer optimized for RTMP. Ijkplayer is a cross-platform player based on FFmpeg. This open source project has been used by many apps, among which Inke, Meipai and Douyu use iJkPlayer.
(2) Desktop recording or sharing
ffmpeg -f avfoundation -i "1" -vcodec libx264 -preset ultrafast -acodec libfaac -f flv rtmp://localhost:1935/rtmplive/room
Copy the code
(3) Desktop + microphone
ffmpeg -f avfoundation -i "1:0" -vcodec libx264 -preset ultrafast -acodec libmp3lame -ar 44100 -ac 1 -f flv rtmp://localhost:1935/rtmplive/room
Copy the code
(4), desktop + microphone, and camera to shoot yourself
ffmpeg -f avfoundation -framerate 30 -i "1:0" \-f avfoundation -framerate 30 -video_size 640x480 -i "0" \-c:v libx264 -preset ultrafast \-filter_complex 'overlay=main_w-overlay_w-10:main_h-overlay_h-10' -acodec libmp3lame -ar 44100 -ac 1 -f flv rtmp://localhost:2016/rtmplive/room
Copy the code
Six, mobile phone push flow
You can useLFLiveKitIntegrated into the project to push the stream, LFLiveKit has helped us to achieve video capture, background recording, beauty features, support for H264, AAC coding, dynamic rate change, RTMP transmission, etc., when we developed it was very simplelocalhost:8080Use your computer’s IP address instead:
RTMP: / / 10.0.0.17:1935 / rtmplive/roomCopy the code
Note To check the PC’s LAN IP address over the network, replace localhost.
A: Watch mobile phone push stream through VLC after opening mobile phone live, and then open VLC on the computer (ditto), you can achieve mobile phone push stream, pull stream on the computer play!! (Note: Your phone needs to be connected to the same network as your computer!)
B: You can watch the stream on your mobile phone (this is the final implementation of those live streaming apps in the market) by integrating iJkPlayer and changing the address to the stream address.
PS: A very subtle error:
If you find that your push and pull addresses work fine on your computer but fail on your phone, it’s probably because of the Mac firewall.
ERROR: PILI_RTMP_Connect0, failed to connect socket. 60 (Operation timed out)
ERROR: WriteN, PILI_RTMP send error 9, Bad file descriptor, (140 bytes)
ERROR: PILI_RTMP_Connect0, failed to connect socket. 60 (Operation timed out)
ERROR: WriteN, PILI_RTMP send error 9, Bad file descriptor, (140 bytes)
Copy the code
Disabling the Mac firewall solves the problem.
Simpler streaming media server
mac-local-rtmp-serverAfter installation directly open can generate local push stream live address, we directly copy and paste the address is good, we do not need to do redundant configuration
We type directly into the terminalFfmpeg -f avfoundation - 10 - pixel_format framerate yuyv422 -i "0" - copy - f f FLV RTMP: / / 127.0.0.1 / live/Skkv8MTIF
You can see it like thisPush stream is successful, we use againIINA
To open theRTMP: / / 127.0.0.1 / live/Skkv8MTIF
You can plug into the picture captured by the camera (because I don’t own a cat, so simply take the material of the cat to demonstrate)
You think this is the end of it? No, no, no, this is only a local area network, and it must take 24 hours to masturbate cats regardless of time and place. In this case, I would like to push the video stream to Bilibili. As long as the link is disconnected for a short period of time, the streaming address and streaming code of the live broadcast platform will be the same as before. So HERE I simply wrote a shell script to push the stream, so that we only need to keep automatic push every time we start./bilibili.sh.
### # @Description: # @Author: itgoyo # @E-mail: [email protected] # @Github: itgoyo ### while true do ffmpeg -f avfoundation -framerate 10 -pixel_format yuyv422 -i "0" -f copy -f flv "rtmp://live-push.bilivideo.com/live-bvc/?streamname=live_12767066_6265400&key=0c32218670c24b8ea4bb89xxxxxxx4b6c2&schedu le=rtmp&pflag=9" doneCopy the code
However, sometimes I find that the live broadcast is disconnected and the while loop still fails to push the stream. It may be because the stream server or the stream code is changed due to the long disconnect or other reasons. In this way, I cannot find that the live broadcast has been disconnected in time. So I searched the Internet for the interface data related to the live broadcast of STATION B, and finally I found it. So it simply uses vue to realize a disconnection judgment, then it will call the browser popup window, displayed in the upper right corner of the monitor. This leads to another problem. If you use the browser to listen for disconnections, you need to make sure that the browser is alive, which means that the browser is open, which is not what I’d like it to be. The number of times you can use the previous Server sauce is now limited, and the effect is not obvious. The interface is called once a minute, and the most important code is shown below. The interface is called once a minute.
[sudo]gem install terminal-notifier # The notifier function "Description: Author: itgoyo E-mail: [email protected] Github: itgoyo ''' import json import requests import os from datetime import datetime from threading import Timer def notify(title, subtitle, message,appIcon): t = '-title {! r}'.format(title) s = '-subtitle {! r}'.format(subtitle) m = '-message {! r}'.format(message) i = '-contentImage {! R}'.format(' terminal-notifier {}'.format('.join([m, t, s, I]))) def printTime(inc): print(datetime.now().strftime("%Y-%m-%d %H:%M:%S")) res = requests.get("https://api.bilibili.com/x/space/acc/info?mid=12767066").json() # print(res) # print(res["data"]) # print(res["data"]["live_room"]) # print(res["data"]["live_room"]["liveStatus"]) if (res["data"]["live_room"]["liveStatus"])! = 1: #1 is live, # Calling the function notify(subtitle = res["data"]["live_room"]["title"], Message = '⚡️⚡️ ️⚡ ⚡ appIcon = 'https://i2.hdslb.com/bfs/face/863b88d596eed9dbef28c67a4796bec08e478d79.jpg') t = Timer(inc, printTime,(inc,)) t.start() printTime(1*60)Copy the code
In this case, we may not notice it. In the system alert popover, we set it as resident. As long as you do not click the close button, it will always be displayed in the upper right corner. At least now this has met my needs of 24 hours a day cloud cat, if you have a better solution, welcome to discuss in the comments section, if you have questions can also discuss.
Article Reference:
- Gist.github.com/docPhil99/d…
- Stackoverflow.com/questions/3…