ffmpeg-mux.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275
  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/threading.h>
  26. #include <util/platform.h>
  27. #include <util/circlebuf.h>
  28. #include <util/dstr.h>
  29. #include <libavcodec/avcodec.h>
  30. #include <libavformat/avformat.h>
  31. #include <libavutil/channel_layout.h>
  32. #include <libavutil/mastering_display_metadata.h>
  33. #define ANSI_COLOR_RED "\x1b[0;91m"
  34. #define ANSI_COLOR_MAGENTA "\x1b[0;95m"
  35. #define ANSI_COLOR_RESET "\x1b[0m"
  36. #if LIBAVCODEC_VERSION_MAJOR >= 58
  37. #define CODEC_FLAG_GLOBAL_H AV_CODEC_FLAG_GLOBAL_HEADER
  38. #else
  39. #define CODEC_FLAG_GLOBAL_H CODEC_FLAG_GLOBAL_HEADER
  40. #endif
  41. #define AVIO_BUFFER_SIZE 65536
  42. /* ------------------------------------------------------------------------- */
  43. static char *global_stream_key = "";
  44. struct resize_buf {
  45. uint8_t *buf;
  46. size_t size;
  47. size_t capacity;
  48. };
  49. static inline void resize_buf_resize(struct resize_buf *rb, size_t size)
  50. {
  51. if (!rb->buf) {
  52. rb->buf = malloc(size);
  53. rb->size = size;
  54. rb->capacity = size;
  55. } else {
  56. if (rb->capacity < size) {
  57. size_t capx2 = rb->capacity * 2;
  58. size_t new_cap = capx2 > size ? capx2 : size;
  59. rb->buf = realloc(rb->buf, new_cap);
  60. rb->capacity = new_cap;
  61. }
  62. rb->size = size;
  63. }
  64. }
  65. static inline void resize_buf_free(struct resize_buf *rb)
  66. {
  67. free(rb->buf);
  68. }
  69. /* ------------------------------------------------------------------------- */
  70. struct main_params {
  71. char *file;
  72. /* printable_file is file with any stream key information removed */
  73. struct dstr printable_file;
  74. int has_video;
  75. int tracks;
  76. char *vcodec;
  77. int vbitrate;
  78. int gop;
  79. int width;
  80. int height;
  81. int fps_num;
  82. int fps_den;
  83. int color_primaries;
  84. int color_trc;
  85. int colorspace;
  86. int color_range;
  87. int max_luminance;
  88. char *acodec;
  89. char *muxer_settings;
  90. };
  91. struct audio_params {
  92. char *name;
  93. int abitrate;
  94. int sample_rate;
  95. int frame_size;
  96. int channels;
  97. };
  98. struct header {
  99. uint8_t *data;
  100. int size;
  101. };
  102. struct audio_info {
  103. AVStream *stream;
  104. AVCodecContext *ctx;
  105. };
  106. struct io_header {
  107. uint64_t seek_offset;
  108. size_t data_length;
  109. };
  110. struct io_buffer {
  111. bool active;
  112. bool shutdown_requested;
  113. bool output_error;
  114. os_event_t *buffer_space_available_event;
  115. os_event_t *new_data_available_event;
  116. pthread_t io_thread;
  117. pthread_mutex_t data_mutex;
  118. FILE *output_file;
  119. struct circlebuf data;
  120. uint64_t next_pos;
  121. };
  122. struct ffmpeg_mux {
  123. AVFormatContext *output;
  124. AVStream *video_stream;
  125. AVCodecContext *video_ctx;
  126. AVPacket *packet;
  127. struct audio_info *audio_infos;
  128. struct main_params params;
  129. struct audio_params *audio;
  130. struct header video_header;
  131. struct header *audio_header;
  132. int num_audio_streams;
  133. bool initialized;
  134. struct io_buffer io;
  135. };
  136. static void header_free(struct header *header)
  137. {
  138. free(header->data);
  139. }
  140. static void free_avformat(struct ffmpeg_mux *ffm)
  141. {
  142. if (ffm->output) {
  143. avcodec_free_context(&ffm->video_ctx);
  144. if ((ffm->output->oformat->flags & AVFMT_NOFILE) == 0)
  145. avio_close(ffm->output->pb);
  146. avformat_free_context(ffm->output);
  147. ffm->output = NULL;
  148. }
  149. if (ffm->audio_infos) {
  150. for (int i = 0; i < ffm->num_audio_streams; ++i)
  151. avcodec_free_context(&ffm->audio_infos[i].ctx);
  152. free(ffm->audio_infos);
  153. }
  154. ffm->video_stream = NULL;
  155. ffm->audio_infos = NULL;
  156. ffm->num_audio_streams = 0;
  157. }
  158. static void ffmpeg_mux_free(struct ffmpeg_mux *ffm)
  159. {
  160. if (ffm->initialized) {
  161. av_write_trailer(ffm->output);
  162. }
  163. // If we're writing to a file with the circlebuf, shut it
  164. // down gracefully
  165. if (ffm->io.active) {
  166. os_atomic_set_bool(&ffm->io.shutdown_requested, true);
  167. // Wakes up the I/O thread and waits for it to finish
  168. pthread_mutex_lock(&ffm->io.data_mutex);
  169. os_event_signal(ffm->io.new_data_available_event);
  170. pthread_mutex_unlock(&ffm->io.data_mutex);
  171. pthread_join(ffm->io.io_thread, NULL);
  172. // Cleanup everything else
  173. av_free(ffm->output->pb->buffer);
  174. avio_context_free(&ffm->output->pb);
  175. os_event_destroy(ffm->io.new_data_available_event);
  176. os_event_destroy(ffm->io.buffer_space_available_event);
  177. pthread_mutex_destroy(&ffm->io.data_mutex);
  178. circlebuf_free(&ffm->io.data);
  179. }
  180. free_avformat(ffm);
  181. header_free(&ffm->video_header);
  182. if (ffm->audio_header) {
  183. for (int i = 0; i < ffm->params.tracks; i++) {
  184. header_free(&ffm->audio_header[i]);
  185. }
  186. free(ffm->audio_header);
  187. }
  188. if (ffm->audio) {
  189. free(ffm->audio);
  190. }
  191. dstr_free(&ffm->params.printable_file);
  192. av_packet_free(&ffm->packet);
  193. memset(ffm, 0, sizeof(*ffm));
  194. }
  195. static bool get_opt_str(int *p_argc, char ***p_argv, char **str,
  196. const char *opt)
  197. {
  198. int argc = *p_argc;
  199. char **argv = *p_argv;
  200. if (!argc) {
  201. printf("Missing expected option: '%s'\n", opt);
  202. return false;
  203. }
  204. (*p_argc)--;
  205. (*p_argv)++;
  206. *str = argv[0];
  207. return true;
  208. }
  209. static bool get_opt_int(int *p_argc, char ***p_argv, int *i, const char *opt)
  210. {
  211. char *str;
  212. if (!get_opt_str(p_argc, p_argv, &str, opt)) {
  213. return false;
  214. }
  215. *i = atoi(str);
  216. return true;
  217. }
  218. static bool get_audio_params(struct audio_params *audio, int *argc,
  219. char ***argv)
  220. {
  221. if (!get_opt_str(argc, argv, &audio->name, "audio track name"))
  222. return false;
  223. if (!get_opt_int(argc, argv, &audio->abitrate, "audio bitrate"))
  224. return false;
  225. if (!get_opt_int(argc, argv, &audio->sample_rate, "audio sample rate"))
  226. return false;
  227. if (!get_opt_int(argc, argv, &audio->frame_size, "audio frame size"))
  228. return false;
  229. if (!get_opt_int(argc, argv, &audio->channels, "audio channels"))
  230. return false;
  231. return true;
  232. }
  233. static void ffmpeg_log_callback(void *param, int level, const char *format,
  234. va_list args)
  235. {
  236. #ifdef ENABLE_FFMPEG_MUX_DEBUG
  237. char out_buffer[4096];
  238. struct dstr out = {0};
  239. vsnprintf(out_buffer, sizeof(out_buffer), format, args);
  240. dstr_copy(&out, out_buffer);
  241. if (global_stream_key && *global_stream_key) {
  242. dstr_replace(&out, global_stream_key, "{stream_key}");
  243. }
  244. switch (level) {
  245. case AV_LOG_INFO:
  246. fprintf(stdout, "info: [ffmpeg_muxer] %s", out.array);
  247. fflush(stdout);
  248. break;
  249. case AV_LOG_WARNING:
  250. fprintf(stdout, "%swarning: [ffmpeg_muxer] %s%s",
  251. ANSI_COLOR_MAGENTA, out.array, ANSI_COLOR_RESET);
  252. fflush(stdout);
  253. break;
  254. case AV_LOG_ERROR:
  255. fprintf(stderr, "%serror: [ffmpeg_muxer] %s%s", ANSI_COLOR_RED,
  256. out.array, ANSI_COLOR_RESET);
  257. fflush(stderr);
  258. }
  259. dstr_free(&out);
  260. #else
  261. UNUSED_PARAMETER(level);
  262. UNUSED_PARAMETER(format);
  263. UNUSED_PARAMETER(args);
  264. #endif
  265. UNUSED_PARAMETER(param);
  266. }
  267. static bool init_params(int *argc, char ***argv, struct main_params *params,
  268. struct audio_params **p_audio)
  269. {
  270. struct audio_params *audio = NULL;
  271. if (!get_opt_str(argc, argv, &params->file, "file name"))
  272. return false;
  273. if (!get_opt_int(argc, argv, &params->has_video, "video track count"))
  274. return false;
  275. if (!get_opt_int(argc, argv, &params->tracks, "audio track count"))
  276. return false;
  277. if (params->has_video > 1 || params->has_video < 0) {
  278. puts("Invalid number of video tracks\n");
  279. return false;
  280. }
  281. if (params->tracks < 0) {
  282. puts("Invalid number of audio tracks\n");
  283. return false;
  284. }
  285. if (params->has_video == 0 && params->tracks == 0) {
  286. puts("Must have at least 1 audio track or 1 video track\n");
  287. return false;
  288. }
  289. if (params->has_video) {
  290. if (!get_opt_str(argc, argv, &params->vcodec, "video codec"))
  291. return false;
  292. if (!get_opt_int(argc, argv, &params->vbitrate,
  293. "video bitrate"))
  294. return false;
  295. if (!get_opt_int(argc, argv, &params->width, "video width"))
  296. return false;
  297. if (!get_opt_int(argc, argv, &params->height, "video height"))
  298. return false;
  299. if (!get_opt_int(argc, argv, &params->color_primaries,
  300. "video color primaries"))
  301. return false;
  302. if (!get_opt_int(argc, argv, &params->color_trc,
  303. "video color trc"))
  304. return false;
  305. if (!get_opt_int(argc, argv, &params->colorspace,
  306. "video colorspace"))
  307. return false;
  308. if (!get_opt_int(argc, argv, &params->color_range,
  309. "video color range"))
  310. return false;
  311. if (!get_opt_int(argc, argv, &params->max_luminance,
  312. "video max luminance"))
  313. return false;
  314. if (!get_opt_int(argc, argv, &params->fps_num, "video fps num"))
  315. return false;
  316. if (!get_opt_int(argc, argv, &params->fps_den, "video fps den"))
  317. return false;
  318. }
  319. if (params->tracks) {
  320. if (!get_opt_str(argc, argv, &params->acodec, "audio codec"))
  321. return false;
  322. audio = calloc(params->tracks, sizeof(*audio));
  323. for (int i = 0; i < params->tracks; i++) {
  324. if (!get_audio_params(&audio[i], argc, argv)) {
  325. free(audio);
  326. return false;
  327. }
  328. }
  329. }
  330. *p_audio = audio;
  331. dstr_copy(&params->printable_file, params->file);
  332. get_opt_str(argc, argv, &global_stream_key, "stream key");
  333. if (strcmp(global_stream_key, "") != 0) {
  334. dstr_replace(&params->printable_file, global_stream_key,
  335. "{stream_key}");
  336. }
  337. av_log_set_callback(ffmpeg_log_callback);
  338. get_opt_str(argc, argv, &params->muxer_settings, "muxer settings");
  339. return true;
  340. }
  341. static bool new_stream(struct ffmpeg_mux *ffm, AVStream **stream,
  342. const char *name)
  343. {
  344. *stream = avformat_new_stream(ffm->output, NULL);
  345. if (!*stream) {
  346. fprintf(stderr, "Couldn't create stream for encoder '%s'\n",
  347. name);
  348. return false;
  349. }
  350. (*stream)->id = ffm->output->nb_streams - 1;
  351. return true;
  352. }
  353. static void create_video_stream(struct ffmpeg_mux *ffm)
  354. {
  355. AVCodecContext *context;
  356. void *extradata = NULL;
  357. const char *name = ffm->params.vcodec;
  358. const AVCodecDescriptor *codec = avcodec_descriptor_get_by_name(name);
  359. if (!codec) {
  360. fprintf(stderr, "Couldn't find codec '%s'\n", name);
  361. return;
  362. }
  363. if (!new_stream(ffm, &ffm->video_stream, name))
  364. return;
  365. if (ffm->video_header.size) {
  366. extradata = av_memdup(ffm->video_header.data,
  367. ffm->video_header.size);
  368. }
  369. context = avcodec_alloc_context3(NULL);
  370. context->codec_type = codec->type;
  371. context->codec_id = codec->id;
  372. context->bit_rate = (int64_t)ffm->params.vbitrate * 1000;
  373. context->width = ffm->params.width;
  374. context->height = ffm->params.height;
  375. context->coded_width = ffm->params.width;
  376. context->coded_height = ffm->params.height;
  377. context->color_primaries = ffm->params.color_primaries;
  378. context->color_trc = ffm->params.color_trc;
  379. context->colorspace = ffm->params.colorspace;
  380. context->color_range = ffm->params.color_range;
  381. context->chroma_sample_location =
  382. (ffm->params.colorspace == AVCOL_SPC_BT2020_NCL)
  383. ? AVCHROMA_LOC_TOPLEFT
  384. : AVCHROMA_LOC_LEFT;
  385. context->extradata = extradata;
  386. context->extradata_size = ffm->video_header.size;
  387. context->time_base =
  388. (AVRational){ffm->params.fps_den, ffm->params.fps_num};
  389. ffm->video_stream->time_base = context->time_base;
  390. #if LIBAVFORMAT_VERSION_MAJOR < 59
  391. // codec->time_base may still be used if LIBAVFORMAT_VERSION_MAJOR < 59
  392. ffm->video_stream->codec->time_base = context->time_base;
  393. #endif
  394. ffm->video_stream->avg_frame_rate = av_inv_q(context->time_base);
  395. const int max_luminance = ffm->params.max_luminance;
  396. if (max_luminance > 0) {
  397. size_t content_size;
  398. AVContentLightMetadata *const content =
  399. av_content_light_metadata_alloc(&content_size);
  400. content->MaxCLL = max_luminance;
  401. content->MaxFALL = max_luminance;
  402. av_stream_add_side_data(ffm->video_stream,
  403. AV_PKT_DATA_CONTENT_LIGHT_LEVEL,
  404. (uint8_t *)content, content_size);
  405. AVMasteringDisplayMetadata *const mastering =
  406. av_mastering_display_metadata_alloc();
  407. mastering->display_primaries[0][0] = av_make_q(17, 25);
  408. mastering->display_primaries[0][1] = av_make_q(8, 25);
  409. mastering->display_primaries[1][0] = av_make_q(53, 200);
  410. mastering->display_primaries[1][1] = av_make_q(69, 100);
  411. mastering->display_primaries[2][0] = av_make_q(3, 20);
  412. mastering->display_primaries[2][1] = av_make_q(3, 50);
  413. mastering->white_point[0] = av_make_q(3127, 10000);
  414. mastering->white_point[1] = av_make_q(329, 1000);
  415. mastering->min_luminance = av_make_q(0, 1);
  416. mastering->max_luminance = av_make_q(max_luminance, 1);
  417. mastering->has_primaries = 1;
  418. mastering->has_luminance = 1;
  419. av_stream_add_side_data(ffm->video_stream,
  420. AV_PKT_DATA_MASTERING_DISPLAY_METADATA,
  421. (uint8_t *)mastering,
  422. sizeof(*mastering));
  423. }
  424. if (ffm->output->oformat->flags & AVFMT_GLOBALHEADER)
  425. context->flags |= CODEC_FLAG_GLOBAL_H;
  426. avcodec_parameters_from_context(ffm->video_stream->codecpar, context);
  427. ffm->video_ctx = context;
  428. }
  429. static void create_audio_stream(struct ffmpeg_mux *ffm, int idx)
  430. {
  431. AVCodecContext *context;
  432. AVStream *stream;
  433. void *extradata = NULL;
  434. const char *name = ffm->params.acodec;
  435. const AVCodecDescriptor *codec = avcodec_descriptor_get_by_name(name);
  436. if (!codec) {
  437. fprintf(stderr, "Couldn't find codec '%s'\n", name);
  438. return;
  439. }
  440. if (!new_stream(ffm, &stream, name))
  441. return;
  442. av_dict_set(&stream->metadata, "title", ffm->audio[idx].name, 0);
  443. stream->time_base = (AVRational){1, ffm->audio[idx].sample_rate};
  444. if (ffm->audio_header[idx].size) {
  445. extradata = av_memdup(ffm->audio_header[idx].data,
  446. ffm->audio_header[idx].size);
  447. }
  448. context = avcodec_alloc_context3(NULL);
  449. context->codec_type = codec->type;
  450. context->codec_id = codec->id;
  451. context->bit_rate = (int64_t)ffm->audio[idx].abitrate * 1000;
  452. context->channels = ffm->audio[idx].channels;
  453. context->sample_rate = ffm->audio[idx].sample_rate;
  454. context->frame_size = ffm->audio[idx].frame_size;
  455. context->sample_fmt = AV_SAMPLE_FMT_S16;
  456. context->time_base = stream->time_base;
  457. context->extradata = extradata;
  458. context->extradata_size = ffm->audio_header[idx].size;
  459. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(59, 24, 100)
  460. context->channel_layout =
  461. av_get_default_channel_layout(context->channels);
  462. //avutil default channel layout for 5 channels is 5.0 ; fix for 4.1
  463. if (context->channels == 5)
  464. context->channel_layout = av_get_channel_layout("4.1");
  465. #else
  466. av_channel_layout_default(&context->ch_layout, context->channels);
  467. //avutil default channel layout for 5 channels is 5.0 ; fix for 4.1
  468. if (context->channels == 5)
  469. context->ch_layout = (AVChannelLayout)AV_CHANNEL_LAYOUT_4POINT1;
  470. #endif
  471. if (ffm->output->oformat->flags & AVFMT_GLOBALHEADER)
  472. context->flags |= CODEC_FLAG_GLOBAL_H;
  473. avcodec_parameters_from_context(stream->codecpar, context);
  474. ffm->audio_infos[ffm->num_audio_streams].stream = stream;
  475. ffm->audio_infos[ffm->num_audio_streams].ctx = context;
  476. ffm->num_audio_streams++;
  477. }
  478. static bool init_streams(struct ffmpeg_mux *ffm)
  479. {
  480. if (ffm->params.has_video)
  481. create_video_stream(ffm);
  482. if (ffm->params.tracks) {
  483. ffm->audio_infos =
  484. calloc(ffm->params.tracks, sizeof(*ffm->audio_infos));
  485. for (int i = 0; i < ffm->params.tracks; i++)
  486. create_audio_stream(ffm, i);
  487. }
  488. if (!ffm->video_stream && !ffm->num_audio_streams)
  489. return false;
  490. return true;
  491. }
  492. static void set_header(struct header *header, uint8_t *data, size_t size)
  493. {
  494. header->size = (int)size;
  495. header->data = malloc(size);
  496. memcpy(header->data, data, size);
  497. }
  498. static void ffmpeg_mux_header(struct ffmpeg_mux *ffm, uint8_t *data,
  499. struct ffm_packet_info *info)
  500. {
  501. if (info->type == FFM_PACKET_VIDEO) {
  502. set_header(&ffm->video_header, data, (size_t)info->size);
  503. } else {
  504. set_header(&ffm->audio_header[info->index], data,
  505. (size_t)info->size);
  506. }
  507. }
  508. static size_t safe_read(void *vdata, size_t size)
  509. {
  510. uint8_t *data = vdata;
  511. size_t total = size;
  512. while (size > 0) {
  513. size_t in_size = fread(data, 1, size, stdin);
  514. if (in_size == 0)
  515. return 0;
  516. size -= in_size;
  517. data += in_size;
  518. }
  519. return total;
  520. }
  521. static bool ffmpeg_mux_get_header(struct ffmpeg_mux *ffm)
  522. {
  523. struct ffm_packet_info info = {0};
  524. bool success = safe_read(&info, sizeof(info)) == sizeof(info);
  525. if (success) {
  526. uint8_t *data = malloc(info.size);
  527. if (safe_read(data, info.size) == info.size) {
  528. ffmpeg_mux_header(ffm, data, &info);
  529. } else {
  530. success = false;
  531. }
  532. free(data);
  533. }
  534. return success;
  535. }
  536. static inline bool ffmpeg_mux_get_extra_data(struct ffmpeg_mux *ffm)
  537. {
  538. if (ffm->params.has_video) {
  539. if (!ffmpeg_mux_get_header(ffm)) {
  540. return false;
  541. }
  542. }
  543. for (int i = 0; i < ffm->params.tracks; i++) {
  544. if (!ffmpeg_mux_get_header(ffm)) {
  545. return false;
  546. }
  547. }
  548. return true;
  549. }
  550. #ifdef _MSC_VER
  551. #pragma warning(disable : 4996)
  552. #endif
  553. #define CHUNK_SIZE 1048576
  554. static void *ffmpeg_mux_io_thread(void *data)
  555. {
  556. struct ffmpeg_mux *ffm = data;
  557. // Chunk collects the writes into a larger batch
  558. size_t chunk_used = 0;
  559. unsigned char *chunk = malloc(CHUNK_SIZE);
  560. if (!chunk) {
  561. os_atomic_set_bool(&ffm->io.output_error, true);
  562. fprintf(stderr, "Error allocating memory for output\n");
  563. goto error;
  564. }
  565. bool shutting_down;
  566. bool want_seek = false;
  567. bool force_flush_chunk = false;
  568. // current_seek_position is a virtual position updated as we read from
  569. // the buffer, if it becomes discontinuous due to a seek request from
  570. // ffmpeg, then we flush the chunk. next_seek_position is the actual
  571. // offset we should seek to when we write the chunk.
  572. uint64_t current_seek_position = 0;
  573. uint64_t next_seek_position;
  574. for (;;) {
  575. // Wait for ffmpeg to write data to the buffer
  576. os_event_wait(ffm->io.new_data_available_event);
  577. // Loop to write in chunk_size chunks
  578. for (;;) {
  579. shutting_down = os_atomic_load_bool(
  580. &ffm->io.shutdown_requested);
  581. pthread_mutex_lock(&ffm->io.data_mutex);
  582. // Fetch as many writes as possible from the circlebuf
  583. // and fill up our local chunk. This may involve seeking
  584. // if ffmpeg needs to, so take care of that as well.
  585. for (;;) {
  586. size_t available = ffm->io.data.size;
  587. // Buffer is empty (now) or was already empty (we got
  588. // woken up to exit)
  589. if (!available)
  590. break;
  591. // Get seek offset and data size
  592. struct io_header header;
  593. circlebuf_peek_front(&ffm->io.data, &header,
  594. sizeof(header));
  595. // Do we need to seek?
  596. if (header.seek_offset !=
  597. current_seek_position) {
  598. // If there's already part of a chunk pending,
  599. // flush it at the current offset. Similarly,
  600. // if we already plan to seek, then seek.
  601. if (chunk_used || want_seek) {
  602. force_flush_chunk = true;
  603. break;
  604. }
  605. // Mark that we need to seek and where to
  606. want_seek = true;
  607. next_seek_position = header.seek_offset;
  608. // Update our virtual position
  609. current_seek_position =
  610. header.seek_offset;
  611. }
  612. // Make sure there's enough room for the data, if
  613. // not then force a flush
  614. if (header.data_length + chunk_used >
  615. CHUNK_SIZE) {
  616. force_flush_chunk = true;
  617. break;
  618. }
  619. // Remove header that we already read
  620. circlebuf_pop_front(&ffm->io.data, NULL,
  621. sizeof(header));
  622. // Copy from the buffer to our local chunk
  623. circlebuf_pop_front(&ffm->io.data,
  624. chunk + chunk_used,
  625. header.data_length);
  626. // Update offsets
  627. chunk_used += header.data_length;
  628. current_seek_position += header.data_length;
  629. }
  630. // Signal that there is more room in the buffer
  631. os_event_signal(ffm->io.buffer_space_available_event);
  632. // Try to avoid lots of small writes unless this was the final
  633. // data left in the buffer. The buffer might be entirely empty
  634. // if we were woken up to exit.
  635. if (!force_flush_chunk &&
  636. (!chunk_used ||
  637. (chunk_used < 65536 && !shutting_down))) {
  638. os_event_reset(
  639. ffm->io.new_data_available_event);
  640. pthread_mutex_unlock(&ffm->io.data_mutex);
  641. break;
  642. }
  643. pthread_mutex_unlock(&ffm->io.data_mutex);
  644. // Seek if we need to
  645. if (want_seek) {
  646. os_fseeki64(ffm->io.output_file,
  647. next_seek_position, SEEK_SET);
  648. current_seek_position = next_seek_position;
  649. want_seek = false;
  650. }
  651. // Write the current chunk to the output file
  652. if (fwrite(chunk, chunk_used, 1, ffm->io.output_file) !=
  653. 1) {
  654. os_atomic_set_bool(&ffm->io.output_error, true);
  655. fprintf(stderr, "Error writing to '%s', %s\n",
  656. ffm->params.printable_file.array,
  657. strerror(errno));
  658. goto error;
  659. }
  660. chunk_used = 0;
  661. force_flush_chunk = false;
  662. }
  663. // If this was the last chunk, time to exit
  664. if (shutting_down)
  665. break;
  666. }
  667. error:
  668. if (chunk)
  669. free(chunk);
  670. fclose(ffm->io.output_file);
  671. return NULL;
  672. }
  673. static int64_t ffmpeg_mux_seek_av_buffer(void *opaque, int64_t offset,
  674. int whence)
  675. {
  676. struct ffmpeg_mux *ffm = opaque;
  677. // If the output thread failed, signal that back up the stack
  678. if (os_atomic_load_bool(&ffm->io.output_error))
  679. return -1;
  680. // Update where the next write should go
  681. pthread_mutex_lock(&ffm->io.data_mutex);
  682. if (whence == SEEK_SET)
  683. ffm->io.next_pos = offset;
  684. else if (whence == SEEK_CUR)
  685. ffm->io.next_pos += offset;
  686. pthread_mutex_unlock(&ffm->io.data_mutex);
  687. return 0;
  688. }
  689. static int ffmpeg_mux_write_av_buffer(void *opaque, uint8_t *buf, int buf_size)
  690. {
  691. struct ffmpeg_mux *ffm = opaque;
  692. // If the output thread failed, signal that back up the stack
  693. if (os_atomic_load_bool(&ffm->io.output_error))
  694. return -1;
  695. for (;;) {
  696. pthread_mutex_lock(&ffm->io.data_mutex);
  697. // Avoid unbounded growth of the circlebuf, cap to 256 MB
  698. if (ffm->io.data.capacity >= 256 * 1048576 &&
  699. ffm->io.data.capacity - ffm->io.data.size <
  700. buf_size + sizeof(struct io_header)) {
  701. // No space, wait for the I/O thread to make space
  702. os_event_reset(ffm->io.buffer_space_available_event);
  703. pthread_mutex_unlock(&ffm->io.data_mutex);
  704. os_event_wait(ffm->io.buffer_space_available_event);
  705. } else {
  706. break;
  707. }
  708. }
  709. struct io_header header;
  710. header.data_length = buf_size;
  711. header.seek_offset = ffm->io.next_pos;
  712. // Copy the data into the buffer
  713. circlebuf_push_back(&ffm->io.data, &header, sizeof(header));
  714. circlebuf_push_back(&ffm->io.data, buf, buf_size);
  715. // Advance the next write position
  716. ffm->io.next_pos += buf_size;
  717. // Tell the I/O thread that there's new data to be written
  718. os_event_signal(ffm->io.new_data_available_event);
  719. pthread_mutex_unlock(&ffm->io.data_mutex);
  720. return buf_size;
  721. }
  722. #define SRT_PROTO "srt"
  723. #define UDP_PROTO "udp"
  724. #define TCP_PROTO "tcp"
  725. #define HTTP_PROTO "http"
  726. #define RIST_PROTO "rist"
  727. static bool ffmpeg_mux_is_network(struct ffmpeg_mux *ffm)
  728. {
  729. return !strncmp(ffm->params.file, SRT_PROTO, sizeof(SRT_PROTO) - 1) ||
  730. !strncmp(ffm->params.file, UDP_PROTO, sizeof(UDP_PROTO) - 1) ||
  731. !strncmp(ffm->params.file, TCP_PROTO, sizeof(TCP_PROTO) - 1) ||
  732. !strncmp(ffm->params.file, HTTP_PROTO, sizeof(HTTP_PROTO) - 1) ||
  733. !strncmp(ffm->params.file, RIST_PROTO, sizeof(RIST_PROTO) - 1);
  734. }
  735. static inline int open_output_file(struct ffmpeg_mux *ffm)
  736. {
  737. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(59, 0, 100)
  738. AVOutputFormat *format = ffm->output->oformat;
  739. #else
  740. const AVOutputFormat *format = ffm->output->oformat;
  741. #endif
  742. int ret;
  743. if ((format->flags & AVFMT_NOFILE) == 0) {
  744. if (!ffmpeg_mux_is_network(ffm)) {
  745. // If not outputting to a network, write to a circlebuf
  746. // instead of relying on ffmpeg disk output. This hopefully
  747. // works around too small buffers somewhere causing output
  748. // stalls when recording.
  749. // We're in charge of managing the actual file now
  750. ffm->io.output_file = os_fopen(ffm->params.file, "wb");
  751. if (!ffm->io.output_file) {
  752. fprintf(stderr, "Couldn't open '%s', %s\n",
  753. ffm->params.printable_file.array,
  754. strerror(errno));
  755. return FFM_ERROR;
  756. }
  757. // Start at 1MB, this can grow up to 256 MB depending
  758. // how fast data is going in and out (limited in
  759. // ffmpeg_mux_write_av_buffer)
  760. circlebuf_reserve(&ffm->io.data, 1048576);
  761. pthread_mutex_init(&ffm->io.data_mutex, NULL);
  762. os_event_init(&ffm->io.buffer_space_available_event,
  763. OS_EVENT_TYPE_AUTO);
  764. os_event_init(&ffm->io.new_data_available_event,
  765. OS_EVENT_TYPE_AUTO);
  766. pthread_create(&ffm->io.io_thread, NULL,
  767. ffmpeg_mux_io_thread, ffm);
  768. unsigned char *avio_ctx_buffer =
  769. av_malloc(AVIO_BUFFER_SIZE);
  770. ffm->output->pb = avio_alloc_context(
  771. avio_ctx_buffer, AVIO_BUFFER_SIZE, 1, ffm, NULL,
  772. ffmpeg_mux_write_av_buffer,
  773. ffmpeg_mux_seek_av_buffer);
  774. ffm->io.active = true;
  775. } else {
  776. ret = avio_open(&ffm->output->pb, ffm->params.file,
  777. AVIO_FLAG_WRITE);
  778. if (ret < 0) {
  779. fprintf(stderr, "Couldn't open '%s', %s\n",
  780. ffm->params.printable_file.array,
  781. av_err2str(ret));
  782. return FFM_ERROR;
  783. }
  784. }
  785. }
  786. AVDictionary *dict = NULL;
  787. if ((ret = av_dict_parse_string(&dict, ffm->params.muxer_settings, "=",
  788. " ", 0))) {
  789. fprintf(stderr, "Failed to parse muxer settings: %s\n%s\n",
  790. av_err2str(ret), ffm->params.muxer_settings);
  791. av_dict_free(&dict);
  792. }
  793. if (av_dict_count(dict) > 0) {
  794. printf("Using muxer settings:");
  795. AVDictionaryEntry *entry = NULL;
  796. while ((entry = av_dict_get(dict, "", entry,
  797. AV_DICT_IGNORE_SUFFIX)))
  798. printf("\n\t%s=%s", entry->key, entry->value);
  799. printf("\n");
  800. }
  801. ret = avformat_write_header(ffm->output, &dict);
  802. if (ret < 0) {
  803. fprintf(stderr, "Error opening '%s': %s",
  804. ffm->params.printable_file.array, av_err2str(ret));
  805. av_dict_free(&dict);
  806. return ret == -22 ? FFM_UNSUPPORTED : FFM_ERROR;
  807. }
  808. av_dict_free(&dict);
  809. return FFM_SUCCESS;
  810. }
  811. static int ffmpeg_mux_init_context(struct ffmpeg_mux *ffm)
  812. {
  813. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(59, 0, 100)
  814. AVOutputFormat *output_format;
  815. #else
  816. const AVOutputFormat *output_format;
  817. #endif
  818. int ret;
  819. bool is_http = false;
  820. is_http = (strncmp(ffm->params.file, HTTP_PROTO,
  821. sizeof(HTTP_PROTO) - 1) == 0);
  822. bool is_network = ffmpeg_mux_is_network(ffm);
  823. if (is_network) {
  824. avformat_network_init();
  825. }
  826. if (is_network && !is_http)
  827. output_format = av_guess_format("mpegts", NULL, "video/M2PT");
  828. else
  829. output_format = av_guess_format(NULL, ffm->params.file, NULL);
  830. if (output_format == NULL) {
  831. fprintf(stderr, "Couldn't find an appropriate muxer for '%s'\n",
  832. ffm->params.printable_file.array);
  833. return FFM_ERROR;
  834. }
  835. #ifdef ENABLE_FFMPEG_MUX_DEBUG
  836. printf("info: Output format name and long_name: %s, %s\n",
  837. output_format->name ? output_format->name : "unknown",
  838. output_format->long_name ? output_format->long_name : "unknown");
  839. #endif
  840. ret = avformat_alloc_output_context2(&ffm->output, output_format, NULL,
  841. ffm->params.file);
  842. if (ret < 0) {
  843. fprintf(stderr, "Couldn't initialize output context: %s\n",
  844. av_err2str(ret));
  845. return FFM_ERROR;
  846. }
  847. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(59, 0, 100)
  848. ffm->output->oformat->video_codec = AV_CODEC_ID_NONE;
  849. ffm->output->oformat->audio_codec = AV_CODEC_ID_NONE;
  850. #endif
  851. if (!init_streams(ffm)) {
  852. free_avformat(ffm);
  853. return FFM_ERROR;
  854. }
  855. ret = open_output_file(ffm);
  856. if (ret != FFM_SUCCESS) {
  857. free_avformat(ffm);
  858. return ret;
  859. }
  860. return FFM_SUCCESS;
  861. }
  862. static int ffmpeg_mux_init_internal(struct ffmpeg_mux *ffm, int argc,
  863. char *argv[])
  864. {
  865. argc--;
  866. argv++;
  867. if (!init_params(&argc, &argv, &ffm->params, &ffm->audio))
  868. return FFM_ERROR;
  869. if (ffm->params.tracks) {
  870. ffm->audio_header =
  871. calloc(ffm->params.tracks, sizeof(*ffm->audio_header));
  872. }
  873. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(58, 9, 100)
  874. av_register_all();
  875. #endif
  876. if (!ffmpeg_mux_get_extra_data(ffm))
  877. return FFM_ERROR;
  878. ffm->packet = av_packet_alloc();
  879. /* ffmpeg does not have a way of telling what's supported
  880. * for a given output format, so we try each possibility */
  881. return ffmpeg_mux_init_context(ffm);
  882. }
  883. static int ffmpeg_mux_init(struct ffmpeg_mux *ffm, int argc, char *argv[])
  884. {
  885. int ret = ffmpeg_mux_init_internal(ffm, argc, argv);
  886. if (ret != FFM_SUCCESS) {
  887. ffmpeg_mux_free(ffm);
  888. return ret;
  889. }
  890. ffm->initialized = true;
  891. return ret;
  892. }
  893. static inline int get_index(struct ffmpeg_mux *ffm,
  894. struct ffm_packet_info *info)
  895. {
  896. if (info->type == FFM_PACKET_VIDEO) {
  897. if (ffm->video_stream) {
  898. return ffm->video_stream->id;
  899. }
  900. } else {
  901. if ((int)info->index < ffm->num_audio_streams) {
  902. return ffm->audio_infos[info->index].stream->id;
  903. }
  904. }
  905. return -1;
  906. }
  907. static AVCodecContext *get_codec_context(struct ffmpeg_mux *ffm,
  908. struct ffm_packet_info *info)
  909. {
  910. if (info->type == FFM_PACKET_VIDEO) {
  911. if (ffm->video_stream) {
  912. return ffm->video_ctx;
  913. }
  914. } else {
  915. if ((int)info->index < ffm->num_audio_streams) {
  916. return ffm->audio_infos[info->index].ctx;
  917. }
  918. }
  919. return NULL;
  920. }
  921. static inline AVStream *get_stream(struct ffmpeg_mux *ffm, int idx)
  922. {
  923. return ffm->output->streams[idx];
  924. }
  925. static inline int64_t rescale_ts(struct ffmpeg_mux *ffm,
  926. AVRational codec_time_base, int64_t val,
  927. int idx)
  928. {
  929. AVStream *stream = get_stream(ffm, idx);
  930. return av_rescale_q_rnd(val / codec_time_base.num, codec_time_base,
  931. stream->time_base,
  932. AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
  933. }
  934. static inline bool ffmpeg_mux_packet(struct ffmpeg_mux *ffm, uint8_t *buf,
  935. struct ffm_packet_info *info)
  936. {
  937. int idx = get_index(ffm, info);
  938. /* The muxer might not support video/audio, or multiple audio tracks */
  939. if (idx == -1) {
  940. return true;
  941. }
  942. const AVRational codec_time_base =
  943. get_codec_context(ffm, info)->time_base;
  944. ffm->packet->data = buf;
  945. ffm->packet->size = (int)info->size;
  946. ffm->packet->stream_index = idx;
  947. ffm->packet->pts = rescale_ts(ffm, codec_time_base, info->pts, idx);
  948. ffm->packet->dts = rescale_ts(ffm, codec_time_base, info->dts, idx);
  949. if (info->keyframe)
  950. ffm->packet->flags = AV_PKT_FLAG_KEY;
  951. int ret = av_interleaved_write_frame(ffm->output, ffm->packet);
  952. if (ret < 0) {
  953. fprintf(stderr, "av_interleaved_write_frame failed: %d: %s\n",
  954. ret, av_err2str(ret));
  955. }
  956. /* Treat "Invalid data found when processing input" and "Invalid argument" as non-fatal */
  957. if (ret == AVERROR_INVALIDDATA || ret == -EINVAL) {
  958. return true;
  959. }
  960. return ret >= 0;
  961. }
  962. static inline bool read_change_file(struct ffmpeg_mux *ffm, uint32_t size,
  963. struct resize_buf *filename, int argc,
  964. char **argv)
  965. {
  966. resize_buf_resize(filename, size + 1);
  967. if (safe_read(filename->buf, size) != size) {
  968. return false;
  969. }
  970. filename->buf[size] = 0;
  971. #ifdef ENABLE_FFMPEG_MUX_DEBUG
  972. fprintf(stderr, "info: New output file name: %s\n", filename->buf);
  973. #endif
  974. int ret;
  975. char *argv1_backup = argv[1];
  976. argv[1] = (char *)filename->buf;
  977. ffmpeg_mux_free(ffm);
  978. ret = ffmpeg_mux_init(ffm, argc, argv);
  979. if (ret != FFM_SUCCESS) {
  980. fprintf(stderr, "Couldn't initialize muxer\n");
  981. return false;
  982. }
  983. argv[1] = argv1_backup;
  984. return true;
  985. }
  986. /* ------------------------------------------------------------------------- */
  987. #ifdef _WIN32
  988. int wmain(int argc, wchar_t *argv_w[])
  989. #else
  990. int main(int argc, char *argv[])
  991. #endif
  992. {
  993. struct ffm_packet_info info = {0};
  994. struct ffmpeg_mux ffm = {0};
  995. struct resize_buf rb = {0};
  996. struct resize_buf rb_filename = {0};
  997. bool fail = false;
  998. int ret;
  999. #ifdef _WIN32
  1000. char **argv;
  1001. SetErrorMode(SEM_FAILCRITICALERRORS);
  1002. argv = malloc(argc * sizeof(char *));
  1003. for (int i = 0; i < argc; i++) {
  1004. size_t len = wcslen(argv_w[i]);
  1005. int size;
  1006. size = WideCharToMultiByte(CP_UTF8, 0, argv_w[i], (int)len,
  1007. NULL, 0, NULL, NULL);
  1008. argv[i] = malloc(size + 1);
  1009. WideCharToMultiByte(CP_UTF8, 0, argv_w[i], (int)len, argv[i],
  1010. size + 1, NULL, NULL);
  1011. argv[i][size] = 0;
  1012. }
  1013. _setmode(_fileno(stdin), O_BINARY);
  1014. #endif
  1015. setvbuf(stderr, NULL, _IONBF, 0);
  1016. ret = ffmpeg_mux_init(&ffm, argc, argv);
  1017. if (ret != FFM_SUCCESS) {
  1018. fprintf(stderr, "Couldn't initialize muxer\n");
  1019. return ret;
  1020. }
  1021. while (!fail && safe_read(&info, sizeof(info)) == sizeof(info)) {
  1022. if (info.type == FFM_PACKET_CHANGE_FILE) {
  1023. fail = !read_change_file(&ffm, info.size, &rb_filename,
  1024. argc, argv);
  1025. continue;
  1026. }
  1027. resize_buf_resize(&rb, info.size);
  1028. if (safe_read(rb.buf, info.size) == info.size) {
  1029. fail = !ffmpeg_mux_packet(&ffm, rb.buf, &info);
  1030. } else {
  1031. fail = true;
  1032. }
  1033. }
  1034. ffmpeg_mux_free(&ffm);
  1035. resize_buf_free(&rb);
  1036. resize_buf_free(&rb_filename);
  1037. #ifdef _WIN32
  1038. for (int i = 0; i < argc; i++)
  1039. free(argv[i]);
  1040. free(argv);
  1041. #endif
  1042. return 0;
  1043. }