ffmpeg-mux.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958
  1. /*
  2. * Copyright (c) 2015 Hugh Bailey <[email protected]>
  3. *
  4. * Permission to use, copy, modify, and distribute this software for any
  5. * purpose with or without fee is hereby granted, provided that the above
  6. * copyright notice and this permission notice appear in all copies.
  7. *
  8. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  11. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  14. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. */
  16. #ifdef _WIN32
  17. #include <io.h>
  18. #include <fcntl.h>
  19. #include <windows.h>
  20. #define inline __inline
  21. #endif
  22. #include <stdio.h>
  23. #include <stdlib.h>
  24. #include "ffmpeg-mux.h"
  25. #include <util/dstr.h>
  26. #include <libavcodec/avcodec.h>
  27. #include <libavformat/avformat.h>
  28. #include <libavutil/channel_layout.h>
  29. #include <libavutil/mastering_display_metadata.h>
  30. #define ANSI_COLOR_RED "\x1b[0;91m"
  31. #define ANSI_COLOR_MAGENTA "\x1b[0;95m"
  32. #define ANSI_COLOR_RESET "\x1b[0m"
  33. #if LIBAVCODEC_VERSION_MAJOR >= 58
  34. #define CODEC_FLAG_GLOBAL_H AV_CODEC_FLAG_GLOBAL_HEADER
  35. #else
  36. #define CODEC_FLAG_GLOBAL_H CODEC_FLAG_GLOBAL_HEADER
  37. #endif
  38. /* ------------------------------------------------------------------------- */
  39. static char *global_stream_key = "";
  40. struct resize_buf {
  41. uint8_t *buf;
  42. size_t size;
  43. size_t capacity;
  44. };
  45. static inline void resize_buf_resize(struct resize_buf *rb, size_t size)
  46. {
  47. if (!rb->buf) {
  48. rb->buf = malloc(size);
  49. rb->size = size;
  50. rb->capacity = size;
  51. } else {
  52. if (rb->capacity < size) {
  53. size_t capx2 = rb->capacity * 2;
  54. size_t new_cap = capx2 > size ? capx2 : size;
  55. rb->buf = realloc(rb->buf, new_cap);
  56. rb->capacity = new_cap;
  57. }
  58. rb->size = size;
  59. }
  60. }
  61. static inline void resize_buf_free(struct resize_buf *rb)
  62. {
  63. free(rb->buf);
  64. }
  65. /* ------------------------------------------------------------------------- */
  66. struct main_params {
  67. char *file;
  68. /* printable_file is file with any stream key information removed */
  69. struct dstr printable_file;
  70. int has_video;
  71. int tracks;
  72. char *vcodec;
  73. int vbitrate;
  74. int gop;
  75. int width;
  76. int height;
  77. int fps_num;
  78. int fps_den;
  79. int color_primaries;
  80. int color_trc;
  81. int colorspace;
  82. int color_range;
  83. int max_luminance;
  84. char *acodec;
  85. char *muxer_settings;
  86. };
  87. struct audio_params {
  88. char *name;
  89. int abitrate;
  90. int sample_rate;
  91. int frame_size;
  92. int channels;
  93. };
  94. struct header {
  95. uint8_t *data;
  96. int size;
  97. };
  98. struct audio_info {
  99. AVStream *stream;
  100. AVCodecContext *ctx;
  101. };
  102. struct ffmpeg_mux {
  103. AVFormatContext *output;
  104. AVStream *video_stream;
  105. AVCodecContext *video_ctx;
  106. AVPacket *packet;
  107. struct audio_info *audio_infos;
  108. struct main_params params;
  109. struct audio_params *audio;
  110. struct header video_header;
  111. struct header *audio_header;
  112. int num_audio_streams;
  113. bool initialized;
  114. char error[4096];
  115. };
  116. static void header_free(struct header *header)
  117. {
  118. free(header->data);
  119. }
  120. static void free_avformat(struct ffmpeg_mux *ffm)
  121. {
  122. if (ffm->output) {
  123. avcodec_free_context(&ffm->video_ctx);
  124. if ((ffm->output->oformat->flags & AVFMT_NOFILE) == 0)
  125. avio_close(ffm->output->pb);
  126. avformat_free_context(ffm->output);
  127. ffm->output = NULL;
  128. }
  129. if (ffm->audio_infos) {
  130. for (int i = 0; i < ffm->num_audio_streams; ++i)
  131. avcodec_free_context(&ffm->audio_infos[i].ctx);
  132. free(ffm->audio_infos);
  133. }
  134. ffm->video_stream = NULL;
  135. ffm->audio_infos = NULL;
  136. ffm->num_audio_streams = 0;
  137. }
  138. static void ffmpeg_mux_free(struct ffmpeg_mux *ffm)
  139. {
  140. if (ffm->initialized) {
  141. av_write_trailer(ffm->output);
  142. }
  143. free_avformat(ffm);
  144. header_free(&ffm->video_header);
  145. if (ffm->audio_header) {
  146. for (int i = 0; i < ffm->params.tracks; i++) {
  147. header_free(&ffm->audio_header[i]);
  148. }
  149. free(ffm->audio_header);
  150. }
  151. if (ffm->audio) {
  152. free(ffm->audio);
  153. }
  154. dstr_free(&ffm->params.printable_file);
  155. av_packet_free(&ffm->packet);
  156. memset(ffm, 0, sizeof(*ffm));
  157. }
  158. static bool get_opt_str(int *p_argc, char ***p_argv, char **str,
  159. const char *opt)
  160. {
  161. int argc = *p_argc;
  162. char **argv = *p_argv;
  163. if (!argc) {
  164. printf("Missing expected option: '%s'\n", opt);
  165. return false;
  166. }
  167. (*p_argc)--;
  168. (*p_argv)++;
  169. *str = argv[0];
  170. return true;
  171. }
  172. static bool get_opt_int(int *p_argc, char ***p_argv, int *i, const char *opt)
  173. {
  174. char *str;
  175. if (!get_opt_str(p_argc, p_argv, &str, opt)) {
  176. return false;
  177. }
  178. *i = atoi(str);
  179. return true;
  180. }
  181. static bool get_audio_params(struct audio_params *audio, int *argc,
  182. char ***argv)
  183. {
  184. if (!get_opt_str(argc, argv, &audio->name, "audio track name"))
  185. return false;
  186. if (!get_opt_int(argc, argv, &audio->abitrate, "audio bitrate"))
  187. return false;
  188. if (!get_opt_int(argc, argv, &audio->sample_rate, "audio sample rate"))
  189. return false;
  190. if (!get_opt_int(argc, argv, &audio->frame_size, "audio frame size"))
  191. return false;
  192. if (!get_opt_int(argc, argv, &audio->channels, "audio channels"))
  193. return false;
  194. return true;
  195. }
  196. static void ffmpeg_log_callback(void *param, int level, const char *format,
  197. va_list args)
  198. {
  199. #ifdef ENABLE_FFMPEG_MUX_DEBUG
  200. char out_buffer[4096];
  201. struct dstr out = {0};
  202. vsnprintf(out_buffer, sizeof(out_buffer), format, args);
  203. dstr_copy(&out, out_buffer);
  204. if (global_stream_key && *global_stream_key) {
  205. dstr_replace(&out, global_stream_key, "{stream_key}");
  206. }
  207. switch (level) {
  208. case AV_LOG_INFO:
  209. fprintf(stdout, "info: [ffmpeg_muxer] %s", out.array);
  210. fflush(stdout);
  211. break;
  212. case AV_LOG_WARNING:
  213. fprintf(stdout, "%swarning: [ffmpeg_muxer] %s%s",
  214. ANSI_COLOR_MAGENTA, out.array, ANSI_COLOR_RESET);
  215. fflush(stdout);
  216. break;
  217. case AV_LOG_ERROR:
  218. fprintf(stderr, "%serror: [ffmpeg_muxer] %s%s", ANSI_COLOR_RED,
  219. out.array, ANSI_COLOR_RESET);
  220. fflush(stderr);
  221. }
  222. dstr_free(&out);
  223. #else
  224. UNUSED_PARAMETER(level);
  225. UNUSED_PARAMETER(format);
  226. UNUSED_PARAMETER(args);
  227. #endif
  228. UNUSED_PARAMETER(param);
  229. }
  230. static bool init_params(int *argc, char ***argv, struct main_params *params,
  231. struct audio_params **p_audio)
  232. {
  233. struct audio_params *audio = NULL;
  234. if (!get_opt_str(argc, argv, &params->file, "file name"))
  235. return false;
  236. if (!get_opt_int(argc, argv, &params->has_video, "video track count"))
  237. return false;
  238. if (!get_opt_int(argc, argv, &params->tracks, "audio track count"))
  239. return false;
  240. if (params->has_video > 1 || params->has_video < 0) {
  241. puts("Invalid number of video tracks\n");
  242. return false;
  243. }
  244. if (params->tracks < 0) {
  245. puts("Invalid number of audio tracks\n");
  246. return false;
  247. }
  248. if (params->has_video == 0 && params->tracks == 0) {
  249. puts("Must have at least 1 audio track or 1 video track\n");
  250. return false;
  251. }
  252. if (params->has_video) {
  253. if (!get_opt_str(argc, argv, &params->vcodec, "video codec"))
  254. return false;
  255. if (!get_opt_int(argc, argv, &params->vbitrate,
  256. "video bitrate"))
  257. return false;
  258. if (!get_opt_int(argc, argv, &params->width, "video width"))
  259. return false;
  260. if (!get_opt_int(argc, argv, &params->height, "video height"))
  261. return false;
  262. if (!get_opt_int(argc, argv, &params->color_primaries,
  263. "video color primaries"))
  264. return false;
  265. if (!get_opt_int(argc, argv, &params->color_trc,
  266. "video color trc"))
  267. return false;
  268. if (!get_opt_int(argc, argv, &params->colorspace,
  269. "video colorspace"))
  270. return false;
  271. if (!get_opt_int(argc, argv, &params->color_range,
  272. "video color range"))
  273. return false;
  274. if (!get_opt_int(argc, argv, &params->max_luminance,
  275. "video max luminance"))
  276. return false;
  277. if (!get_opt_int(argc, argv, &params->fps_num, "video fps num"))
  278. return false;
  279. if (!get_opt_int(argc, argv, &params->fps_den, "video fps den"))
  280. return false;
  281. }
  282. if (params->tracks) {
  283. if (!get_opt_str(argc, argv, &params->acodec, "audio codec"))
  284. return false;
  285. audio = calloc(params->tracks, sizeof(*audio));
  286. for (int i = 0; i < params->tracks; i++) {
  287. if (!get_audio_params(&audio[i], argc, argv)) {
  288. free(audio);
  289. return false;
  290. }
  291. }
  292. }
  293. *p_audio = audio;
  294. dstr_copy(&params->printable_file, params->file);
  295. get_opt_str(argc, argv, &global_stream_key, "stream key");
  296. if (strcmp(global_stream_key, "") != 0) {
  297. dstr_replace(&params->printable_file, global_stream_key,
  298. "{stream_key}");
  299. }
  300. av_log_set_callback(ffmpeg_log_callback);
  301. get_opt_str(argc, argv, &params->muxer_settings, "muxer settings");
  302. return true;
  303. }
  304. static bool new_stream(struct ffmpeg_mux *ffm, AVStream **stream,
  305. const char *name)
  306. {
  307. *stream = avformat_new_stream(ffm->output, NULL);
  308. if (!*stream) {
  309. fprintf(stderr, "Couldn't create stream for encoder '%s'\n",
  310. name);
  311. return false;
  312. }
  313. (*stream)->id = ffm->output->nb_streams - 1;
  314. return true;
  315. }
  316. static void create_video_stream(struct ffmpeg_mux *ffm)
  317. {
  318. AVCodecContext *context;
  319. void *extradata = NULL;
  320. const char *name = ffm->params.vcodec;
  321. const AVCodecDescriptor *codec = avcodec_descriptor_get_by_name(name);
  322. if (!codec) {
  323. fprintf(stderr, "Couldn't find codec '%s'\n", name);
  324. return;
  325. }
  326. if (!new_stream(ffm, &ffm->video_stream, name))
  327. return;
  328. if (ffm->video_header.size) {
  329. extradata = av_memdup(ffm->video_header.data,
  330. ffm->video_header.size);
  331. }
  332. context = avcodec_alloc_context3(NULL);
  333. context->codec_type = codec->type;
  334. context->codec_id = codec->id;
  335. context->bit_rate = (int64_t)ffm->params.vbitrate * 1000;
  336. context->width = ffm->params.width;
  337. context->height = ffm->params.height;
  338. context->coded_width = ffm->params.width;
  339. context->coded_height = ffm->params.height;
  340. context->color_primaries = ffm->params.color_primaries;
  341. context->color_trc = ffm->params.color_trc;
  342. context->colorspace = ffm->params.colorspace;
  343. context->color_range = ffm->params.color_range;
  344. context->extradata = extradata;
  345. context->extradata_size = ffm->video_header.size;
  346. context->time_base =
  347. (AVRational){ffm->params.fps_den, ffm->params.fps_num};
  348. ffm->video_stream->time_base = context->time_base;
  349. #if LIBAVFORMAT_VERSION_MAJOR < 59
  350. // codec->time_base may still be used if LIBAVFORMAT_VERSION_MAJOR < 59
  351. ffm->video_stream->codec->time_base = context->time_base;
  352. #endif
  353. ffm->video_stream->avg_frame_rate = av_inv_q(context->time_base);
  354. if (ffm->params.max_luminance > 0) {
  355. AVMasteringDisplayMetadata *const mastering =
  356. av_mastering_display_metadata_alloc();
  357. mastering->display_primaries[0][0] = av_make_q(17, 25);
  358. mastering->display_primaries[0][1] = av_make_q(8, 25);
  359. mastering->display_primaries[1][0] = av_make_q(53, 200);
  360. mastering->display_primaries[1][1] = av_make_q(69, 100);
  361. mastering->display_primaries[2][0] = av_make_q(3, 20);
  362. mastering->display_primaries[2][1] = av_make_q(3, 50);
  363. mastering->white_point[0] = av_make_q(3127, 10000);
  364. mastering->white_point[1] = av_make_q(329, 1000);
  365. mastering->min_luminance = av_make_q(0, 1);
  366. mastering->max_luminance =
  367. av_make_q(ffm->params.max_luminance, 1);
  368. mastering->has_primaries = 1;
  369. mastering->has_luminance = 1;
  370. av_stream_add_side_data(ffm->video_stream,
  371. AV_PKT_DATA_MASTERING_DISPLAY_METADATA,
  372. (uint8_t *)mastering,
  373. sizeof(*mastering));
  374. }
  375. if (ffm->output->oformat->flags & AVFMT_GLOBALHEADER)
  376. context->flags |= CODEC_FLAG_GLOBAL_H;
  377. avcodec_parameters_from_context(ffm->video_stream->codecpar, context);
  378. ffm->video_ctx = context;
  379. }
  380. static void create_audio_stream(struct ffmpeg_mux *ffm, int idx)
  381. {
  382. AVCodecContext *context;
  383. AVStream *stream;
  384. void *extradata = NULL;
  385. const char *name = ffm->params.acodec;
  386. const AVCodecDescriptor *codec = avcodec_descriptor_get_by_name(name);
  387. if (!codec) {
  388. fprintf(stderr, "Couldn't find codec '%s'\n", name);
  389. return;
  390. }
  391. if (!new_stream(ffm, &stream, name))
  392. return;
  393. av_dict_set(&stream->metadata, "title", ffm->audio[idx].name, 0);
  394. stream->time_base = (AVRational){1, ffm->audio[idx].sample_rate};
  395. if (ffm->audio_header[idx].size) {
  396. extradata = av_memdup(ffm->audio_header[idx].data,
  397. ffm->audio_header[idx].size);
  398. }
  399. context = avcodec_alloc_context3(NULL);
  400. context->codec_type = codec->type;
  401. context->codec_id = codec->id;
  402. context->bit_rate = (int64_t)ffm->audio[idx].abitrate * 1000;
  403. context->channels = ffm->audio[idx].channels;
  404. context->sample_rate = ffm->audio[idx].sample_rate;
  405. context->frame_size = ffm->audio[idx].frame_size;
  406. context->sample_fmt = AV_SAMPLE_FMT_S16;
  407. context->time_base = stream->time_base;
  408. context->extradata = extradata;
  409. context->extradata_size = ffm->audio_header[idx].size;
  410. context->channel_layout =
  411. av_get_default_channel_layout(context->channels);
  412. //avutil default channel layout for 4 channels is 4.0 ; fix for quad
  413. if (context->channels == 4)
  414. context->channel_layout = av_get_channel_layout("quad");
  415. //avutil default channel layout for 5 channels is 5.0 ; fix for 4.1
  416. if (context->channels == 5)
  417. context->channel_layout = av_get_channel_layout("4.1");
  418. if (ffm->output->oformat->flags & AVFMT_GLOBALHEADER)
  419. context->flags |= CODEC_FLAG_GLOBAL_H;
  420. avcodec_parameters_from_context(stream->codecpar, context);
  421. ffm->audio_infos[ffm->num_audio_streams].stream = stream;
  422. ffm->audio_infos[ffm->num_audio_streams].ctx = context;
  423. ffm->num_audio_streams++;
  424. }
  425. static bool init_streams(struct ffmpeg_mux *ffm)
  426. {
  427. if (ffm->params.has_video)
  428. create_video_stream(ffm);
  429. if (ffm->params.tracks) {
  430. ffm->audio_infos =
  431. calloc(ffm->params.tracks, sizeof(*ffm->audio_infos));
  432. for (int i = 0; i < ffm->params.tracks; i++)
  433. create_audio_stream(ffm, i);
  434. }
  435. if (!ffm->video_stream && !ffm->num_audio_streams)
  436. return false;
  437. return true;
  438. }
  439. static void set_header(struct header *header, uint8_t *data, size_t size)
  440. {
  441. header->size = (int)size;
  442. header->data = malloc(size);
  443. memcpy(header->data, data, size);
  444. }
  445. static void ffmpeg_mux_header(struct ffmpeg_mux *ffm, uint8_t *data,
  446. struct ffm_packet_info *info)
  447. {
  448. if (info->type == FFM_PACKET_VIDEO) {
  449. set_header(&ffm->video_header, data, (size_t)info->size);
  450. } else {
  451. set_header(&ffm->audio_header[info->index], data,
  452. (size_t)info->size);
  453. }
  454. }
  455. static size_t safe_read(void *vdata, size_t size)
  456. {
  457. uint8_t *data = vdata;
  458. size_t total = size;
  459. while (size > 0) {
  460. size_t in_size = fread(data, 1, size, stdin);
  461. if (in_size == 0)
  462. return 0;
  463. size -= in_size;
  464. data += in_size;
  465. }
  466. return total;
  467. }
  468. static bool ffmpeg_mux_get_header(struct ffmpeg_mux *ffm)
  469. {
  470. struct ffm_packet_info info = {0};
  471. bool success = safe_read(&info, sizeof(info)) == sizeof(info);
  472. if (success) {
  473. uint8_t *data = malloc(info.size);
  474. if (safe_read(data, info.size) == info.size) {
  475. ffmpeg_mux_header(ffm, data, &info);
  476. } else {
  477. success = false;
  478. }
  479. free(data);
  480. }
  481. return success;
  482. }
  483. static inline bool ffmpeg_mux_get_extra_data(struct ffmpeg_mux *ffm)
  484. {
  485. if (ffm->params.has_video) {
  486. if (!ffmpeg_mux_get_header(ffm)) {
  487. return false;
  488. }
  489. }
  490. for (int i = 0; i < ffm->params.tracks; i++) {
  491. if (!ffmpeg_mux_get_header(ffm)) {
  492. return false;
  493. }
  494. }
  495. return true;
  496. }
  497. #ifdef _MSC_VER
  498. #pragma warning(disable : 4996)
  499. #endif
  500. static inline int open_output_file(struct ffmpeg_mux *ffm)
  501. {
  502. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(59, 0, 100)
  503. AVOutputFormat *format = ffm->output->oformat;
  504. #else
  505. const AVOutputFormat *format = ffm->output->oformat;
  506. #endif
  507. int ret;
  508. if ((format->flags & AVFMT_NOFILE) == 0) {
  509. ret = avio_open(&ffm->output->pb, ffm->params.file,
  510. AVIO_FLAG_WRITE);
  511. if (ret < 0) {
  512. fprintf(stderr, "Couldn't open '%s', %s\n",
  513. ffm->params.printable_file.array,
  514. av_err2str(ret));
  515. return FFM_ERROR;
  516. }
  517. }
  518. AVDictionary *dict = NULL;
  519. if ((ret = av_dict_parse_string(&dict, ffm->params.muxer_settings, "=",
  520. " ", 0))) {
  521. fprintf(stderr, "Failed to parse muxer settings: %s\n%s\n",
  522. av_err2str(ret), ffm->params.muxer_settings);
  523. av_dict_free(&dict);
  524. }
  525. if (av_dict_count(dict) > 0) {
  526. printf("Using muxer settings:");
  527. AVDictionaryEntry *entry = NULL;
  528. while ((entry = av_dict_get(dict, "", entry,
  529. AV_DICT_IGNORE_SUFFIX)))
  530. printf("\n\t%s=%s", entry->key, entry->value);
  531. printf("\n");
  532. }
  533. ret = avformat_write_header(ffm->output, &dict);
  534. if (ret < 0) {
  535. fprintf(stderr, "Error opening '%s': %s",
  536. ffm->params.printable_file.array, av_err2str(ret));
  537. av_dict_free(&dict);
  538. return ret == -22 ? FFM_UNSUPPORTED : FFM_ERROR;
  539. }
  540. av_dict_free(&dict);
  541. return FFM_SUCCESS;
  542. }
  543. #define SRT_PROTO "srt"
  544. #define UDP_PROTO "udp"
  545. #define TCP_PROTO "tcp"
  546. #define HTTP_PROTO "http"
  547. #define RIST_PROTO "rist"
  548. static bool ffmpeg_mux_is_network(struct ffmpeg_mux *ffm)
  549. {
  550. return !strncmp(ffm->params.file, SRT_PROTO, sizeof(SRT_PROTO) - 1) ||
  551. !strncmp(ffm->params.file, UDP_PROTO, sizeof(UDP_PROTO) - 1) ||
  552. !strncmp(ffm->params.file, TCP_PROTO, sizeof(TCP_PROTO) - 1) ||
  553. !strncmp(ffm->params.file, HTTP_PROTO, sizeof(HTTP_PROTO) - 1) ||
  554. !strncmp(ffm->params.file, RIST_PROTO, sizeof(RIST_PROTO) - 1);
  555. }
  556. static int ffmpeg_mux_init_context(struct ffmpeg_mux *ffm)
  557. {
  558. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(59, 0, 100)
  559. AVOutputFormat *output_format;
  560. #else
  561. const AVOutputFormat *output_format;
  562. #endif
  563. int ret;
  564. bool is_http = false;
  565. is_http = (strncmp(ffm->params.file, HTTP_PROTO,
  566. sizeof(HTTP_PROTO) - 1) == 0);
  567. bool is_network = ffmpeg_mux_is_network(ffm);
  568. if (is_network) {
  569. avformat_network_init();
  570. }
  571. if (is_network && !is_http)
  572. output_format = av_guess_format("mpegts", NULL, "video/M2PT");
  573. else
  574. output_format = av_guess_format(NULL, ffm->params.file, NULL);
  575. if (output_format == NULL) {
  576. fprintf(stderr, "Couldn't find an appropriate muxer for '%s'\n",
  577. ffm->params.printable_file.array);
  578. return FFM_ERROR;
  579. }
  580. #ifdef ENABLE_FFMPEG_MUX_DEBUG
  581. printf("info: Output format name and long_name: %s, %s\n",
  582. output_format->name ? output_format->name : "unknown",
  583. output_format->long_name ? output_format->long_name : "unknown");
  584. #endif
  585. ret = avformat_alloc_output_context2(&ffm->output, output_format, NULL,
  586. ffm->params.file);
  587. if (ret < 0) {
  588. fprintf(stderr, "Couldn't initialize output context: %s\n",
  589. av_err2str(ret));
  590. return FFM_ERROR;
  591. }
  592. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(59, 0, 100)
  593. ffm->output->oformat->video_codec = AV_CODEC_ID_NONE;
  594. ffm->output->oformat->audio_codec = AV_CODEC_ID_NONE;
  595. #endif
  596. if (!init_streams(ffm)) {
  597. free_avformat(ffm);
  598. return FFM_ERROR;
  599. }
  600. ret = open_output_file(ffm);
  601. if (ret != FFM_SUCCESS) {
  602. free_avformat(ffm);
  603. return ret;
  604. }
  605. return FFM_SUCCESS;
  606. }
  607. static int ffmpeg_mux_init_internal(struct ffmpeg_mux *ffm, int argc,
  608. char *argv[])
  609. {
  610. argc--;
  611. argv++;
  612. if (!init_params(&argc, &argv, &ffm->params, &ffm->audio))
  613. return FFM_ERROR;
  614. if (ffm->params.tracks) {
  615. ffm->audio_header =
  616. calloc(ffm->params.tracks, sizeof(*ffm->audio_header));
  617. }
  618. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(58, 9, 100)
  619. av_register_all();
  620. #endif
  621. if (!ffmpeg_mux_get_extra_data(ffm))
  622. return FFM_ERROR;
  623. ffm->packet = av_packet_alloc();
  624. /* ffmpeg does not have a way of telling what's supported
  625. * for a given output format, so we try each possibility */
  626. return ffmpeg_mux_init_context(ffm);
  627. }
  628. static int ffmpeg_mux_init(struct ffmpeg_mux *ffm, int argc, char *argv[])
  629. {
  630. int ret = ffmpeg_mux_init_internal(ffm, argc, argv);
  631. if (ret != FFM_SUCCESS) {
  632. ffmpeg_mux_free(ffm);
  633. return ret;
  634. }
  635. ffm->initialized = true;
  636. return ret;
  637. }
  638. static inline int get_index(struct ffmpeg_mux *ffm,
  639. struct ffm_packet_info *info)
  640. {
  641. if (info->type == FFM_PACKET_VIDEO) {
  642. if (ffm->video_stream) {
  643. return ffm->video_stream->id;
  644. }
  645. } else {
  646. if ((int)info->index < ffm->num_audio_streams) {
  647. return ffm->audio_infos[info->index].stream->id;
  648. }
  649. }
  650. return -1;
  651. }
  652. static AVCodecContext *get_codec_context(struct ffmpeg_mux *ffm,
  653. struct ffm_packet_info *info)
  654. {
  655. if (info->type == FFM_PACKET_VIDEO) {
  656. if (ffm->video_stream) {
  657. return ffm->video_ctx;
  658. }
  659. } else {
  660. if ((int)info->index < ffm->num_audio_streams) {
  661. return ffm->audio_infos[info->index].ctx;
  662. }
  663. }
  664. return NULL;
  665. }
  666. static inline AVStream *get_stream(struct ffmpeg_mux *ffm, int idx)
  667. {
  668. return ffm->output->streams[idx];
  669. }
  670. static inline int64_t rescale_ts(struct ffmpeg_mux *ffm,
  671. AVRational codec_time_base, int64_t val,
  672. int idx)
  673. {
  674. AVStream *stream = get_stream(ffm, idx);
  675. return av_rescale_q_rnd(val / codec_time_base.num, codec_time_base,
  676. stream->time_base,
  677. AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
  678. }
  679. static inline bool ffmpeg_mux_packet(struct ffmpeg_mux *ffm, uint8_t *buf,
  680. struct ffm_packet_info *info)
  681. {
  682. int idx = get_index(ffm, info);
  683. /* The muxer might not support video/audio, or multiple audio tracks */
  684. if (idx == -1) {
  685. return true;
  686. }
  687. const AVRational codec_time_base =
  688. get_codec_context(ffm, info)->time_base;
  689. ffm->packet->data = buf;
  690. ffm->packet->size = (int)info->size;
  691. ffm->packet->stream_index = idx;
  692. ffm->packet->pts = rescale_ts(ffm, codec_time_base, info->pts, idx);
  693. ffm->packet->dts = rescale_ts(ffm, codec_time_base, info->dts, idx);
  694. if (info->keyframe)
  695. ffm->packet->flags = AV_PKT_FLAG_KEY;
  696. int ret = av_interleaved_write_frame(ffm->output, ffm->packet);
  697. if (ret < 0) {
  698. fprintf(stderr, "av_interleaved_write_frame failed: %d: %s\n",
  699. ret, av_err2str(ret));
  700. }
  701. /* Treat "Invalid data found when processing input" and "Invalid argument" as non-fatal */
  702. if (ret == AVERROR_INVALIDDATA || ret == -EINVAL) {
  703. return true;
  704. }
  705. return ret >= 0;
  706. }
  707. static inline bool read_change_file(struct ffmpeg_mux *ffm, uint32_t size,
  708. struct resize_buf *filename, int argc,
  709. char **argv)
  710. {
  711. resize_buf_resize(filename, size + 1);
  712. if (safe_read(filename->buf, size) != size) {
  713. return false;
  714. }
  715. filename->buf[size] = 0;
  716. #ifdef ENABLE_FFMPEG_MUX_DEBUG
  717. fprintf(stderr, "info: New output file name: %s\n", filename->buf);
  718. #endif
  719. int ret;
  720. char *argv1_backup = argv[1];
  721. argv[1] = (char *)filename->buf;
  722. ffmpeg_mux_free(ffm);
  723. ret = ffmpeg_mux_init(ffm, argc, argv);
  724. if (ret != FFM_SUCCESS) {
  725. fprintf(stderr, "Couldn't initialize muxer\n");
  726. return false;
  727. }
  728. argv[1] = argv1_backup;
  729. return true;
  730. }
  731. /* ------------------------------------------------------------------------- */
  732. #ifdef _WIN32
  733. int wmain(int argc, wchar_t *argv_w[])
  734. #else
  735. int main(int argc, char *argv[])
  736. #endif
  737. {
  738. struct ffm_packet_info info = {0};
  739. struct ffmpeg_mux ffm = {0};
  740. struct resize_buf rb = {0};
  741. struct resize_buf rb_filename = {0};
  742. bool fail = false;
  743. int ret;
  744. #ifdef _WIN32
  745. char **argv;
  746. SetErrorMode(SEM_FAILCRITICALERRORS);
  747. argv = malloc(argc * sizeof(char *));
  748. for (int i = 0; i < argc; i++) {
  749. size_t len = wcslen(argv_w[i]);
  750. int size;
  751. size = WideCharToMultiByte(CP_UTF8, 0, argv_w[i], (int)len,
  752. NULL, 0, NULL, NULL);
  753. argv[i] = malloc(size + 1);
  754. WideCharToMultiByte(CP_UTF8, 0, argv_w[i], (int)len, argv[i],
  755. size + 1, NULL, NULL);
  756. argv[i][size] = 0;
  757. }
  758. _setmode(_fileno(stdin), O_BINARY);
  759. #endif
  760. setvbuf(stderr, NULL, _IONBF, 0);
  761. ret = ffmpeg_mux_init(&ffm, argc, argv);
  762. if (ret != FFM_SUCCESS) {
  763. fprintf(stderr, "Couldn't initialize muxer\n");
  764. return ret;
  765. }
  766. while (!fail && safe_read(&info, sizeof(info)) == sizeof(info)) {
  767. if (info.type == FFM_PACKET_CHANGE_FILE) {
  768. fail = !read_change_file(&ffm, info.size, &rb_filename,
  769. argc, argv);
  770. continue;
  771. }
  772. resize_buf_resize(&rb, info.size);
  773. if (safe_read(rb.buf, info.size) == info.size) {
  774. fail = !ffmpeg_mux_packet(&ffm, rb.buf, &info);
  775. } else {
  776. fail = true;
  777. }
  778. }
  779. ffmpeg_mux_free(&ffm);
  780. resize_buf_free(&rb);
  781. resize_buf_free(&rb_filename);
  782. #ifdef _WIN32
  783. for (int i = 0; i < argc; i++)
  784. free(argv[i]);
  785. free(argv);
  786. #endif
  787. return 0;
  788. }