Skip to content

Instantly share code, notes, and snippets.

@kevmo314
Last active February 7, 2025 23:31
Show Gist options
  • Save kevmo314/d2afc4f82e4327d82d7f3a6cd792e77a to your computer and use it in GitHub Desktop.
Save kevmo314/d2afc4f82e4327d82d7f3a6cd792e77a to your computer and use it in GitHub Desktop.
// An example of how to use the FFmpeg HLS muxer without ever touching the disk.
//
// To compile:
// cc main.c -lavcodec -lavformat -lavutil
//
// To run:
// ffmpeg -hide_banner -loglevel error -f lavfi -i testsrc -pix_fmt yuv420p -f mpegts - | ./a.out
#include <unistd.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
int write_packet(void *opaque, uint8_t *data, int size)
{
printf("write packet %d to file %s\n", size, (char *)opaque);
return size;
}
int handle_io_open(struct AVFormatContext *s, AVIOContext **pb, const char *url,
int flags, AVDictionary **options)
{
printf("handle io open %s\n", url);
uint8_t *buf = NULL;
size_t size = 4096;
buf = av_malloc(size);
*pb = avio_alloc_context(buf, size, 1, (void *)url, NULL, write_packet, NULL);
s->opaque = (void *)url;
return 0;
}
int handle_io_close(struct AVFormatContext *s, AVIOContext *pb)
{
printf("handle io close %s\n", (char *)s->opaque);
avio_context_free(&pb);
return 0;
}
int main(int argc, char **argv)
{
AVFormatContext *fmt_ctx;
uint8_t buf[188];
AVPacket *pkt = av_packet_alloc();
// the io: prefix can be anything but is necessary to trick the hls muxer into
// thinking this is not on disk
avformat_alloc_output_context2(&fmt_ctx, NULL, "hls", "io:example-prefix");
fmt_ctx->io_open = handle_io_open;
fmt_ctx->io_close2 = handle_io_close;
avformat_new_stream(fmt_ctx, NULL);
avformat_write_header(fmt_ctx, NULL);
for (int i = 0;; i++)
{
// read 188 byte packet from stdin
int size = read(0, buf, 188);
if (size <= 0)
break;
pkt->data = buf;
pkt->size = size;
pkt->pts = pkt->dts = i * 1000;
pkt->duration = 1;
av_write_frame(fmt_ctx, pkt);
}
av_write_trailer(fmt_ctx);
avformat_free_context(fmt_ctx);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment