ffmpeg-mux.c 31 KB

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