ffmpeg-mux.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948
  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->max_luminance =
  358. av_make_q(ffm->params.max_luminance, 1);
  359. mastering->has_luminance = 1;
  360. av_stream_add_side_data(ffm->video_stream,
  361. AV_PKT_DATA_MASTERING_DISPLAY_METADATA,
  362. (uint8_t *)mastering,
  363. sizeof(*mastering));
  364. }
  365. if (ffm->output->oformat->flags & AVFMT_GLOBALHEADER)
  366. context->flags |= CODEC_FLAG_GLOBAL_H;
  367. avcodec_parameters_from_context(ffm->video_stream->codecpar, context);
  368. ffm->video_ctx = context;
  369. }
  370. static void create_audio_stream(struct ffmpeg_mux *ffm, int idx)
  371. {
  372. AVCodecContext *context;
  373. AVStream *stream;
  374. void *extradata = NULL;
  375. const char *name = ffm->params.acodec;
  376. const AVCodecDescriptor *codec = avcodec_descriptor_get_by_name(name);
  377. if (!codec) {
  378. fprintf(stderr, "Couldn't find codec '%s'\n", name);
  379. return;
  380. }
  381. if (!new_stream(ffm, &stream, name))
  382. return;
  383. av_dict_set(&stream->metadata, "title", ffm->audio[idx].name, 0);
  384. stream->time_base = (AVRational){1, ffm->audio[idx].sample_rate};
  385. if (ffm->audio_header[idx].size) {
  386. extradata = av_memdup(ffm->audio_header[idx].data,
  387. ffm->audio_header[idx].size);
  388. }
  389. context = avcodec_alloc_context3(NULL);
  390. context->codec_type = codec->type;
  391. context->codec_id = codec->id;
  392. context->bit_rate = (int64_t)ffm->audio[idx].abitrate * 1000;
  393. context->channels = ffm->audio[idx].channels;
  394. context->sample_rate = ffm->audio[idx].sample_rate;
  395. context->frame_size = ffm->audio[idx].frame_size;
  396. context->sample_fmt = AV_SAMPLE_FMT_S16;
  397. context->time_base = stream->time_base;
  398. context->extradata = extradata;
  399. context->extradata_size = ffm->audio_header[idx].size;
  400. context->channel_layout =
  401. av_get_default_channel_layout(context->channels);
  402. //avutil default channel layout for 4 channels is 4.0 ; fix for quad
  403. if (context->channels == 4)
  404. context->channel_layout = av_get_channel_layout("quad");
  405. //avutil default channel layout for 5 channels is 5.0 ; fix for 4.1
  406. if (context->channels == 5)
  407. context->channel_layout = av_get_channel_layout("4.1");
  408. if (ffm->output->oformat->flags & AVFMT_GLOBALHEADER)
  409. context->flags |= CODEC_FLAG_GLOBAL_H;
  410. avcodec_parameters_from_context(stream->codecpar, context);
  411. ffm->audio_infos[ffm->num_audio_streams].stream = stream;
  412. ffm->audio_infos[ffm->num_audio_streams].ctx = context;
  413. ffm->num_audio_streams++;
  414. }
  415. static bool init_streams(struct ffmpeg_mux *ffm)
  416. {
  417. if (ffm->params.has_video)
  418. create_video_stream(ffm);
  419. if (ffm->params.tracks) {
  420. ffm->audio_infos =
  421. calloc(ffm->params.tracks, sizeof(*ffm->audio_infos));
  422. for (int i = 0; i < ffm->params.tracks; i++)
  423. create_audio_stream(ffm, i);
  424. }
  425. if (!ffm->video_stream && !ffm->num_audio_streams)
  426. return false;
  427. return true;
  428. }
  429. static void set_header(struct header *header, uint8_t *data, size_t size)
  430. {
  431. header->size = (int)size;
  432. header->data = malloc(size);
  433. memcpy(header->data, data, size);
  434. }
  435. static void ffmpeg_mux_header(struct ffmpeg_mux *ffm, uint8_t *data,
  436. struct ffm_packet_info *info)
  437. {
  438. if (info->type == FFM_PACKET_VIDEO) {
  439. set_header(&ffm->video_header, data, (size_t)info->size);
  440. } else {
  441. set_header(&ffm->audio_header[info->index], data,
  442. (size_t)info->size);
  443. }
  444. }
  445. static size_t safe_read(void *vdata, size_t size)
  446. {
  447. uint8_t *data = vdata;
  448. size_t total = size;
  449. while (size > 0) {
  450. size_t in_size = fread(data, 1, size, stdin);
  451. if (in_size == 0)
  452. return 0;
  453. size -= in_size;
  454. data += in_size;
  455. }
  456. return total;
  457. }
  458. static bool ffmpeg_mux_get_header(struct ffmpeg_mux *ffm)
  459. {
  460. struct ffm_packet_info info = {0};
  461. bool success = safe_read(&info, sizeof(info)) == sizeof(info);
  462. if (success) {
  463. uint8_t *data = malloc(info.size);
  464. if (safe_read(data, info.size) == info.size) {
  465. ffmpeg_mux_header(ffm, data, &info);
  466. } else {
  467. success = false;
  468. }
  469. free(data);
  470. }
  471. return success;
  472. }
  473. static inline bool ffmpeg_mux_get_extra_data(struct ffmpeg_mux *ffm)
  474. {
  475. if (ffm->params.has_video) {
  476. if (!ffmpeg_mux_get_header(ffm)) {
  477. return false;
  478. }
  479. }
  480. for (int i = 0; i < ffm->params.tracks; i++) {
  481. if (!ffmpeg_mux_get_header(ffm)) {
  482. return false;
  483. }
  484. }
  485. return true;
  486. }
  487. #ifdef _MSC_VER
  488. #pragma warning(disable : 4996)
  489. #endif
  490. static inline int open_output_file(struct ffmpeg_mux *ffm)
  491. {
  492. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(59, 0, 100)
  493. AVOutputFormat *format = ffm->output->oformat;
  494. #else
  495. const AVOutputFormat *format = ffm->output->oformat;
  496. #endif
  497. int ret;
  498. if ((format->flags & AVFMT_NOFILE) == 0) {
  499. ret = avio_open(&ffm->output->pb, ffm->params.file,
  500. AVIO_FLAG_WRITE);
  501. if (ret < 0) {
  502. fprintf(stderr, "Couldn't open '%s', %s\n",
  503. ffm->params.printable_file.array,
  504. av_err2str(ret));
  505. return FFM_ERROR;
  506. }
  507. }
  508. AVDictionary *dict = NULL;
  509. if ((ret = av_dict_parse_string(&dict, ffm->params.muxer_settings, "=",
  510. " ", 0))) {
  511. fprintf(stderr, "Failed to parse muxer settings: %s\n%s\n",
  512. av_err2str(ret), ffm->params.muxer_settings);
  513. av_dict_free(&dict);
  514. }
  515. if (av_dict_count(dict) > 0) {
  516. printf("Using muxer settings:");
  517. AVDictionaryEntry *entry = NULL;
  518. while ((entry = av_dict_get(dict, "", entry,
  519. AV_DICT_IGNORE_SUFFIX)))
  520. printf("\n\t%s=%s", entry->key, entry->value);
  521. printf("\n");
  522. }
  523. ret = avformat_write_header(ffm->output, &dict);
  524. if (ret < 0) {
  525. fprintf(stderr, "Error opening '%s': %s",
  526. ffm->params.printable_file.array, av_err2str(ret));
  527. av_dict_free(&dict);
  528. return ret == -22 ? FFM_UNSUPPORTED : FFM_ERROR;
  529. }
  530. av_dict_free(&dict);
  531. return FFM_SUCCESS;
  532. }
  533. #define SRT_PROTO "srt"
  534. #define UDP_PROTO "udp"
  535. #define TCP_PROTO "tcp"
  536. #define HTTP_PROTO "http"
  537. #define RIST_PROTO "rist"
  538. static bool ffmpeg_mux_is_network(struct ffmpeg_mux *ffm)
  539. {
  540. return !strncmp(ffm->params.file, SRT_PROTO, sizeof(SRT_PROTO) - 1) ||
  541. !strncmp(ffm->params.file, UDP_PROTO, sizeof(UDP_PROTO) - 1) ||
  542. !strncmp(ffm->params.file, TCP_PROTO, sizeof(TCP_PROTO) - 1) ||
  543. !strncmp(ffm->params.file, HTTP_PROTO, sizeof(HTTP_PROTO) - 1) ||
  544. !strncmp(ffm->params.file, RIST_PROTO, sizeof(RIST_PROTO) - 1);
  545. }
  546. static int ffmpeg_mux_init_context(struct ffmpeg_mux *ffm)
  547. {
  548. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(59, 0, 100)
  549. AVOutputFormat *output_format;
  550. #else
  551. const AVOutputFormat *output_format;
  552. #endif
  553. int ret;
  554. bool is_http = false;
  555. is_http = (strncmp(ffm->params.file, HTTP_PROTO,
  556. sizeof(HTTP_PROTO) - 1) == 0);
  557. bool is_network = ffmpeg_mux_is_network(ffm);
  558. if (is_network) {
  559. avformat_network_init();
  560. }
  561. if (is_network && !is_http)
  562. output_format = av_guess_format("mpegts", NULL, "video/M2PT");
  563. else
  564. output_format = av_guess_format(NULL, ffm->params.file, NULL);
  565. if (output_format == NULL) {
  566. fprintf(stderr, "Couldn't find an appropriate muxer for '%s'\n",
  567. ffm->params.printable_file.array);
  568. return FFM_ERROR;
  569. }
  570. #ifdef ENABLE_FFMPEG_MUX_DEBUG
  571. printf("info: Output format name and long_name: %s, %s\n",
  572. output_format->name ? output_format->name : "unknown",
  573. output_format->long_name ? output_format->long_name : "unknown");
  574. #endif
  575. ret = avformat_alloc_output_context2(&ffm->output, output_format, NULL,
  576. ffm->params.file);
  577. if (ret < 0) {
  578. fprintf(stderr, "Couldn't initialize output context: %s\n",
  579. av_err2str(ret));
  580. return FFM_ERROR;
  581. }
  582. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(59, 0, 100)
  583. ffm->output->oformat->video_codec = AV_CODEC_ID_NONE;
  584. ffm->output->oformat->audio_codec = AV_CODEC_ID_NONE;
  585. #endif
  586. if (!init_streams(ffm)) {
  587. free_avformat(ffm);
  588. return FFM_ERROR;
  589. }
  590. ret = open_output_file(ffm);
  591. if (ret != FFM_SUCCESS) {
  592. free_avformat(ffm);
  593. return ret;
  594. }
  595. return FFM_SUCCESS;
  596. }
  597. static int ffmpeg_mux_init_internal(struct ffmpeg_mux *ffm, int argc,
  598. char *argv[])
  599. {
  600. argc--;
  601. argv++;
  602. if (!init_params(&argc, &argv, &ffm->params, &ffm->audio))
  603. return FFM_ERROR;
  604. if (ffm->params.tracks) {
  605. ffm->audio_header =
  606. calloc(ffm->params.tracks, sizeof(*ffm->audio_header));
  607. }
  608. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(58, 9, 100)
  609. av_register_all();
  610. #endif
  611. if (!ffmpeg_mux_get_extra_data(ffm))
  612. return FFM_ERROR;
  613. ffm->packet = av_packet_alloc();
  614. /* ffmpeg does not have a way of telling what's supported
  615. * for a given output format, so we try each possibility */
  616. return ffmpeg_mux_init_context(ffm);
  617. }
  618. static int ffmpeg_mux_init(struct ffmpeg_mux *ffm, int argc, char *argv[])
  619. {
  620. int ret = ffmpeg_mux_init_internal(ffm, argc, argv);
  621. if (ret != FFM_SUCCESS) {
  622. ffmpeg_mux_free(ffm);
  623. return ret;
  624. }
  625. ffm->initialized = true;
  626. return ret;
  627. }
  628. static inline int get_index(struct ffmpeg_mux *ffm,
  629. struct ffm_packet_info *info)
  630. {
  631. if (info->type == FFM_PACKET_VIDEO) {
  632. if (ffm->video_stream) {
  633. return ffm->video_stream->id;
  634. }
  635. } else {
  636. if ((int)info->index < ffm->num_audio_streams) {
  637. return ffm->audio_infos[info->index].stream->id;
  638. }
  639. }
  640. return -1;
  641. }
  642. static AVCodecContext *get_codec_context(struct ffmpeg_mux *ffm,
  643. struct ffm_packet_info *info)
  644. {
  645. if (info->type == FFM_PACKET_VIDEO) {
  646. if (ffm->video_stream) {
  647. return ffm->video_ctx;
  648. }
  649. } else {
  650. if ((int)info->index < ffm->num_audio_streams) {
  651. return ffm->audio_infos[info->index].ctx;
  652. }
  653. }
  654. return NULL;
  655. }
  656. static inline AVStream *get_stream(struct ffmpeg_mux *ffm, int idx)
  657. {
  658. return ffm->output->streams[idx];
  659. }
  660. static inline int64_t rescale_ts(struct ffmpeg_mux *ffm,
  661. AVRational codec_time_base, int64_t val,
  662. int idx)
  663. {
  664. AVStream *stream = get_stream(ffm, idx);
  665. return av_rescale_q_rnd(val / codec_time_base.num, codec_time_base,
  666. stream->time_base,
  667. AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
  668. }
  669. static inline bool ffmpeg_mux_packet(struct ffmpeg_mux *ffm, uint8_t *buf,
  670. struct ffm_packet_info *info)
  671. {
  672. int idx = get_index(ffm, info);
  673. /* The muxer might not support video/audio, or multiple audio tracks */
  674. if (idx == -1) {
  675. return true;
  676. }
  677. const AVRational codec_time_base =
  678. get_codec_context(ffm, info)->time_base;
  679. ffm->packet->data = buf;
  680. ffm->packet->size = (int)info->size;
  681. ffm->packet->stream_index = idx;
  682. ffm->packet->pts = rescale_ts(ffm, codec_time_base, info->pts, idx);
  683. ffm->packet->dts = rescale_ts(ffm, codec_time_base, info->dts, idx);
  684. if (info->keyframe)
  685. ffm->packet->flags = AV_PKT_FLAG_KEY;
  686. int ret = av_interleaved_write_frame(ffm->output, ffm->packet);
  687. if (ret < 0) {
  688. fprintf(stderr, "av_interleaved_write_frame failed: %d: %s\n",
  689. ret, av_err2str(ret));
  690. }
  691. /* Treat "Invalid data found when processing input" and "Invalid argument" as non-fatal */
  692. if (ret == AVERROR_INVALIDDATA || ret == -EINVAL) {
  693. return true;
  694. }
  695. return ret >= 0;
  696. }
  697. static inline bool read_change_file(struct ffmpeg_mux *ffm, uint32_t size,
  698. struct resize_buf *filename, int argc,
  699. char **argv)
  700. {
  701. resize_buf_resize(filename, size + 1);
  702. if (safe_read(filename->buf, size) != size) {
  703. return false;
  704. }
  705. filename->buf[size] = 0;
  706. #ifdef ENABLE_FFMPEG_MUX_DEBUG
  707. fprintf(stderr, "info: New output file name: %s\n", filename->buf);
  708. #endif
  709. int ret;
  710. char *argv1_backup = argv[1];
  711. argv[1] = (char *)filename->buf;
  712. ffmpeg_mux_free(ffm);
  713. ret = ffmpeg_mux_init(ffm, argc, argv);
  714. if (ret != FFM_SUCCESS) {
  715. fprintf(stderr, "Couldn't initialize muxer\n");
  716. return false;
  717. }
  718. argv[1] = argv1_backup;
  719. return true;
  720. }
  721. /* ------------------------------------------------------------------------- */
  722. #ifdef _WIN32
  723. int wmain(int argc, wchar_t *argv_w[])
  724. #else
  725. int main(int argc, char *argv[])
  726. #endif
  727. {
  728. struct ffm_packet_info info = {0};
  729. struct ffmpeg_mux ffm = {0};
  730. struct resize_buf rb = {0};
  731. struct resize_buf rb_filename = {0};
  732. bool fail = false;
  733. int ret;
  734. #ifdef _WIN32
  735. char **argv;
  736. SetErrorMode(SEM_FAILCRITICALERRORS);
  737. argv = malloc(argc * sizeof(char *));
  738. for (int i = 0; i < argc; i++) {
  739. size_t len = wcslen(argv_w[i]);
  740. int size;
  741. size = WideCharToMultiByte(CP_UTF8, 0, argv_w[i], (int)len,
  742. NULL, 0, NULL, NULL);
  743. argv[i] = malloc(size + 1);
  744. WideCharToMultiByte(CP_UTF8, 0, argv_w[i], (int)len, argv[i],
  745. size + 1, NULL, NULL);
  746. argv[i][size] = 0;
  747. }
  748. _setmode(_fileno(stdin), O_BINARY);
  749. #endif
  750. setvbuf(stderr, NULL, _IONBF, 0);
  751. ret = ffmpeg_mux_init(&ffm, argc, argv);
  752. if (ret != FFM_SUCCESS) {
  753. fprintf(stderr, "Couldn't initialize muxer\n");
  754. return ret;
  755. }
  756. while (!fail && safe_read(&info, sizeof(info)) == sizeof(info)) {
  757. if (info.type == FFM_PACKET_CHANGE_FILE) {
  758. fail = !read_change_file(&ffm, info.size, &rb_filename,
  759. argc, argv);
  760. continue;
  761. }
  762. resize_buf_resize(&rb, info.size);
  763. if (safe_read(rb.buf, info.size) == info.size) {
  764. fail = !ffmpeg_mux_packet(&ffm, rb.buf, &info);
  765. } else {
  766. fail = true;
  767. }
  768. }
  769. ffmpeg_mux_free(&ffm);
  770. resize_buf_free(&rb);
  771. resize_buf_free(&rb_filename);
  772. #ifdef _WIN32
  773. for (int i = 0; i < argc; i++)
  774. free(argv[i]);
  775. free(argv);
  776. #endif
  777. return 0;
  778. }