Stream your videos XNUMX/XNUMX on YouTube

Recently, as a hobby, I have been filming lectures by a psychologist friend. I mount the footage and publish it on my website. A month ago, I hit on the idea of ​​organizing a round-the-clock broadcast of these lectures on YouTube 24/7. A sort of thematic "TV channel" dedicated to personal growth.

I know how to make a normal broadcast. But how to make it so that it was a broadcast of video files? So that it runs 24/7, is flexible, as autonomous as possible, and at the same time does not depend on my home computer in any way. This is what I had to find out.

Stream your videos XNUMX/XNUMX on YouTube

It took several days to find a solution. I studied many forums and various manuals, without which my broadcast simply would not have happened. And now that the prank has worked, I feel the need to share my solution. That's how this article came about.

In short, the final solution is as follows: VPS + ffmeg + bash script. Under the cut, I describe the steps taken and talk about the "pitfalls" that were discovered during the organization of the broadcast.

Step 1 - Where will the broadcast go from?

At the very beginning, it was necessary to decide where the broadcast would be from, where its source would be. The very first thing that came to mind - from home computer. Collect videos into a playlist and start playing them in any video player. Then capture the image from the screen and broadcast it to YouTube. But I almost immediately dismissed this option. to implement it, you need to keep your home computer constantly on, and this is noise from coolers even at night and increased electricity consumption (+ 100-150 kWh every month). And it turns out that it will be impossible to use the home computer during the broadcast. any movement of the mouse will be visible in the broadcast.

Then I began to look away cloud services. I was looking for a ready-made service where I could upload my videos or, for example, insert links to videos from YouTube and it would all be packed into one non-stop broadcast. But I didn't find anything suitable. Maybe I didn't search well. The only thing that fits the bill is restream.io, a service that helps you stream to multiple platforms at the same time. They seem to be able to upload their videos. But this service was created for a completely different purpose, and they expect the broadcast to last only a couple of hours. I think that if through this service it was possible to organize a round-the-clock broadcast, then it would shoot into tens or even hundreds of dollars a month. But I still wanted to organize the broadcast either for free or with minimal financial investment.

It became clear that under the broadcast you need or separate device Or even a separate computer. I thought in the direction of something like the Raspberry Pi. And what? He doesn't have a cooler. I recorded the video on a USB flash drive, plugged in an Ethernet cable and let it lie somewhere in a secluded place, it broadcasts. Option. But I didn’t have the board itself, nor the experience of working with it, so I also refused this option.

As a result, I came across a certain discussion where they discussed the creation own server broadcasts. It was not exactly what I was looking for, but I got the main idea - you can use the server! In that discussion, it was suggested to use a bunch of VPS + nginx + OBS. It became clear that this bundle could suit me. The only embarrassing thing was that I had never administered a server and it seemed to me that my own dedicated server was confusing and expensive. I decided to find out how much it would cost to rent a server in the minimum configuration and was pleasantly surprised.

Stream your videos XNUMX/XNUMX on YouTube

Prices are in Belarusian rubles and these are just crumbs. For understanding, 8 Belarusian rubles is about 3.5 dollars or 240 Russian rubles. For a month of using a full-fledged computer that is turned on 24/7 and has fast Internet access. For some reason, this discovery became very joyful for me, and for several days I walked terribly pleased like a child who discovered space rockets 🙂

By the way, I took advantage of the offer of the very first site that Google gave me for the query “rent a VPS”. Perhaps there are even more budget solutions, but this price suited me and I did not look further.

When creating a server, you can choose the operating system under which it will run. On any of the listed systems, you can organize a broadcast and make a choice based on your preferences and financial capabilities (for a server with Windows, they ask for an additional fee). I chose CentOS. Just because I had little experience with her before.

Stream your videos XNUMX/XNUMX on YouTube

Step 2 - Server Setup

The first thing after creating a server is to connect to it via SSH. At first I used PuTTy, but then I started using the Secure Shell App, which runs in Google Chrome. That made me feel more comfortable.

Then I changed the hostname, set up time synchronization on the server, updated the system, fiddled with iptables ... and did a bunch of other things, but not because it was necessary. I was just interested in setting up the server and I did it. I love it when it works 🙂

Here are the steps to take:

  1. Connect the EPEL repository.
  2. Set up an FTP server (I chose vsftp).
  3. Install ffmpeg.

I will not give the commands in detail, this instruction is rather conceptual in order to convey the general plan of action. If you have any difficulties with any of the steps, they are quickly solved by a query in the search engine like “CentOS connect EPEL” or “CentOS FTP server installation”. And on the first links you can find detailed step-by-step instructions.

So, as I wrote before, I needed a bunch of VPS + nginx + OBS. VPS - done. But on other points, questions began to arise. OBS is a program for broadcasting, Open Broadcaster Software. And it only works with streams i.e. for example, it takes an image from a webcam and broadcasts it. Or screen recording. Or it redirects an already ongoing broadcast to another site. And I don't have a stream, I only have a set of video files that I need to make a stream.

I began to dig in this direction and came across ffmpeg. FFmpeg is a set of free and open source libraries that allow you to record, convert and stream digital audio and video recordings in various formats.

And I was very surprised how much ffmpeg can do. If you want - pull the sound from the video. If you want, it will cut out a fragment of the video without transcoding. If you want, it will convert from one format to another. And many, many more. Up to the point that he can specify a file, he will convert it into a stream and transfer it to YouTube himself. Everything, the chain is assembled. It remains only to refine the nuances.

Step 3 - Broadcast Setup

We create a broadcast on YouTube. At this stage, we only need a link and a broadcast key. They are highlighted in red in the screenshot below.

Stream your videos XNUMX/XNUMX on YouTube

Next uploading video files to the server, which we plan to broadcast. Actually, FTP is needed only for this stage. If you have another convenient way to upload files to the server, then the FTP server can not be raised.

Stream to YouTube. To start broadcasting, you need to run ffmpeg with several attributes. This is what the shortest command I got looks like:

ffmpeg -re -i lecture1.mp4 -f flv rtmp://a.rtmp.youtube.com/live2/%КЛЮЧ_ТРАНСЛЯЦИИ%

Attribute interpretation-re - indicates that the file should be converted to a stream.

-i – indicates which file is to be played. It is important that the command is run from the same directory where the video file itself is located. Otherwise, you should specify an absolute link to the file, like /usr/media/lecture1.mp4.

-f – sets the format of the output file. In my case, it turns out that ffmpeg converts my file from mp4 to flv on the fly.

And at the end, we indicate the data that we took from YouTube on the broadcast settings page, i.e. the address to which you want to send data, and the broadcast key so that the broadcast is displayed on your channel.

If you did everything correctly, then after running this command, YouTube will see the transmitted stream. To start the broadcast, all you have to do is click the "Start Broadcast" button in YouTube itself.

Step 4 - Add Autonomy

Congratulations! Now you know how to start broadcasting from a video file. But this is not enough for a round-the-clock broadcast. It is important that after the end of the playback of the first video, the next one starts immediately, and when all the videos are shown, the playback starts again.

I came up with the following option: create a .sh file, in which I wrote a command for each video file and at the very end indicated the command to restart the same script. This resulted in a recursion like this:

Команда 1... (запуск трансляции файла lecture1.mp4)
Команда 2... (запуск трансляции файла lecture2.mp4)
Команда 3... (запуск трансляции файла lecture3.mp4)
bash start.sh

And, yes, it worked. I, pleased with myself, launched a test broadcast and went to bed.

In the morning I was in for a nasty surprise. It turned out that the broadcast was only a couple of minutes and ended almost immediately after I turned off my computer. Investigation showed that commands launched in this way are executed while the user is authorized on the server. As soon as I disconnected, the execution of the commands I started was interrupted. To prevent this from happening, it is enough in front of the team bash add command nohup. This will allow the running process to run regardless of your presence.

The final minimum version of the script looks like this:

ffmpeg -re -i lecture1.mp4 -f flv rtmp://a.rtmp.youtube.com/live2/%КЛЮЧ_ТРАНСЛЯЦИИ%
ffmpeg -re -i lecture2.mp4 -f flv rtmp://a.rtmp.youtube.com/live2/%КЛЮЧ_ТРАНСЛЯЦИИ%
ffmpeg -re -i lecture3.mp4 -f flv rtmp://a.rtmp.youtube.com/live2/%КЛЮЧ_ТРАНСЛЯЦИИ%
nohup bash start.sh $

Where start.sh is the file where this script is written. And this file must be located in the same directory as the video files.

Adding a dollar sign at the end allows the process to run in the background so that you can continue to use the console without interrupting the broadcast.

The following bonuses were obtained from the bonuses:

  • You can manually switch playback of files. To do this, you need to "kill" the currently running ffmpeg process. After that, playback of the next file from the list will automatically start.
  • New videos can be added to the broadcast without stopping the broadcast. Just upload the video to the server, add the command to run this file in the script, and save it. And that's it. On the next play circle, the new file will already be broadcast on a par with the old files.

Step 5 - Customize ffmpeg

On this, in principle, it was possible to stop. But I wanted to make the broadcast a little more viewer-friendly.

Suppose a person went to the broadcast, started watching, liked it and wanted to watch this lecture from the beginning, but the broadcast does not provide for rewinding. To view the lecture from the beginning, a person will need to go to my website and get a recording of the lecture of interest. And how to understand what lecture he is interested in? There are already 16 lectures on the site and every week there are only more of them. I think that even I, who filmed and edited all these lectures, will not be able to determine from a random fragment what kind of lecture it is. Therefore, it is necessary that each lecture be somehow marked.

The option to add captions to the source video files in the editing program did not suit me. It was necessary to make sure that the original files were used. To support the broadcast required as little body movements as possible from me.

It turned out that ffmpeg can help me with this as well. It has a special attribute -vf, which allows you to put text on top of the video. To add text to the video, you need to add the following fragment to the command:

-vf drawtext="fontfile=OpenSans.ttf:text='Лекция 13: Психология эмоций. Как создавать радость?':fontsize=26:fontcolor=white:borderw=1:bordercolor=black:x=40:y=670"

Decryption of parametersfontfile= – link to the font file. Without this, the inscription on the video is not added. The easiest way is to put the font file in the same folder with the video. Or you will need to specify the full path to the file.

text= - in fact, the text itself, which must be placed over the video.

fontsize= – font size in pixels.

fontcolor= - font color.

borderw= - the thickness of the outline around the text in pixels (I have white text with a black outline 1 pixel thick).

bordercolor= - outline color.

x= и y= – text coordinates. Dot 0;0 located in the upper left corner. My coordinates are chosen in such a way that the text is placed in the lower left corner with a video resolution of 1280x720 pixels.

It looks like this:

Stream your videos XNUMX/XNUMX on YouTube

Step 6 - determine the quality of the broadcast

Everything, the broadcast is ready. FFmpeg broadcasts, files are played, my presence is not needed for broadcasting. Even each lecture is signed. Look like that's it.

But another nuance surfaced - I chose the minimum server configuration and it did not pull the broadcast. Server configuration: 1 core (like 2.2 GHz), 1 gigabyte of RAM, 25 GB SSD. There was enough RAM, but the processor almost completely went into loading at 100% (and sometimes even at 102-103% 🙂 This led to the broadcast freezing every few seconds. Ugly.

You could just take a more expensive configuration with two cores, fortunately, with cloud technologies, changing the server configuration occurs by pressing a couple of buttons. But I wanted to fit in the capacity of the minimum configuration. I began to study the ffmpeg documentation and yes, there are also settings that allow you to adjust the load on the system.

High image quality can be achieved in two ways: either by high processor load or by high outgoing traffic. It turns out that the more load the processor can take on, the less bandwidth will be needed. Or you can not heavily load the processor, but then you will need a wide channel with a large margin of traffic. If there are restrictions on both the processor and the size of the outgoing channel / traffic, then you will have to reduce the quality of the picture so that the broadcast goes smoothly.

My server has a 10 Mbps channel available. This width is straight with a margin. But there is a traffic limit - 1 TB per month. Therefore, in order to meet the traffic restrictions, my outgoing stream should not exceed ~ 300 Kb per second, i.e. the bitrate of the outgoing stream must be no more than 2,5 Mbps. YouTube, by the way, just recommends broadcasting at this bitrate.

To regulate the load on the system, ffmpeg uses different approaches. Well written about it here. I ended up using two attributes: -crf и -preset.

Constant Rate Factor (CRF) - This is the coefficient by which you can adjust the quality of the picture. CRF can have values ​​from 0 to 51, where 0 is the quality of the source file, 51 is the worst possible quality. It is recommended to use values ​​from 17 to 28, the default is 23. At a factor of 17, the video will be visually identical to the original, but technically it will not be. The documentation also states that the size of the final video, depending on the specified CRF, changes exponentially, i.e. increasing the ratio by 6 points will double the bitrate of the outgoing video.

If using CRF you can pick up the "weight" of the outgoing picture, then using presets (-preset) you can determine how much the processor will be loaded. This attribute has the following parameters:

  • ultrafast
  • superfast
  • veryfast
  • faster
  • fast
  • medium - default value
  • slow
  • slower
  • veryslow

The "faster" parameter is specified, the higher will be the load on the processor.

I first picked up a preset that was, in principle, "too tough" for my processor, and then more finely picked up the load using CRF. In my case, the preset came up fast, and for crf I settled on a value of 24.

Conclusion

That's all. The final command to start the broadcast, I got this:

ffmpeg -re -i lecture1.mp4 -vf drawtext="fontfile=OpenSans.ttf:text='Лекция 1: Жонглирование картинами мира':fontsize=26:fontcolor=white:borderw=1:bordercolor=black:x=40:y=670" -c:v libx264 -preset fast -crf 24 -g 3 -f flv rtmp://a.rtmp.youtube.com/live2/%КЛЮЧ_ТРАНСЛЯЦИИ%

There are only two undescribed moments left here:

1) -c:v libx264 – specifying a specific codec for working with the source file.
2) -g 3 – explicit indication of the number of keyframes. In this case, it is specified that every third frame must be a key frame. The standard value is either 5 or 8, but YouTube swears, asking for at least 3.

What is the quality of the broadcast you can watch here.

The load on the server is as follows:

Stream your videos XNUMX/XNUMX on YouTube

Stream your videos XNUMX/XNUMX on YouTube

Based on the monitoring data, it can be seen that the load on the processor ranges from 70% to 95%, and for a week the broadcast has never reached 100%. So, with such settings, the processor is enough.

By loading the disk, I can say that it is almost not loaded, and a regular HDD should be enough for broadcasting.

But the amount of outgoing traffic worries me. It turns out that my outgoing stream ranges from 450 to 650 KB per second. For a month it will be about 1,8 terabytes. You may have to buy more traffic or still switch to a configuration with two cores. I don't want to lower the picture quality.

***

As a result, I will say that setting up such a broadcast from scratch takes about 1-2 hours. And most of the time will take uploading the video to the server.

As a marketing tool, the launch of such a broadcast did not justify itself. Perhaps if you boost views so that YouTube algorithms pick up this broadcast and begin to actively show it in recommendations, then something would work out. In my case, in 16 days of continuous broadcasting, it was watched 58 times.

That is OK. Broadcast harmoniously fit on the main page of my site. I got a sort of opportunity to quickly form my opinion about the lecturer and the lectures themselves.

And one moment. It is important that the broadcast does not violate anyone's copyrights, otherwise it will be blocked. I am calm for my broadcast. I specifically chose music inserts with free use, and the author of the content is sitting at a nearby computer and doesn’t mind me using her content 🙂

But if you have a radio playing somewhere in the background in your broadcast, or you used your favorite track during editing, or took a video sequence from a popular music video, series or movie, then your broadcast is at risk. It is also important that the broadcast carry at least a minimal semantic load, otherwise it may be blocked as spam.

***

That's all for me. I hope this manual will serve someone well. Well, if you have something to add - write, I will be happy to read additions and clarifications to the article.

Source: habr.com

Add a comment