obs-ffmpeg-mpegts.c 36 KB

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