/* gcc -O1 -o ${HBIN:-.}/grey8_to_h264 Grey8_to_H264.c -lx264 dd if=/dev/random count=100 bs=15000 | grey8_to_h264 10 150 100 > random.h264 */ #include #include #include #include static int EncodeFrame (FILE *out, x264_t *h, x264_picture_t *pic) { x264_picture_t pic_out; x264_nal_t *p_nal; int i_nal, i_frame_size; i_frame_size = x264_encoder_encode (h, &p_nal, &i_nal, pic, &pic_out); if (i_frame_size < 0) fprintf (stderr, "EncodeFrame(): x264_encoder_encode() failed.\n"); if (i_frame_size > 0) i_frame_size = fwrite (p_nal[0].p_payload, i_frame_size, 1, out); return i_frame_size; } static int Grey8_to_H264 (FILE *in, FILE *out, int fps, int width, int height) { int c = 1; x264_t *h; x264_picture_t pic; x264_param_t param; x264_param_default (¶m); #if 1 x264_param_parse (¶m, "threads", "1"); /* <-- avoid endless loop*/ x264_param_parse (¶m, "crf", "0"); /* <-- enforce lossless encoding*/ #endif param.i_width = width; param.i_height = height; param.i_fps_num = fps; param.i_fps_den = 1; h = x264_encoder_open (¶m); if (h != (x264_t*)(0)) { if (x264_picture_alloc (&pic, param.i_csp, param.i_width, param.i_height) == 0) { x264_nal_t *p_nal; int i_nal; if (x264_encoder_headers (h, &p_nal, &i_nal) >= 0) { if (fwrite (p_nal[0].p_payload, (p_nal[0].i_payload + p_nal[1].i_payload + p_nal[2].i_payload), 1, out) > 0) { int cnt = 0; memset (pic.img.plane[1], /*u*/ 128, (param.i_width/2)*(param.i_height/2)); /*have no color*/ memset (pic.img.plane[2], /*v*/ 128, (param.i_width/2)*(param.i_height/2)); /*have no color*/ /*encode sequence*/ while (feof(in) == 0) { for (c = 0; c < param.i_width*param.i_height && feof(in) == 0; ++c) /*read frame, i.e. 'y'*/ ((unsigned char*)(pic.img.plane[0]))[c] = (unsigned char)(fgetc(in)); pic.i_pts = cnt++; /* <-- what is this?*/ pic.i_type = X264_TYPE_AUTO; /* <-- what is this?*/ pic.i_qpplus1 = 0; /* <-- what is this?*/ if (EncodeFrame (out, h, &pic) < 0) break; } /*flush*/ while (x264_encoder_delayed_frames (h) > 0) if (EncodeFrame (out, h, &pic) < 0) break; c = 0; } } x264_picture_clean (&pic); } x264_encoder_close (h); } return c; } int main (int argc, char *argv[]) { int fps, width, height; if (argc >= 4 && sscanf (argv[1], " %d", &fps) == 1 && fps > 0 && sscanf (argv[2], " %d", &width) == 1 && width > 0 && sscanf (argv[3], " %d", &height) == 1 && height > 0) return Grey8_to_H264 (stdin, stdout, fps, width, height); fprintf (stderr, "Usage: %s framerate framewidth frameheight < grey8stream.data > stream.h264\n", argv[0]); return 1; }