Blame view

trunk/src/app/srs_app_ffmpeg.cpp 15.9 KB
1 2 3
/*
The MIT License (MIT)
4
Copyright (c) 2013-2015 SRS(simple-rtmp-server)
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include <srs_app_ffmpeg.hpp>

#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/types.h>
33
using namespace std;
34 35 36 37 38

#include <srs_kernel_error.hpp>
#include <srs_kernel_log.hpp>
#include <srs_app_config.hpp>
39
#ifdef SRS_AUTO_FFMPEG_STUB
40
41 42 43
#define SRS_RTMP_ENCODER_COPY           "copy"
#define SRS_RTMP_ENCODER_NO_VIDEO       "vn"
#define SRS_RTMP_ENCODER_NO_AUDIO       "an"
44
// only support libx264 encoder.
45
#define SRS_RTMP_ENCODER_VCODEC         "libx264"
46 47
// any aac encoder is ok which contains the aac,
// for example, libaacplus, aac, fdkaac
48 49
#define SRS_RTMP_ENCODER_ACODEC         "aac"
#define SRS_RTMP_ENCODER_LIBAACPLUS     "libaacplus"
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71

SrsFFMPEG::SrsFFMPEG(std::string ffmpeg_bin)
{
    started            = false;
    pid                = -1;
    ffmpeg             = ffmpeg_bin;
    
    vbitrate         = 0;
    vfps             = 0;
    vwidth             = 0;
    vheight         = 0;
    vthreads         = 0;
    abitrate         = 0;
    asample_rate     = 0;
    achannels         = 0;
}

SrsFFMPEG::~SrsFFMPEG()
{
    stop();
}
72 73 74 75 76
void SrsFFMPEG::set_iparams(string iparams)
{
    _iparams = iparams;
}
77 78 79 80 81
void SrsFFMPEG::set_oformat(string format)
{
    oformat = format;
}
82 83 84 85 86
string SrsFFMPEG::output()
{
    return _output;
}
winlin authored
87 88 89 90 91 92 93 94 95 96 97 98
int SrsFFMPEG::initialize(string in, string out, string log)
{
    int ret = ERROR_SUCCESS;
    
    input = in;
    _output = out;
    log_file = log;
    
    return ret;
}

int SrsFFMPEG::initialize_transcode(SrsConfDirective* engine)
99 100 101
{
    int ret = ERROR_SUCCESS;
    
102
    iformat             = _srs_config->get_engine_iformat(engine);
winlin authored
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
    vfilter             = _srs_config->get_engine_vfilter(engine);
    vcodec              = _srs_config->get_engine_vcodec(engine);
    vbitrate            = _srs_config->get_engine_vbitrate(engine);
    vfps                = _srs_config->get_engine_vfps(engine);
    vwidth              = _srs_config->get_engine_vwidth(engine);
    vheight             = _srs_config->get_engine_vheight(engine);
    vthreads            = _srs_config->get_engine_vthreads(engine);
    vprofile            = _srs_config->get_engine_vprofile(engine);
    vpreset             = _srs_config->get_engine_vpreset(engine);
    vparams             = _srs_config->get_engine_vparams(engine);
    acodec              = _srs_config->get_engine_acodec(engine);
    abitrate            = _srs_config->get_engine_abitrate(engine);
    asample_rate        = _srs_config->get_engine_asample_rate(engine);
    achannels           = _srs_config->get_engine_achannels(engine);
    aparams             = _srs_config->get_engine_aparams(engine);
118
    oformat             = _srs_config->get_engine_oformat(engine);
119 120 121 122 123
    
    // ensure the size is even.
    vwidth -= vwidth % 2;
    vheight -= vheight % 2;
    
winlin authored
124
    if (vcodec == SRS_RTMP_ENCODER_NO_VIDEO && acodec == SRS_RTMP_ENCODER_NO_AUDIO) {
125 126 127 128 129
        ret = ERROR_ENCODER_VCODEC;
        srs_warn("video and audio disabled. ret=%d", ret);
        return ret;
    }
    
winlin authored
130 131
    if (vcodec != SRS_RTMP_ENCODER_COPY && vcodec != SRS_RTMP_ENCODER_NO_VIDEO) {
        if (vcodec != SRS_RTMP_ENCODER_VCODEC) {
132 133
            ret = ERROR_ENCODER_VCODEC;
            srs_error("invalid vcodec, must be %s, actual %s, ret=%d",
winlin authored
134
                SRS_RTMP_ENCODER_VCODEC, vcodec.c_str(), ret);
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
            return ret;
        }
        if (vbitrate <= 0) {
            ret = ERROR_ENCODER_VBITRATE;
            srs_error("invalid vbitrate: %d, ret=%d", vbitrate, ret);
            return ret;
        }
        if (vfps <= 0) {
            ret = ERROR_ENCODER_VFPS;
            srs_error("invalid vfps: %.2f, ret=%d", vfps, ret);
            return ret;
        }
        if (vwidth <= 0) {
            ret = ERROR_ENCODER_VWIDTH;
            srs_error("invalid vwidth: %d, ret=%d", vwidth, ret);
            return ret;
        }
        if (vheight <= 0) {
            ret = ERROR_ENCODER_VHEIGHT;
            srs_error("invalid vheight: %d, ret=%d", vheight, ret);
            return ret;
        }
        if (vthreads < 0) {
            ret = ERROR_ENCODER_VTHREADS;
            srs_error("invalid vthreads: %d, ret=%d", vthreads, ret);
            return ret;
        }
        if (vprofile.empty()) {
            ret = ERROR_ENCODER_VPROFILE;
            srs_error("invalid vprofile: %s, ret=%d", vprofile.c_str(), ret);
            return ret;
        }
        if (vpreset.empty()) {
            ret = ERROR_ENCODER_VPRESET;
            srs_error("invalid vpreset: %s, ret=%d", vpreset.c_str(), ret);
            return ret;
        }
    }
    
174
    // @see, https://github.com/simple-rtmp-server/srs/issues/145
175 176 177 178 179 180 181 182
    if (acodec == SRS_RTMP_ENCODER_LIBAACPLUS) {
        if (abitrate < 16 || abitrate > 72) {
            ret = ERROR_ENCODER_ABITRATE;
            srs_error("invalid abitrate for aac: %d, must in [16, 72], ret=%d", abitrate, ret);
            return ret;
        }
    }
    
winlin authored
183
    if (acodec != SRS_RTMP_ENCODER_COPY && acodec != SRS_RTMP_ENCODER_NO_AUDIO) {
184 185
        if (abitrate <= 0) {
            ret = ERROR_ENCODER_ABITRATE;
186
            srs_error("invalid abitrate: %d, ret=%d", abitrate, ret);
187 188 189 190
            return ret;
        }
        if (asample_rate <= 0) {
            ret = ERROR_ENCODER_ASAMPLE_RATE;
191
            srs_error("invalid sample rate: %d, ret=%d", asample_rate, ret);
192 193 194 195
            return ret;
        }
        if (achannels != 1 && achannels != 2) {
            ret = ERROR_ENCODER_ACHANNELS;
196
            srs_error("invalid achannels, must be 1 or 2, actual %d, ret=%d", achannels, ret);
197 198 199
            return ret;
        }
    }
200
    if (_output.empty()) {
201 202 203 204 205
        ret = ERROR_ENCODER_OUTPUT;
        srs_error("invalid empty output, ret=%d", ret);
        return ret;
    }
    
206 207
    // for not rtmp input, donot append the iformat,
    // for example, "-f flv" before "-i udp://192.168.1.252:2222"
208
    // @see https://github.com/simple-rtmp-server/srs/issues/290
209 210 211 212
    if (input.find("rtmp://") != 0) {
        iformat = "";
    }
    
213 214 215
    return ret;
}
winlin authored
216 217 218 219
int SrsFFMPEG::initialize_copy()
{
    int ret = ERROR_SUCCESS;
    
winlin authored
220 221
    vcodec = SRS_RTMP_ENCODER_COPY;
    acodec = SRS_RTMP_ENCODER_COPY;
winlin authored
222 223 224 225 226 227 228 229 230 231

    if (_output.empty()) {
        ret = ERROR_ENCODER_OUTPUT;
        srs_error("invalid empty output, ret=%d", ret);
        return ret;
    }
    
    return ret;
}
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
int SrsFFMPEG::start()
{
    int ret = ERROR_SUCCESS;
    
    if (started) {
        return ret;
    }
    
    // prepare exec params
    char tmp[256];
    std::vector<std::string> params;
    
    // argv[0], set to ffmpeg bin.
    // The  execv()  and  execvp() functions ....
    // The first argument, by convention, should point to 
    // the filename associated  with  the file being executed.
    params.push_back(ffmpeg);
    
250 251 252 253 254
    // input params
    if (!_iparams.empty()) {
        params.push_back(_iparams);
    }
    
255
    // input.
256
    if (iformat != "off" && !iformat.empty()) {
257 258 259
        params.push_back("-f");
        params.push_back(iformat);
    }
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
    
    params.push_back("-i");
    params.push_back(input);
    
    // build the filter
    if (!vfilter.empty()) {
        std::vector<std::string>::iterator it;
        for (it = vfilter.begin(); it != vfilter.end(); ++it) {
            std::string p = *it;
            if (!p.empty()) {
                params.push_back(p);
            }
        }
    }
    
    // video specified.
winlin authored
276
    if (vcodec != SRS_RTMP_ENCODER_NO_VIDEO) {
277 278 279 280 281 282 283
        params.push_back("-vcodec");
        params.push_back(vcodec);
    } else {
        params.push_back("-vn");
    }
    
    // the codec params is disabled when copy
winlin authored
284
    if (vcodec != SRS_RTMP_ENCODER_COPY && vcodec != SRS_RTMP_ENCODER_NO_VIDEO) {
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
        params.push_back("-b:v");
        snprintf(tmp, sizeof(tmp), "%d", vbitrate * 1000);
        params.push_back(tmp);
        
        params.push_back("-r");
        snprintf(tmp, sizeof(tmp), "%.2f", vfps);
        params.push_back(tmp);
        
        params.push_back("-s");
        snprintf(tmp, sizeof(tmp), "%dx%d", vwidth, vheight);
        params.push_back(tmp);
        
        // TODO: add aspect if needed.
        params.push_back("-aspect");
        snprintf(tmp, sizeof(tmp), "%d:%d", vwidth, vheight);
        params.push_back(tmp);
        
        params.push_back("-threads");
        snprintf(tmp, sizeof(tmp), "%d", vthreads);
        params.push_back(tmp);
        
        params.push_back("-profile:v");
        params.push_back(vprofile);
        
        params.push_back("-preset");
        params.push_back(vpreset);
        
        // vparams
        if (!vparams.empty()) {
            std::vector<std::string>::iterator it;
            for (it = vparams.begin(); it != vparams.end(); ++it) {
                std::string p = *it;
                if (!p.empty()) {
                    params.push_back(p);
                }
            }
        }
    }
    
    // audio specified.
winlin authored
325
    if (acodec != SRS_RTMP_ENCODER_NO_AUDIO) {
326 327 328 329 330 331 332
        params.push_back("-acodec");
        params.push_back(acodec);
    } else {
        params.push_back("-an");
    }
    
    // the codec params is disabled when copy
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
    if (acodec != SRS_RTMP_ENCODER_NO_AUDIO) {
        if (acodec != SRS_RTMP_ENCODER_COPY) {
            params.push_back("-b:a");
            snprintf(tmp, sizeof(tmp), "%d", abitrate * 1000);
            params.push_back(tmp);
            
            params.push_back("-ar");
            snprintf(tmp, sizeof(tmp), "%d", asample_rate);
            params.push_back(tmp);
            
            params.push_back("-ac");
            snprintf(tmp, sizeof(tmp), "%d", achannels);
            params.push_back(tmp);
            
            // aparams
348 349 350 351 352 353 354
            std::vector<std::string>::iterator it;
            for (it = aparams.begin(); it != aparams.end(); ++it) {
                std::string p = *it;
                if (!p.empty()) {
                    params.push_back(p);
                }
            }
355 356 357 358 359 360 361 362 363 364 365 366 367 368
        } else {
            // for audio copy.
            for (int i = 0; i < (int)aparams.size();) {
                std::string pn = aparams[i++];
                
                // aparams, the adts to asc filter "-bsf:a aac_adtstoasc"
                if (pn == "-bsf:a" && i < (int)aparams.size()) {
                    std::string pv = aparams[i++];
                    if (pv == "aac_adtstoasc") {
                        params.push_back(pn);
                        params.push_back(pv);
                    }
                }
            }
369 370 371 372
        }
    }

    // output
373
    if (oformat != "off" && !oformat.empty()) {
374 375 376
        params.push_back("-f");
        params.push_back(oformat);
    }
377 378
    
    params.push_back("-y");
379
    params.push_back(_output);
380
381
    std::string cli;
382 383 384
    if (true) {
        for (int i = 0; i < (int)params.size(); i++) {
            std::string ffp = params[i];
385 386 387 388
            cli += ffp;
            if (i < (int)params.size() - 1) {
                cli += " ";
            }
389
        }
390
        srs_trace("start ffmpeg, log: %s, params: %s", log_file.c_str(), cli.c_str());
391 392
    }
    
393 394 395
    // for log
    int cid = _srs_context->get_id();
    
396 397 398 399 400 401 402 403 404 405
    // TODO: fork or vfork?
    if ((pid = fork()) < 0) {
        ret = ERROR_ENCODER_FORK;
        srs_error("vfork process failed. ret=%d", ret);
        return ret;
    }
    
    // child process: ffmpeg encoder engine.
    if (pid == 0) {
        // redirect logs to file.
406
        int log_fd = -1;
407 408 409 410 411 412 413
        int flags = O_CREAT|O_WRONLY|O_APPEND;
        mode_t mode = S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH;
        if ((log_fd = ::open(log_file.c_str(), flags, mode)) < 0) {
            ret = ERROR_ENCODER_OPEN;
            srs_error("open encoder file %s failed. ret=%d", log_file.c_str(), ret);
            return ret;
        }
414 415 416 417 418 419 420 421 422 423 424 425 426
        
        // log basic info
        if (true) {
            char buf[4096];
            int pos = 0;
            pos += snprintf(buf + pos, sizeof(buf) - pos, "\n");
            pos += snprintf(buf + pos, sizeof(buf) - pos, "ffmpeg cid=%d\n", cid);
            pos += snprintf(buf + pos, sizeof(buf) - pos, "log=%s\n", log_file.c_str());
            pos += snprintf(buf + pos, sizeof(buf) - pos, "params: %s\n", cli.c_str());
            ::write(log_fd, buf, pos);
        }
        
        // dup to stdout and stderr.
427 428 429 430 431 432 433 434 435 436
        if (dup2(log_fd, STDOUT_FILENO) < 0) {
            ret = ERROR_ENCODER_DUP2;
            srs_error("dup2 encoder file failed. ret=%d", ret);
            return ret;
        }
        if (dup2(log_fd, STDERR_FILENO) < 0) {
            ret = ERROR_ENCODER_DUP2;
            srs_error("dup2 encoder file failed. ret=%d", ret);
            return ret;
        }
437
        
438 439
        // close log fd
        ::close(log_fd);
440 441 442 443 444 445 446 447 448
        // close other fds
        // TODO: do in right way.
        for (int i = 3; i < 1024; i++) {
            ::close(i);
        }
        
        // memory leak in child process, it's ok.
        char** charpv_params = new char*[params.size() + 1];
        for (int i = 0; i < (int)params.size(); i++) {
449 450
            std::string& p = params[i];
            charpv_params[i] = (char*)p.data();
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
        }
        // EOF: NULL
        charpv_params[params.size()] = NULL;
        
        // TODO: execv or execvp
        ret = execv(ffmpeg.c_str(), charpv_params);
        if (ret < 0) {
            fprintf(stderr, "fork ffmpeg failed, errno=%d(%s)", 
                errno, strerror(errno));
        }
        exit(ret);
    }

    // parent.
    if (pid > 0) {
        started = true;
        srs_trace("vfored ffmpeg encoder engine, pid=%d", pid);
        return ret;
    }
    
    return ret;
}

int SrsFFMPEG::cycle()
{
    int ret = ERROR_SUCCESS;
    
    if (!started) {
        return ret;
    }
    
    int status = 0;
    pid_t p = waitpid(pid, &status, WNOHANG);
    
    if (p < 0) {
        ret = ERROR_SYSTEM_WAITPID;
        srs_error("transcode waitpid failed, pid=%d, ret=%d", pid, ret);
        return ret;
    }
    
    if (p == 0) {
        srs_info("transcode process pid=%d is running.", pid);
        return ret;
    }
    
    srs_trace("transcode process pid=%d terminate, restart it.", pid);
    started = false;
    
    return ret;
}

void SrsFFMPEG::stop()
{
    if (!started) {
        return;
    }
    
    // kill the ffmpeg,
    // when rewind, upstream will stop publish(unpublish),
    // unpublish event will stop all ffmpeg encoders,
    // then publish will start all ffmpeg encoders.
    if (pid > 0) {
        if (kill(pid, SIGKILL) < 0) {
            srs_warn("kill the encoder failed, ignored. pid=%d", pid);
        }
        
        // wait for the ffmpeg to quit.
        // ffmpeg will gracefully quit if signal is:
        //         1) SIGHUP     2) SIGINT     3) SIGQUIT
        // other signals, directly exit(123), for example:
        //        9) SIGKILL    15) SIGTERM
        int status = 0;
        if (waitpid(pid, &status, 0) < 0) {
            srs_warn("wait the encoder quit failed, ignored. pid=%d", pid);
        }
        
        srs_trace("stop the encoder success. pid=%d", pid);
        pid = -1;
    }
}

#endif
534