do_rot_180 function in transupp.c in libjpeg (you know how Q has a tag) does exactly what you want.
LOCAL(void) do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo, jvirt_barray_ptr *src_coef_arrays, jvirt_barray_ptr *dst_coef_arrays)
The function is used by jtransform_execute_transformation / JXFORM_ROT_180 and loslessy reorders the internal JPEG elements to achieve a rotation effect. This function demonstrates the use and rotation of a given file and the recording of a new modified file using the specified transformation (angle).
source share