obs-ffmpeg-mpegts.c 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324
  1. /******************************************************************************
  2. Copyright (C) 2023 by Lain Bailey <[email protected]>
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ******************************************************************************/
  14. #include <obs-module.h>
  15. #include <util/circlebuf.h>
  16. #include <util/threading.h>
  17. #include <util/dstr.h>
  18. #include <util/darray.h>
  19. #include <util/platform.h>
  20. #include "obs-ffmpeg-output.h"
  21. #include "obs-ffmpeg-formats.h"
  22. #include "obs-ffmpeg-compat.h"
  23. #include "obs-ffmpeg-rist.h"
  24. #include "obs-ffmpeg-srt.h"
  25. #include <libavutil/channel_layout.h>
  26. #include <libavutil/mastering_display_metadata.h>
  27. /* ------------------------------------------------------------------------- */
  28. #define do_log(level, format, ...) \
  29. blog(level, "[obs-ffmpeg mpegts muxer: '%s']: " format, \
  30. obs_output_get_name(stream->output), ##__VA_ARGS__)
  31. #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__)
  32. #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__)
  33. #define error(format, ...) do_log(LOG_ERROR, format, ##__VA_ARGS__)
  34. static void ffmpeg_mpegts_set_last_error(struct ffmpeg_data *data,
  35. const char *error)
  36. {
  37. if (data->last_error)
  38. bfree(data->last_error);
  39. data->last_error = bstrdup(error);
  40. }
  41. void ffmpeg_mpegts_log_error(int log_level, struct ffmpeg_data *data,
  42. const char *format, ...)
  43. {
  44. va_list args;
  45. char out[4096];
  46. va_start(args, format);
  47. vsnprintf(out, sizeof(out), format, args);
  48. va_end(args);
  49. ffmpeg_mpegts_set_last_error(data, out);
  50. blog(log_level, "%s", out);
  51. }
  52. static bool is_rist(struct ffmpeg_output *stream)
  53. {
  54. return !strncmp(stream->ff_data.config.url, RIST_PROTO,
  55. sizeof(RIST_PROTO) - 1);
  56. }
  57. static bool is_srt(struct ffmpeg_output *stream)
  58. {
  59. return !strncmp(stream->ff_data.config.url, SRT_PROTO,
  60. sizeof(SRT_PROTO) - 1);
  61. }
  62. static bool proto_is_allowed(struct ffmpeg_output *stream)
  63. {
  64. return !strncmp(stream->ff_data.config.url, UDP_PROTO,
  65. sizeof(UDP_PROTO) - 1) ||
  66. !strncmp(stream->ff_data.config.url, TCP_PROTO,
  67. sizeof(TCP_PROTO) - 1) ||
  68. !strncmp(stream->ff_data.config.url, HTTP_PROTO,
  69. sizeof(HTTP_PROTO) - 1);
  70. }
  71. static bool new_stream(struct ffmpeg_data *data, AVStream **stream,
  72. const char *name)
  73. {
  74. *stream = avformat_new_stream(data->output, NULL);
  75. if (!*stream) {
  76. ffmpeg_mpegts_log_error(
  77. LOG_WARNING, data,
  78. "Couldn't create stream for encoder '%s'", name);
  79. return false;
  80. }
  81. (*stream)->id = data->output->nb_streams - 1;
  82. return true;
  83. }
  84. static bool get_audio_headers(struct ffmpeg_output *stream,
  85. struct ffmpeg_data *data, int idx)
  86. {
  87. AVCodecParameters *par = data->audio_infos[idx].stream->codecpar;
  88. obs_encoder_t *aencoder =
  89. obs_output_get_audio_encoder(stream->output, idx);
  90. struct encoder_packet packet = {.type = OBS_ENCODER_AUDIO,
  91. .timebase_den = 1,
  92. .track_idx = idx};
  93. if (obs_encoder_get_extra_data(aencoder, &packet.data, &packet.size)) {
  94. par->extradata = av_memdup(packet.data, packet.size);
  95. par->extradata_size = (int)packet.size;
  96. avcodec_parameters_to_context(data->audio_infos[idx].ctx, par);
  97. return 1;
  98. }
  99. return 0;
  100. }
  101. static bool get_video_headers(struct ffmpeg_output *stream,
  102. struct ffmpeg_data *data)
  103. {
  104. AVCodecParameters *par = data->video->codecpar;
  105. obs_encoder_t *vencoder = obs_output_get_video_encoder(stream->output);
  106. struct encoder_packet packet = {.type = OBS_ENCODER_VIDEO,
  107. .timebase_den = 1};
  108. if (obs_encoder_get_extra_data(vencoder, &packet.data, &packet.size)) {
  109. par->extradata = av_memdup(packet.data, packet.size);
  110. par->extradata_size = (int)packet.size;
  111. avcodec_parameters_to_context(data->video_ctx,
  112. data->video->codecpar);
  113. return 1;
  114. }
  115. return 0;
  116. }
  117. static bool create_video_stream(struct ffmpeg_output *stream,
  118. struct ffmpeg_data *data)
  119. {
  120. AVCodecContext *context;
  121. struct obs_video_info ovi;
  122. if (!obs_get_video_info(&ovi)) {
  123. ffmpeg_mpegts_log_error(LOG_WARNING, data, "No active video");
  124. return false;
  125. }
  126. const char *name = data->config.video_encoder;
  127. const AVCodecDescriptor *codec = avcodec_descriptor_get_by_name(name);
  128. if (!codec) {
  129. error("Couldn't find codec '%s'", name);
  130. return false;
  131. }
  132. if (!new_stream(data, &data->video, name))
  133. return false;
  134. const bool pq = data->config.color_trc == AVCOL_TRC_SMPTE2084;
  135. const bool hlg = data->config.color_trc == AVCOL_TRC_ARIB_STD_B67;
  136. if (pq || hlg) {
  137. const int hdr_nominal_peak_level =
  138. pq ? (int)obs_get_video_hdr_nominal_peak_level()
  139. : (hlg ? 1000 : 0);
  140. size_t content_size;
  141. AVContentLightMetadata *const content =
  142. av_content_light_metadata_alloc(&content_size);
  143. content->MaxCLL = hdr_nominal_peak_level;
  144. content->MaxFALL = hdr_nominal_peak_level;
  145. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(60, 31, 102)
  146. av_stream_add_side_data(data->video,
  147. AV_PKT_DATA_CONTENT_LIGHT_LEVEL,
  148. (uint8_t *)content, content_size);
  149. #else
  150. av_packet_side_data_add(
  151. &data->video->codecpar->coded_side_data,
  152. &data->video->codecpar->nb_coded_side_data,
  153. AV_PKT_DATA_CONTENT_LIGHT_LEVEL, (uint8_t *)content,
  154. content_size, 0);
  155. #endif
  156. AVMasteringDisplayMetadata *const mastering =
  157. av_mastering_display_metadata_alloc();
  158. mastering->display_primaries[0][0] = av_make_q(17, 25);
  159. mastering->display_primaries[0][1] = av_make_q(8, 25);
  160. mastering->display_primaries[1][0] = av_make_q(53, 200);
  161. mastering->display_primaries[1][1] = av_make_q(69, 100);
  162. mastering->display_primaries[2][0] = av_make_q(3, 20);
  163. mastering->display_primaries[2][1] = av_make_q(3, 50);
  164. mastering->white_point[0] = av_make_q(3127, 10000);
  165. mastering->white_point[1] = av_make_q(329, 1000);
  166. mastering->min_luminance = av_make_q(0, 1);
  167. mastering->max_luminance = av_make_q(hdr_nominal_peak_level, 1);
  168. mastering->has_primaries = 1;
  169. mastering->has_luminance = 1;
  170. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(60, 31, 102)
  171. av_stream_add_side_data(data->video,
  172. AV_PKT_DATA_MASTERING_DISPLAY_METADATA,
  173. (uint8_t *)mastering,
  174. sizeof(*mastering));
  175. #else
  176. av_packet_side_data_add(
  177. &data->video->codecpar->coded_side_data,
  178. &data->video->codecpar->nb_coded_side_data,
  179. AV_PKT_DATA_MASTERING_DISPLAY_METADATA,
  180. (uint8_t *)mastering, sizeof(*mastering), 0);
  181. #endif
  182. }
  183. context = avcodec_alloc_context3(NULL);
  184. context->codec_type = codec->type;
  185. context->codec_id = codec->id;
  186. context->bit_rate = (int64_t)data->config.video_bitrate * 1000;
  187. context->width = data->config.scale_width;
  188. context->height = data->config.scale_height;
  189. context->coded_width = data->config.scale_width;
  190. context->coded_height = data->config.scale_height;
  191. context->time_base = (AVRational){ovi.fps_den, ovi.fps_num};
  192. context->gop_size = data->config.gop_size;
  193. context->pix_fmt = data->config.format;
  194. context->color_range = data->config.color_range;
  195. context->color_primaries = data->config.color_primaries;
  196. context->color_trc = data->config.color_trc;
  197. context->colorspace = data->config.colorspace;
  198. context->chroma_sample_location = determine_chroma_location(
  199. data->config.format, data->config.colorspace);
  200. context->thread_count = 0;
  201. data->video->time_base = context->time_base;
  202. #if LIBAVFORMAT_VERSION_MAJOR < 59
  203. data->video->codec->time_base = context->time_base;
  204. #endif
  205. data->video->avg_frame_rate = av_inv_q(context->time_base);
  206. data->video_ctx = context;
  207. data->config.width = data->config.scale_width;
  208. data->config.height = data->config.scale_height;
  209. avcodec_parameters_from_context(data->video->codecpar, context);
  210. return true;
  211. }
  212. static bool create_audio_stream(struct ffmpeg_output *stream,
  213. struct ffmpeg_data *data, int idx)
  214. {
  215. AVCodecContext *context;
  216. AVStream *avstream;
  217. struct obs_audio_info aoi;
  218. const char *name = data->config.audio_encoder;
  219. int channels;
  220. const AVCodecDescriptor *codec = avcodec_descriptor_get_by_name(name);
  221. if (!codec) {
  222. warn("Couldn't find codec '%s'", name);
  223. return false;
  224. }
  225. if (!obs_get_audio_info(&aoi)) {
  226. ffmpeg_mpegts_log_error(LOG_WARNING, data, "No active audio");
  227. return false;
  228. }
  229. if (!new_stream(data, &avstream, data->config.audio_encoder))
  230. return false;
  231. context = avcodec_alloc_context3(NULL);
  232. context->codec_type = codec->type;
  233. context->codec_id = codec->id;
  234. context->bit_rate = (int64_t)data->config.audio_bitrate * 1000;
  235. context->time_base = (AVRational){1, aoi.samples_per_sec};
  236. channels = get_audio_channels(aoi.speakers);
  237. #if LIBAVUTIL_VERSION_INT < AV_VERSION_INT(57, 24, 100)
  238. context->channels = get_audio_channels(aoi.speakers);
  239. #endif
  240. context->sample_rate = aoi.samples_per_sec;
  241. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(59, 24, 100)
  242. context->channel_layout =
  243. av_get_default_channel_layout(context->channels);
  244. //avutil default channel layout for 5 channels is 5.0 ; fix for 4.1
  245. if (aoi.speakers == SPEAKERS_4POINT1)
  246. context->channel_layout = av_get_channel_layout("4.1");
  247. #else
  248. av_channel_layout_default(&context->ch_layout, channels);
  249. if (aoi.speakers == SPEAKERS_4POINT1)
  250. context->ch_layout = (AVChannelLayout)AV_CHANNEL_LAYOUT_4POINT1;
  251. #endif
  252. context->sample_fmt = AV_SAMPLE_FMT_S16;
  253. context->frame_size = data->config.frame_size;
  254. avstream->time_base = context->time_base;
  255. data->audio_samplerate = aoi.samples_per_sec;
  256. data->audio_format = convert_ffmpeg_sample_format(context->sample_fmt);
  257. data->audio_planes = get_audio_planes(data->audio_format, aoi.speakers);
  258. data->audio_size = get_audio_size(data->audio_format, aoi.speakers, 1);
  259. data->audio_infos[idx].stream = avstream;
  260. data->audio_infos[idx].ctx = context;
  261. avcodec_parameters_from_context(data->audio_infos[idx].stream->codecpar,
  262. context);
  263. return true;
  264. }
  265. static inline bool init_streams(struct ffmpeg_output *stream,
  266. struct ffmpeg_data *data)
  267. {
  268. if (!create_video_stream(stream, data))
  269. return false;
  270. if (data->num_audio_streams) {
  271. data->audio_infos = calloc(data->num_audio_streams,
  272. sizeof(*data->audio_infos));
  273. for (int i = 0; i < data->num_audio_streams; i++) {
  274. if (!create_audio_stream(stream, data, i))
  275. return false;
  276. }
  277. }
  278. return true;
  279. }
  280. int ff_network_init(void)
  281. {
  282. #if HAVE_WINSOCK2_H
  283. WSADATA wsaData;
  284. if (WSAStartup(MAKEWORD(1, 1), &wsaData))
  285. return 0;
  286. #endif
  287. return 1;
  288. }
  289. static inline int connect_mpegts_url(struct ffmpeg_output *stream, bool is_rist)
  290. {
  291. int err = 0;
  292. const char *url = stream->ff_data.config.url;
  293. if (!ff_network_init()) {
  294. ffmpeg_mpegts_log_error(LOG_ERROR, &stream->ff_data,
  295. "Couldn't initialize network");
  296. return AVERROR(EIO);
  297. }
  298. URLContext *uc = av_mallocz(sizeof(URLContext) + strlen(url) + 1);
  299. if (!uc) {
  300. ffmpeg_mpegts_log_error(LOG_ERROR, &stream->ff_data,
  301. "Couldn't allocate memory");
  302. goto fail;
  303. }
  304. uc->url = (char *)url;
  305. uc->max_packet_size = is_rist ? RIST_MAX_PAYLOAD_SIZE
  306. : SRT_LIVE_DEFAULT_PAYLOAD_SIZE;
  307. uc->priv_data = is_rist ? av_mallocz(sizeof(RISTContext))
  308. : av_mallocz(sizeof(SRTContext));
  309. if (!uc->priv_data) {
  310. ffmpeg_mpegts_log_error(LOG_ERROR, &stream->ff_data,
  311. "Couldn't allocate memory");
  312. goto fail;
  313. }
  314. /* For SRT, pass streamid & passphrase; for RIST, pass passphrase, username
  315. * & password.
  316. */
  317. if (!is_rist) {
  318. SRTContext *context = (SRTContext *)uc->priv_data;
  319. context->streamid = NULL;
  320. if (stream->ff_data.config.stream_id != NULL) {
  321. if (strlen(stream->ff_data.config.stream_id))
  322. context->streamid = av_strdup(
  323. stream->ff_data.config.stream_id);
  324. }
  325. context->passphrase = NULL;
  326. if (stream->ff_data.config.encrypt_passphrase != NULL) {
  327. if (strlen(stream->ff_data.config.encrypt_passphrase))
  328. context->passphrase =
  329. av_strdup(stream->ff_data.config
  330. .encrypt_passphrase);
  331. }
  332. } else {
  333. RISTContext *context = (RISTContext *)uc->priv_data;
  334. context->secret = NULL;
  335. if (stream->ff_data.config.encrypt_passphrase != NULL) {
  336. if (strlen(stream->ff_data.config.encrypt_passphrase))
  337. context->secret =
  338. bstrdup(stream->ff_data.config
  339. .encrypt_passphrase);
  340. }
  341. context->username = NULL;
  342. if (stream->ff_data.config.username != NULL) {
  343. if (strlen(stream->ff_data.config.username))
  344. context->username = bstrdup(
  345. stream->ff_data.config.username);
  346. }
  347. context->password = NULL;
  348. if (stream->ff_data.config.password != NULL) {
  349. if (strlen(stream->ff_data.config.password))
  350. context->password = bstrdup(
  351. stream->ff_data.config.password);
  352. }
  353. }
  354. stream->h = uc;
  355. if (is_rist)
  356. err = librist_open(uc, uc->url);
  357. else
  358. err = libsrt_open(uc, uc->url);
  359. if (err < 0)
  360. goto fail;
  361. return 0;
  362. fail:
  363. if (uc)
  364. av_freep(&uc->priv_data);
  365. av_freep(&uc);
  366. #if HAVE_WINSOCK2_H
  367. WSACleanup();
  368. #endif
  369. return err;
  370. }
  371. static inline int allocate_custom_aviocontext(struct ffmpeg_output *stream,
  372. bool is_rist)
  373. {
  374. /* allocate buffers */
  375. uint8_t *buffer = NULL;
  376. int buffer_size;
  377. URLContext *h = stream->h;
  378. AVIOContext *s = NULL;
  379. buffer_size = UDP_DEFAULT_PAYLOAD_SIZE;
  380. buffer = av_malloc(buffer_size);
  381. if (!buffer)
  382. return AVERROR(ENOMEM);
  383. /* allocate custom avio_context */
  384. if (is_rist)
  385. s = avio_alloc_context(
  386. buffer, buffer_size, AVIO_FLAG_WRITE, h, NULL,
  387. (int (*)(void *, uint8_t *, int))librist_write, NULL);
  388. else
  389. s = avio_alloc_context(
  390. buffer, buffer_size, AVIO_FLAG_WRITE, h, NULL,
  391. (int (*)(void *, uint8_t *, int))libsrt_write, NULL);
  392. if (!s)
  393. goto fail;
  394. s->max_packet_size = h->max_packet_size;
  395. s->opaque = h;
  396. stream->s = s;
  397. stream->ff_data.output->pb = s;
  398. return 0;
  399. fail:
  400. av_freep(&buffer);
  401. return AVERROR(ENOMEM);
  402. }
  403. static inline int open_output_file(struct ffmpeg_output *stream,
  404. struct ffmpeg_data *data)
  405. {
  406. int ret;
  407. bool rist = is_rist(stream);
  408. bool srt = is_srt(stream);
  409. bool allowed_proto = proto_is_allowed(stream);
  410. AVDictionary *dict = NULL;
  411. /* Retrieve protocol settings for udp, tcp, rtp ... (not srt or rist).
  412. * These options will be passed to protocol by avio_open2 through dict.
  413. * The invalid options will be left in dict. */
  414. if (!rist && !srt) {
  415. if ((ret = av_dict_parse_string(&dict,
  416. data->config.protocol_settings,
  417. "=", " ", 0))) {
  418. ffmpeg_mpegts_log_error(
  419. LOG_WARNING, data,
  420. "Failed to parse protocol settings: %s, %s",
  421. data->config.protocol_settings,
  422. av_err2str(ret));
  423. av_dict_free(&dict);
  424. return OBS_OUTPUT_INVALID_STREAM;
  425. }
  426. if (av_dict_count(dict) > 0) {
  427. struct dstr str = {0};
  428. AVDictionaryEntry *entry = NULL;
  429. while ((entry = av_dict_get(dict, "", entry,
  430. AV_DICT_IGNORE_SUFFIX)))
  431. dstr_catf(&str, "\n\t%s=%s", entry->key,
  432. entry->value);
  433. info("Using protocol settings: %s", str.array);
  434. dstr_free(&str);
  435. }
  436. }
  437. /* Ensure h264 bitstream auto conversion from avcc to annex B */
  438. data->output->flags |= AVFMT_FLAG_AUTO_BSF;
  439. /* Open URL for rist, srt or other protocols compatible with mpegts
  440. * muxer supported by avformat (udp, tcp, rtp ...).
  441. */
  442. if (rist) {
  443. ret = connect_mpegts_url(stream, true);
  444. } else if (srt) {
  445. ret = connect_mpegts_url(stream, false);
  446. } else if (allowed_proto) {
  447. ret = avio_open2(&data->output->pb, data->config.url,
  448. AVIO_FLAG_WRITE, NULL, &dict);
  449. } else {
  450. info("[ffmpeg mpegts muxer]: Invalid protocol: %s",
  451. data->config.url);
  452. return OBS_OUTPUT_BAD_PATH;
  453. }
  454. if (ret < 0) {
  455. if ((rist || srt) && (ret == OBS_OUTPUT_CONNECT_FAILED ||
  456. ret == OBS_OUTPUT_INVALID_STREAM)) {
  457. error("Failed to open the url or invalid stream");
  458. } else {
  459. ffmpeg_mpegts_log_error(LOG_WARNING, data,
  460. "Couldn't open '%s', %s",
  461. data->config.url,
  462. av_err2str(ret));
  463. av_dict_free(&dict);
  464. }
  465. return ret;
  466. }
  467. /* Log invalid protocol settings for all protocols except srt or rist.
  468. * Or for srt & rist, allocate custom avio_ctx which will host the
  469. * protocols write callbacks.
  470. */
  471. if (!rist && !srt) {
  472. if (av_dict_count(dict) > 0) {
  473. struct dstr str = {0};
  474. AVDictionaryEntry *entry = NULL;
  475. while ((entry = av_dict_get(dict, "", entry,
  476. AV_DICT_IGNORE_SUFFIX)))
  477. dstr_catf(&str, "\n\t%s=%s", entry->key,
  478. entry->value);
  479. info("[ffmpeg mpegts muxer]: Invalid protocol settings: %s",
  480. str.array);
  481. dstr_free(&str);
  482. }
  483. av_dict_free(&dict);
  484. } else {
  485. ret = allocate_custom_aviocontext(stream, rist);
  486. if (ret < 0) {
  487. info("Couldn't allocate custom avio_context for url: '%s', %s",
  488. data->config.url, av_err2str(ret));
  489. return OBS_OUTPUT_INVALID_STREAM;
  490. }
  491. }
  492. return 0;
  493. }
  494. static void close_video(struct ffmpeg_data *data)
  495. {
  496. avcodec_free_context(&data->video_ctx);
  497. }
  498. static void close_audio(struct ffmpeg_data *data)
  499. {
  500. for (int idx = 0; idx < data->num_audio_streams; idx++) {
  501. for (size_t i = 0; i < MAX_AV_PLANES; i++)
  502. circlebuf_free(&data->excess_frames[idx][i]);
  503. if (data->samples[idx][0])
  504. av_freep(&data->samples[idx][0]);
  505. if (data->audio_infos[idx].ctx) {
  506. avcodec_free_context(&data->audio_infos[idx].ctx);
  507. }
  508. if (data->aframe[idx])
  509. av_frame_free(&data->aframe[idx]);
  510. }
  511. }
  512. static void close_mpegts_url(struct ffmpeg_output *stream, bool is_rist)
  513. {
  514. int err = 0;
  515. AVIOContext *s = stream->s;
  516. if (!s)
  517. return;
  518. URLContext *h = s->opaque;
  519. if (!h)
  520. return; /* can happen when opening the url fails */
  521. /* close rist or srt URLs ; free URLContext */
  522. if (is_rist) {
  523. err = librist_close(h);
  524. } else {
  525. err = libsrt_close(h);
  526. }
  527. av_freep(&h->priv_data);
  528. av_freep(h);
  529. /* close custom avio_context for srt or rist */
  530. avio_flush(stream->s);
  531. stream->s->opaque = NULL;
  532. av_freep(&stream->s->buffer);
  533. avio_context_free(&stream->s);
  534. if (err)
  535. info("[ffmpeg mpegts muxer]: Error closing URL %s",
  536. stream->ff_data.config.url);
  537. }
  538. void ffmpeg_mpegts_data_free(struct ffmpeg_output *stream,
  539. struct ffmpeg_data *data)
  540. {
  541. if (data->initialized)
  542. av_write_trailer(data->output);
  543. if (data->video)
  544. close_video(data);
  545. if (data->audio_infos) {
  546. close_audio(data);
  547. free(data->audio_infos);
  548. }
  549. if (data->output) {
  550. if (is_rist(stream) || is_srt(stream)) {
  551. close_mpegts_url(stream, is_rist(stream));
  552. } else {
  553. avio_close(data->output->pb);
  554. }
  555. avformat_free_context(data->output);
  556. data->video = NULL;
  557. data->audio_infos = NULL;
  558. data->output = NULL;
  559. data->num_audio_streams = 0;
  560. }
  561. if (data->last_error)
  562. bfree(data->last_error);
  563. memset(data, 0, sizeof(struct ffmpeg_data));
  564. }
  565. bool ffmpeg_mpegts_data_init(struct ffmpeg_output *stream,
  566. struct ffmpeg_data *data,
  567. struct ffmpeg_cfg *config)
  568. {
  569. memset(data, 0, sizeof(struct ffmpeg_data));
  570. data->config = *config;
  571. data->num_audio_streams = config->audio_mix_count;
  572. data->audio_tracks = config->audio_tracks;
  573. if (!config->url || !*config->url)
  574. return false;
  575. avformat_network_init();
  576. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(59, 0, 100)
  577. AVOutputFormat *output_format;
  578. #else
  579. const AVOutputFormat *output_format;
  580. #endif
  581. output_format = av_guess_format("mpegts", NULL, "video/M2PT");
  582. if (output_format == NULL) {
  583. ffmpeg_mpegts_log_error(LOG_WARNING, data,
  584. "Couldn't set output format to mpegts");
  585. goto fail;
  586. } else {
  587. info("Output format name and long_name: %s, %s",
  588. output_format->name ? output_format->name : "unknown",
  589. output_format->long_name ? output_format->long_name
  590. : "unknown");
  591. }
  592. avformat_alloc_output_context2(&data->output, output_format, NULL,
  593. data->config.url);
  594. if (!data->output) {
  595. ffmpeg_mpegts_log_error(LOG_WARNING, data,
  596. "Couldn't create avformat context");
  597. goto fail;
  598. }
  599. return true;
  600. fail:
  601. warn("ffmpeg_data_init failed");
  602. return false;
  603. }
  604. /* ------------------------------------------------------------------------- */
  605. static inline bool stopping(struct ffmpeg_output *output)
  606. {
  607. return os_atomic_load_bool(&output->stopping);
  608. }
  609. static const char *ffmpeg_mpegts_getname(void *unused)
  610. {
  611. UNUSED_PARAMETER(unused);
  612. return obs_module_text("FFmpegMpegts");
  613. }
  614. static void ffmpeg_mpegts_log_callback(void *param, int level,
  615. const char *format, va_list args)
  616. {
  617. if (level <= AV_LOG_INFO)
  618. blogva(LOG_DEBUG, format, args);
  619. UNUSED_PARAMETER(param);
  620. }
  621. static void *ffmpeg_mpegts_create(obs_data_t *settings, obs_output_t *output)
  622. {
  623. struct ffmpeg_output *data = bzalloc(sizeof(struct ffmpeg_output));
  624. pthread_mutex_init_value(&data->write_mutex);
  625. data->output = output;
  626. if (pthread_mutex_init(&data->write_mutex, NULL) != 0)
  627. goto fail;
  628. if (os_event_init(&data->stop_event, OS_EVENT_TYPE_AUTO) != 0)
  629. goto fail;
  630. if (os_sem_init(&data->write_sem, 0) != 0)
  631. goto fail;
  632. av_log_set_callback(ffmpeg_mpegts_log_callback);
  633. UNUSED_PARAMETER(settings);
  634. return data;
  635. fail:
  636. pthread_mutex_destroy(&data->write_mutex);
  637. os_event_destroy(data->stop_event);
  638. bfree(data);
  639. return NULL;
  640. }
  641. static void ffmpeg_mpegts_full_stop(void *data);
  642. static void ffmpeg_mpegts_deactivate(struct ffmpeg_output *output);
  643. static void ffmpeg_mpegts_destroy(void *data)
  644. {
  645. struct ffmpeg_output *output = data;
  646. if (output) {
  647. if (output->connecting)
  648. pthread_join(output->start_thread, NULL);
  649. ffmpeg_mpegts_full_stop(output);
  650. pthread_mutex_destroy(&output->write_mutex);
  651. os_sem_destroy(output->write_sem);
  652. os_event_destroy(output->stop_event);
  653. bfree(data);
  654. }
  655. }
  656. static uint64_t get_packet_sys_dts(struct ffmpeg_output *output,
  657. AVPacket *packet)
  658. {
  659. struct ffmpeg_data *data = &output->ff_data;
  660. uint64_t pause_offset = obs_output_get_pause_offset(output->output);
  661. uint64_t start_ts;
  662. AVRational time_base;
  663. if (data->video && data->video->index == packet->stream_index) {
  664. time_base = data->video->time_base;
  665. start_ts = output->video_start_ts;
  666. } else {
  667. time_base = data->audio_infos[0].stream->time_base;
  668. start_ts = output->audio_start_ts;
  669. }
  670. return start_ts + pause_offset +
  671. (uint64_t)av_rescale_q(packet->dts, time_base,
  672. (AVRational){1, 1000000000});
  673. }
  674. static int mpegts_process_packet(struct ffmpeg_output *output)
  675. {
  676. AVPacket *packet = NULL;
  677. int ret = 0;
  678. pthread_mutex_lock(&output->write_mutex);
  679. if (output->packets.num) {
  680. packet = output->packets.array[0];
  681. da_erase(output->packets, 0);
  682. }
  683. pthread_mutex_unlock(&output->write_mutex);
  684. if (!packet)
  685. return 0;
  686. //blog(LOG_DEBUG,
  687. // "size = %d, flags = %lX, stream = %d, "
  688. // "packets queued: %lu",
  689. // packet->size, packet->flags, packet->stream_index,
  690. // output->packets.num);
  691. if (stopping(output)) {
  692. uint64_t sys_ts = get_packet_sys_dts(output, packet);
  693. if (sys_ts >= output->stop_ts) {
  694. ret = 0;
  695. goto end;
  696. }
  697. }
  698. output->total_bytes += packet->size;
  699. uint8_t *buf = packet->data;
  700. ret = av_interleaved_write_frame(output->ff_data.output, packet);
  701. av_freep(&buf);
  702. if (ret < 0) {
  703. ffmpeg_mpegts_log_error(
  704. LOG_WARNING, &output->ff_data,
  705. "process_packet: Error writing packet: %s",
  706. av_err2str(ret));
  707. /* Treat "Invalid data found when processing input" and
  708. * "Invalid argument" as non-fatal */
  709. if (ret == AVERROR_INVALIDDATA || ret == -EINVAL) {
  710. ret = 0;
  711. }
  712. }
  713. end:
  714. av_packet_free(&packet);
  715. return ret;
  716. }
  717. static void *write_thread(void *data)
  718. {
  719. struct ffmpeg_output *output = data;
  720. while (os_sem_wait(output->write_sem) == 0) {
  721. /* check to see if shutting down */
  722. if (os_event_try(output->stop_event) == 0)
  723. break;
  724. int ret = mpegts_process_packet(output);
  725. if (ret != 0) {
  726. int code = OBS_OUTPUT_DISCONNECTED;
  727. pthread_detach(output->write_thread);
  728. output->write_thread_active = false;
  729. if (ret == -ENOSPC)
  730. code = OBS_OUTPUT_NO_SPACE;
  731. obs_output_signal_stop(output->output, code);
  732. ffmpeg_mpegts_deactivate(output);
  733. break;
  734. }
  735. }
  736. os_atomic_set_bool(&output->active, false);
  737. return NULL;
  738. }
  739. static bool get_extradata(struct ffmpeg_output *stream)
  740. {
  741. struct ffmpeg_data *ff_data = &stream->ff_data;
  742. /* get extradata for av headers from encoders */
  743. if (!get_video_headers(stream, ff_data))
  744. return false;
  745. for (int i = 0; i < ff_data->num_audio_streams; i++) {
  746. if (!get_audio_headers(stream, ff_data, i))
  747. return false;
  748. }
  749. return true;
  750. }
  751. /* set ffmpeg_config & init write_thread & capture */
  752. static bool set_config(struct ffmpeg_output *stream)
  753. {
  754. struct ffmpeg_cfg config;
  755. bool success;
  756. int ret;
  757. int code;
  758. /* 1. Get URL/username/password from service & set format + mime-type. */
  759. obs_service_t *service;
  760. service = obs_output_get_service(stream->output);
  761. if (!service)
  762. return false;
  763. config.url = obs_service_get_connect_info(
  764. service, OBS_SERVICE_CONNECT_INFO_SERVER_URL);
  765. config.username = obs_service_get_connect_info(
  766. service, OBS_SERVICE_CONNECT_INFO_USERNAME);
  767. config.password = obs_service_get_connect_info(
  768. service, OBS_SERVICE_CONNECT_INFO_PASSWORD);
  769. config.stream_id = obs_service_get_connect_info(
  770. service, OBS_SERVICE_CONNECT_INFO_STREAM_ID);
  771. config.encrypt_passphrase = obs_service_get_connect_info(
  772. service, OBS_SERVICE_CONNECT_INFO_ENCRYPT_PASSPHRASE);
  773. config.format_name = "mpegts";
  774. config.format_mime_type = "video/M2PT";
  775. /* 2. video settings */
  776. // 2.a) set width & height
  777. config.width = (int)obs_output_get_width(stream->output);
  778. config.height = (int)obs_output_get_height(stream->output);
  779. config.scale_width = config.width;
  780. config.scale_height = config.height;
  781. // 2.b) set video codec & ID from video encoder
  782. obs_encoder_t *vencoder = obs_output_get_video_encoder(stream->output);
  783. config.video_encoder = obs_encoder_get_codec(vencoder);
  784. if (strcmp(config.video_encoder, "h264") == 0)
  785. config.video_encoder_id = AV_CODEC_ID_H264;
  786. else
  787. config.video_encoder_id = AV_CODEC_ID_AV1;
  788. // 2.c) set video format from OBS to FFmpeg
  789. video_t *video = obs_encoder_video(vencoder);
  790. config.format =
  791. obs_to_ffmpeg_video_format(video_output_get_format(video));
  792. if (config.format == AV_PIX_FMT_NONE) {
  793. blog(LOG_WARNING,
  794. "Invalid pixel format used for mpegts output");
  795. return false;
  796. }
  797. // 2.d) set colorspace, color_range & transfer characteristic (from voi)
  798. const struct video_output_info *voi = video_output_get_info(video);
  799. config.color_range = voi->range == VIDEO_RANGE_FULL ? AVCOL_RANGE_JPEG
  800. : AVCOL_RANGE_MPEG;
  801. config.colorspace = format_is_yuv(voi->format) ? AVCOL_SPC_BT709
  802. : AVCOL_SPC_RGB;
  803. switch (voi->colorspace) {
  804. case VIDEO_CS_601:
  805. config.color_primaries = AVCOL_PRI_SMPTE170M;
  806. config.color_trc = AVCOL_TRC_SMPTE170M;
  807. config.colorspace = AVCOL_SPC_SMPTE170M;
  808. break;
  809. case VIDEO_CS_DEFAULT:
  810. case VIDEO_CS_709:
  811. config.color_primaries = AVCOL_PRI_BT709;
  812. config.color_trc = AVCOL_TRC_BT709;
  813. config.colorspace = AVCOL_SPC_BT709;
  814. break;
  815. case VIDEO_CS_SRGB:
  816. config.color_primaries = AVCOL_PRI_BT709;
  817. config.color_trc = AVCOL_TRC_IEC61966_2_1;
  818. config.colorspace = AVCOL_SPC_BT709;
  819. break;
  820. case VIDEO_CS_2100_PQ:
  821. config.color_primaries = AVCOL_PRI_BT2020;
  822. config.color_trc = AVCOL_TRC_SMPTE2084;
  823. config.colorspace = AVCOL_SPC_BT2020_NCL;
  824. break;
  825. case VIDEO_CS_2100_HLG:
  826. config.color_primaries = AVCOL_PRI_BT2020;
  827. config.color_trc = AVCOL_TRC_ARIB_STD_B67;
  828. config.colorspace = AVCOL_SPC_BT2020_NCL;
  829. }
  830. // 2.e) set video bitrate & gop through video encoder settings
  831. obs_data_t *settings = obs_encoder_get_settings(vencoder);
  832. config.video_bitrate = (int)obs_data_get_int(settings, "bitrate");
  833. int keyint_sec = (int)obs_data_get_int(settings, "keyint_sec");
  834. config.gop_size = keyint_sec ? keyint_sec * voi->fps_num / voi->fps_den
  835. : 250;
  836. obs_data_release(settings);
  837. /* 3. Audio settings */
  838. // 3.a) set audio codec & id from audio encoder
  839. obs_encoder_t *aencoder =
  840. obs_output_get_audio_encoder(stream->output, 0);
  841. config.audio_encoder = obs_encoder_get_codec(aencoder);
  842. if (strcmp(config.audio_encoder, "aac") == 0)
  843. config.audio_encoder_id = AV_CODEC_ID_AAC;
  844. else if (strcmp(config.audio_encoder, "opus") == 0)
  845. config.audio_encoder_id = AV_CODEC_ID_OPUS;
  846. // 3.b) get audio bitrate from the audio encoder.
  847. settings = obs_encoder_get_settings(aencoder);
  848. config.audio_bitrate = (int)obs_data_get_int(settings, "bitrate");
  849. obs_data_release(settings);
  850. // 3.c set audio frame size
  851. config.frame_size = (int)obs_encoder_get_frame_size(aencoder);
  852. // 3.d) set the number of tracks
  853. // The UI for multiple tracks is not written for streaming outputs.
  854. // When it is, modify write_packet & uncomment :
  855. // config.audio_tracks = (int)obs_output_get_mixers(stream->output);
  856. // config.audio_mix_count = get_audio_mix_count(config.audio_tracks);
  857. config.audio_tracks = 1;
  858. config.audio_mix_count = 1;
  859. /* 4. Muxer & protocol settings */
  860. // This requires some UI to be written for the output.
  861. // at the service level unless one can load the output in the settings/stream screen.
  862. settings = obs_output_get_settings(stream->output);
  863. obs_data_set_default_string(settings, "muxer_settings", "");
  864. config.muxer_settings = obs_data_get_string(settings, "muxer_settings");
  865. obs_data_release(settings);
  866. config.protocol_settings = "";
  867. /* 5. unused ffmpeg codec settings */
  868. config.video_settings = "";
  869. config.audio_settings = "";
  870. success = ffmpeg_mpegts_data_init(stream, &stream->ff_data, &config);
  871. if (!success) {
  872. if (stream->ff_data.last_error) {
  873. obs_output_set_last_error(stream->output,
  874. stream->ff_data.last_error);
  875. }
  876. ffmpeg_mpegts_data_free(stream, &stream->ff_data);
  877. code = OBS_OUTPUT_INVALID_STREAM;
  878. goto fail;
  879. }
  880. struct ffmpeg_data *ff_data = &stream->ff_data;
  881. if (!stream->got_headers) {
  882. if (!init_streams(stream, ff_data)) {
  883. error("mpegts avstream failed to be created");
  884. code = OBS_OUTPUT_INVALID_STREAM;
  885. goto fail;
  886. }
  887. code = open_output_file(stream, ff_data);
  888. if (code != 0) {
  889. error("Failed to open the url");
  890. goto fail;
  891. }
  892. av_dump_format(ff_data->output, 0, NULL, 1);
  893. }
  894. if (!obs_output_can_begin_data_capture(stream->output, 0))
  895. return false;
  896. if (!obs_output_initialize_encoders(stream->output, 0))
  897. return false;
  898. ret = pthread_create(&stream->write_thread, NULL, write_thread, stream);
  899. if (ret != 0) {
  900. ffmpeg_mpegts_log_error(
  901. LOG_WARNING, &stream->ff_data,
  902. "ffmpeg_output_start: Failed to create write "
  903. "thread.");
  904. code = OBS_OUTPUT_ERROR;
  905. goto fail;
  906. }
  907. os_atomic_set_bool(&stream->active, true);
  908. stream->write_thread_active = true;
  909. stream->total_bytes = 0;
  910. obs_output_begin_data_capture(stream->output, 0);
  911. return true;
  912. fail:
  913. obs_output_signal_stop(stream->output, code);
  914. ffmpeg_mpegts_full_stop(stream);
  915. return false;
  916. }
  917. static void *start_thread(void *data)
  918. {
  919. struct ffmpeg_output *output = data;
  920. set_config(output);
  921. output->connecting = false;
  922. return NULL;
  923. }
  924. static bool ffmpeg_mpegts_start(void *data)
  925. {
  926. struct ffmpeg_output *output = data;
  927. int ret;
  928. if (output->connecting)
  929. return false;
  930. os_atomic_set_bool(&output->stopping, false);
  931. output->audio_start_ts = 0;
  932. output->video_start_ts = 0;
  933. output->total_bytes = 0;
  934. output->got_headers = false;
  935. ret = pthread_create(&output->start_thread, NULL, start_thread, output);
  936. return (output->connecting = (ret == 0));
  937. }
  938. static void ffmpeg_mpegts_full_stop(void *data)
  939. {
  940. struct ffmpeg_output *output = data;
  941. if (output->active) {
  942. obs_output_end_data_capture(output->output);
  943. ffmpeg_mpegts_deactivate(output);
  944. }
  945. }
  946. static void ffmpeg_mpegts_stop(void *data, uint64_t ts)
  947. {
  948. struct ffmpeg_output *output = data;
  949. if (output->active) {
  950. if (ts > 0) {
  951. output->stop_ts = ts;
  952. os_atomic_set_bool(&output->stopping, true);
  953. }
  954. ffmpeg_mpegts_full_stop(output);
  955. } else {
  956. obs_output_signal_stop(output->output, OBS_OUTPUT_SUCCESS);
  957. }
  958. }
  959. static void ffmpeg_mpegts_deactivate(struct ffmpeg_output *output)
  960. {
  961. if (output->write_thread_active) {
  962. os_event_signal(output->stop_event);
  963. os_sem_post(output->write_sem);
  964. pthread_join(output->write_thread, NULL);
  965. output->write_thread_active = false;
  966. }
  967. pthread_mutex_lock(&output->write_mutex);
  968. for (size_t i = 0; i < output->packets.num; i++)
  969. av_packet_free(output->packets.array + i);
  970. da_free(output->packets);
  971. pthread_mutex_unlock(&output->write_mutex);
  972. ffmpeg_mpegts_data_free(output, &output->ff_data);
  973. }
  974. static uint64_t ffmpeg_mpegts_total_bytes(void *data)
  975. {
  976. struct ffmpeg_output *output = data;
  977. return output->total_bytes;
  978. }
  979. static inline int64_t rescale_ts2(AVStream *stream, AVRational codec_time_base,
  980. int64_t val)
  981. {
  982. return av_rescale_q_rnd(val / codec_time_base.num, codec_time_base,
  983. stream->time_base,
  984. AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
  985. }
  986. /* Convert obs encoder_packet to FFmpeg AVPacket and write to circular buffer
  987. * where it will be processed in the write_thread by process_packet.
  988. */
  989. void mpegts_write_packet(struct ffmpeg_output *stream,
  990. struct encoder_packet *encpacket)
  991. {
  992. if (stopping(stream) || !stream->ff_data.video ||
  993. !stream->ff_data.video_ctx || !stream->ff_data.audio_infos)
  994. return;
  995. if (!stream->ff_data.audio_infos[encpacket->track_idx].stream)
  996. return;
  997. bool is_video = encpacket->type == OBS_ENCODER_VIDEO;
  998. AVStream *avstream =
  999. is_video ? stream->ff_data.video
  1000. : stream->ff_data.audio_infos[encpacket->track_idx]
  1001. .stream;
  1002. AVPacket *packet = NULL;
  1003. const AVRational codec_time_base =
  1004. is_video ? stream->ff_data.video_ctx->time_base
  1005. : stream->ff_data.audio_infos[encpacket->track_idx]
  1006. .ctx->time_base;
  1007. packet = av_packet_alloc();
  1008. packet->data = av_memdup(encpacket->data, (int)encpacket->size);
  1009. if (packet->data == NULL) {
  1010. error("Couldn't allocate packet data");
  1011. goto fail;
  1012. }
  1013. packet->size = (int)encpacket->size;
  1014. packet->stream_index = avstream->id;
  1015. packet->pts = rescale_ts2(avstream, codec_time_base, encpacket->pts);
  1016. packet->dts = rescale_ts2(avstream, codec_time_base, encpacket->dts);
  1017. if (encpacket->keyframe)
  1018. packet->flags = AV_PKT_FLAG_KEY;
  1019. pthread_mutex_lock(&stream->write_mutex);
  1020. da_push_back(stream->packets, &packet);
  1021. pthread_mutex_unlock(&stream->write_mutex);
  1022. os_sem_post(stream->write_sem);
  1023. return;
  1024. fail:
  1025. av_packet_free(&packet);
  1026. }
  1027. static bool write_header(struct ffmpeg_output *stream, struct ffmpeg_data *data)
  1028. {
  1029. AVDictionary *dict = NULL;
  1030. int ret;
  1031. /* get mpegts muxer settings (can be used with rist, srt, rtp, etc ... */
  1032. if ((ret = av_dict_parse_string(&dict, data->config.muxer_settings, "=",
  1033. " ", 0))) {
  1034. ffmpeg_mpegts_log_error(
  1035. LOG_WARNING, data,
  1036. "Failed to parse muxer settings: %s, %s",
  1037. data->config.muxer_settings, av_err2str(ret));
  1038. av_dict_free(&dict);
  1039. return false;
  1040. }
  1041. if (av_dict_count(dict) > 0) {
  1042. struct dstr str = {0};
  1043. AVDictionaryEntry *entry = NULL;
  1044. while ((entry = av_dict_get(dict, "", entry,
  1045. AV_DICT_IGNORE_SUFFIX)))
  1046. dstr_catf(&str, "\n\t%s=%s", entry->key, entry->value);
  1047. info("Using muxer settings: %s", str.array);
  1048. dstr_free(&str);
  1049. }
  1050. /* Allocate the stream private data and write the stream header. */
  1051. ret = avformat_write_header(data->output, &dict);
  1052. if (ret < 0) {
  1053. ffmpeg_mpegts_log_error(
  1054. LOG_WARNING, data,
  1055. "Error setting stream header for '%s': %s",
  1056. data->config.url, av_err2str(ret));
  1057. return false;
  1058. }
  1059. /* Log invalid muxer settings. */
  1060. if (av_dict_count(dict) > 0) {
  1061. struct dstr str = {0};
  1062. AVDictionaryEntry *entry = NULL;
  1063. while ((entry = av_dict_get(dict, "", entry,
  1064. AV_DICT_IGNORE_SUFFIX)))
  1065. dstr_catf(&str, "\n\t%s=%s", entry->key, entry->value);
  1066. info("[ffmpeg mpegts muxer]: Invalid mpegts muxer settings: %s",
  1067. str.array);
  1068. dstr_free(&str);
  1069. }
  1070. av_dict_free(&dict);
  1071. return true;
  1072. }
  1073. static void ffmpeg_mpegts_data(void *data, struct encoder_packet *packet)
  1074. {
  1075. struct ffmpeg_output *stream = data;
  1076. struct ffmpeg_data *ff_data = &stream->ff_data;
  1077. int code;
  1078. if (!stream->got_headers) {
  1079. if (get_extradata(stream)) {
  1080. stream->got_headers = true;
  1081. } else {
  1082. warn("Failed to retrieve headers");
  1083. code = OBS_OUTPUT_INVALID_STREAM;
  1084. goto fail;
  1085. }
  1086. if (!write_header(stream, ff_data)) {
  1087. error("Failed to write headers");
  1088. code = OBS_OUTPUT_INVALID_STREAM;
  1089. goto fail;
  1090. }
  1091. av_dump_format(ff_data->output, 0, NULL, 1);
  1092. ff_data->initialized = true;
  1093. }
  1094. if (!stream->active)
  1095. return;
  1096. /* encoder failure */
  1097. if (!packet) {
  1098. obs_output_signal_stop(stream->output, OBS_OUTPUT_ENCODE_ERROR);
  1099. ffmpeg_mpegts_deactivate(stream);
  1100. return;
  1101. }
  1102. if (stopping(stream)) {
  1103. if (packet->sys_dts_usec >= (int64_t)stream->stop_ts) {
  1104. ffmpeg_mpegts_deactivate(stream);
  1105. return;
  1106. }
  1107. }
  1108. mpegts_write_packet(stream, packet);
  1109. return;
  1110. fail:
  1111. obs_output_signal_stop(stream->output, code);
  1112. ffmpeg_mpegts_full_stop(stream);
  1113. }
  1114. static obs_properties_t *ffmpeg_mpegts_properties(void *unused)
  1115. {
  1116. UNUSED_PARAMETER(unused);
  1117. obs_properties_t *props = obs_properties_create();
  1118. obs_properties_add_text(props, "path", obs_module_text("FilePath"),
  1119. OBS_TEXT_DEFAULT);
  1120. return props;
  1121. }
  1122. struct obs_output_info ffmpeg_mpegts_muxer = {
  1123. .id = "ffmpeg_mpegts_muxer",
  1124. .flags = OBS_OUTPUT_AV | OBS_OUTPUT_ENCODED | OBS_OUTPUT_MULTI_TRACK |
  1125. OBS_OUTPUT_SERVICE,
  1126. .protocols = "SRT;RIST",
  1127. #ifdef ENABLE_HEVC
  1128. .encoded_video_codecs = "h264;hevc",
  1129. #else
  1130. .encoded_video_codecs = "h264",
  1131. #endif
  1132. .encoded_audio_codecs = "aac;opus",
  1133. .get_name = ffmpeg_mpegts_getname,
  1134. .create = ffmpeg_mpegts_create,
  1135. .destroy = ffmpeg_mpegts_destroy,
  1136. .start = ffmpeg_mpegts_start,
  1137. .stop = ffmpeg_mpegts_stop,
  1138. .encoded_packet = ffmpeg_mpegts_data,
  1139. .get_total_bytes = ffmpeg_mpegts_total_bytes,
  1140. .get_properties = ffmpeg_mpegts_properties,
  1141. };