obs-ffmpeg-mpegts.c 36 KB

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